UserViewData(User mu) { this(mu.getId(), mu.getUsername()); firstName = (null == mu.getFirstName() ? "" : mu.getFirstName()); middleName = (null == mu.getMiddleNames() ? "" : mu.getMiddleNames()); lastName = (null == mu.getLastName() ? "" : mu.getLastName()); fullName = firstName + ' ' + middleName + ' ' + lastName; this.active = mu.isActive(); this.superuser = mu.isSuperuser(); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication instanceof UsernamePasswordAuthenticationToken && authentication.isAuthenticated() && !authentication.getName().equals(ANONYMOUS_USERNAME) && !httpRequest.getRequestURI().equalsIgnoreCase(CHANGE_PASSWORD_URI)) { User user = userService.getUser(authentication.getName()); if (user == null) { throw new RuntimeException("Unknown username [" + authentication.getName() + "]"); } if (user.isChangePassword() != null && user.isChangePassword()) { redirectStrategy.sendRedirect(httpRequest, httpResponse, CHANGE_PASSWORD_URI); return; } } chain.doFilter(request, response); } }
private User createUser(OidcUser oidcUser) { User user = userFactory.create(); user.setUsername(oidcUser.getEmail()); user.setPassword(UUID.randomUUID().toString()); user.setEmail(oidcUser.getEmail()); user.setActive(true); user.setFirstName(oidcUser.getGivenName()); user.setLastName(oidcUser.getFamilyName()); dataService.add(UserMetaData.USER, user); return user; }
private String createActivatedEmailText(User user, String appName) { return "Dear " + user.getFirstName() + " " + user.getLastName() + ",\n\n" + "your registration request for " + appName + " was approved.\n" + "Your account is now active.\n"; }
static UserResponse fromEntity(User user) { return new AutoValue_UserResponse(user.getId(), user.getUsername()); } }
@RunAsSystem public Collection<? extends GrantedAuthority> getAuthorities(User user) { Set<GrantedAuthority> authorities = new LinkedHashSet<>(); if (user.isSuperuser() != null && user.isSuperuser()) { authorities.add(new SimpleGrantedAuthority(SecurityUtils.AUTHORITY_SU)); } if (user.getUsername().equals(SecurityUtils.ANONYMOUS_USERNAME)) { authorities.add(new SimpleGrantedAuthority(SecurityUtils.AUTHORITY_ANONYMOUS)); } else { authorities.add(new SimpleGrantedAuthority(AUTHORITY_USER)); } dataService .query(ROLE_MEMBERSHIP, RoleMembership.class) .eq(USER, user) .findAll() .filter(RoleMembership::isCurrent) .map(RoleMembership::getRole) .map(Role::getName) .map(SidUtils::createRoleAuthority) .map(SimpleGrantedAuthority::new) .forEach(authorities::add); return grantedAuthoritiesMapper.mapAuthorities(authorities); } }
User.class); if (user.isChangePassword()) { throw new BadCredentialsException( "Unable to log in because a password reset is required. Sign in to the website to reset your password."); tokenService.generateAndStoreToken(authentication.getName(), "REST API login"); return new LoginResponse( token, user.getUsername(), user.getFirstName(), user.getLastName()); });
private String createActivationEmailText(User user, URI activationUri) { return "User registration for " + appSettings.getTitle() + '\n' + "User name: " + user.getUsername() + " Full name: " + user.getFirstName() + ' ' + user.getLastName() + '\n' + "In order to activate the user visit the following URL:" + '\n' + activationUri + '\n' + '\n'; }
@GetMapping public String init(Model model) { model.addAttribute("username", userAccountService.getCurrentUser().getUsername()); return "view-jobs"; }
throws UsernameAlreadyExistsException, EmailAlreadyExistsException { if (userService.getUser(user.getUsername()) != null) { throw new UsernameAlreadyExistsException( "Username '" + user.getUsername() + "' already exists."); if (userService.getUserByEmail(user.getEmail()) != null) { throw new EmailAlreadyExistsException( "Email '" + user.getEmail() + "' is already registered."); 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 = singletonList(activationEmailAddress); user.setActivationCode(activationCode); user.setActive(false); dataService.add(USER, user); LOG.debug("created user {}", user.getUsername()); LOG.debug( "send activation email for user {} to {}", user.getUsername(), StringUtils.join(activationEmailAddresses, ','));
/** * Formats a MolgenisUser's name. * * @return String containing the user's first name, middle names and last name. */ private static String getFormattedName(User user) { List<String> parts = new ArrayList<>(); if (user.getTitle() != null) { parts.add(user.getTitle()); } if (user.getFirstName() != null) { parts.add(user.getFirstName()); } if (user.getMiddleNames() != null) { parts.add(user.getMiddleNames()); } if (user.getLastName() != null) { parts.add(user.getLastName()); } if (parts.isEmpty()) { return null; } else { return StringUtils.collectionToDelimitedString(parts, " "); } }
@Override @RunAsSystem public UserDetails loadUserByUsername(String username) { User user = dataService .query(UserMetaData.USER, User.class) .eq(UserMetaData.USERNAME, username) .findOne(); if (user == null) { throw new UsernameNotFoundException("unknown user '" + username + "'"); } Collection<? extends GrantedAuthority> authorities = getAuthorities(user); return new org.springframework.security.core.userdetails.User( user.getUsername(), user.getPassword(), user.isActive(), true, true, true, authorities); }
@Override @RunAsSystem public void resetPassword(String userEmail) { User user = dataService.query(USER, User.class).eq(EMAIL, userEmail).findOne(); if (user != null) { if (!user.isActive()) { throw new DisabledException(MolgenisLoginController.ERROR_MESSAGE_DISABLED); } String newPassword = idGenerator.generateId(SHORT_SECURE_RANDOM); user.setPassword(newPassword); user.setChangePassword(true); dataService.update(USER, user); // send password reseted email to user SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setTo(user.getEmail()); mailMessage.setSubject("Your new password request"); mailMessage.setText(createPasswordResettedEmailText(newPassword)); mailSender.send(mailMessage); } else { throw new MolgenisUserException("Invalid email address."); } }
@Override @RunAsSystem public void changePassword(String username, String newPassword) { User user = dataService.query(USER, User.class).eq(USERNAME, username).findOne(); if (user == null) { throw new MolgenisUserException(format("Unknown user [%s]", username)); } if (!user.isActive()) { throw new DisabledException(MolgenisLoginController.ERROR_MESSAGE_DISABLED); } user.setPassword(newPassword); user.setChangePassword(false); dataService.update(USER, user); LOG.info("Changed password of user [{}]", username); }
@ApiOperation("Show account") @ApiResponses({ @ApiResponse(code = 200, message = "Return the view of the account", response = String.class) }) @GetMapping public String showAccount( Model model, @RequestParam(value = "showCodes", defaultValue = "false") boolean showCodes) { TwoFactorAuthenticationSetting twoFactorAuthenticationApp = authenticationSettings.getTwoFactorAuthentication(); boolean isTwoFactorAuthenticationEnableForUser = userAccountService.getCurrentUser().isTwoFactorAuthentication(); model.addAttribute("user", userAccountService.getCurrentUser()); model.addAttribute("countries", CountryCodes.get()); model.addAttribute("min_password_length", MIN_PASSWORD_LENGTH); model.addAttribute("two_factor_authentication_app_option", twoFactorAuthenticationApp); model.addAttribute( "two_factor_authentication_user_enabled", isTwoFactorAuthenticationEnableForUser); model.addAttribute("show_recovery_codes", showCodes); return "view-useraccount"; }
@Override @Transactional public Stream<RecoveryCode> generateRecoveryCodes() { String userId = getUser().getId(); deleteOldRecoveryCodes(userId); List<RecoveryCode> newRecoveryCodes = generateRecoveryCodes(userId); //noinspection RedundantCast runAsSystem((Runnable) () -> dataService.add(RECOVERY_CODE, newRecoveryCodes.stream())); return newRecoveryCodes.stream(); }
protected void init(Model model, final String pluginId) { languageCode = LocaleContextHolder.getLocale().getLanguage(); model.addAttribute("baseUrl", getBaseUrl(pluginId)); model.addAttribute("lng", this.languageCode); model.addAttribute("fallbackLng", appSettings.getLanguageCode()); model.addAttribute("isSuperUser", userAccountService.getCurrentUser().isSuperuser()); }
@Override @RunAsSystem public void activateUser(String activationCode) { User user = dataService .query(USER, User.class) .eq(ACTIVE, false) .and() .eq(ACTIVATIONCODE, activationCode) .findOne(); if (user != null) { user.setActive(true); dataService.update(USER, user); // send activated email to user SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setTo(user.getEmail()); mailMessage.setSubject("Your registration request for " + appSettings.getTitle()); mailMessage.setText(createActivatedEmailText(user, appSettings.getTitle())); mailSender.send(mailMessage); } else { throw new MolgenisUserException("Invalid activation code or account already activated."); } }
@Override @PreAuthorize("hasAnyRole('ROLE_SU','ROLE_MANAGER')") @Transactional public void setActivationUser(String userId, Boolean active) { User mu = this.dataService.findOneById(USER, userId, User.class); mu.setActive(active); this.dataService.update(USER, mu); }
/** Serves feedback form. */ @Override @GetMapping public String init(final Model model) { super.init(model); model.addAttribute("adminEmails", userService.getSuEmailAddresses()); if (SecurityUtils.currentUserIsAuthenticated()) { User currentUser = userService.getUser(SecurityUtils.getCurrentUsername()); model.addAttribute("userName", getFormattedName(currentUser)); model.addAttribute("userEmail", currentUser.getEmail()); } model.addAttribute("isRecaptchaEnabled", appSettings.getRecaptchaIsEnabled()); model.addAttribute("recaptchaPublicKey", appSettings.getRecaptchaPublicKey()); return VIEW_FEEDBACK; }