Project

General

Profile

1
package eu.dnetlib.openaire.usermanagement.api;
2

    
3
import com.google.gson.JsonArray;
4
import com.google.gson.JsonObject;
5
import com.google.gson.JsonParser;
6
import eu.dnetlib.openaire.user.pojos.ManagerVerification;
7
import eu.dnetlib.openaire.user.utils.EmailSender;
8
import eu.dnetlib.openaire.usermanagement.dto.Role;
9
import eu.dnetlib.openaire.usermanagement.utils.JsonUtils;
10
import eu.dnetlib.openaire.usermanagement.utils.RegistryCalls;
11
import eu.dnetlib.openaire.usermanagement.utils.VerificationUtils;
12
import org.apache.log4j.Logger;
13
import org.springframework.beans.factory.annotation.Autowired;
14
import org.springframework.http.HttpStatus;
15
import org.springframework.security.access.prepost.PreAuthorize;
16
import org.springframework.stereotype.Component;
17
import org.springframework.web.bind.annotation.RequestBody;
18

    
19
import javax.mail.MessagingException;
20
import javax.ws.rs.*;
21
import javax.ws.rs.core.MediaType;
22
import javax.ws.rs.core.Response;
23

    
24
@Component(value = "RegistryService")
25
@Path("/registry")
26
public class RegistryService {
27

    
28
    private static final Logger logger = Logger.getLogger(RegistryService.class);
29

    
30
    @Autowired
31
    private RegistryCalls calls;
32

    
33
    @Autowired
34
    private JsonUtils jsonUtils;
35

    
36
    @Autowired
37
    private EmailSender emailSender;
38

    
39
    @Autowired
40
    private VerificationUtils verificationUtils;
41

    
42

    
43
    /**
44
     * Subscribe to a type(Community, etc.) with id(ee, egi, etc.)
45
     */
46
    @Path("/subscribe/{type}/{id}")
47
    @POST
48
    @Produces(MediaType.APPLICATION_JSON)
49
    @PreAuthorize("isAuthenticated()")
50
    public Response subscribe(@PathParam("type") String type, @PathParam("id") String id) {
51
        Integer coPersonId = calls.getCoPersonIdByIdentifier();
52
        Integer couId = calls.getCouId(type, id);
53
        if (couId != null) {
54
            Integer role = calls.getRoleId(coPersonId, couId);
55
            calls.assignMemberRole(coPersonId, couId, role);
56
            return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build();
57
        } else {
58
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
59
        }
60
    }
61

    
62
    /**
63
     * Subscribe from type(Community, etc.) with id(ee, egi, etc.).
64
     * If user has manager role for this entity, it will be removed too.
65
     */
66
    @Path("/unsubscribe/{type}/{id}")
67
    @POST
68
    @Produces(MediaType.APPLICATION_JSON)
69
    @PreAuthorize("isAuthenticated()")
70
    public Response unsubscribe(@PathParam("type") String type, @PathParam("id") String id) {
71
        Integer coPersonId = calls.getCoPersonIdByIdentifier();
72
        Integer couId = calls.getCouId(type, id);
73
        if (couId != null) {
74
            Integer role = calls.getRoleId(coPersonId, couId);
75
            if (role != null) {
76
                calls.removeAdminRole(coPersonId, couId);
77
                calls.removeMemberRole(coPersonId, couId, role);
78
                return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Role has been removed").toString()).type(MediaType.APPLICATION_JSON).build();
79
            } else
80
                return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("User does not have this role").toString()).type(MediaType.APPLICATION_JSON).build();
81
        } else {
82
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
83
        }
84
    }
85

    
86
    /**
87
     * Create a new role with the given name and description.
88
     **/
89
    @Path("/createRole")
90
    @POST
91
    @Produces(MediaType.APPLICATION_JSON)
92
    @Consumes(MediaType.APPLICATION_JSON)
93
    @PreAuthorize("hasAnyAuthority(@AuthoritiesService.SUPER_ADMIN, @AuthoritiesService.USER_ADMIN)")
94
    public Response createRole(@RequestBody Role role) {
95
        calls.createRole(role);
96
        return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Role has been created").toString()).type(MediaType.APPLICATION_JSON).build();
97
    }
98

    
99
    /**
100
     * Invite user with email to manage a type(Community, etc.) with id(ee, egi, etc.)
101
     * Auto generated link and code will be sent as response.
102
     */
103
    @Path("/invite/{type}/{id}/manager/{email}")
