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