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
@CrossOrigin(origins = "*")
31
public class UserTokensController {
32
    private final Logger log = Logger.getLogger(this.getClass());
33
    private final Logger orcid_log = Logger.getLogger("ORCID-"+this.getClass().getName());
34

    
35
    @Autowired
36
    private OrcidConfig orcidConfig;
37

    
38
    @Autowired
39
    private UserTokensService userTokensService;
40

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

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

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

    
61
    @PreAuthorize("isAuthenticated()")
62
    @RequestMapping(value = "/orcid/token/save", method = RequestMethod.GET)
63
    public String 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 null;
98
        } else {
99
            orcid_log.info("Response: "+response);
100

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

    
104
            return "\""+userTokens.getAccessToken()+"\"";
105
        }
106
    }
107

    
108
    @RequestMapping(value = "/orcid/personal-details", method = RequestMethod.GET)
109
    public String getPersonalDetailsFromOrcid() throws BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, IOException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeySpecException {
110
        log.debug("getPersonalDetailsFromOrcid");
111

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

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

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

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

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

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

    
153

    
154
    @PreAuthorize("isAuthenticated()")
155
    @RequestMapping(value = "/local/tokens/decrypt", method = RequestMethod.GET)
156
    public UserTokens decryptToken(@RequestParam String aaiId) throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, InvalidKeySpecException, IOException {
157
        return userTokensService.getUserTokensByAai(aaiId);
158
    }
159

    
160

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