Project

General

Profile

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.log4j.Logger;
18
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
19
import org.mitre.openid.connect.model.UserInfo;
20
import org.springframework.beans.factory.annotation.Autowired;
21
import org.springframework.beans.factory.annotation.Value;
22
import org.springframework.http.*;
23
import org.springframework.http.HttpMethod;
24
import org.springframework.security.core.context.SecurityContextHolder;
25
import org.springframework.stereotype.Component;
26
import org.springframework.web.client.DefaultResponseErrorHandler;
27
import org.springframework.web.client.RestTemplate;
28

    
29
import javax.ws.rs.*;
30
import javax.ws.rs.core.MediaType;
31
import javax.ws.rs.core.Response;
32
import java.sql.SQLException;
33

    
34
/**
35
 * Created by sofia on 24/11/2016.
36
 */
37
@Component(value = "test3service")
38
@Path("/users")
39
public class Test3Service {
40

    
41
    private static final Logger logger = Logger.getLogger(Test3Service.class);
42

    
43
    @Autowired
44
    private SQLMigrationUserDAO sqlMigrationUserDAO;
45

    
46
    @Autowired
47
    private MUserActionsLDAP mUserActionsLDAP;
48

    
49
    @Autowired
50
    private DataSourceConnector dataSourceConnector;
51

    
52
    @Value("${oidc.issuer}")
53
    private String issuer;
54

    
55
    @GET
56
    @Path("/getUserInfo")
57
    @Produces(MediaType.APPLICATION_JSON)
58
    public Response getUserInfo(@QueryParam("accessToken") String accessToken) throws JsonProcessingException {
59
        //return Response.status(404).entity(compose404Message("This is a test message.")).type(MediaType.APPLICATION_JSON).build();
60
        // call aai with accessToken
61
        RestTemplate restTemplate = new RestTemplate();
62
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
63
            protected boolean hasError(HttpStatus statusCode) {
64
                return false;
65
            }});
66
        HttpHeaders headers = new HttpHeaders();
67
        headers.add("Authorization","Bearer " + accessToken);
68
        HttpEntity request = new HttpEntity(null, headers);
69
        String fooResourceUrl = issuer +"userinfo";
70

    
71
        //logger.info(restTemplate.exchange(fooResourceUrl, HttpMethod.GET, request, Object.class));
72
        ResponseEntity response1 = restTemplate.exchange(fooResourceUrl, HttpMethod.GET, request, Object.class);
73
        logger.info(response1.getBody().toString());
74
        ObjectMapper mapper = new ObjectMapper();
75

    
76
        return Response.status(response1.getStatusCode().value()).entity(mapper.writeValueAsString(response1.getBody())).type(MediaType.APPLICATION_JSON).build();
77

    
78
    }
79

    
80
    @GET
81
    @Path("/getUser")
82
    @Produces(MediaType.APPLICATION_JSON)
83
    public Response getUser()  {
84
        JsonObject userInfoJson = new JsonObject();
85
        try {
86
            OIDCAuthenticationToken authentication = null;
87
            try {
88
                authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
89
            }catch (Exception e){
90
                logger.info("Try to get User info - no context found ");
91
                return Response.status(404).entity(compose404Message("Get User info: no context found ")).type(MediaType.APPLICATION_JSON).build();
92
            }
93
            UserInfo userInfo = authentication.getUserInfo();
94
            if(userInfo == null){
95
                return Response.status(404).entity(compose404Message("Get User info: user info is null ")).type(MediaType.APPLICATION_JSON).build();
96
            }
97
            logger.info("Get User:\n name: " + authentication.getUserInfo().getGivenName() + " " + authentication.getUserInfo().getFamilyName());
98

    
99

    
100
            userInfoJson.addProperty("sub", userInfo.getSub());
101
            userInfoJson.addProperty("name", userInfo.getName());
102
            userInfoJson.addProperty("given_name", userInfo.getGivenName());
103
            userInfoJson.addProperty("family_name", userInfo.getFamilyName());
104
            userInfoJson.addProperty("email", userInfo.getEmail());
105

    
106
            JsonArray roles = new JsonArray();
107
            JsonObject source = authentication.getUserInfo().getSource();
108
            roles = source.getAsJsonArray("edu_person_entitlements");
109
            userInfoJson.add("edu_person_entitlements", roles);
110
        }catch (Exception e){
111
            logger.error("Get User info: An error occured ",e);
112
            return Response.status(500).entity(compose500Message("Get User info: An error occured ",e)).type(MediaType.APPLICATION_JSON).build();
113
        }
114
        return Response.status(200).entity(userInfoJson.toString()).type(MediaType.APPLICATION_JSON).build();
115
    }
116
    /* JSON Utility Methods */
117

    
118
    private String compose401Message(String message) {
119
        return  "{ \"status\" : \"error\", \"code\" : \"401\", \"message\" : \"  " + message +" \" }";
120
    }
121

    
122
    private String compose404Message(String message) {
123
        return  "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \"  " + message +" \" }";
124
    }
125

    
126
    private String compose500Message(String message, Exception exception) {
127
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
128
                "\"description\" : \""+  exception.getMessage() +"\" }";
129
    }
130

    
131
    private String composeDataResponse(LDAPUser user) {
132
        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(user) + " }";
133
    }
134

    
135
    private String composeDataResponse(String fullname) {
136
        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(fullname) + " }";
137
    }
138

    
139
    public String getIssuer() {
140
        return issuer;
141
    }
142

    
143
    public void setIssuer(String issuer) {
144
        this.issuer = issuer;
145
    }
146
}
    (1-1/1)