use of io.gravitee.rest.api.service.exceptions.InvitationEmailAlreadyExistsException in project gravitee-management-rest-api by gravitee-io.
the class InvitationServiceImpl method create.
@Override
public InvitationEntity create(final NewInvitationEntity invitation) {
final List<InvitationEntity> invitations = findByReference(invitation.getReferenceType(), invitation.getReferenceId());
if (invitations.stream().map(InvitationEntity::getEmail).anyMatch(invitation.getEmail()::equals)) {
throw new InvitationEmailAlreadyExistsException(invitation.getEmail());
}
try {
// First check if user exists
final Optional<UserEntity> existingUser = userService.findByEmail(invitation.getEmail());
if (existingUser.isPresent()) {
final UserEntity user = existingUser.get();
Set<String> groupUsers = membershipService.getMembershipsByReference(MembershipReferenceType.GROUP, invitation.getReferenceId()).stream().map(MembershipEntity::getMemberId).collect(Collectors.toSet());
final GroupEntity group = groupService.findById(invitation.getReferenceId());
if (groupUsers.contains(user.getId())) {
throw new MemberEmailAlreadyExistsException(invitation.getEmail());
}
// override permission if not allowed
final boolean hasPermission = permissionService.hasPermission(RolePermission.ENVIRONMENT_GROUP, GraviteeContext.getCurrentEnvironment(), CREATE, UPDATE, DELETE);
if (!hasPermission && group.isLockApiRole()) {
invitation.setApiRole(null);
}
if (!hasPermission && group.isLockApplicationRole()) {
invitation.setApplicationRole(null);
}
addMember(invitation.getReferenceType().name(), invitation.getReferenceId(), user.getId(), invitation.getApiRole(), invitation.getApplicationRole());
return null;
} else {
sendGroupInvitationEmail(invitation);
final Invitation createdInvitation = invitationRepository.create(convert(invitation));
return convert(createdInvitation);
}
} catch (TechnicalException ex) {
final String message = "An error occurs while trying to create invitation for email " + invitation.getEmail();
LOGGER.error(message, ex);
throw new TechnicalManagementException(message, ex);
}
}
Aggregations