Project

General

Profile

1
package eu.dnetlib.uoaorcidservice.controllers;
2

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

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

    
25
@RestController
26
@RequestMapping("/orcid")
27
@CrossOrigin(origins = "*")
28
public class UserTokensController {
29
    private final Logger log = Logger.getLogger(this.getClass());
30

    
31
    @Autowired
32
    private UserTokensService userTokensService;
33

    
34
//    @RequestMapping(value = "/tokens", method = RequestMethod.GET)
35
//    public List<UserTokens> getAllUserTokens() {
36
//        return userTokensService.getAllUserTokens();
37
//    }
38

    
39
//    @RequestMapping(value = "/token/access_token", method = RequestMethod.GET)
40
//    public String getUserAccessTokenByOrcid(@RequestParam String orcid) {
41
//        return "\""+userTokensService.getUserAccessToken(orcid)+"\"";
42
//    }
43

    
44
    @PreAuthorize("isAuthenticated()")
45
    @RequestMapping(value = "/token/save", method = RequestMethod.GET)
46
    public String saveUserTokens(@RequestParam String code) throws BadPaddingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException, IOException {
47
        log.debug("saveUserTokens: code="+code);
48

    
49
        String url = "https://sandbox.orcid.org/oauth/token";
50
        String clientId = "APP-A5M3KTX6NCN67L91";
51
        String clientSecret = "96b20d71-ae06-4286-bb00-9172536c1ad4";
52

    
53

    
54
        RestTemplate restTemplate = new RestTemplate();
55
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
56
            protected boolean hasError(HttpStatus statusCode) {
57
                return false;
58
            }});
59
        HttpHeaders headers = new HttpHeaders();
60
        headers.add("Content-Type","application/x-www-form-urlencoded");
61
        headers.add("Accept","application/json");
62

    
63
        String inputString =
64
                "client_id="+clientId
65
                        +"&client_secret="+clientSecret
66
                        +"&grant_type=authorization_code"
67
                        +"&code="+code
68
                        +"&redirect_uri=http://duffy.di.uoa.gr:4300/orcid";
69
        log.debug(inputString);
70

    
71
        HttpEntity<String> request = new HttpEntity<>(inputString, headers);
72
        //logger.info(restTemplate.exchange(fooResourceUrl, HttpMethod.GET, request, Object.class));
73
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
74
        if(response.getStatusCode() != HttpStatus.OK) {
75
            log.debug("User tokens response code is: " + response.getStatusCode());
76
            log.debug(response.getBody());
77
            return null;
78
        } else {
79
            log.debug(response);
80

    
81
            UserTokens userTokens = userTokensService.json2UserTokens(response.getBody().toString());
82
                userTokensService.saveUserTokens(userTokens);
83

    
84
            return "\""+userTokens.getAccessToken()+"\"";
85
        }
86

    
87
//        try {
88
//            URL obj = new URL(url);
89
//
90
//            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
91
//            con.setRequestMethod("POST");
92
//            con.setDoOutput(true);
93
//            con.setInstanceFollowRedirects(true);
94
//            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
95
//            con.setRequestProperty("Accept", "application/json");
96
//
97
//            String inputString =
98
//                    "client_id="+clientId
99
//                    +"&client_secret="+clientSecret
100
//                    +"&grant_type=authorization_code"
101
//                    +"&code="+code
102
//                    +"&redirect_uri=http://duffy.di.uoa.gr:4300/orcid";
103
//
104
//            log.debug(inputString);
105
//
106
//            try(OutputStream os = con.getOutputStream()) {
107
////                byte[] input = inputString.getBytes();
108
////                os.write(inputString, 0, inputString.length());
109
//
110
//                OutputStreamWriter osw = new OutputStreamWriter(os);
111
//                osw.write(inputString);
112
//                osw.flush();
113
//                osw.close();
114
//
115
//                os.close();  //don't forget to close the OutputStream
116
//                log.debug("http request body added");
117
//            } catch (Exception e) {
118
//                log.error("Failed to add http request body", e);
119
//            }
120
//
121
//            con.connect();
122
//
123
////            log.debug(con.getRequestMethod());
124
////            log.debug(con.getErrorStream());
125
////            log.debug(con.getContent());
126
//
127
//
128
//            if (con.getResponseCode() != 200) {
129
//                log.debug("User tokens response code is: " + con.getResponseCode());
130
//                return null;
131
//            } else {
132
//                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
133
//                StringBuilder response = new StringBuilder();
134
//                String inputLine;
135
//                while ((inputLine = in.readLine()) != null) {
136
//                    response.append(inputLine).append("\n");
137
//                }
138
//                in.close();
139
//                log.debug(response);
140
//
141
//                UserTokens userTokens = userTokensService.json2UserTokens(response.toString());
142
//                userTokensService.saveUserTokens(userTokens);
143
//
144
//                return "\""+userTokens.getAccessToken()+"\"";
145
//            }
146
//
147
//        } catch (Exception e) {
148
//            log.error("An error occured while trying to fetch user tokens ", e);
149
//            return null;
150
//        }
151
    }
152

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

    
159
}
(3-3/4)