use of org.molgenis.data.security.auth.GroupMember in project molgenis by molgenis.
the class AccountServiceImpl method createUser.
@Override
@RunAsSystem
@Transactional
public void createUser(User user, String baseActivationUri) throws UsernameAlreadyExistsException, EmailAlreadyExistsException {
// Check if username already exists
if (userService.getUser(user.getUsername()) != null) {
throw new UsernameAlreadyExistsException("Username '" + user.getUsername() + "' already exists.");
}
// Check if email already exists
if (userService.getUserByEmail(user.getEmail()) != null) {
throw new EmailAlreadyExistsException("Email '" + user.getEmail() + "' is already registered.");
}
// collect activation info
String activationCode = idGenerator.generateId(SECURE_RANDOM);
List<String> activationEmailAddresses;
if (authenticationSettings.getSignUpModeration()) {
activationEmailAddresses = userService.getSuEmailAddresses();
if (activationEmailAddresses == null || activationEmailAddresses.isEmpty())
throw new MolgenisDataException("Administrator account is missing required email address");
} else {
String activationEmailAddress = user.getEmail();
if (activationEmailAddress == null || activationEmailAddress.isEmpty())
throw new MolgenisDataException("User '" + user.getUsername() + "' is missing required email address");
activationEmailAddresses = asList(activationEmailAddress);
}
// create user
user.setActivationCode(activationCode);
user.setActive(false);
dataService.add(USER, user);
LOG.debug("created user " + user.getUsername());
// add user to group
Group group = dataService.query(GROUP, Group.class).eq(NAME, ALL_USER_GROUP).findOne();
GroupMember groupMember = null;
if (group != null) {
groupMember = groupMemberFactory.create();
groupMember.setGroup(group);
groupMember.setUser(user);
dataService.add(GROUP_MEMBER, groupMember);
}
// send activation email
URI activationUri = URI.create(baseActivationUri + '/' + activationCode);
try {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setTo(activationEmailAddresses.toArray(new String[] {}));
mailMessage.setSubject("User registration for " + appSettings.getTitle());
mailMessage.setText(createActivationEmailText(user, activationUri));
mailSender.send(mailMessage);
} catch (MailException mce) {
LOG.error("Could not send signup mail", mce);
if (groupMember != null) {
dataService.delete(GROUP_MEMBER, groupMember);
}
dataService.delete(USER, user);
throw new MolgenisUserException("An error occurred. Please contact the administrator. You are not signed up!");
}
LOG.debug("send activation email for user " + user.getUsername() + " to " + StringUtils.join(activationEmailAddresses, ','));
}
Aggregations