104
    @POST
105
    @Produces(MediaType.APPLICATION_JSON)
106
    @PreAuthorize("hasAnyAuthority(@AuthoritiesService.SUPER_ADMIN, @AuthoritiesService.USER_ADMIN, @AuthoritiesService.PORTAL_ADMIN, " +
107
            "@AuthoritiesService.curator(#type), @AuthoritiesService.manager(#type, #id))")
108
    public Response inviteUser(@PathParam("type") String type, @PathParam("id") String id, @PathParam("email") String email, @RequestBody String body) {
109
        Integer couId = calls.getCouId(type, id);
110
        if (couId != null) {
111
            Integer coPersonId = calls.getCoPersonIdByEmail(email);
112
            if (calls.getUserAdminGroup(coPersonId, couId) == null) {
113
                JsonObject invitation = verificationUtils.createInvitation(email, type, id);
114
                String name = calls.getUserNames(coPersonId);
115
                JsonObject details = new JsonParser().parse(body).getAsJsonObject();
116
                String link = details.get("link").getAsString() + "/" + invitation.get("link").getAsString();
117
                String subject = "Invite to manage " + details.get("name").getAsString();
118
                String message = "<p>Hello " + name + ",</p>" +
119
                        "<p> You have been invited to manage " + details.get("name").getAsString() + ". " +
120
                        "Use the verification code below to accept the invitation." +
121
                        "</p>" +
122
                        "<p>" +
123
                        "The verification code is " + invitation.get("code").getAsString() +
124
                        "</p>" +
125
                        "Click the URL below and proceed with the process." +
126
                        "<p><a href=" + link + ">" + link + "</a></p>" +
127
                        "<p>Thank you,</p>" +
128
                        "<p>OpenAIRE technical team</p>";
129
                try {
130
                    emailSender.sendEmail(email, subject, message);
131
                    return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(invitation).toString()).type(MediaType.APPLICATION_JSON).build();
132
                } catch (MessagingException e) {
133
                    logger.error(e.getMessage());
134
                    verificationUtils.deleteVerification(invitation.get("link").getAsString());
135
                    return Response.status(HttpStatus.BAD_REQUEST.value()).entity(jsonUtils.createResponse("Email sent failed").toString()).type(MediaType.APPLICATION_JSON).build();
136
                }
137
            } else {
138
                return Response.status(HttpStatus.CONFLICT.value()).entity(jsonUtils.createResponse("User has been already manager of this " + type).toString()).type(MediaType.APPLICATION_JSON).build();
139
            }
140
        } else {
141
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
142
        }
143
    }
144

    
145
    /**
146
     * Cancel invitation to user with email for managing a type(Community, etc.) with id(ee, egi, etc.)
147
     */
148
    @Path("/invite/{type}/{id}/manager/{email}")
149
    @DELETE
150
    @Produces(MediaType.APPLICATION_JSON)
151
    @PreAuthorize("hasAnyAuthority(@AuthoritiesService.SUPER_ADMIN, @AuthoritiesService.USER_ADMIN, @AuthoritiesService.PORTAL_ADMIN, " +
152
            "@AuthoritiesService.curator(#type), @AuthoritiesService.manager(#type, #id))")
153
    public Response cancelUserInvitations(@PathParam("type") String type, @PathParam("id") String id, @PathParam("email") String email) {
154
        Integer couId = calls.getCouId(type, id);
155
        if (couId != null) {
156
            verificationUtils.deleteUserVerifications(email, type, id);
157
            return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Invitations have been deleted").toString()).type(MediaType.APPLICATION_JSON).build();
158
        } else {
159
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
160
        }
161
    }
162

    
163
    /**
164
     * Get the invited managers for a type(Community, etc.) with id(ee, egi, etc.)
165
     */
166
    @Path("/invite/{type}/{id}/managers/")
167
    @GET
168
    @Produces(MediaType.APPLICATION_JSON)
169
    @PreAuthorize("hasAnyAuthority(@AuthoritiesService.SUPER_ADMIN, @AuthoritiesService.USER_ADMIN, @AuthoritiesService.PORTAL_ADMIN, " +
170
            "@AuthoritiesService.curator(#type), @AuthoritiesService.manager(#type, #id))")
171
    public Response getInvitedManagers(@PathParam("type") String type, @PathParam("id") String id) {
172
        JsonArray invited = verificationUtils.getInvitedUsers(type, id);
173
        return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(invited).toString()).type(MediaType.APPLICATION_JSON).build();
