1
|
package eu.dnetlib.openaire.usermanagement.api;
|
2
|
|
3
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
4
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
5
|
import com.google.gson.Gson;
|
6
|
import com.google.gson.JsonArray;
|
7
|
import com.google.gson.JsonObject;
|
8
|
import com.google.gson.JsonParser;
|
9
|
import eu.dnetlib.openaire.user.dao.SQLMigrationUserDAO;
|
10
|
import eu.dnetlib.openaire.user.ldap.MUserActionsLDAP;
|
11
|
import eu.dnetlib.openaire.user.login.utils.AuthoritiesMapper;
|
12
|
import eu.dnetlib.openaire.user.pojos.migration.LDAPUser;
|
13
|
import eu.dnetlib.openaire.user.store.DataSourceConnector;
|
14
|
import org.apache.commons.io.IOUtils;
|
15
|
import org.apache.http.HttpResponse;
|
16
|
import org.apache.http.NameValuePair;
|
17
|
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
18
|
import org.apache.http.client.methods.HttpPost;
|
19
|
import org.apache.http.impl.client.CloseableHttpClient;
|
20
|
import org.apache.http.impl.client.HttpClients;
|
21
|
import org.apache.http.message.BasicNameValuePair;
|
22
|
import org.apache.log4j.Logger;
|
23
|
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
|
24
|
import org.mitre.openid.connect.model.UserInfo;
|
25
|
import org.springframework.beans.factory.annotation.Autowired;
|
26
|
import org.springframework.beans.factory.annotation.Value;
|
27
|
import org.springframework.http.*;
|
28
|
import org.springframework.security.core.GrantedAuthority;
|
29
|
import org.springframework.security.core.context.SecurityContextHolder;
|
30
|
import org.springframework.stereotype.Component;
|
31
|
import org.springframework.web.bind.annotation.CookieValue;
|
32
|
import org.springframework.web.client.DefaultResponseErrorHandler;
|
33
|
import org.springframework.web.client.RestTemplate;
|
34
|
|
35
|
import javax.ws.rs.GET;
|
36
|
import javax.ws.rs.Path;
|
37
|
import javax.ws.rs.Produces;
|
38
|
import javax.ws.rs.QueryParam;
|
39
|
import javax.ws.rs.core.MediaType;
|
40
|
import javax.ws.rs.core.Response;
|
41
|
import java.io.IOException;
|
42
|
import java.io.InputStream;
|
43
|
import java.io.UnsupportedEncodingException;
|
44
|
import java.nio.charset.StandardCharsets;
|
45
|
import java.util.ArrayList;
|
46
|
import java.util.HashSet;
|
47
|
import java.util.List;
|
48
|
import java.util.Set;
|
49
|
|
50
|
/**
|
51
|
* Created by sofia on 24/11/2016.
|
52
|
*/
|
53
|
@Component(value = "test3service")
|
54
|
@Path("/users")
|
55
|
public class Test3Service {
|
56
|
|
57
|
private static final Logger logger = Logger.getLogger(Test3Service.class);
|
58
|
|
59
|
@Autowired
|
60
|
private SQLMigrationUserDAO sqlMigrationUserDAO;
|
61
|
|
62
|
@Autowired
|
63
|
private MUserActionsLDAP mUserActionsLDAP;
|
64
|
|
65
|
@Autowired
|
66
|
private DataSourceConnector dataSourceConnector;
|
67
|
|
68
|
@Value("${oidc.issuer}")
|
69
|
private String issuer;
|
70
|
|
71
|
@Value("${oidc.secret}")
|
72
|
private String secret;
|
73
|
|
74
|
@Value("${oidc.id}")
|
75
|
private String id;
|
76
|
|
77
|
@GET
|
78
|
@Path("/getToken")
|
79
|
@Produces(MediaType.APPLICATION_JSON)
|
80
|
public Response getToken(@QueryParam("accessToken") String accessToken){
|
81
|
logger.debug("Refresh token " + accessToken);
|
82
|
CloseableHttpClient httpclient = HttpClients.createDefault();
|
83
|
HttpPost httppost = new HttpPost(issuer+"/token");
|
84
|
|
85
|
// Request parameters and other properties.
|
86
|
List<NameValuePair> params = new ArrayList<NameValuePair>();
|
87
|
params.add(new BasicNameValuePair("client_id", id));
|
88
|
params.add(new BasicNameValuePair("client_secret", secret));
|
89
|
params.add(new BasicNameValuePair("grant_type", "refresh_token"));
|
90
|
params.add(new BasicNameValuePair("refresh_token", accessToken));
|
91
|
params.add(new BasicNameValuePair("scope", "openid email profile"));
|
92
|
try {
|
93
|
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
|
94
|
//Execute and get the response.
|
95
|
HttpResponse response = null;
|
96
|
response = httpclient.execute(httppost);
|
97
|
org.apache.http.HttpEntity entity = response.getEntity();
|
98
|
if (entity != null) {
|
99
|
try (InputStream instream = entity.getContent()) {
|
100
|
logger.debug(IOUtils.toString(instream, StandardCharsets.UTF_8.name()));
|
101
|
}
|
102
|
}
|
103
|
|
104
|
} catch (UnsupportedEncodingException e) {
|
105
|
logger.error(e);
|
106
|
|
107
|
} catch (IOException e) {
|
108
|
logger.error(e);
|
109
|
}
|
110
|
|
111
|
return Response.status(200).type(MediaType.APPLICATION_JSON).build();
|
112
|
}
|
113
|
|
114
|
@GET
|
115
|
@Path("/getUserInfo")
|
116
|
@Produces(MediaType.APPLICATION_JSON)
|
117
|
public Response getUserInfo(@QueryParam("accessToken") String accessToken) throws JsonProcessingException {
|
118
|
//return Response.status(404).entity(compose404Message("This is a test message.")).type(MediaType.APPLICATION_JSON).build();
|
119
|
// call aai with accessToken
|
120
|
logger.info(accessToken);
|
121
|
RestTemplate restTemplate = new RestTemplate();
|
122
|
restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
|
123
|
protected boolean hasError(HttpStatus statusCode) {
|
124
|
return false;
|
125
|
}});
|
126
|
HttpHeaders headers = new HttpHeaders();
|
127
|
headers.add("Authorization","Bearer " + accessToken);
|
128
|
HttpEntity<String> request = new HttpEntity<>(headers);
|
129
|
//logger.info(restTemplate.exchange(fooResourceUrl, HttpMethod.GET, request, Object.class));
|
130
|
ResponseEntity<String> response = restTemplate.exchange(issuer +"userinfo", HttpMethod.GET, request, String.class);
|
131
|
if(response.getStatusCode() == HttpStatus.OK) {
|
132
|
JsonObject userInfo = new JsonParser().parse(response.getBody()).getAsJsonObject();
|
133
|
JsonArray roles = new JsonArray();
|
134
|
AuthoritiesMapper.map(userInfo.get("edu_person_entitlements").getAsJsonArray()).forEach(grantedAuthority -> {
|
135
|
roles.add(grantedAuthority.getAuthority());
|
136
|
});
|
137
|
userInfo.add("roles", roles);
|
138
|
return Response.status(response.getStatusCode().value()).entity(userInfo.toString()).type(MediaType.APPLICATION_JSON).build();
|
139
|
} else {
|
140
|
return Response.status(response.getStatusCode().value()).entity(response.getBody()).type(MediaType.APPLICATION_JSON).build();
|
141
|
}
|
142
|
|
143
|
}
|
144
|
|
145
|
@GET
|
146
|
@Path("/getUser")
|
147
|
@Produces(MediaType.APPLICATION_JSON)
|
148
|
public Response getUser() {
|
149
|
JsonObject userInfoJson = new JsonObject();
|
150
|
try {
|
151
|
OIDCAuthenticationToken authentication = null;
|
152
|
try {
|
153
|
authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
|
154
|
}catch (Exception e){
|
155
|
logger.info("Try to get User info - no context found ");
|
156
|
return Response.status(404).entity(compose404Message("Get User info: no context found ")).type(MediaType.APPLICATION_JSON).build();
|
157
|
}
|
158
|
UserInfo userInfo = authentication.getUserInfo();
|
159
|
if(userInfo == null){
|
160
|
return Response.status(404).entity(compose404Message("Get User info: user info is null ")).type(MediaType.APPLICATION_JSON).build();
|
161
|
}
|
162
|
logger.info("Get User:\n name: " + authentication.getUserInfo().getGivenName() + " " + authentication.getUserInfo().getFamilyName());
|
163
|
|
164
|
|
165
|
userInfoJson.addProperty("sub", userInfo.getSub());
|
166
|
userInfoJson.addProperty("name", userInfo.getName());
|
167
|
userInfoJson.addProperty("given_name", userInfo.getGivenName());
|
168
|
userInfoJson.addProperty("family_name", userInfo.getFamilyName());
|
169
|
userInfoJson.addProperty("email", userInfo.getEmail());
|
170
|
JsonArray roles = new JsonArray();
|
171
|
authentication.getAuthorities().forEach(grantedAuthority -> {
|
172
|
roles.add(grantedAuthority.getAuthority());
|
173
|
});
|
174
|
userInfoJson.add("roles", roles);
|
175
|
}catch (Exception e){
|
176
|
logger.error("Get User info: An error occurred ",e);
|
177
|
return Response.status(500).entity(compose500Message("Get User info: An error occurred ",e)).type(MediaType.APPLICATION_JSON).build();
|
178
|
}
|
179
|
return Response.status(200).entity(userInfoJson.toString()).type(MediaType.APPLICATION_JSON).build();
|
180
|
}
|
181
|
|
182
|
/*
|
183
|
@GET
|
184
|
@Path("/katerina")
|
185
|
@Produces(MediaType.APPLICATION_JSON)
|
186
|
//@PreAuthorize("hasRole('ROLE_USER')")
|
187
|
@PreAuthorize("hasAuthority('urn:geant:openaire.eu:group:Registered+User#aai.openaire.eu')")
|
188
|
public Response getKaterina() {
|
189
|
return Response.status(200).build();
|
190
|
}
|
191
|
|
192
|
@GET
|
193
|
@Path("/skata")
|
194
|
@Produces(MediaType.APPLICATION_JSON)
|
195
|
@PreAuthorize("hasRole('ROLE_USER')")
|
196
|
public Response getKaterina2() {
|
197
|
return Response.status(200).build();
|
198
|
}
|
199
|
|
200
|
@GET
|
201
|
@Path("/skata2")
|
202
|
@Produces(MediaType.APPLICATION_JSON)
|
203
|
@PreAuthorize("hasAuthority('skata')")
|
204
|
public Response getKaterina3() {
|
205
|
return Response.status(200).build();
|
206
|
}
|
207
|
|
208
|
|
209
|
@GET
|
210
|
@Path("/me")
|
211
|
//@Produces(MediaType.APPLICATION_JSON)
|
212
|
public Response getKaterina(@AuthenticationPrincipal UserDetails userDetails) {
|
213
|
//return Response.status(200).entity(userDetails).type(MediaType.APPLICATION_JSON).build();
|
214
|
return Response.status(200).build();
|
215
|
}
|
216
|
*/
|
217
|
|
218
|
/* JSON Utility Methods */
|
219
|
private String compose401Message(String message) {
|
220
|
return "{ \"status\" : \"error\", \"code\" : \"401\", \"message\" : \" " + message +" \" }";
|
221
|
}
|
222
|
|
223
|
private String compose404Message(String message) {
|
224
|
return "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \" " + message +" \" }";
|
225
|
}
|
226
|
|
227
|
private String compose500Message(String message, Exception exception) {
|
228
|
return "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \" " + message + "\", " +
|
229
|
"\"description\" : \""+ exception.getMessage() +"\" }";
|
230
|
}
|
231
|
|
232
|
private String composeDataResponse(LDAPUser user) {
|
233
|
return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(user) + " }";
|
234
|
}
|
235
|
|
236
|
private String composeDataResponse(String fullname) {
|
237
|
return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(fullname) + " }";
|
238
|
}
|
239
|
}
|