Project

General

Profile

« Previous | Next » 

Revision 57921

MERGE login branch 56991:57920 using uoa-login-core

View differences:

Test3Service.java
14 14
import eu.dnetlib.openaire.user.dao.SQLMigrationUserDAO;
15 15
import eu.dnetlib.openaire.user.ldap.MUserActionsLDAP;
16 16
import eu.dnetlib.openaire.user.store.DataSourceConnector;
17
import eu.dnetlib.openaire.usermanagement.security.JWTGenerator;
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;
18 25
import org.apache.log4j.Logger;
19 26
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
20 27
import org.mitre.openid.connect.model.UserInfo;
......
22 29
import org.springframework.beans.factory.annotation.Value;
23 30
import org.springframework.http.*;
24 31
import org.springframework.http.HttpMethod;
32
import org.springframework.security.access.prepost.PreAuthorize;
33
import org.springframework.security.core.annotation.AuthenticationPrincipal;
25 34
import org.springframework.security.core.context.SecurityContextHolder;
35
import org.springframework.security.core.userdetails.UserDetails;
26 36
import org.springframework.stereotype.Component;
27 37
import org.springframework.web.client.DefaultResponseErrorHandler;
28 38
import org.springframework.web.client.RestTemplate;
39
import sun.net.www.http.HttpClient;
29 40

  
30 41
import javax.ws.rs.*;
31 42
import javax.ws.rs.core.MediaType;
32 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;
33 48
import java.sql.SQLException;
49
import java.util.ArrayList;
50
import java.util.List;
34 51

  
35 52
/**
36 53
 * Created by sofia on 24/11/2016.
......
53 70
    @Value("${oidc.issuer}")
54 71
    private String issuer;
55 72

  
56
    @GET
57
    @Path("/{userId}")
58
    @Produces(MediaType.APPLICATION_JSON)
59
    public Response getUserById(@PathParam("userId") int userId) {
60
        try {
61
            MigrationUser mUser = sqlMigrationUserDAO.fetchById(userId);
73
    @Value("${oidc.secret}")
74
    private String secret;
62 75

  
63
            // Invalide user ID
64
            if (mUser == null) {
65
                String errorMessageJson = compose404Message("Cannot find user with id " + userId + ".");
76
    @Value("${oidc.id}")
77
    private String id;
66 78

  
67
                return Response
68
                        .status(Response.Status.NOT_FOUND)
69
                        .entity(errorMessageJson)
70
                        .type(MediaType.APPLICATION_JSON)
71
                        .build();
72
            }
73

  
74
            return Response.status(200).entity(composeDataResponse(mUser)).build();
75
        }
76
        catch (SQLException e) {
77
            return Response
78
                    .status(Response.Status.INTERNAL_SERVER_ERROR)
79
                    .entity(compose500Message("Fail to fetch users.", e))
80
                    .type(MediaType.APPLICATION_JSON)
81
                    .build();
82
        }
83
    }
84

  
85
     /* How to check @browser ../authenticate/?username=MY_USERNAME&password=MY_PASSWORD
86
     * http://localhost:8080/uoa-user-management-1.0.0-SNAPSHOT/api/users/authenticate?username=sba&password=12345678
87 79
    @GET
88
    @Path("/authenticate")
80
    @Path("/getToken")
89 81
    @Produces(MediaType.APPLICATION_JSON)
90
    public Response authenticateUserGET(@QueryParam("username") String username, @QueryParam("password") String password)
91
    {
92
        return commonAuthenticateFunction(username, password);
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");
93 87

  
94
    }*/
95

  
96
    @POST
97
    @Path("/authenticates")
98
    @Produces(MediaType.APPLICATION_JSON)
99
    @Consumes(MediaType.APPLICATION_JSON)
100
    public Response authenticateUserPOST(String input) {
101
        JsonObject jsonObject = new JsonParser().parse(input).getAsJsonObject();
102

  
103
        String username = jsonObject.get("username").getAsString();
104
        String password = jsonObject.get("password").getAsString();
105

  
106
        return commonAuthenticateFunction(username, password);
107
    }
108

  
109
    private Response commonAuthenticateFunction(String username, String password)
110
    {
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"));
111 95
        try {
112
            boolean usernameExists = mUserActionsLDAP.usernameExists(username);
96
            httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
97
            //Execute and get the response.
98
            HttpResponse response = null;
113 99

  
114
            // if user was not found
115
            if (!usernameExists) {
116
                String errorMessageJson = compose401Message("Wrong credentials.");
100
            response = httpclient.execute(httppost);
117 101

  
118
                return Response
119
                        .status(Response.Status.UNAUTHORIZED)
120
                        .entity(errorMessageJson)
121
                        .type(MediaType.APPLICATION_JSON)
122
                        .build();
123
            }
102
            org.apache.http.HttpEntity entity = response.getEntity();
124 103

  
125
            boolean authenticated = mUserActionsLDAP.authenticate(username, password);
126

  
127
            // if user was not authenticated
128
            if (!authenticated) {
129
                return Response
130
                        .status(Response.Status.UNAUTHORIZED)
131
                        .entity(compose401Message("User " + username + " could not be authenticated."))
132
                        .type(MediaType.APPLICATION_JSON)
133
                        .build();
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
                }
134 109
            }
135 110

  
136
            MigrationUser mUser = sqlMigrationUserDAO.fetchByUsername(username);
111
        }  catch (UnsupportedEncodingException e) {
112
            logger.error(e);
137 113

  
138
            // if user was not found in my db
139
            LDAPUser ldapUser = null;
140
            if (mUser == null) {
141
                mUser = new MigrationUser(username);
142
                ldapUser = mUserActionsLDAP.getUser(username);
143
                mUser.setFullname(ldapUser.getDisplayName());
144
                mUser.setEmail(ldapUser.getEmail());
145
                mUser.setRoleId(2);
146

  
147

  
148
                sqlMigrationUserDAO.insert(mUser);
149
            }
150
            return Response.status(200).entity(composeDataResponse(mUser)).type(MediaType.APPLICATION_JSON).build();
151

  
152
        } catch (LDAPException exc) {
153
            logger.error("Fail to connect to LDAP. ", exc);
154
            return Response
155
                    .status(Response.Status.INTERNAL_SERVER_ERROR)
156
                    .entity(compose500Message("LDAP error.", exc))
157
                    .type(MediaType.APPLICATION_JSON)
158
                    .build();
159

  
160
        } catch (SQLException exc) {
161
            logger.error("Fail to fetch users. ", exc);
162
            return Response
163
                    .status(Response.Status.INTERNAL_SERVER_ERROR)
164
                    .entity(compose500Message("Fail to fetch users.", exc))
165
                    .type(MediaType.APPLICATION_JSON)
166
                    .build();
114
        } catch (IOException e) {
115
            logger.error(e);
167 116
        }
