-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathInvitationController.java
More file actions
574 lines (537 loc) · 32 KB
/
InvitationController.java
File metadata and controls
574 lines (537 loc) · 32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
package invite.api;
import invite.audit.UserRoleAuditService;
import invite.exception.InvitationEmailMatchingException;
import invite.exception.InvitationExpiredException;
import invite.exception.InvitationStatusException;
import invite.exception.InvitationUniqueCrmOrganisationException;
import invite.exception.NotFoundException;
import invite.logging.AccessLogger;
import invite.logging.Event;
import invite.mail.MailBox;
import invite.manage.Manage;
import invite.model.AcceptInvitation;
import invite.model.Authority;
import invite.model.Invitation;
import invite.model.InvitationRequest;
import invite.model.InvitationResponse;
import invite.model.InvitationRole;
import invite.model.Role;
import invite.model.Status;
import invite.model.StatusResponse;
import invite.model.User;
import invite.model.UserRole;
import invite.model.UserRoleAudit;
import invite.provision.Provisioning;
import invite.provision.ProvisioningService;
import invite.provision.graph.GraphResponse;
import invite.provision.scim.OperationType;
import invite.repository.InvitationRepository;
import invite.repository.RoleRepository;
import invite.repository.UserRepository;
import invite.security.SuperAdmin;
import invite.security.UserPermissions;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Getter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import static invite.SwaggerOpenIdConfig.API_TOKENS_SCHEME_NAME;
import static invite.SwaggerOpenIdConfig.OPEN_ID_SCHEME_NAME;
import static java.util.Collections.emptyList;
@RestController
@RequestMapping(value = {
"/api/v1/invitations",
"/api/external/v1/invitations"}
, produces = MediaType.APPLICATION_JSON_VALUE)
@Transactional
@SecurityRequirement(name = OPEN_ID_SCHEME_NAME, scopes = {"openid"})
@SecurityRequirement(name = API_TOKENS_SCHEME_NAME)
@EnableConfigurationProperties(SuperAdmin.class)
public class InvitationController implements InvitationResource {
private static final Log LOG = LogFactory.getLog(InvitationController.class);
@Getter
private final MailBox mailBox;
@Getter
private final Manage manage;
@Getter
private final InvitationRepository invitationRepository;
@Getter
private final RoleRepository roleRepository;
private final UserRepository userRepository;
private final ProvisioningService provisioningService;
private final SecurityContextRepository securityContextRepository;
private final SuperAdmin superAdmin;
private final InvitationOperations invitationOperations;
private final UserRoleAuditService userRoleAuditService;
public InvitationController(MailBox mailBox,
Manage manage,
InvitationRepository invitationRepository,
UserRepository userRepository,
RoleRepository roleRepository,
ProvisioningService provisioningService,
SecurityContextRepository securityContextRepository,
SuperAdmin superAdmin, UserRoleAuditService userRoleAuditService) {
this.mailBox = mailBox;
this.manage = manage;
this.invitationRepository = invitationRepository;
this.userRepository = userRepository;
this.roleRepository = roleRepository;
this.provisioningService = provisioningService;
this.securityContextRepository = securityContextRepository;
this.superAdmin = superAdmin;
this.invitationOperations = new InvitationOperations(this);
this.userRoleAuditService = userRoleAuditService;
}
@PostMapping("")
@Operation(summary = "Invite member for existing Role",
description = """
Invite a member for an existing role. An invitation email will be sent. Do not forget to set guestRoleIncluded to true.
At least one email must be either present in invites or invitesWithInternalPlaceholderIdentifiers.
When using the invitations you can also specify the
internalPlaceholderIdentifier, which will be used as the id in the SCIM POST to /User.
""",
requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
required = true,
content = {@Content(
mediaType = "application/json",
schema = @Schema(implementation = InvitationRequest.class),
examples = {@ExampleObject(value = """
{
"intendedAuthority": "INVITER",
"message": "Personal message included in the email",
"language": "en",
"guestRoleIncluded": true,
"invites": [
"admin@service.org"
],
"invitesWithInternalPlaceholderIdentifiers": [
{
"email": "admin2@service.org",
"internalPlaceholderIdentifier": "4EFF937F-EE78-4A54-9FD8-A214FD64D7E1"
}
],
"roleIdentifiers": [
99
],
"roleExpiryDate": 1760788376,
"expiryDate": 1730461976
}
"""
)}
)}
),
responses = {
@ApiResponse(responseCode = "201", description = "Created",
content = {@Content(
mediaType = "application/json",
schema = @Schema(implementation = InvitationResponse.class),
examples = {@ExampleObject(value = """
{
"status": 201,
"recipientInvitationURLs": [
{
"recipient": "admin@service.nl",
"invitationURL": "https://invite.test.surfconext.nl/invitation/accept?{hash}"
}
]
}
"""
)})}),
@ApiResponse(responseCode = "400", description = "BadRequest",
content = {@Content(
mediaType = "application/json",
schema = @Schema(implementation = StatusResponse.class),
examples = {
@ExampleObject(value = """
{
"timestamp": 1717672263253,
"status": 400,
"error": "BadRequest",
"exception": "access.exception.UserRestrictionException",
"message": "No access to application",
"path": "/api/internal/invite/invitations"
}
"""
)})}),
@ApiResponse(responseCode = "404", description = "Role not found",
content = {@Content(
mediaType = "application/json",
schema = @Schema(implementation = StatusResponse.class),
examples = {@ExampleObject(value = """
{
"timestamp": 1717672263253,
"status": 404,
"error": "Not found",
"exception": "access.exception.NotFoundException",
"message": "Role not found",
"path": "/api/internal/invite/invitations"
}
"""
)})})})
public ResponseEntity<InvitationResponse> newInvitation(@Validated @RequestBody InvitationRequest invitationRequest,
@Parameter(hidden = true) User user) {
LOG.debug(String.format("New invitation request by user %s", user.getEduPersonPrincipalName()));
return this.invitationOperations.sendInvitation(invitationRequest, user, null);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteInvitation(@PathVariable("id") Long id,
@Parameter(hidden = true) User user) {
LOG.debug(String.format("/deleteInvitation/%s by user %s", id, user.getEduPersonPrincipalName()));
//We need to assert validations on the roles soo we need to load them
Invitation invitation = invitationRepository.findById(id).orElseThrow(() -> new NotFoundException("Invitation not found"));
List<Role> requestedRoles = invitation.getRoles().stream()
.map(InvitationRole::getRole).toList();
Authority intendedAuthority = invitation.getIntendedAuthority();
UserPermissions.assertValidInvitation(user, intendedAuthority, requestedRoles);
AccessLogger.invitation(LOG, Event.Deleted, invitation);
invitationRepository.delete(invitation);
return Results.deleteResult();
}
@PutMapping("/{id}")
public ResponseEntity<Map<String, Integer>> resendInvitation(@PathVariable("id") Long id,
@Parameter(hidden = true) User user) {
LOG.debug(String.format("ResendInvitation with id %s by user %s ", id, user.getEduPersonPrincipalName()));
return this.invitationOperations.resendInvitation(id, user, null);
}
@GetMapping("public")
@Transactional(readOnly = true)
public ResponseEntity<Invitation> getInvitation(@RequestParam("hash") String hash) {
LOG.debug(String.format("getInvitation with hash %s", hash));
Invitation invitation = invitationRepository.findByHash(hash).orElseThrow(() -> new NotFoundException("Invitation not found"));
if (!invitation.getStatus().equals(Status.OPEN)) {
throw new InvitationStatusException("Invitation is not OPEN anymore");
}
manage.addManageMetaData(invitation.getRoles().stream().map(InvitationRole::getRole).toList());
return ResponseEntity.ok(invitation);
}
@GetMapping("all")
@Transactional(readOnly = true)
public ResponseEntity<List<Invitation>> all(@Parameter(hidden = true) User user) {
LOG.debug("GET /all invitations");
UserPermissions.assertAuthority(user, Authority.SUPER_USER);
return ResponseEntity.ok(invitationRepository.findByStatus(Status.OPEN));
}
@PostMapping("accept")
public ResponseEntity<Map<String, Object>> accept(@Validated @RequestBody AcceptInvitation acceptInvitation,
Authentication authentication,
HttpServletRequest servletRequest,
HttpServletResponse servletResponse) {
Invitation invitation = invitationRepository.findByHash(acceptInvitation.hash())
.orElseThrow(() -> new NotFoundException("Invitation not found"));
LOG.debug("POST /accept invitation");
if (!invitation.getId().equals(acceptInvitation.invitationId())) {
throw new NotFoundException("Invitation not found");
}
if (!invitation.getStatus().equals(Status.OPEN)) {
throw new InvitationStatusException("Invitation is not OPEN anymore");
}
if (invitation.getExpiryDate().isBefore(Instant.now())) {
throw new InvitationExpiredException("Invitation has expired");
}
OAuth2AuthenticationToken token = (OAuth2AuthenticationToken) authentication;
Map<String, Object> attributes = token.getPrincipal().getAttributes();
String sub = (String) attributes.get("sub");
LOG.info(String.format("Accept invitation with id %s by user %s", invitation.getId(), sub));
Optional<User> optionalUser = userRepository.findBySubIgnoreCase(sub);
Authority intendedAuthority = invitation.getIntendedAuthority();
User user = optionalUser.orElseGet(() -> {
boolean superUser = this.superAdmin.getUsers().stream().anyMatch(superSub -> superSub.equals(sub))
|| intendedAuthority.equals(Authority.SUPER_USER);
return new User(superUser, attributes);
});
checkEmailEquality(user, invitation);
checkCrmUniqueOrganisation(user, invitation);
user.setLastActivity(Instant.now());
invitation.setStatus(Status.ACCEPTED);
invitation.setAcceptedAt(Instant.now());
invitation.setSubInvitee(sub);
invitationRepository.save(invitation);
AccessLogger.invitation(LOG, Event.Accepted, invitation);
/*
* Chicken & egg problem. The user including his / hers roles must be first provisioned, and then we
* need to send the updateRoleRequests for each new Role of this user.
*/
List<UserRole> newUserRoles = new ArrayList<>();
User inviter = invitation.getInviter();
invitation.getRoles()
.forEach(invitationRole -> {
Role role = invitationRole.getRole();
Optional<UserRole> optionalUserRole = user.getUserRoles().stream()
.filter(userRole -> userRole.getRole().getId().equals(role.getId())).findFirst();
if (optionalUserRole.isPresent()) {
UserRole userRole = optionalUserRole.get();
Authority currentAuthority = userRole.getAuthority();
//Only act upon different authorities
if (!currentAuthority.equals(intendedAuthority)) {
boolean userRoleChanged = false;
if (intendedAuthority.hasHigherRights(currentAuthority)) {
userRole.setAuthority(intendedAuthority);
userRole.setEndDate(invitation.getRoleExpiryDate());
userRoleChanged = true;
}
if (currentAuthority.equals(Authority.GUEST) || intendedAuthority.equals(Authority.GUEST) ||
invitation.isGuestRoleIncluded()) {
userRole.setGuestRoleIncluded(true);
userRoleChanged = true;
}
if (userRoleChanged) {
userRoleAuditService.logAction(userRole, UserRoleAudit.ActionType.UPDATE);
}
}
} else {
UserRole userRole = new UserRole(
inviter != null ? inviter.getName() : invitation.getRemoteApiUser(),
user,
role,
intendedAuthority,
invitation.isGuestRoleIncluded(),
invitation.getRoleExpiryDate());
user.addUserRole(userRole);
newUserRoles.add(userRole);
}
});
if (intendedAuthority.equals(Authority.INSTITUTION_ADMIN) && inviter != null) {
user.setInstitutionAdmin(true);
user.setInstitutionAdminByInvite(true);
//Might be that a super-user has invited the institution admin or a different institution admin
if (inviter.isSuperUser()) {
user.setOrganizationGUID(invitation.getOrganizationGUID());
} else {
user.setOrganizationGUID(inviter.getOrganizationGUID());
}
//Rare case - a new institution admin has logged in, but was not yet enriched by the CustomOidcUserService
if (optionalUser.isEmpty()) {
saveOAuth2AuthenticationToken(authentication, user, servletRequest, servletResponse);
}
}
user.setInternalPlaceholderIdentifier(invitation.getInternalPlaceholderIdentifier());
userRepository.save(user);
AccessLogger.user(LOG, Event.Created, user);
newUserRoles.forEach(userRole -> userRoleAuditService.logAction(userRole, UserRoleAudit.ActionType.ADD));
//Only interact with the provisioning service if there is a guest role
boolean isGuest = user.getUserRoles().stream()
.anyMatch(userRole -> userRole.isGuestRoleIncluded() || userRole.getAuthority().equals(Authority.GUEST));
//Already provisioned users in the remote systems are ignored / excluded
Optional<GraphResponse> optionalGraphResponse = isGuest ? provisioningService.newUserRequest(user) : Optional.empty();
if (isGuest) {
newUserRoles.forEach(userRole -> provisioningService.updateGroupRequest(userRole, OperationType.add));
}
LOG.info(String.format("User %s accepted invitation with role(s) %s",
user.getEduPersonPrincipalName(),
invitation.getRoles().stream().map(role -> role.getRole().getName()).collect(Collectors.joining(", "))));
//Must be mutable, because of possible userWaitTime
Map<String, Object> body = new HashMap<>();
optionalGraphResponse.ifPresentOrElse(graphResponse -> {
if (graphResponse.isErrorResponse()) {
body.put("errorResponse", Boolean.TRUE);
} else {
body.put("inviteRedeemUrl", graphResponse.inviteRedeemUrl());
}
}, () -> body.put("status", "ok"));
if (!isGuest) {
//We are done then
return ResponseEntity.status(HttpStatus.CREATED).body(body);
}
// See if there is a userWaitTime on of the provisionings
List<Provisioning> provisionings = provisioningService.getProvisionings(newUserRoles);
provisionings.stream()
.filter(provisioning -> provisioning.getUserWaitTime() != null)
.max(Comparator.comparingInt(Provisioning::getUserWaitTime))
.ifPresent(provisioning -> {
Set<String> manageIdentifiers = provisioning.getRemoteApplications().stream()
.map(app -> app.manageId()).collect(Collectors.toSet());
newUserRoles.stream()
.map(userRole -> userRole.getRole())
.filter(role -> role.getApplicationUsages().stream()
.anyMatch(appUsage -> manageIdentifiers.contains(appUsage.getApplication().getManageId())))
.min(Comparator.comparing(Role::getName))
.ifPresent(role -> {
body.put("userWaitTime", provisioning.getUserWaitTime());
body.put("role", role.getName());
});
});
return ResponseEntity.status(HttpStatus.CREATED).body(body);
}
private void saveOAuth2AuthenticationToken(Authentication authentication,
User user,
HttpServletRequest servletRequest,
HttpServletResponse servletResponse) {
//Boilerplate code for setting updated Authentication on the SecurityContextHolder
OAuth2AuthenticationToken existingToken = (OAuth2AuthenticationToken) authentication;
DefaultOidcUser existingTokenPrincipal = (DefaultOidcUser) existingToken.getPrincipal();
//Claims of the tokenPrincipal are immutable, so we need to instantiate a new Map
Map<String, Object> claims = new HashMap<>(existingTokenPrincipal.getClaims());
claims.putAll(manage.enrichInstitutionAdmin(user.getOrganizationGUID(), claims));
DefaultOidcUser oidcUser = new DefaultOidcUser(
existingToken.getAuthorities(),
existingTokenPrincipal.getIdToken(),
new OidcUserInfo(claims)
);
OAuth2AuthenticationToken newToken = new OAuth2AuthenticationToken(
oidcUser,
existingToken.getAuthorities(),
existingToken.getAuthorizedClientRegistrationId()
);
SecurityContextHolder.getContext().setAuthentication(newToken);
//New in Spring security 6.x,
// See https://docs.spring.io/spring-security/reference/5.8/migration/servlet/session-management.html#_require_explicit_saving_of_securitycontextrepository
securityContextRepository.saveContext(SecurityContextHolder.getContext(), servletRequest, servletResponse);
}
@GetMapping("roles/{roleId}")
public ResponseEntity<List<Invitation>> byRole(@PathVariable("roleId") Long roleId, @Parameter(hidden = true) User user) {
LOG.debug(String.format("GET /roles/%s by user %s", roleId, user.getEduPersonPrincipalName()));
Role role = roleRepository.findById(roleId).orElseThrow(() -> new NotFoundException("Role not found"));
UserPermissions.assertRoleAccess(user, role, Authority.INVITER);
List<Invitation> invitations = invitationRepository.findByStatusAndRoles_role(Status.OPEN, role);
return ResponseEntity.ok(invitations);
}
@GetMapping("search")
@Transactional(readOnly = true)
public ResponseEntity<Page<Map<String, Object>>> search(@Parameter(hidden = true) User user,
@RequestParam(value = "roleId", required = false) Long roleId,
@RequestParam(value = "query", required = false, defaultValue = "") String query,
@RequestParam(value = "pageNumber", required = false, defaultValue = "0") int pageNumber,
@RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize,
@RequestParam(value = "sort", required = false, defaultValue = "name") String sort,
@RequestParam(value = "sortDirection", required = false, defaultValue = "ASC") String sortDirection) {
LOG.debug(String.format("GET /search for invitations %s", user.getEduPersonPrincipalName()));
Page<Map<String, Object>> invitationsPage;
Pageable pageable = PageRequest.of(pageNumber, pageSize, Sort.by(Sort.Direction.fromString(sortDirection), sort));
boolean queryHasText = StringUtils.hasText(query);
query = queryHasText ? URLDecoder.decode(query, Charset.defaultCharset()) : query;
String parsedQuery = queryHasText ? FullSearchQueryParser.parse(query) : "";
boolean noSearchTokens = parsedQuery.equals("*");
if (roleId == null) {
UserPermissions.assertSuperUser(user);
if (queryHasText && !noSearchTokens) {
invitationsPage = invitationRepository.searchByStatusPageWithKeyword(Status.OPEN.name(), parsedQuery, pageable);
} else if (noSearchTokens) {
//Rare condition if users search on kb.nl, at@ex where all the parsed tokens are < 3 characters
query = query.toUpperCase() + "%";
invitationsPage = invitationRepository.searchByStatusPageWithStrictSearch(Status.OPEN.name(), query, pageable);
} else {
invitationsPage = invitationRepository.searchByStatusPage(Status.OPEN.name(), pageable);
}
} else {
Role role = roleRepository.findById(roleId).orElseThrow(() -> new NotFoundException("Role not found"));
UserPermissions.assertRoleAccess(user, role, Authority.INVITER);
if (queryHasText && !noSearchTokens) {
invitationsPage = invitationRepository.searchByStatusAndRoleWithKeywordPage(Status.OPEN.name(), role.getId(), parsedQuery, pageable);
} else if (noSearchTokens) {
//Rare condition if users search on kb.nl, at@ex where all the parsed tokens are < 3 characters
query = query.toUpperCase() + "%";
invitationsPage = invitationRepository.searchByStatusAndRoleWithStrictSearch(Status.OPEN.name(), role.getId(), query, pageable);
} else {
invitationsPage = invitationRepository.searchByStatusAndRolePage(Status.OPEN.name(), role.getId(), pageable);
}
}
if (invitationsPage.getTotalElements() == 0L) {
return ResponseEntity.ok(invitationsPage);
}
List<Long> invitationIdentifiers = invitationsPage.getContent().stream()
.map(m -> (Long) m.get("id")).toList();
//The rolesAndManageIdentifiers is a cartesian product, but the relationship between invitation, role and application is mainly 1-1-1
List<Map<String, Object>> rolesAndManageIdentifiers = invitationRepository.findRoles(invitationIdentifiers);
Map<Long, List<Map<String, Object>>> rolesGroupedByInvitation = rolesAndManageIdentifiers
.stream()
.collect(Collectors.groupingBy(m -> (Long) m.get("id")));
//We need to add all roles, but also a list of manageIdentifiers for each role
List<Map<String, Object>> invitations = invitationsPage.getContent()
.stream()
//Must copy to avoid java.lang.UnsupportedOperationException: A TupleBackedMap cannot be modified
.map(invitationMap -> {
Map<String, Object> copy = new HashMap<>(invitationMap);
List<Map<String, Object>> aggregatedRoles = rolesGroupedByInvitation.get((Long) invitationMap.get("id"));
//For Invitations for SuperUsers and InstitutionAdmins have no userRoles
if (CollectionUtils.isEmpty(aggregatedRoles)) {
copy.put("roles", emptyList());
return copy;
}
Map<Long, List<Map<String, Object>>> rolesGroupedByRole = aggregatedRoles
.stream()
.collect(Collectors.groupingBy(m -> (Long) m.get("role_id")));
List<Map<String, Object>> roles = rolesGroupedByRole
.entrySet()
.stream()
.map(entry -> Map.of(
"id", entry.getKey(),
"name", entry.getValue().getFirst().get("name"),
"manageIdentifiers", entry.getValue().stream().map(m -> m.get("manage_id")).toList()
))
.toList();
copy.put("roles", roles);
return copy;
})
.toList();
return Pagination.of(invitationsPage, invitations);
}
private void checkEmailEquality(User user, Invitation invitation) {
if (invitation.isEnforceEmailEquality() && !invitation.getEmail().equalsIgnoreCase(user.getEmail())) {
throw new InvitationEmailMatchingException(
String.format("Invitation email %s does not match user email %s", invitation.getEmail(), user.getEmail()));
}
}
private void checkCrmUniqueOrganisation(User user, Invitation invitation) {
if (StringUtils.hasText(invitation.getCrmContactId()) && user.getUserRoles().stream()
.map(userRole -> userRole.getRole().getCrmOrganisationId())
.anyMatch(crmOrganisationId -> StringUtils.hasText(crmOrganisationId) &&
invitation.getRoles().stream()
.map(invitationRole -> invitationRole.getRole())
.anyMatch(role -> StringUtils.hasText(role.getCrmOrganisationId()) && !role.getCrmOrganisationId().equals(crmOrganisationId)))) {
throw new InvitationUniqueCrmOrganisationException(
String.format("User %s is not allowed to accept an invitation from Organisation %s, because it already has roles for Organisation %s",
user.getEmail(),
user.getUserRoles().stream()
.map(userRole -> userRole.getRole().getCrmOrganisationId())
.toList(),
invitation.getRoles().stream()
.map(invitationRole -> invitationRole.getRole().getCrmOrganisationId())
.toList()));
}
}
}