174
    }
175

    
176
    /**
177
     * Get the verification with a specific id only if it refers to the logged in user
178
     */
179
    @Path("verification/{id}")
180
    @GET
181
    @Produces(MediaType.APPLICATION_JSON)
182
    @PreAuthorize("isAuthenticated()")
183
    public Response getVerification(@PathParam("id") String id) {
184
        ManagerVerification managerVerification = verificationUtils.getVerification(id);
185
        if (managerVerification != null) {
186
            if (calls.getCoPersonIdByEmail(managerVerification.getEmail()).equals(calls.getCoPersonIdByIdentifier())) {
187
                return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(jsonUtils.createVerification(managerVerification)).toString()).type(MediaType.APPLICATION_JSON).build();
188
            } else {
189
                return Response.status(HttpStatus.FORBIDDEN.value()).entity(jsonUtils.createResponse("Forbidden verification").toString()).type(MediaType.APPLICATION_JSON).build();
190
            }
191
        } else {
192
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Verification has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
193
        }
194
    }
195

    
196
    /**
197
     * Delete the verification with a specific id.
198
     */
199
    @Path("verification/{id}")
200
    @DELETE
201
    @Produces(MediaType.APPLICATION_JSON)
202
    @PreAuthorize("isAuthenticated() && @VerificationUtils.ownedVerification(#id)")
203
    public Response deleteVerification(@PathParam("id") String id) {
204
        if (verificationUtils.getVerification(id) != null) {
205
            verificationUtils.deleteVerification(id);
206
            return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(jsonUtils.createResponse("Verification deleted")).toString()).type(MediaType.APPLICATION_JSON).build();
207
        } else {
208
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse(jsonUtils.createResponse("Verification has not been found")).toString()).type(MediaType.APPLICATION_JSON).build();
209
        }
210
    }
211

    
212
    /**
213
     * Verify the verification with the specific id, if the code is correct and it refers to the logged in user.
214
     * Manager role is assigned to this user, along with the member role.
215
     */
216
    @Path("verification/{id}")
217
    @POST
218
    @Produces(MediaType.APPLICATION_JSON)
219
    @PreAuthorize("isAuthenticated()")
220
    public Response verify(@PathParam("id") String id, @RequestBody String code) {
221
        ManagerVerification managerVerification = verificationUtils.getVerification(id);
222
        if (managerVerification != null) {
223
            Integer coPersonId = calls.getCoPersonIdByEmail(managerVerification.getEmail());
224
            if (coPersonId != null) {
225
                if (coPersonId.equals(calls.getCoPersonIdByIdentifier())) {
226
                    if (managerVerification.getVerificationCode().equals(code)) {
227
                        verificationUtils.deleteRelatedVerifications(managerVerification);
228
                        Integer couId = calls.getCouId(managerVerification.getType(), managerVerification.getEntity());
229
                        if (couId != null) {
230
                            Integer role = calls.getRoleId(coPersonId, couId);
231
                            calls.assignMemberRole(coPersonId, couId, role);
232
                            if (calls.getUserAdminGroup(coPersonId, couId) == null) {
233
                                calls.assignAdminRole(coPersonId, couId);
234
                                return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Admin role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build();
235
                            } else {
236
                                return Response.status(HttpStatus.CONFLICT.value()).entity(jsonUtils.createResponse("User is already admin of this cou").toString()).type(MediaType.APPLICATION_JSON).build();
237
                            }
238
                        } else {
239
                            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
240
                        }
241
                    } else {
242
                        return Response.status(HttpStatus.FORBIDDEN.value()).entity(jsonUtils.createResponse("Verification code is wrong").toString()).type(MediaType.APPLICATION_JSON).build();
243
                    }
244
                } else {
245
                    return Response.status(HttpStatus.FORBIDDEN.value()).entity(jsonUtils.createResponse("Forbidden verification").toString()).type(MediaType.APPLICATION_JSON).build();
246
                }
247
            } else {
248
                return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("User has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
249
            }
250
        } else {
251
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Verification has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
252
        }
253
    }
254

    
255
    /**
256
     * Remove the manager role from user with email for a type(Community, etc.) with id(ee, egi, etc.)
257
     */
258
    @Path("/{type}/{id}/manager/{email}")
259
    @DELETE
260
    @Produces(MediaType.APPLICATION_JSON)
261
    @Consumes(MediaType.APPLICATION_JSON)
262
    @PreAuthorize("hasAnyAuthority(@AuthoritiesService.SUPER_ADMIN, @AuthoritiesService.USER_ADMIN," +
263
            "@AuthoritiesService.PORTAL_ADMIN, @AuthoritiesService.curator(#type), @AuthoritiesService.manager(#type, #id))")
264
    public Response removeManagerRole(@PathParam("type") String type, @PathParam("id") String
265
            id, @PathParam("email") String email) {
266
        Integer coPersonId = calls.getCoPersonIdByEmail(email);
267
        if (coPersonId != null) {
268
            Integer couId = calls.getCouId(type, id);
269
            if (couId != null) {
270
                calls.removeAdminRole(coPersonId, couId);
271
                return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Role has been removed").toString()).type(MediaType.APPLICATION_JSON).build();
272
            } else {
273
                return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
274
            }
275
        } else {
276
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("User has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
277
        }
278
    }
279

    
280
    /**
281
     * Get the names of the subscribers of a type(Community, etc.) with id(ee, egi, etc.)
282
     */
283
    @Path("/{type}/{id}/subscribers")
284
    @GET
285
    @Produces(MediaType.APPLICATION_JSON)
286
    @PreAuthorize("hasAnyAuthority(@AuthoritiesService.SUPER_ADMIN, @AuthoritiesService.PORTAL_ADMIN," +
287
            "@AuthoritiesService.curator(#type), @AuthoritiesService.manager(#type, #id))")
288
    public Response getSubscribers(@PathParam("type") String type, @PathParam("id") String id) {
289
        Integer couId = calls.getCouId(type, id);
290
        JsonArray subscribers = calls.getUserNamesByCouId(couId, false);
291
        return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(subscribers).toString()).type(MediaType.APPLICATION_JSON).build();
292
    }
293

    
294
    /**
295
     * Get the emails of the subscribers of a type(Community, etc.) with id(ee, egi, etc.)
296
     */
297
    @Path("/{type}/{id}/subscribers/email")
298
    @GET
299
    @Produces(MediaType.APPLICATION_JSON)
300
    @PreAuthorize("hasAnyAuthority(@AuthoritiesService.SUPER_ADMIN, @AuthoritiesService.PORTAL_ADMIN," +
301
            "@AuthoritiesService.curator(#type), @AuthoritiesService.manager(#type, #id))")
302
    public Response getSubscribersEmail(@PathParam("type") String type, @PathParam("id") String id) {
303
        Integer couId = calls.getCouId(type, id);
304
        JsonArray subscribers = calls.getUserEmailByCouId(couId, false);
305
        return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(subscribers).toString()).type(MediaType.APPLICATION_JSON).build();
306
    }
307

    
308
    /**
309
     * Get the number of the subscribers of a type(Community, etc.) with id(ee, egi, etc.)
310
     */
311
    @Path("/{type}/{id}/subscribers/count")
312
    @GET
313
    @Produces(MediaType.APPLICATION_JSON)
314
    public Response getSubscribersCount(@PathParam("type") String type, @PathParam("id") String id) {
315
        Integer couId = calls.getCouId(type, id);
316
        int count = calls.getUserNamesByCouId(couId, false).size();
317
        return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(count).toString()).type(MediaType.APPLICATION_JSON).build();
318
    }
319

    
320
    /**
321
     * Get the names of the managers of a type(Community, etc.) with id(ee, egi, etc.)
322
     */
323
    @Path("/{type}/{id}/managers")
324
    @GET
325
    @Produces(MediaType.APPLICATION_JSON)
326
    public Response getManagers(@PathParam("type") String type, @PathParam("id") String id) {
327
        Integer couId = calls.getCouId(type, id);
328
        JsonArray managers = calls.getUserNamesByCouId(couId, true);
329
        return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(managers).toString()).type(MediaType.APPLICATION_JSON).build();
330
    }
331

    
332
    /**
333
     * Get the emails of the managers of a type(Community, etc.) with id(ee, egi, etc.)
334
     */
335
    @Path("/{type}/{id}/managers/email")
336
    @GET
337
    @Produces(MediaType.APPLICATION_JSON)
338
    public Response getManagersEmail(@PathParam("type") String type, @PathParam("id") String id) {
339
        Integer couId = calls.getCouId(type, id);
340
        JsonArray managers = calls.getUserEmailByCouId(couId, true);
341
        return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(managers).toString()).type(MediaType.APPLICATION_JSON).build();
342
    }
343
}
(1-1/2)