Project

General

Profile

« Previous | Next » 

Revision 61857

Update production with role-management integration

View differences:

modules/dnet-openaire-users/branches/prod/src/main/java/eu/dnetlib/openaire/usermanagement/dto/User.java
1
package eu.dnetlib.openaire.usermanagement.dto;
2

  
3
import com.fasterxml.jackson.annotation.JsonIgnore;
4

  
5
public class User {
6

  
7
    @JsonIgnore
8
    private String coPersonId;
9
    private String id;
10
    private String email;
11
    private String name;
12
    private String memberSince;
13

  
14
    public User() {
15
    }
16

  
17
    @JsonIgnore
18
    public String getCoPersonId() {
19
        return coPersonId;
20
    }
21

  
22
    public void setCoPersonId(String coPersonId) {
23
        this.coPersonId = coPersonId;
24
    }
25

  
26
    public String getId() {
27
        return id;
28
    }
29

  
30
    public void setId(String id) {
31
        this.id = id;
32
    }
33

  
34
    public String getEmail() {
35
        return email;
36
    }
37

  
38
    public void setEmail(String email) {
39
        this.email = email;
40
    }
41

  
42
    public String getName() {
43
        return name;
44
    }
45

  
46
    public void setName(String name) {
47
        this.name = name;
48
    }
49

  
50
    public String getMemberSince() {
51
        return memberSince;
52
    }
53

  
54
    public void setMemberSince(String memberSince) {
55
        this.memberSince = memberSince;
56
    }
57
}
modules/dnet-openaire-users/branches/prod/src/main/java/eu/dnetlib/openaire/usermanagement/utils/RegistryCalls.java
1
package eu.dnetlib.openaire.usermanagement.utils;
2

  
3
import com.google.gson.JsonArray;
4
import com.google.gson.JsonElement;
5
import com.google.gson.JsonObject;
6
import eu.dnetlib.openaire.usermanagement.dto.Role;
7
import org.apache.log4j.Logger;
8
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
9
import org.springframework.beans.factory.annotation.Autowired;
10
import org.springframework.beans.factory.annotation.Value;
11
import org.springframework.security.access.method.P;
12
import org.springframework.security.core.context.SecurityContextHolder;
13
import org.springframework.stereotype.Service;
14

  
15
import java.util.ArrayList;
16
import java.util.HashMap;
17
import java.util.List;
18
import java.util.Map;
19

  
20
@Service
21
public class RegistryCalls {
22

  
23
    private static final Logger logger = Logger.getLogger(RegistryCalls.class);
24

  
25
    @Value("${registry.coid}")
26
    private String coid;
27

  
28
    @Autowired
29
    public HttpUtils httpUtils;
30

  
31
    @Autowired
32
    public JsonUtils jsonUtils;
33

  
34

  
35
    public String mapType(String type, boolean communityMap) {
36
        if (type.equals("organization")) {
37
            type = "institution";
38
        } else if (type.equals("ri") && communityMap) {
39
            type = "community";
40
        }
41
        return type;
42
    }
43

  
44
    /**
45
     * 1. Get CoPersonId by Email
46
     */
47
    public Integer getCoPersonIdByEmail() {
48
        try {
49
            OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
50
            String email = authentication.getUserInfo().getEmail();
51
            Map<String, String> params = new HashMap<>();
52
            params.put("coid", coid);
53
            params.put("mail", email);
54
            JsonElement response = httpUtils.get("co_people.json", params);
55
            return (response != null) ? response.getAsJsonObject().get("CoPeople").getAsJsonArray().get(0).getAsJsonObject().get("Id").getAsInt() : null;
56
        } catch (Exception e) {
57
            logger.error("Get User info: An error occurred ", e);
58
            return null;
59
        }
60
    }
61

  
62
    public Integer getCoPersonIdByEmail(String email) {
63
        Map<String, String> params = new HashMap<>();
64
        params.put("coid", coid);
65
        params.put("mail", email);
66
        JsonElement response = httpUtils.get("co_people.json", params);
67
        if (response != null) {
68
            JsonArray coPeople = response.getAsJsonObject().get("CoPeople").getAsJsonArray();
69
            if (coPeople.size() > 0) {
70
                return coPeople.get(0).getAsJsonObject().get("Id").getAsInt();
71
            }
72
        }
73
        return null;
74
    }
75

  
76
    public List<Integer> getCoPersonIdsByEmail(String email) {
77
        List<Integer> coPersonIds = new ArrayList<>();
78
        Map<String, String> params = new HashMap<>();
79
        params.put("coid", coid);
80
        params.put("mail", email);
81
        JsonElement response = httpUtils.get("co_people.json", params);
82
        if (response != null) {
83
            JsonArray coPeople = response.getAsJsonObject().get("CoPeople").getAsJsonArray();
84
            for (int i = 0; i < coPeople.size(); i++) {
85
                coPersonIds.add(coPeople.get(i).getAsJsonObject().get("Id").getAsInt());
86
            }
87
        }
88
        return coPersonIds;
89
    }
90

  
91
    /**
92
     * 2. Get CoPersonId by AAI identifier
93
     */
94
    public Integer getCoPersonIdByIdentifier() {
95
        try {
96
            OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
97
            String sub = authentication.getUserInfo().getSub();
98
            Map<String, String> params = new HashMap<>();
99
            params.put("coid", coid);
100
            params.put("search.identifier", sub);
101
            JsonElement response = httpUtils.get("co_people.json", params);
102
            return (response != null) ? response.getAsJsonObject().get("CoPeople").getAsJsonArray().get(0).getAsJsonObject().get("Id").getAsInt() : null;
103
        } catch (Exception e) {
104
            logger.error("Get User info: An error occurred ", e);
105
            return null;
106
        }
107
    }
108

  
109
    public Integer getCoPersonIdByIdentifier(String sub) {
110
        Map<String, String> params = new HashMap<>();
111
        params.put("coid", coid);
112
        params.put("search.identifier", sub);
113
        JsonElement response = httpUtils.get("co_people.json", params);
114
        return (response != null) ? response.getAsJsonObject().get("CoPeople").getAsJsonArray().get(0).getAsJsonObject().get("Id").getAsInt() : null;
115
    }
116

  
117
    /**
118
     * 3.1 Get OpenAIRE cous with a specific name(or substring)
119
     */
120
    public JsonArray getCous(String name) {
121
        Map<String, String> params = new HashMap<>();
122
        params.put("coid", coid);
123
        if (name != null) {
124
            params.put("name", name.toLowerCase());
125
        }
126
        JsonElement response = httpUtils.get("cous.json", params);
127
        return (response != null) ? response.getAsJsonObject().get("Cous").getAsJsonArray() : new JsonArray();
128
    }
129

  
130
    /**
131
     * 3.2 Get all OpenAIRE cous
132
     */
133
    public JsonArray getCous() {
134
        return getCous(null);
135
    }
136

  
137
    /**
138
     * 4.1 Get a couId by name
139
     *
140
     * @param name
141
     * @return
142
     */
143
    public Integer getCouId(String name) {
144
        JsonArray cous = getCous(name);
145
        for (JsonElement cou : cous) {
146
            if (cou.getAsJsonObject().get("Name").getAsString().toLowerCase().equals(name.toLowerCase())) {
147
                return cou.getAsJsonObject().get("Id").getAsInt();
148
            }
149
        }
150
        return null;
151
    }
152

  
153
    /**
154
     * 4.2 Get a couId by type.id with/without mapping type
155
     *
156
     * @param type
157
     * @param id
158
     * @return
159
     */
160
    public Integer getCouId(String type, String id, boolean communityMap) {
161
        return getCouId(mapType(type, communityMap) + "." + id);
162
    }
163

  
164
    /**
165
     * 4.3 Get a couId by type.id with mapping type
166
     *
167
     * @param type
168
     * @param id
169
     * @return
170
     */
171
    public Integer getCouId(String type, String id) {
172
        return getCouId(type, id, true);
173
    }
174

  
175
    /**
176
     * 5. Get User non admin roles
177
     */
178
    public JsonArray getRoles(Integer coPersonId) {
179
        Map<String, String> params = new HashMap<>();
180
        params.put("copersonid", coPersonId.toString());
181
        JsonElement response = httpUtils.get("co_person_roles.json", params);
182
        return (response != null) ? response.getAsJsonObject().get("CoPersonRoles").getAsJsonArray() : new JsonArray();
183
    }
184

  
185
    /**
186
     * 6. Get Role id of User base on couId.
187
     */
188
    public Integer getRoleId(Integer coPersonId, Integer couId) {
189
        JsonArray roles = getRoles(coPersonId);
190
        for (JsonElement role : roles) {
191
            JsonObject object = role.getAsJsonObject();
192
            if (object.get("CouId").getAsInt() == couId && !object.get("Status").getAsString().equals("Deleted")) {
193
                return object.get("Id").getAsInt();
194
            }
195
        }
196
        return null;
197
    }
198

  
199
    /**
200
     * 7. Get User Groups
201
     */
202
    public JsonArray getUserGroups(Integer coPersonId) {
203
        Map<String, String> params = new HashMap<>();
204
        params.put("copersonid", coPersonId.toString());
205
        JsonElement response = httpUtils.get("co_groups.json", params);
206
        return (response != null) ? response.getAsJsonObject().get("CoGroups").getAsJsonArray() : new JsonArray();
207
    }
208

  
209
    /**
210
     * 8. Get User Admin Group of a Cou
211
     */
212
    public JsonObject getUserAdminGroup(Integer coPersonId, Integer couId) {
213
        Map<String, String> params = new HashMap<>();
214
        params.put("copersonid", coPersonId.toString());
215
        JsonElement response = httpUtils.get("co_groups.json", params);
216
        JsonArray roles = (response != null) ? response.getAsJsonObject().get("CoGroups").getAsJsonArray() : new JsonArray();
217
        for (JsonElement role : roles) {
218
            JsonObject object = role.getAsJsonObject();
219
            if (object.get("CouId") != null && object.get("CouId").getAsInt() == couId) {
220
                if (object.get("Name").getAsString().contains("admins")) {
221
                    return object;
222
                }
223
            }
224
        }
225
        return null;
226
    }
227

  
228
    /**
229
     * 9. Get Groups of a Cou
230
     */
231
    public JsonArray getCouGroups(Integer couId) {
232
        Map<String, String> params = new HashMap<>();
233
        params.put("coid", coid);
234
        params.put("couid", couId.toString());
235
        JsonElement response = httpUtils.get("co_groups.json", params);
236
        return (response != null) ? response.getAsJsonObject().get("CoGroups").getAsJsonArray() : new JsonArray();
237
    }
238

  
239
    /**
240
     * 10. Get Admin Group of a Cou
241
     */
242
    public JsonObject getCouAdminGroup(Integer couId) {
243
        JsonArray groups = getCouGroups(couId);
244
        for (JsonElement group : groups) {
245
            if (group.getAsJsonObject().get("Name").getAsString().contains("admins")) {
246
                return group.getAsJsonObject();
247
            }
248
        }
249
        return null;
250
    }
251

  
252
    /**
253
     * 11. Get users of a group
254
     */
255
    public JsonArray getGroupMembers(Integer coGroupId) {
256
        Map<String, String> params = new HashMap<>();
257
        params.put("cogroupid", coGroupId.toString());
258
        JsonElement response = httpUtils.get("co_group_members.json", params);
259
        return (response != null) ? response.getAsJsonObject().get("CoGroupMembers").getAsJsonArray() : new JsonArray();
260
    }
261

  
262

  
263
    /**
264
     * 12. Get Users' email of a Cou
265
     */
266
    public JsonArray getUserEmailByCouId(Integer couId, boolean admin) {
267
        Map<String, String> params = new HashMap<>();
268
        params.put("couid", couId.toString());
269
        if (admin) {
270
            params.put("admin", "true");
271
        }
272
        JsonElement response = httpUtils.get("email_addresses.json", params);
273
        JsonArray infos = (response != null) ? response.getAsJsonObject().get("EmailAddresses").getAsJsonArray() : new JsonArray();
274
        JsonArray emails = new JsonArray();
275
        infos.forEach(info -> {
276
            JsonObject user = new JsonObject();
277
            user.addProperty("coPersonId", info.getAsJsonObject().get("Person").getAsJsonObject().get("Id").getAsString());
278
            user.addProperty("email", info.getAsJsonObject().get("Mail").getAsString());
279
            user.addProperty("memberSince", info.getAsJsonObject().get("Created").getAsString());
280
            emails.add(user);
281
        });
282
        return emails;
283
    }
284

  
285
    /**
286
     * 13. Get Users' names of a Cou
287
     */
288
    public JsonArray getUserNamesByCouId(Integer couId, boolean admin) {
289
        Map<String, String> params = new HashMap<>();
290
        params.put("couid", couId.toString());
291
        if (admin) {
292
            params.put("admin", "true");
293
        }
294
        JsonElement response = httpUtils.get("names.json", params);
295
        JsonArray infos = (response != null) ? response.getAsJsonObject().get("Names").getAsJsonArray() : new JsonArray();
296
        JsonArray names = new JsonArray();
297
        infos.forEach(info -> {
298
            JsonObject user = new JsonObject();
299
            user.addProperty("coPersonId", info.getAsJsonObject().get("Person").getAsJsonObject().get("Id").getAsString());
300
            user.addProperty("name", info.getAsJsonObject().get("Given").getAsString() + " " + info.getAsJsonObject().get("Family").getAsString());
301
            user.addProperty("memberSince", info.getAsJsonObject().get("Created").getAsString());
302
            names.add(user);
303
        });
304
        return names;
305
    }
306

  
307
    /**
308
     * 14. Get Users' identifiers of a Cou
309
     */
310
    public JsonArray getUserIdByCouId(Integer couId, boolean admin) {
311
        Map<String, String> params = new HashMap<>();
312
        params.put("couid", couId.toString());
313
        if (admin) {
314
            params.put("admin", "true");
315
        }
316
        JsonElement response = httpUtils.get("identifiers.json", params);
317
        JsonArray infos = (response != null) ? response.getAsJsonObject().get("Identifiers").getAsJsonArray() : new JsonArray();
318
        JsonArray ids = new JsonArray();
319
        infos.forEach(info -> {
320
            JsonObject user = new JsonObject();
321
            user.addProperty("coPersonId", info.getAsJsonObject().get("Person").getAsJsonObject().get("Id").getAsString());
322
            user.addProperty("id", info.getAsJsonObject().get("Identifier").getAsString());
323
            user.addProperty("memberSince", info.getAsJsonObject().get("Created").getAsString());
324
            ids.add(user);
325
        });
326
        return ids;
327
    }
328

  
329
    /**
330
     * 15. Assign a member role to a User
331
     */
332
    public void assignMemberRole(Integer coPersonId, Integer couId, Integer id) {
333
        if (id != null) {
334
            httpUtils.put("co_person_roles/" + id.toString() + ".json", jsonUtils.coPersonRoles(coPersonId, couId, "Active"));
335
        } else {
336
            httpUtils.post("co_person_roles.json", jsonUtils.coPersonRoles(coPersonId, couId, "Active"));
337
        }
338
    }
339

  
340
    /**
341
     * 16. Remove a member role from a User
342
     */
343
    public void removeMemberRole(Integer coPersonId, Integer couId, Integer id) {
344
        if (id != null) {
345
            httpUtils.put("co_person_roles/" + id.toString() + ".json", jsonUtils.coPersonRoles(coPersonId, couId, "Deleted"));
346
        }
347
    }
348

  
349
    /**
350
     * 17. Create a new role
351
     */
352
    public Integer createRole(Role role) {
353
        JsonElement element = httpUtils.post("cous.json", jsonUtils.createNewCou(role));
354
        return element.getAsJsonObject().get("Id").getAsInt();
355
    }
356

  
357
    /**
358
     * 18. Get User's email
359
     */
360
    public String getUserEmail(Integer coPersonId) {
361
        Map<String, String> params = new HashMap<>();
362
        params.put("copersonid", coPersonId.toString());
363
        JsonElement response = httpUtils.get("email_addresses.json", params);
364
        JsonObject info = (response != null) ? response.getAsJsonObject().get("EmailAddresses").getAsJsonArray().get(0).getAsJsonObject() : null;
365
        return (info != null) ? info.getAsJsonObject().get("Mail").getAsString() : null;
366
    }
367

  
368
    /**
369
     * 19. Get User's names
370
     */
371
    public String getUserNames(Integer coPersonId) {
372
        Map<String, String> params = new HashMap<>();
373
        params.put("copersonid", coPersonId.toString());
374
        JsonElement response = httpUtils.get("names.json", params);
375
        JsonObject info = (response != null) ? response.getAsJsonObject().get("Names").getAsJsonArray().get(0).getAsJsonObject() : null;
376
        return (info != null) ? info.getAsJsonObject().get("Given").getAsString() + " " + info.getAsJsonObject().get("Family").getAsString() : null;
377
    }
378

  
379
    /**
380
     * 20. Get User's identifier
381
     */
382
    public String getUserId(Integer coPersonId) {
383
        Map<String, String> params = new HashMap<>();
384
        params.put("copersonid", coPersonId.toString());
385
        JsonElement response = httpUtils.get("identifiers.json", params);
386
        JsonObject info = (response != null) ? response.getAsJsonObject().get("Identifiers").getAsJsonArray().get(0).getAsJsonObject() : null;
387
        return (info != null) ? info.getAsJsonObject().get("Identifier").getAsString() : null;
388
    }
389

  
390
    /**
391
     * 21. Assign an admin role to a User
392
     */
393
    public void assignAdminRole(Integer coPersonId, Integer couId) {
394
        JsonObject group = getCouAdminGroup(couId);
395
        if (group != null) {
396
            httpUtils.post("co_group_members.json", jsonUtils.coGroupMembers(group.get("Id").getAsInt(), coPersonId, true));
397
        }
398
    }
399

  
400
    /**
401
     * 22. Remove an admin role from a User
402
     */
403
    public void removeAdminRole(Integer coPersonId, Integer couId) {
404
        JsonObject adminGroup = this.getCouAdminGroup(couId);
405
        JsonArray admins = this.getGroupMembers(adminGroup.get("Id").getAsInt());
406
        Integer id = null;
407
        for (JsonElement admin : admins) {
408
            if (admin.getAsJsonObject().get("Person").getAsJsonObject().get("Id").getAsInt() == coPersonId) {
409
                id = admin.getAsJsonObject().get("Id").getAsInt();
410
            }
411
        }
412
        if (id != null) {
413
            httpUtils.delete("co_group_members/" + id.toString() + ".json");
414
        }
415
    }
416
}
modules/dnet-openaire-users/branches/prod/pom.xml
25 25
        <dependency>
