Project

General

Profile

1
package eu.dnetlib.uoaorcidservice.controllers;
2

    
3
import eu.dnetlib.uoaorcidservice.configuration.properties.OrcidConfig;
4
import eu.dnetlib.uoaorcidservice.entities.UserTokens;
5
import eu.dnetlib.uoaorcidservice.handlers.utils.AESUtils;
6
import eu.dnetlib.uoaorcidservice.responses.SingleValueWrapperResponse;
7
import eu.dnetlib.uoaorcidservice.services.UserTokensService;
8
import org.apache.log4j.Logger;
9
import org.springframework.beans.factory.annotation.Autowired;
10
import org.springframework.http.*;
11
import org.springframework.security.access.AuthorizationServiceException;
12
import org.springframework.security.access.prepost.PreAuthorize;
13
import org.springframework.web.bind.annotation.*;
14
import org.springframework.web.client.DefaultResponseErrorHandler;
15
import org.springframework.web.client.RestTemplate;
16

    
17
import javax.crypto.BadPaddingException;
18
import javax.crypto.IllegalBlockSizeException;
19
import javax.crypto.NoSuchPaddingException;
20
import java.io.IOException;
21
import java.security.InvalidAlgorithmParameterException;
22
import java.security.InvalidKeyException;
23
import java.security.NoSuchAlgorithmException;
24
import java.security.spec.InvalidKeySpecException;
25
import java.util.ArrayList;
26
import java.util.List;
27

    
28
@RestController
29
//@RequestMapping("/orcid")
30
@PreAuthorize("isAuthenticated()")
31
@CrossOrigin(origins = "*")
32
public class UserTokensController {
33
    private final Logger log = Logger.getLogger(this.getClass());
34
    private final Logger orcid_log = Logger.getLogger("ORCID-"+this.getClass().getName());
35

    
36
    @Autowired
37
    private OrcidConfig orcidConfig;
38

    
39
    @Autowired
40
    private UserTokensService userTokensService;
41

    
42
//    @RequestMapping(value = "/tokens", method = RequestMethod.GET)
43
//    public List<UserTokens> getAllUserTokens() {
44
//        return userTokensService.getAllUserTokens();
45
//    }
46

    
47
//    @RequestMapping(value = "/token/access_token", method = RequestMethod.GET)
48
//    public String getUserAccessTokenByOrcid(@RequestParam String orcid) {
49
//        return "\""+userTokensService.getUserAccessToken(orcid)+"\"";
50
//    }
51

    
52
    @RequestMapping(value = "/local/orcidId", method = RequestMethod.GET)
53
    public SingleValueWrapperResponse<String> getUserOrcidId() throws BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, IOException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeySpecException {
54
        UserTokens userTokens = userTokensService.getUserTokens();
55
        if(userTokens == null) {
56
            throw new AuthorizationServiceException("User is not registered");
57
        }
58
        String userOrcid = userTokens.getOrcid();
59
        return new SingleValueWrapperResponse<String>(userOrcid);
60
    }
61

    
62
    @RequestMapping(value = "/orcid/token/save", method = RequestMethod.GET)
63
    public SingleValueWrapperResponse<Boolean> saveUserTokens(@RequestParam String code
64
//            , @RequestParam String redirect_uri
65
    ) throws BadPaddingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException, IOException {
66
        log.debug("saveUserTokens: code="+code);
67

    
68
        String url = orcidConfig.getTokenURL();//"https://sandbox.orcid.org/oauth/token";
69
        String clientId = orcidConfig.getClientId();//"APP-A5M3KTX6NCN67L91";
70
        String clientSecret = orcidConfig.getClientSecret();//"96b20d71-ae06-4286-bb00-9172536c1ad4";
71

    
72

    
73
        RestTemplate restTemplate = new RestTemplate();
74
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
75
            protected boolean hasError(HttpStatus statusCode) {
76
                return false;
77
            }});
78
        HttpHeaders headers = new HttpHeaders();
79
        headers.add("Content-Type","application/x-www-form-urlencoded");
80
        headers.add("Accept","application/json");
81

    
82
        String inputString =
83
                "client_id="+clientId
84
                        +"&client_secret="+clientSecret
85
                        +"&grant_type=authorization_code"
86
                        +"&code="+code;
87
//                        +"&redirect_uri="+redirect_uri;//http://duffy.di.uoa.gr:4300/orcid";
88

    
89
        HttpEntity<String> request = new HttpEntity<>(inputString, headers);
90
        orcid_log.info("url: "+url);
91
        orcid_log.info("request: "+request);
92

    
93
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
94
        if(response.getStatusCode() != HttpStatus.OK) {
95
            orcid_log.error("User tokens response code is: " + response.getStatusCode());
96
            orcid_log.error("Unexpected Response: "+response.getBody());
97
            return new SingleValueWrapperResponse<Boolean>(false);
98
        } else {
99
            orcid_log.info("Response: "+response);
100

    
101
            UserTokens userTokens = userTokensService.json2UserTokens(response.getBody().toString());
102
            userTokensService.saveUserTokens(userTokens);
103

    
104
            return new SingleValueWrapperResponse<Boolean>(true);
105
//            return "\""+userTokens.getAccessToken()+"\"";
106
        }
107
    }
108

    
109
    @RequestMapping(value = "/orcid/personal-details", method = RequestMethod.GET)
110
    public String getPersonalDetailsFromOrcid() throws Exception {
111
        log.debug("getPersonalDetailsFromOrcid");
112

    
113
        UserTokens userTokens = userTokensService.getUserTokens();
114
        if(userTokens == null) {
115
            throw new AuthorizationServiceException("User is not registered");
116
        }
117
        String userOrcid = userTokens.getOrcid();
118
        String userAccessToken = userTokens.getAccessToken();
119

    
120
        if(userOrcid == null || userAccessToken == null) {
121
            throw new AuthorizationServiceException("User is not registered");
122
        }
123

    
124
//        log.debug("Access token: " + userAccessToken);
125
//        log.debug("User orcid: " + userOrcid);
126

    
127
        String url = orcidConfig.getApiURL()+userOrcid+"/personal-details";
128

    
129
        RestTemplate restTemplate = new RestTemplate();
130
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
131
            protected boolean hasError(HttpStatus statusCode) {
132
                return false;
133
            }
134
        });
135
        HttpHeaders headers = new HttpHeaders();
136
        headers.add("Accept", "application/json");
137
        headers.add("Authorization", "Bearer " + userAccessToken);
138
        headers.add("Content-Type", "application/orcid+json");
139
        HttpEntity<String> request = new HttpEntity<>(headers);
140

    
141
        orcid_log.info("request: "+request);
142
        orcid_log.info("url: "+url);
143
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
144
        if (response.getStatusCode() != HttpStatus.OK) {
145
            orcid_log.error("Getting user details response code is: " + response.getStatusCode());
146
            orcid_log.error("Unexpected Response: "+response.getBody());
147

    
148
            if(response.getStatusCode() == HttpStatus.UNAUTHORIZED) {
149
                throw new AuthorizationServiceException("You are not allowed to get personal details");
150
            } else {
151
                throw new Exception("Internal server error");
152
            }
153
//            return null;
154
        } else {
155
            orcid_log.info("response: "+response);
156
            return response.getBody().toString();
157
        }
158
    }
159

    
160

    
161
//    @PreAuthorize("isAuthenticated()")
162
//    @RequestMapping(value = "/local/tokens/decrypt", method = RequestMethod.GET)
163
//    public UserTokens decryptToken(@RequestParam String aaiId) throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, InvalidKeySpecException, IOException {
164
//        return userTokensService.getUserTokensByAai(aaiId);
165
//    }
166
//
167
//
168
//    @PreAuthorize("isAuthenticated()")
169
//    @RequestMapping(value = "/local/tokens/encrypt", method = RequestMethod.GET)
170
//    public UserTokens encryptToken(@RequestParam String aaiId) throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, InvalidKeySpecException, IOException {
171
//        UserTokens userTokens = userTokensService.getEncryptedUserTokensByAai(aaiId);
172
//        return userTokensService.encryptTokens(userTokens);
173
//    }
174
}
(3-3/4)