168 117

  
169
    }
118
        logger.info("DDDDDDDD");
170 119

  
171
    @GET
172
    @Path("/changeRole")
173
    @Produces(MediaType.APPLICATION_JSON)
174
    public Response changeRole(@QueryParam("roleId") int roleId, @QueryParam("userId") int userId)
175
    {
176
        RoleDAO roleDAO = new RoleDAO();
177
        try
178
        {
179
            Role role = roleDAO.fetchById(roleId);
180
            if (role == null)
181
            {
182
                //fetch all roleids TODO
183
                String errorMessageJson = compose404Message("Cannot find role with id" + roleId + ".");
184

  
185
                return Response
186
                        .status(Response.Status.NOT_FOUND)
187
                        .entity(errorMessageJson)
188
                        .type(MediaType.APPLICATION_JSON)
189
                        .build();
190
            }
191

  
192
            MigrationUser mUser = sqlMigrationUserDAO.fetchById(userId);
193

  
194
            if (mUser == null)
195
            {
196
                String errorMessageJson = compose404Message("Cannot find user with id " + userId + ".");
197

  
198
                return Response
199
                        .status(Response.Status.NOT_FOUND)
200
                        .entity(errorMessageJson)
201
                        .type(MediaType.APPLICATION_JSON)
202
                        .build();
203
            }
204

  
205
            mUser.setRoleId(roleId);
206
            sqlMigrationUserDAO.update(mUser);
207

  
208
            return Response.status(200).entity(composeDataResponse(mUser)).build();
209
        }
210
        catch (SQLException exc)
211
        {
212
            return Response
213
                    .status(Response.Status.INTERNAL_SERVER_ERROR)
214
                    .entity(compose500Message("Fail to fetch users.", exc))
215
                    .type(MediaType.APPLICATION_JSON)
216
                    .build();
217
        }
120
        return Response.status(200).type(MediaType.APPLICATION_JSON).build();
218 121
    }
219 122

  
220 123
    @GET
221 124
    @Path("/getUserInfo")
222 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
223 127
    public Response getUserInfo(@QueryParam("accessToken") String accessToken) throws JsonProcessingException {
224 128
        //return Response.status(404).entity(compose404Message("This is a test message.")).type(MediaType.APPLICATION_JSON).build();
225 129
        // call aai with accessToken
......
236 140
        //logger.info(restTemplate.exchange(fooResourceUrl, HttpMethod.GET, request, Object.class));
237 141
        ResponseEntity response1 = restTemplate.exchange(fooResourceUrl, HttpMethod.GET, request, Object.class);
238 142
        logger.info(response1.getBody().toString());
143

  
239 144
        ObjectMapper mapper = new ObjectMapper();
240 145

  
241 146
        return Response.status(response1.getStatusCode().value()).entity(mapper.writeValueAsString(response1.getBody())).type(MediaType.APPLICATION_JSON).build();
......
278 183
        }
279 184
        return Response.status(200).entity(userInfoJson.toString()).type(MediaType.APPLICATION_JSON).build();
280 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

  
281 223
    /* JSON Utility Methods */
282

  
283 224
    private String compose401Message(String message) {
284 225
        return  "{ \"status\" : \"error\", \"code\" : \"401\", \"message\" : \"  " + message +" \" }";
285 226
    }
......
293 234
                "\"description\" : \""+  exception.getMessage() +"\" }";
294 235
    }
295 236

  
296
    private String composeDataResponse(UserInfo user) {
297
        return "{ \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : \"" + JWTGenerator.generateToken(user, "my-very-secret") + "\" }";
298
    }
299

  
300
    private String composeDataResponse(MigrationUser user) {
301
        //return "{ \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(user) + " }";
302
        return "{ \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : \"" + JWTGenerator.generateToken(user, "my-very-secret") + "\" }";
303
    }
304

  
305 237
    private String composeDataResponse(LDAPUser user) {
306 238
        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(user) + " }";
307 239
    }
308 240

  
309
//        private String composeDataResponse(String username) {
310
//            return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(username) + " }";
311
//        }
312

  
313 241
    private String composeDataResponse(String fullname) {
314 242
        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(fullname) + " }";
315 243
    }

Also available in: Unified diff