26 26
            <groupId>eu.dnetlib</groupId>
27 27
            <artifactId>uoa-login-core</artifactId>
28
            <version>1.0.2</version>
28
            <version>1.0.3</version>
29 29
        </dependency>
30 30
        <dependency>
31 31
            <groupId>org.slf4j</groupId>
modules/dnet-openaire-users/branches/prod/src/main/java/eu/dnetlib/openaire/usermanagement/api/RegistryService.java
1 1
package eu.dnetlib.openaire.usermanagement.api;
2 2

  
3
import com.google.gson.*;
4
import eu.dnetlib.openaire.user.login.utils.AuthoritiesUpdater;
3
import com.google.gson.JsonArray;
4
import com.google.gson.JsonElement;
5
import com.google.gson.JsonObject;
6
import com.google.gson.JsonParser;
5 7
import eu.dnetlib.openaire.user.pojos.RoleVerification;
6 8
import eu.dnetlib.openaire.user.utils.EmailSender;
7 9
import eu.dnetlib.openaire.usermanagement.dto.Role;
8
import eu.dnetlib.openaire.usermanagement.dto.User;
9 10
import eu.dnetlib.openaire.usermanagement.utils.AuthorizationService;
10 11
import eu.dnetlib.openaire.usermanagement.utils.JsonUtils;
11
import eu.dnetlib.openaire.usermanagement.utils.RegistryCalls;
12
import eu.dnetlib.openaire.usermanagement.utils.RoleManagement;
12 13
import eu.dnetlib.openaire.usermanagement.utils.VerificationUtils;
13 14
import org.apache.log4j.Logger;
14 15
import org.springframework.beans.factory.annotation.Autowired;
15 16
import org.springframework.http.HttpStatus;
16 17
import org.springframework.security.access.prepost.PreAuthorize;
17
import org.springframework.security.core.authority.SimpleGrantedAuthority;
18 18
import org.springframework.stereotype.Component;
19
import org.springframework.web.bind.annotation.RequestBody;
19
import org.springframework.web.bind.annotation.*;
20
import org.springframework.web.client.HttpClientErrorException;
20 21

  
21 22
import javax.mail.MessagingException;
23
import javax.servlet.http.HttpServletRequest;
22 24
import javax.ws.rs.*;
25
import javax.ws.rs.core.Context;
23 26
import javax.ws.rs.core.MediaType;
24 27
import javax.ws.rs.core.Response;
25
import java.util.*;
26 28

  
27 29
@Component(value = "RegistryService")
30
@CrossOrigin("*")
28 31
@Path("/registry")
29 32
public class RegistryService {
30 33

  
31 34
    private static final Logger logger = Logger.getLogger(RegistryService.class);
32 35

  
33 36
    @Autowired
34
    private RegistryCalls calls;
37
    private RoleManagement calls;
35 38

  
36 39
    @Autowired
37 40
    private JsonUtils jsonUtils;
38 41

  
39 42
    @Autowired
40
    private EmailSender emailSender;
41

  
42
    @Autowired
43 43
    private VerificationUtils verificationUtils;
44 44

  
45 45
    @Autowired
46
    private AuthoritiesUpdater authoritiesUpdater;
46
    private EmailSender emailSender;
47 47

  
48 48
    @Autowired
49 49
    private AuthorizationService authorizationService;
50 50

  
51
    private final Gson gson = new Gson();
52

  
53 51
    /**
54 52
     * Subscribe to a type(Community, etc.) with id(ee, egi, etc.)
55 53
     */
......
57 55
    @POST
58 56
    @Produces(MediaType.APPLICATION_JSON)
59 57
    @PreAuthorize("isAuthenticated() and @AuthorizationService.isCommunity(#type)")
60
    public Response subscribe(@PathParam("type") String type, @PathParam("id") String id) {
61
        Integer coPersonId = calls.getCoPersonIdByIdentifier();
62
        Integer couId = calls.getCouId(type, id);
63
        if (couId != null) {
64
            Integer role = calls.getRoleId(coPersonId, couId);
65
            calls.assignMemberRole(coPersonId, couId, role);
66
            authoritiesUpdater.update(authorizationService.getEmail(), old -> {
67
                HashSet<SimpleGrantedAuthority> authorities = new HashSet<>((Collection<? extends SimpleGrantedAuthority>) old);
68
                authorities.add(new SimpleGrantedAuthority(authorizationService.member(type, id)));
69
                return authorities;
70
            });
71
            return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build();
72
        } else {
73
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
58
    public Response subscribe(@PathParam("type") String type, @PathParam("id") String id, @Context final HttpServletRequest request) {
59
        try {
60
            JsonElement response = calls.assignMemberRole(type, id, request);
61
            return Response.status(HttpStatus.OK.value()).entity(response.toString()).type(MediaType.APPLICATION_JSON).build();
62
        } catch (HttpClientErrorException e) {
63
            String message = new JsonParser().parse(e.getResponseBodyAsString()).getAsJsonObject().get("message").getAsString();
64
            return Response.status(e.getStatusCode().value()).entity(jsonUtils.createResponse(message).toString()).type(MediaType.APPLICATION_JSON).build();
74 65
        }
75 66
    }
76 67

  
......
82 73
    @POST
83 74
    @Produces(MediaType.APPLICATION_JSON)
84 75
    @PreAuthorize("isAuthenticated() and @AuthorizationService.isCommunity(#type)")
85
    public Response unsubscribe(@PathParam("type") String type, @PathParam("id") String id) {
86
        Integer coPersonId = calls.getCoPersonIdByIdentifier();
87
        Integer couId = calls.getCouId(type, id);
88
        if (couId != null) {
89
            Integer role = calls.getRoleId(coPersonId, couId);
90
            if (role != null) {
91
                calls.removeAdminRole(coPersonId, couId);
92
                calls.removeMemberRole(coPersonId, couId, role);
93
                authoritiesUpdater.update(authorizationService.getEmail(), old -> {
94
                    HashSet<SimpleGrantedAuthority> authorities = new HashSet<>((Collection<? extends SimpleGrantedAuthority>) old);
95
                    authorities.remove(new SimpleGrantedAuthority(authorizationService.manager(type, id)));
96
                    authorities.remove(new SimpleGrantedAuthority(authorizationService.member(type, id)));
97
                    return authorities;
98
                });
99
                return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Role has been removed").toString()).type(MediaType.APPLICATION_JSON).build();
100
            } else
101
                return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("User does not have this role").toString()).type(MediaType.APPLICATION_JSON).build();
102
        } else {
103
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
76
    public Response unsubscribe(@PathParam("type") String type, @PathParam("id") String id, @Context final HttpServletRequest request) {
77
        try {
78
            JsonElement response = calls.removeMemberRole(type, id, request);
79
            return Response.status(HttpStatus.OK.value()).entity(response.toString()).type(MediaType.APPLICATION_JSON).build();
80
        } catch (HttpClientErrorException e) {
81
            String message = new JsonParser().parse(e.getResponseBodyAsString()).getAsJsonObject().get("message").getAsString();
82
            return Response.status(e.getStatusCode().value()).entity(jsonUtils.createResponse(message).toString()).type(MediaType.APPLICATION_JSON).build();
104 83
        }
105 84
    }
106 85

  
107 86
    /**
87
     * Create a new curator role with the given type(Community, etc.).
88
     **/
89
    @Path("/create/{type}")
90
    @POST
91
    @Produces(MediaType.APPLICATION_JSON)
92
    @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)")
93
    public Response createCuratorRole(@PathParam("type") String type) {
94
        try {
95
            JsonElement response = calls.createCuratorRole(type);
96
            return Response.status(HttpStatus.CREATED.value()).entity(response.toString()).type(MediaType.APPLICATION_JSON).build();
97
        } catch (HttpClientErrorException e) {
98
            String message = new JsonParser().parse(e.getResponseBodyAsString()).getAsJsonObject().get("message").getAsString();
99
            return Response.status(e.getStatusCode().value()).entity(jsonUtils.createResponse(message).toString()).type(MediaType.APPLICATION_JSON).build();
100
        }
101
    }
102

  
103
    /**
108 104
     * Create a new role with the given type(Community, etc.) with id(ee, egi, etc.).
109 105
     **/
110 106
    @Path("/create/{type}/{id}")
......
112 108
    @Produces(MediaType.APPLICATION_JSON)
113 109
    @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)")
114 110
    public Response createMemberRole(@PathParam("type") String type, @PathParam("id") String id) {
115
        if (calls.getCouId(type, id) != null) {
116
            if(calls.createRole(new Role(type + "." + id,calls.mapType(type, false) + " " + id)) != null) {
117
                return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Role has been created").toString()).type(MediaType.APPLICATION_JSON).build();
118
            } else {
119
                return Response.status(HttpStatus.BAD_REQUEST.value()).entity(jsonUtils.createResponse("An error has occurred. Please try again later").toString()).type(MediaType.APPLICATION_JSON).build();
120
            }
121
        } else {
122
            return Response.status(HttpStatus.CONFLICT.value()).entity(jsonUtils.createResponse("Role has already existed").toString()).type(MediaType.APPLICATION_JSON).build();
111
        try {
112
            JsonElement response = calls.createMemberRole(type, id);
113
            return Response.status(HttpStatus.CREATED.value()).entity(response.toString()).type(MediaType.APPLICATION_JSON).build();
114
        } catch (HttpClientErrorException e) {
115
            String message = new JsonParser().parse(e.getResponseBodyAsString()).getAsJsonObject().get("message").getAsString();
116
            return Response.status(e.getStatusCode().value()).entity(jsonUtils.createResponse(message).toString()).type(MediaType.APPLICATION_JSON).build();
123 117
        }
124 118
    }
125 119

  
126 120
    /**
121
     * @deprecated
122
     *
127 123
     * Create a new role with the given name and description.
128 124
     **/
129 125
    @Path("/createRole")
......
132 128
    @Consumes(MediaType.APPLICATION_JSON)
133 129
    @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)")
134 130
    public Response createRole(@RequestBody Role role) {
135
        if (calls.getCouId(role.getName()) == null) {
136
            if(calls.createRole(role) != null) {
137
                return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Role has been created").toString()).type(MediaType.APPLICATION_JSON).build();
138
            } else {
139
                return Response.status(HttpStatus.BAD_REQUEST.value()).entity(jsonUtils.createResponse("An error has occurred. Please try again later").toString()).type(MediaType.APPLICATION_JSON).build();
140
            }
141
        } else {
142
            return Response.status(HttpStatus.CONFLICT.value()).entity(jsonUtils.createResponse("Role has already existed").toString()).type(MediaType.APPLICATION_JSON).build();
131
        try {
132
            JsonElement response = calls.createRole(role.getName(), role.getDescription());
133
            return Response.status(HttpStatus.CREATED.value()).entity(response.toString()).type(MediaType.APPLICATION_JSON).build();
134
        } catch (HttpClientErrorException e) {
135
            String message = new JsonParser().parse(e.getResponseBodyAsString()).getAsJsonObject().get("message").getAsString();
136
            return Response.status(e.getStatusCode().value()).entity(jsonUtils.createResponse(message).toString()).type(MediaType.APPLICATION_JSON).build();
143 137
        }
144 138
    }
145 139

  
......
153 147
    @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN, " +
154 148
            "@AuthorizationService.curator(#type), @AuthorizationService.manager(#type, #id))")
155 149
    public Response inviteManager(@PathParam("type") String type, @PathParam("id") String id, @RequestBody String body) {
156
        Integer couId = calls.getCouId(type, id);
157
        if (couId != null) {
150
        try {
158 151
            JsonObject details = new JsonParser().parse(body).getAsJsonObject();
159 152
            JsonObject email = details.get("email").getAsJsonObject();
160 153
            String recipient = email.get("recipient").getAsString();
161
            Integer coPersonId = calls.getCoPersonIdByEmail(recipient);
162
            if (coPersonId == null || calls.getUserAdminGroup(coPersonId, couId) == null) {
154
            if (!calls.isManager(type, id, recipient)) {
163 155
                JsonObject invitation = verificationUtils.createManagerInvitation(recipient, type, id);
164
                return sendEmail(details, email, coPersonId, invitation);
156
                return sendEmail(details, email, invitation);
165 157
            } else {
166 158
                return Response.status(HttpStatus.CONFLICT.value()).entity(jsonUtils.createResponse("User has been already manager of this " + type).toString()).type(MediaType.APPLICATION_JSON).build();
167 159
            }
168
        } else {
169
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
160
        } catch (HttpClientErrorException e) {
161
            String message = new JsonParser().parse(e.getResponseBodyAsString()).getAsJsonObject().get("message").getAsString();
162
            return Response.status(e.getStatusCode().value()).entity(jsonUtils.createResponse(message).toString()).type(MediaType.APPLICATION_JSON).build();
170 163
        }
171 164
    }
172 165

  
......
180 173
    @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN, " +
181 174
            "@AuthorizationService.curator(#type), @AuthorizationService.manager(#type, #id))")
182 175
    public Response inviteMember(@PathParam("type") String type, @PathParam("id") String id, @RequestBody String body) {
183
        Integer couId = calls.getCouId(type, id, false);
184
        if (couId != null) {
176
        try {
185 177
            JsonObject details = new JsonParser().parse(body).getAsJsonObject();
186 178
            JsonObject email = details.get("email").getAsJsonObject();
187 179
            String recipient = email.get("recipient").getAsString();
188
            Integer coPersonId = calls.getCoPersonIdByEmail(recipient);
189
            if (coPersonId == null || calls.getRoleId(coPersonId, couId) == null) {
180
            if (!calls.isMember(type, id, recipient)) {
190 181
                JsonObject invitation = verificationUtils.createMemberInvitation(recipient, type, id);
191
                return sendEmail(details, email, coPersonId, invitation);
182
                return sendEmail(details, email, invitation);
192 183
            } else {
193 184
                return Response.status(HttpStatus.CONFLICT.value()).entity(jsonUtils.createResponse("User has been already member of this " + type).toString()).type(MediaType.APPLICATION_JSON).build();
194 185
            }
195
        } else {
196
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
186
        } catch (HttpClientErrorException e) {
187
            String message = new JsonParser().parse(e.getResponseBodyAsString()).getAsJsonObject().get("message").getAsString();
188
            return Response.status(e.getStatusCode().value()).entity(jsonUtils.createResponse(message).toString()).type(MediaType.APPLICATION_JSON).build();
197 189
        }
198 190
    }
199 191

  
200
    private Response sendEmail(JsonObject details, JsonObject email, Integer coPersonId, JsonObject invitation) {
201
        String name = (coPersonId != null) ? calls.getUserNames(coPersonId) : "User";
192
    private Response sendEmail(JsonObject details, JsonObject email, JsonObject invitation) {
202 193
        String link = details.get("link").getAsString() + invitation.get("link").getAsString();
203 194
        String subject = email.get("subject").getAsString();
204 195
        String message = email.get("body").getAsString().
205
                replace("((__user__))", name).
196
                replace("((__user__))", "User").
206 197
                replace("((__link__))", link).
207 198
                replace("((__code__))", invitation.get("code").getAsString());
208 199
        try {
209 200
            emailSender.sendEmail(email.get("recipient").getAsString(), subject, message);
210 201
            return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(invitation).toString()).type(MediaType.APPLICATION_JSON).build();
211 202
        } catch (MessagingException e) {
212
            logger.error(e.getMessage());
213 203
            verificationUtils.deleteVerification(invitation.get("link").getAsString());
214 204
            return Response.status(HttpStatus.BAD_REQUEST.value()).entity(jsonUtils.createResponse("Email sent failed").toString()).type(MediaType.APPLICATION_JSON).build();
215 205
        }
......
224 214
    @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN, " +
225 215
            "@AuthorizationService.curator(#type), @AuthorizationService.manager(#type, #id))")
226 216
    public Response cancelManagerInvitations(@PathParam("type") String type, @PathParam("id") String id, @PathParam("email") String email) {
227
        Integer couId = calls.getCouId(type, id);
228
        if (couId != null) {
229
            verificationUtils.deleteManagerVerifications(email, type, id);
230
            return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Invitations have been deleted").toString()).type(MediaType.APPLICATION_JSON).build();
231
        } else {
232
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
233
        }
217
        verificationUtils.deleteManagerVerifications(email, type, id);
218
        return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Invitations have been deleted").toString()).type(MediaType.APPLICATION_JSON).build();
234 219
    }
235 220

  
236 221
    /**
......
242 227
    @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN, " +
243 228
            "@AuthorizationService.curator(#type), @AuthorizationService.manager(#type, #id))")
244 229
    public Response cancelMemberInvitations(@PathParam("type") String type, @PathParam("id") String id, @PathParam("email") String email) {
245
        Integer couId = calls.getCouId(type, id, false);
246
        if (couId != null) {
247
            verificationUtils.deleteMemberVerifications(email, type, id);
248
            return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Invitations have been deleted").toString()).type(MediaType.APPLICATION_JSON).build();
249
        } else {
250
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
251
        }
230
        verificationUtils.deleteMemberVerifications(email, type, id);
231
        return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Invitations have been deleted").toString()).type(MediaType.APPLICATION_JSON).build();
252 232
    }
253 233

  
254 234
    /**
......
280 260
    /**
281 261
     * Get the verification with a specific id only if it refers to the logged in user
282 262
     */
283
    @Path("verification/{id}")
263
    @Path("/verification/{id}")
284 264
    @GET
285 265
    @Produces(MediaType.APPLICATION_JSON)
286 266
    @PreAuthorize("isAuthenticated()")
......
300 280
    /**
301 281
     * Delete the verification with a specific id.
302 282
     */
303
    @Path("verification/{id}")
283
    @Path("/verification/{id}")
304 284
    @DELETE
305 285
    @Produces(MediaType.APPLICATION_JSON)
306 286
    @PreAuthorize("isAuthenticated() && @VerificationUtils.ownedVerification(#id)")
......
317 297
     * Verify the verification with the specific id, if the code is correct and it refers to the logged in user.
318 298
     * Manager role is assigned to this user, along with the member role.
319 299
     */
320
    @Path("verification/manager/{id}")
300
    @Path("/verification/manager/{id}")
321 301
    @POST
322 302
    @Produces(MediaType.APPLICATION_JSON)
323 303
    @PreAuthorize("isAuthenticated()")
324
    public Response verifyManager(@PathParam("id") String id, @RequestBody String code) {
304
    public Response verifyManager(@PathParam("id") String id, @RequestBody String code, @Context final HttpServletRequest request) {
325 305
        RoleVerification verification = verificationUtils.getVerification(id);
326 306
        if (verification != null && verification.getVerificationType().equals("manager")) {
327
            Integer coPersonId = calls.getCoPersonIdByIdentifier();
328
            if (coPersonId != null) {
329
                if (verification.getEmail().equalsIgnoreCase(authorizationService.getEmail())) {
330
                    if (verification.getVerificationCode().equals(code)) {
331
                        Integer couId = calls.getCouId(verification.getType(), verification.getEntity());
332
                        if (couId != null) {
333
                            Integer role = calls.getRoleId(coPersonId, couId);
334
                            calls.assignMemberRole(coPersonId, couId, role);
335
                            if (verification.getType().equals("community") || verification.getType().equals("ri")) {
336
                                Integer riCouId = calls.getCouId("ri", verification.getEntity(), false);
337
                                if (riCouId != null) {
338
                                    calls.assignMemberRole(coPersonId, riCouId, calls.getRoleId(coPersonId, riCouId));
339
                                    verificationUtils.deleteMemberVerifications(verification.getEmail(), "community", verification.getEntity());
340
                                    verificationUtils.deleteMemberVerifications(verification.getEmail(), "ri", verification.getEntity());
341
                                } else {
342
                                    verificationUtils.deleteMemberVerifications(verification.getEmail(), "community", verification.getEntity());
343
                                }
344
                            } else {
345
                                verificationUtils.deleteMemberVerifications(verification.getEmail(), verification.getType(), verification.getEntity());
346
                            }
347
                            if (calls.getUserAdminGroup(coPersonId, couId) == null) {
348
                                if (verification.getType().equals("community") || verification.getType().equals("ri")) {
349
                                    verificationUtils.deleteManagerVerifications(verification.getEmail(), "community", verification.getEntity());
350
                                    verificationUtils.deleteManagerVerifications(verification.getEmail(), "ri", verification.getEntity());
351
                                } else {
352
                                    verificationUtils.deleteManagerVerifications(verification.getEmail(), verification.getType(), verification.getEntity());
353
                                }
354
                                calls.assignAdminRole(coPersonId, couId);
355
                                authoritiesUpdater.update(verification.getEmail(), old -> {
356
                                    HashSet<SimpleGrantedAuthority> authorities = new HashSet<>((Collection<? extends SimpleGrantedAuthority>) old);
357
                                    authorities.add(new SimpleGrantedAuthority(authorizationService.member(verification.getType(), verification.getEntity())));
358
                                    authorities.add(new SimpleGrantedAuthority(authorizationService.manager(verification.getType(), verification.getEntity())));
359
                                    return authorities;
360
                                });
361
                                return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Admin role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build();
362
                            } else {
363
                                return Response.status(HttpStatus.CONFLICT.value()).entity(jsonUtils.createResponse("User is already admin of this cou").toString()).type(MediaType.APPLICATION_JSON).build();
364
                            }
307
            if (verification.getEmail().equalsIgnoreCase(authorizationService.getEmail())) {
308
                if (verification.getVerificationCode().equals(code)) {
309
                    try {
310
                        calls.assignManagerRole(verification.getType(), verification.getEntity(), request);
311
                        if (verification.getType().equals("community") || verification.getType().equals("ri")) {
312
                            calls.assignMemberRole("ri", verification.getEntity(), request);
313
                            verificationUtils.deleteMemberVerifications(verification.getEmail(), "community", verification.getEntity());
314
                            verificationUtils.deleteMemberVerifications(verification.getEmail(), "ri", verification.getEntity());
315
                            verificationUtils.deleteManagerVerifications(verification.getEmail(), "community", verification.getEntity());
316
                            verificationUtils.deleteManagerVerifications(verification.getEmail(), "ri", verification.getEntity());
365 317
                        } else {
366
                            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
318
                            verificationUtils.deleteMemberVerifications(verification.getEmail(), verification.getType(), verification.getEntity());
319
                            verificationUtils.deleteManagerVerifications(verification.getEmail(), verification.getType(), verification.getEntity());
367 320
                        }
368
                    } else {
369
                        return Response.status(HttpStatus.BAD_REQUEST.value()).entity(jsonUtils.createResponse("Verification code is wrong").toString()).type(MediaType.APPLICATION_JSON).build();
321
                        return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Admin role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build();
322
                    } catch (HttpClientErrorException e) {
323
                        String message = new JsonParser().parse(e.getResponseBodyAsString()).getAsJsonObject().get("message").getAsString();
324
                        return Response.status(e.getStatusCode().value()).entity(jsonUtils.createResponse(message).toString()).type(MediaType.APPLICATION_JSON).build();
370 325
                    }
371 326
                } else {
372
                    return Response.status(HttpStatus.FORBIDDEN.value()).entity(jsonUtils.createResponse("Forbidden verification").toString()).type(MediaType.APPLICATION_JSON).build();
327
                    return Response.status(HttpStatus.BAD_REQUEST.value()).entity(jsonUtils.createResponse("Verification code is wrong").toString()).type(MediaType.APPLICATION_JSON).build();
373 328
                }
374 329
            } else {
375
                return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("User has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
330
                return Response.status(HttpStatus.FORBIDDEN.value()).entity(jsonUtils.createResponse("Forbidden verification").toString()).type(MediaType.APPLICATION_JSON).build();
376 331
            }
377 332
        } else {
378 333
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Verification has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
......
383 338
     * Verify the verification with the specific id, if the code is correct and it refers to the logged in user.
384 339
     * Member role is assigned to this user, along with the member role.
385 340
     */
386
    @Path("verification/member/{id}")
341
    @Path("/verification/member/{id}")
387 342
    @POST
388 343
    @Produces(MediaType.APPLICATION_JSON)
389 344
    @PreAuthorize("isAuthenticated()")
390
    public Response verifyMember(@PathParam("id") String id, @RequestBody String code) {
345
    public Response verifyMember(@PathParam("id") String id, @RequestBody String code, @Context final HttpServletRequest request) {
391 346
        RoleVerification verification = verificationUtils.getVerification(id);
392 347
        if (verification != null && verification.getVerificationType().equals("member")) {
393
            Integer coPersonId = calls.getCoPersonIdByIdentifier();
394
            if (coPersonId != null) {
395
                if (verification.getEmail().equalsIgnoreCase(authorizationService.getEmail())) {
396
                    if (verification.getVerificationCode().equals(code)) {
397
                        Integer couId = calls.getCouId(verification.getType(), verification.getEntity(), false);
398
                        if (couId != null) {
399
                            Integer role = calls.getRoleId(coPersonId, couId);
400
                            calls.assignMemberRole(coPersonId, couId, role);
401
                            authoritiesUpdater.update(verification.getEmail(), old -> {
402
                                HashSet<SimpleGrantedAuthority> authorities = new HashSet<>((Collection<? extends SimpleGrantedAuthority>) old);
403
                                authorities.add(new SimpleGrantedAuthority(authorizationService.member(verification.getType(), verification.getEntity())));
404
                                return authorities;
405
                            });
406
                            verificationUtils.deleteMemberVerifications(verification.getEmail(), verification.getType(), verification.getEntity());
407
                            return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Member role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build();
408
                        } else {
409
                            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
410
                        }
411
                    } else {
412
                        return Response.status(HttpStatus.FORBIDDEN.value()).entity(jsonUtils.createResponse("Verification code is wrong").toString()).type(MediaType.APPLICATION_JSON).build();
348
            if (verification.getEmail().equalsIgnoreCase(authorizationService.getEmail())) {
349
                if (verification.getVerificationCode().equals(code)) {
350
                    try {
351
                        calls.assignMemberRole(verification.getType(), verification.getEntity(), request);
352
                        verificationUtils.deleteMemberVerifications(verification.getEmail(), verification.getType(), verification.getEntity());
353
                        return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Member role has been assigned").toString()).type(MediaType.APPLICATION_JSON).build();
354
                    } catch (HttpClientErrorException e) {
355
                        String message = new JsonParser().parse(e.getResponseBodyAsString()).getAsJsonObject().get("message").getAsString();
356
                        return Response.status(e.getStatusCode().value()).entity(jsonUtils.createResponse(message).toString()).type(MediaType.APPLICATION_JSON).build();
413 357
                    }
414 358
                } else {
415
                    return Response.status(HttpStatus.FORBIDDEN.value()).entity(jsonUtils.createResponse("Forbidden verification").toString()).type(MediaType.APPLICATION_JSON).build();
359
                    return Response.status(HttpStatus.BAD_REQUEST.value()).entity(jsonUtils.createResponse("Verification code is wrong").toString()).type(MediaType.APPLICATION_JSON).build();
416 360
                }
417 361
            } else {
418
                return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("User has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
362
                return Response.status(HttpStatus.FORBIDDEN.value()).entity(jsonUtils.createResponse("Forbidden verification").toString()).type(MediaType.APPLICATION_JSON).build();
419 363
            }
420 364
        } else {
421 365
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Verification has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
......
432 376
    @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN, @AuthorizationService.curator(#type), @AuthorizationService.manager(#type, #id))")
433 377
    public Response removeManagerRole(@PathParam("type") String type, @PathParam("id") String
434 378
            id, @PathParam("email") String email) {
435
        List<Integer> coPersonIds = calls.getCoPersonIdsByEmail(email);
436
        if (coPersonIds.size() > 0) {
437
            Integer couId = calls.getCouId(type, id);
438
            if (couId != null) {
439
                coPersonIds.forEach(coPersonId -> {
440
                    calls.removeAdminRole(coPersonId, couId);
441
                });
442
                authoritiesUpdater.update(email, old -> {
443
                    HashSet<SimpleGrantedAuthority> authorities = new HashSet<>((Collection<? extends SimpleGrantedAuthority>) old);
444
                    authorities.remove(new SimpleGrantedAuthority(authorizationService.manager(type, id)));
445
                    return authorities;
446
                });
447
                return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Role has been removed").toString()).type(MediaType.APPLICATION_JSON).build();
448
            } else {
449
                return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
450
            }
451
        } else {
452
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("User has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
379
        try {
380
            JsonElement response = calls.removeManagerRole(type, id, email);
381
            return Response.status(HttpStatus.OK.value()).entity(response.toString()).type(MediaType.APPLICATION_JSON).build();
382
        } catch (HttpClientErrorException e) {
383
            String message = new JsonParser().parse(e.getResponseBodyAsString()).getAsJsonObject().get("message").getAsString();
384
            return Response.status(e.getStatusCode().value()).entity(jsonUtils.createResponse(message).toString()).type(MediaType.APPLICATION_JSON).build();
453 385
        }
454 386
    }
455 387

  
......
463 395
    @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN, @AuthorizationService.curator(#type), @AuthorizationService.manager(#type, #id))")
464 396
    public Response removeMemberRole(@PathParam("type") String type, @PathParam("id") String
465 397
            id, @PathParam("email") String email) {
466
        List<Integer> coPersonIds = calls.getCoPersonIdsByEmail(email);
467
        if (coPersonIds.size() > 0) {
468
            Integer couId = calls.getCouId(type, id, false);
469
            if (couId != null) {
470
                coPersonIds.forEach(coPersonId -> {
471
                    Integer role = calls.getRoleId(coPersonId, couId);
472
                    calls.removeAdminRole(coPersonId, couId);
473
                    calls.removeMemberRole(coPersonId, couId, role);
474
                });
475
                authoritiesUpdater.update(email, old -> {
476
                    HashSet<SimpleGrantedAuthority> authorities = new HashSet<>((Collection<? extends SimpleGrantedAuthority>) old);
477
                    authorities.remove(new SimpleGrantedAuthority(authorizationService.manager(type, id)));
478
                    authorities.remove(new SimpleGrantedAuthority(authorizationService.member(type, id)));
479
                    return authorities;
480
                });
481
                return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse("Role has been removed").toString()).type(MediaType.APPLICATION_JSON).build();
482
            } else {
483
                return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
484
            }
485
        } else {
486
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("User has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
398
        try {
399
            JsonElement response = calls.removeMemberRole(type, id, email);
400
            return Response.status(HttpStatus.OK.value()).entity(response.toString()).type(MediaType.APPLICATION_JSON).build();
401
        } catch (HttpClientErrorException e) {
402
            String message = new JsonParser().parse(e.getResponseBodyAsString()).getAsJsonObject().get("message").getAsString();
403
            return Response.status(e.getStatusCode().value()).entity(jsonUtils.createResponse(message).toString()).type(MediaType.APPLICATION_JSON).build();
487 404
        }
488 405
    }
489 406

  
......
494 411
    @GET
495 412
    @Produces(MediaType.APPLICATION_JSON)
496 413
    public Response getMembersCount(@PathParam("type") String type, @PathParam("id") String id) {
497
        Integer couId = calls.getCouId(type, id, false);
498
        int count = 0;
499
        if (couId != null) {
500
            count = calls.getUserIdByCouId(couId, false).size();
414
        try {
415
            int response = calls.getAllMembersCount(type, id);
416
            return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(response).toString()).type(MediaType.APPLICATION_JSON).build();
417
        } catch (HttpClientErrorException e) {
418
            String message = new JsonParser().parse(e.getResponseBodyAsString()).getAsJsonObject().get("message").getAsString();
419
            return Response.status(e.getStatusCode().value()).entity(jsonUtils.createResponse(message).toString()).type(MediaType.APPLICATION_JSON).build();
501 420
        }
502
        return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(count).toString()).type(MediaType.APPLICATION_JSON).build();
503 421
    }
504 422

  
505 423
    /**
506
     * Get the names of the members of a type(Community, etc.) with id(ee, egi, etc.)
424
     * Get infos of the members of a type(Community, etc.) with id(ee, egi, etc.)
507 425
     */
508 426
    @Path("/{type}/{id}/members{var:.*}")
509 427
    @GET
......
511 429
    @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN," +
512 430
            "@AuthorizationService.curator(#type), @AuthorizationService.manager(#type, #id))")
513 431
    public Response getMembers(@PathParam("type") String type, @PathParam("id") String id) {
514
        Integer couId = calls.getCouId(type, id, false);
515
        if (couId != null) {
516
            JsonArray members = calls.getUserIdByCouId(couId, false);
517
            JsonArray emails = calls.getUserEmailByCouId(couId, false);
518
            JsonArray names = calls.getUserNamesByCouId(couId, false);
519
            JsonArray managers = calls.getUserIdByCouId(couId, true);
520
            members.getAsJsonArray().forEach(element -> {
521
                element.getAsJsonObject().addProperty("isManager", managers.contains(element));
522
            });
523
            JsonUtils.mergeUserInfo(members, emails, names, gson);
524
            return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(members).toString()).type(MediaType.APPLICATION_JSON).build();
525
        } else {
526
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
432
        try {
433
            JsonElement response = calls.getAllMembers(type, id);
434
            return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(response).toString()).type(MediaType.APPLICATION_JSON).build();
435
        } catch (HttpClientErrorException e) {
436
            String message = new JsonParser().parse(e.getResponseBodyAsString()).getAsJsonObject().get("message").getAsString();
437
            return Response.status(e.getStatusCode().value()).entity(jsonUtils.createResponse(message).toString()).type(MediaType.APPLICATION_JSON).build();
527 438
        }
528 439
    }
529 440

  
......
534 445
    @GET
535 446
    @Produces(MediaType.APPLICATION_JSON)
536 447
    public Response getManagers(@PathParam("type") String type, @PathParam("id") String id) {
537
        Integer couId = calls.getCouId(type, id);
538
        if (couId != null) {
539
            JsonArray managers = calls.getUserIdByCouId(couId, true);
540
            if(authorizationService.isManager(type, id) || authorizationService.isPortalAdmin() || authorizationService.isCurator(type)) {
541
                JsonArray emails = calls.getUserEmailByCouId(couId, true);
542
                JsonArray names = calls.getUserNamesByCouId(couId, true);
543
                JsonUtils.mergeUserInfo(managers, emails, names, gson);
544
            } else {
545
                managers.forEach(user -> {
546
                    user.getAsJsonObject().remove("coPersonId");
547
                });
548
            }
549
            return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(managers).toString()).type(MediaType.APPLICATION_JSON).build();
550
        } else {
551
            return Response.status(HttpStatus.NOT_FOUND.value()).entity(jsonUtils.createResponse("Role has not been found").toString()).type(MediaType.APPLICATION_JSON).build();
448
        try {
449
            JsonElement response = calls.getAllManagers(type, id);
450
            return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(response).toString()).type(MediaType.APPLICATION_JSON).build();
451
        } catch (HttpClientErrorException e) {
452
            String message = new JsonParser().parse(e.getResponseBodyAsString()).getAsJsonObject().get("message").getAsString();
453
            return Response.status(e.getStatusCode().value()).entity(jsonUtils.createResponse(message).toString()).type(MediaType.APPLICATION_JSON).build();
552 454
        }
553 455
    }
554
}
456

  
457
    /**
458
     * Get infos of the curators of a type(Community, etc.)
459
     */
460
    @Path("/{type}/curators{var:.*}")
461
    @GET
462
    @Produces(MediaType.APPLICATION_JSON)
463
    @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN, @AuthorizationService.curator(#type))")
464
    public Response getCurators(@PathParam("type") String type) {
465
        try {
466
            JsonElement response = calls.getAllCurators(type);
467
            return Response.status(HttpStatus.OK.value()).entity(jsonUtils.createResponse(response.toString())).type(MediaType.APPLICATION_JSON).build();
468
        } catch (HttpClientErrorException e) {
469
            String message = new JsonParser().parse(e.getResponseBodyAsString()).getAsJsonObject().get("message").getAsString();
470
            return Response.status(e.getStatusCode().value()).entity(jsonUtils.createResponse(message).toString()).type(MediaType.APPLICATION_JSON).build();
471
        }
472
    }
473
}
modules/dnet-openaire-users/branches/prod/src/main/java/eu/dnetlib/openaire/usermanagement/utils/HttpUtils.java
10 10
import org.springframework.stereotype.Component;
11 11
import org.springframework.web.client.RestTemplate;
12 12

  
13
import javax.servlet.http.Cookie;
14
import javax.servlet.http.HttpServletRequest;
13 15
import java.nio.charset.Charset;
16
import java.util.Arrays;
14 17
import java.util.Map;
15 18

  
16 19
@Component
......
18 21

  
19 22
    private static final Logger logger = Logger.getLogger(HttpUtils.class);
20 23

  
21
    @Value("${registry.issuer}")
22
    private String issuer;
23

  
24
    @Value("${registry.user}")
25
    private String user;
26

  
27
    @Value("${registry.password}")
28
    private String password;
29

  
30
    public JsonElement post(String path, JsonObject body) {
24
    public JsonElement post(String path, String session, JsonObject body, Map<String, String> params) {
31 25
        RestTemplate restTemplate = new RestTemplate();
32
        HttpHeaders headers = createHeaders(user, password);
26
        String url = path + ((params != null) ? createParams(params) : "");
27
        HttpHeaders headers = createHeaders(session);
33 28
        headers.setContentType(MediaType.APPLICATION_JSON);
34
        HttpEntity<String> request = new HttpEntity<>(body.toString(), headers);
35
        ResponseEntity<String> responseEntity = restTemplate.exchange(issuer + path, HttpMethod.POST, request, String.class);
29
        HttpEntity<String> request = new HttpEntity<>((body != null)?body.toString():"", headers);
30
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
36 31
        if (responseEntity.getBody() != null) {
37 32
            return new JsonParser().parse(responseEntity.getBody());
38 33
        } else {
......
40 35
        }
41 36
    }
42 37

  
43
    public JsonElement put(String path, JsonObject body) {
38
    public JsonElement put(String path, String session, JsonObject body) {
44 39
        RestTemplate restTemplate = new RestTemplate();
45
        HttpHeaders headers = createHeaders(user, password);
40
        HttpHeaders headers = createHeaders(session);
46 41
        headers.setContentType(MediaType.APPLICATION_JSON);
47 42
        HttpEntity<String> request = new HttpEntity<>(body.toString(), headers);
48
        ResponseEntity<String> responseEntity = restTemplate.exchange(issuer + path, HttpMethod.PUT, request, String.class);
43
        ResponseEntity<String> responseEntity = restTemplate.exchange(path, HttpMethod.PUT, request, String.class);
49 44
        if (responseEntity.getBody() != null) {
50 45
            return new JsonParser().parse(responseEntity.getBody());
51 46
        } else {
......
53 48
        }
54 49
    }
55 50

  
56
    public JsonElement get(String path, Map<String, String> params) {
51
    public JsonElement get(String path, String session, Map<String, String> params) {
57 52
        RestTemplate restTemplate = new RestTemplate();
58
        String url = issuer + path + ((params != null) ? createParams(params) : null);
53
        String url = path + ((params != null) ? createParams(params) : "");
54
        HttpHeaders headers = createHeaders(session);
59 55
        ResponseEntity<String> responseEntity = restTemplate.exchange
60
                (url, HttpMethod.GET, new HttpEntity<>(createHeaders(user, password)), String.class);
56
                (url, HttpMethod.GET, new HttpEntity<>(headers), String.class);
61 57
        if (responseEntity.getBody() != null) {
62 58
            return new JsonParser().parse(responseEntity.getBody());
63 59
        } else {
......
65 61
        }
66 62
    }
67 63

  
68
    public JsonElement delete(String path) {
64
    public JsonElement delete(String path, String session, Map<String, String> params) {
69 65
        RestTemplate restTemplate = new RestTemplate();
70
        String url = issuer + path;
66
        String url = path + ((params != null) ? createParams(params) : "");
67
        HttpHeaders headers = createHeaders(session);
71 68
        ResponseEntity<String> responseEntity = restTemplate.exchange
72
                (url, HttpMethod.DELETE, new HttpEntity<>(createHeaders(user, password)), String.class);
69
                (url, HttpMethod.DELETE, new HttpEntity<>(headers), String.class);
73 70
        if (responseEntity.getBody() != null) {
74 71
            return new JsonParser().parse(responseEntity.getBody());
75 72
        } else {
......
92 89
        return ret.toString();
93 90
    }
94 91

  
95
    private HttpHeaders createHeaders(String username, String password) {
96
        return new HttpHeaders() {{
97
            String auth = username + ":" + password;
98
            byte[] encodedAuth = Base64.encodeBase64(
99
                    auth.getBytes(Charset.forName("US-ASCII")));
100
            String authHeader = "Basic " + new String(encodedAuth);
101
            set("Authorization", authHeader);
102
        }};
92
    private HttpHeaders createHeaders(String token) {
93
        if(token != null) {
94
            return new HttpHeaders() {{
95
                set("Session", token);
96
            }};
97
        } else {
98
            return new HttpHeaders();
99
        }
103 100
    }
101

  
102
    public String getCookie(HttpServletRequest req, String cookieName) {
103
        return Arrays.stream(req.getCookies())
104
                .filter(c -> c.getName().equals(cookieName))
105
                .findFirst()
106
                .map(Cookie::getValue)
107
                .orElse(null);
108
    }
104 109
}
modules/dnet-openaire-users/branches/prod/src/main/java/eu/dnetlib/openaire/usermanagement/utils/JsonUtils.java
1 1
package eu.dnetlib.openaire.usermanagement.utils;
2 2

  
3
import com.google.gson.Gson;
4
import com.google.gson.JsonArray;
5 3
import com.google.gson.JsonElement;
6 4
import com.google.gson.JsonObject;
7 5
import eu.dnetlib.openaire.user.pojos.RoleVerification;
8
import eu.dnetlib.openaire.usermanagement.dto.Role;
9
import eu.dnetlib.openaire.usermanagement.dto.User;
10
import org.springframework.beans.factory.annotation.Value;
11 6
import org.springframework.stereotype.Component;
12 7

  
13
import java.util.Arrays;
14
import java.util.Optional;
15

  
16 8
@Component
17 9
public class JsonUtils {
18 10

  
19
    @Value("${registry.version}")
20
    private String version;
21

  
22
    @Value("${registry.coid}")
23
    private String coid;
24

  
25
    public JsonObject coPersonRoles(Integer coPersonId, Integer couId, String status) {
26
        JsonObject role = new JsonObject();
27
        JsonArray coPersonRoles = new JsonArray();
28
        JsonObject coPersonRole = new JsonObject();
29
        JsonObject person = new JsonObject();
30
        person.addProperty("Type", "CO");
31
        person.addProperty("Id", coPersonId.toString());
32
        coPersonRole.addProperty("Version", version);
33
        coPersonRole.add("Person", person);
34
        coPersonRole.addProperty("CouId", couId.toString());
35
        coPersonRole.addProperty("Affiliation", "member");
36
        coPersonRole.addProperty("Title", "");
37
        coPersonRole.addProperty("O", "Openaire");
38
        coPersonRole.addProperty("Status", status);
39
        coPersonRole.addProperty("ValidFrom", "");
40
        coPersonRole.addProperty("ValidThrough", "");
41
        coPersonRoles.add(coPersonRole);
42
        role.addProperty("RequestType", "CoPersonRoles");
43
        role.addProperty("Version", version);
44
        role.add("CoPersonRoles", coPersonRoles);
45
        return role;
46
    }
47

  
48
    public JsonObject coGroupMembers(Integer coGroupId, Integer coPersonId, boolean member) {
49
        JsonObject coGroup = new JsonObject();
50
        JsonArray coGroupMembers = new JsonArray();
51
        JsonObject coGroupMember = new JsonObject();
52
        JsonObject person = new JsonObject();
53
        person.addProperty("Type", "CO");
54
        person.addProperty("Id", coPersonId.toString());
55
        coGroupMember.addProperty("Version", version);
56
        coGroupMember.add("Person", person);
57
        coGroupMember.addProperty("CoGroupId", coGroupId.toString());
58
        coGroupMember.addProperty("Member", member);
59
        coGroupMember.addProperty("Owner", false);
60
        coGroupMember.addProperty("ValidFrom", "");
61
        coGroupMember.addProperty("ValidThrough", "");
62
        coGroupMembers.add(coGroupMember);
63
        coGroup.addProperty("RequestType", "CoGroupMembers");
64
        coGroup.addProperty("Version", version);
65
        coGroup.add("CoGroupMembers", coGroupMembers);
66
        return coGroup;
67
    }
68

  
69
    public JsonObject createNewCou(Role role) {
70
        JsonObject cou = new JsonObject();
71
        JsonArray cous = new JsonArray();
72
        JsonObject newCou = new JsonObject();
73
        newCou.addProperty("Version", version);
74
        newCou.addProperty("CoId", coid);
75
        newCou.addProperty("Name", role.getName());
76
        newCou.addProperty("Description", role.getDescription());
77
        cous.add(newCou);
78
        cou.addProperty("RequestType", "Cous");
79
        cou.addProperty("Version", version);
80
        cou.add("Cous", cous);
81
        return cou;
82
    }
83

  
84 11
    public JsonObject createVerification(RoleVerification roleVerification) {
85 12
        JsonObject verification = new JsonObject();
86 13
        verification.addProperty("id", roleVerification.getId());
......
92 19
        return verification;
93 20
    }
94 21

  
95
    public static JsonArray mergeUserInfo(JsonArray users, JsonArray emails, JsonArray names, Gson gson) {
96
        User[] emailsMapped =  gson.fromJson(emails, User[].class);
97
        User[] namesMapped =  gson.fromJson(names, User[].class);
98
        for(JsonElement user: users) {
99
            Optional<User> emailUser = Arrays.stream(emailsMapped).filter(email -> user.getAsJsonObject().get("coPersonId").getAsString().equals(email.getCoPersonId())).findFirst();
100
            Optional<User> nameUser = Arrays.stream(namesMapped).filter(name -> user.getAsJsonObject().get("coPersonId").getAsString().equals(name.getCoPersonId())).findFirst();
101
            emailUser.ifPresent(value -> user.getAsJsonObject().addProperty("email", value.getEmail()));
102
            nameUser.ifPresent(value -> user.getAsJsonObject().addProperty("name", value.getName()));
103
            user.getAsJsonObject().remove("coPersonId");
104
        }
105
        return users;
106
    }
107

  
108 22
    public JsonObject createResponse(JsonElement response) {
109 23
        JsonObject json = new JsonObject();
110 24
        json.add("response", response);
modules/dnet-openaire-users/branches/prod/src/main/java/eu/dnetlib/openaire/usermanagement/utils/RoleManagement.java
1
package eu.dnetlib.openaire.usermanagement.utils;
2

  
3
import com.google.gson.JsonElement;
4
import org.apache.log4j.Logger;
5
import org.springframework.beans.factory.annotation.Autowired;
6
import org.springframework.beans.factory.annotation.Value;
7
import org.springframework.stereotype.Service;
8
import org.springframework.web.client.HttpClientErrorException;
9

  
10
import javax.servlet.http.HttpServletRequest;
11
import java.util.HashMap;
12
import java.util.Map;
13

  
14
@Service
15
public class RoleManagement {
16

  
17
    private static final Logger logger = Logger.getLogger(RoleManagement.class);
18

  
19
    @Value("${role-management.url}")
20
    private String url;
21
    public HttpUtils httpUtils;
22
    public AuthorizationService authorizationService;
23

  
24
    @Autowired
25
    public RoleManagement(HttpUtils httpUtils, AuthorizationService authorizationService) {
26
        this.httpUtils = httpUtils;
27
        this.authorizationService = authorizationService;
28
    }
29

  
30
    private String mapType(String type, boolean communityMap) {
31
        if (type.equals("organization")) {
32
            type = "institution";
33
        } else if (type.equals("ri") && communityMap) {
34
            type = "community";
35
        }
36
        return type;
37
    }
38

  
39
    public JsonElement assignMemberRole(String type, String id, HttpServletRequest request) throws HttpClientErrorException {
40
        return this.httpUtils.post(url + "/member/" + mapType(type, false) + "/" + id, getSessionCookie(request), null, null);
41
    }
42

  
43
    public JsonElement assignManagerRole(String type, String id, HttpServletRequest request) throws HttpClientErrorException {
44
        Map<String, String> params = new HashMap<>();
45
        params.put("force", "true");
46
        return this.httpUtils.post(url + "/admin/" + mapType(type, true) + "/" + id, getSessionCookie(request), null, params);
47
    }
48

  
49
    public JsonElement removeMemberRole(String type, String id, HttpServletRequest request) throws HttpClientErrorException {
50
        Map<String, String> params = new HashMap<>();
51
        params.put("force", "true");
52
        return this.httpUtils.delete(url + "/member/" + mapType(type, false) + "/" + id, getSessionCookie(request), params);
53
    }
54

  
55
    public JsonElement removeMemberRole(String type, String id, String email) throws HttpClientErrorException {
56
        Map<String, String> params = new HashMap<>();
57
        params.put("email", email);
58
        return this.httpUtils.delete(url + "/member/" + mapType(type, false) + "/" + id, null, params);
59
    }
60

  
61
    public JsonElement removeManagerRole(String type, String id, HttpServletRequest request) throws HttpClientErrorException {
62
        return this.httpUtils.delete(url + "/admin/" + mapType(type, true) + "/" + id, getSessionCookie(request), null);
63
    }
64

  
65
    public JsonElement removeManagerRole(String type, String id, String email) throws HttpClientErrorException {
66
        Map<String, String> params = new HashMap<>();
67
        params.put("email", email);
68
        return this.httpUtils.delete(url + "/admin/" + mapType(type, true) + "/" + id, null, params);
69
    }
70

  
71
    public JsonElement getAllMembers(String type, String id) throws HttpClientErrorException {
72
        return this.httpUtils.get(url + "/member/" + mapType(type, false) + "/" + id, null, null);
73
    }
74

  
75
    public int getAllMembersCount(String type, String id) throws HttpClientErrorException {
76
        return this.httpUtils.get(url + "/member/" + mapType(type, false) + "/" + id + "/count", null, null).getAsInt();
77
    }
78

  
79
    public JsonElement getAllManagers(String type, String id) throws HttpClientErrorException {
80
        Map<String, String> params = new HashMap<>();
81
        if(!authorizationService.isPortalAdmin() && !authorizationService.isCurator(type) && !authorizationService.isManager(type, id)) {
82
            params.put("name", "false");
83
            params.put("email", "false");
84
        }
85
        return this.httpUtils.get(url + "/admin/" + mapType(type, true) + "/" + id, null, params);
86
    }
87

  
88
    public JsonElement getAllCurators(String type) throws HttpClientErrorException {
89
        return this.httpUtils.get(url + "/curator/" + mapType(type, false), null, null);
90
    }
91

  
92
    public boolean isMember(String type, String id, String email) throws HttpClientErrorException {
93
        for (JsonElement element : this.httpUtils.get(url + "/member/" + mapType(type, false) + "/" + id, null, null).getAsJsonArray()) {
94
            if (element.getAsJsonObject().get("email").getAsString().equalsIgnoreCase(email)) {
95
                return true;
96
            }
97
        }
98
        return false;
99
    }
100

  
101
    public boolean isManager(String type, String id, String email) throws HttpClientErrorException {
102
        for (JsonElement element : this.httpUtils.get(url + "/admin/" + mapType(type, true) + "/" + id, null, null).getAsJsonArray()) {
103
            if (element.getAsJsonObject().get("email").getAsString().equalsIgnoreCase(email)) {
104
                return true;
105
            }
106
        }
107
        return false;
108
    }
109

  
110
    public JsonElement createMemberRole(String type, String id) {
111
        Map<String, String> params = new HashMap<>();
112
        params.put("description", mapType(type, false) + " " + id);
113
        return this.httpUtils.post(url + "/member/" + mapType(type, false) + "/" + id + "/create", null, null, params);
114
    }
115

  
116
    public JsonElement createCuratorRole(String type) {
117
        Map<String, String> params = new HashMap<>();
118
        params.put("description", mapType(type, false) + " Curator");
119
        return this.httpUtils.post(url + "/curator/" + mapType(type, false) + "/create", null, null, params);
120
    }
121

  
122
    public JsonElement createRole(String name, String description) {
123
        Map<String, String> params = new HashMap<>();
124
        params.put("name", name);
125
        params.put("description", description);
126
        return this.httpUtils.post(url + "/super/create", null, null, params);
127
    }
128

  
129
    private String getSessionCookie(HttpServletRequest request) {
130
        return httpUtils.getCookie(request, "openAIRESession");
131
    }
132
}
modules/dnet-openaire-users/branches/prod/src/main/resources/eu/dnet/openaire/usermanagement/springContext-dnetOpenaireUsersService.properties
1 1
google.recaptcha.secret = 6LfYrU8UAAAAADwrbImPvDo_XcxEZvrkkgMy9yU0
2 2
google.recaptcha.key = 6LfYrU8UAAAAAFsl3m2YhP1uavdmAdFEXBkoY_vd
3 3

  
4
registry.issuer = https://openaire-dev.aai-dev.grnet.gr/registry
5
registry.user = user
6
registry.password = pass
7
registry.version = 1.0
8
registry.coid = 2
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff