@RequestMapping(value = "/createUser", method = RequestMethod.POST) public final BaseResponse createUser( @RequestHeader("Accept-Language") final String encoding, @RequestParam("username") final String username, @RequestParam("password") final String password, @RequestParam("enabled") final boolean enabled, @RequestParam("email") final String email, @RequestParam("groups") final Group group) { final BaseResponse response = new BaseResponse(); try { PasswordEncoder encoder = new BCryptPasswordEncoder(); User user = new User(); user.setUsername(username); String encryptionPassword = encoder.encode(password); user.setPassword(encryptionPassword); user.setEnabled(enabled); user.setEmail(email); user.setGroups(Arrays.asList(group)); userRepository.save(user); response.setSuccess(); response.setResponseMessage("Success!"); } catch (Exception e) { response.setError(ErrorCodeEnum.SQL_QUERY_ERROR, e.getMessage()); LOGGER.error(e.getMessage()); } return response; }
@RequestMapping(value = "/{id}/resetPassword", method = RequestMethod.POST) public final BaseResponse resetPassword( @RequestHeader("Accept-Language") final String encoding, @PathVariable("id") final long id, @RequestParam("oldPassword") final String oldPassword, @RequestParam("password") final String password) { final BaseResponse response = new BaseResponse(); try { User user = userRepository.findOne(id); PasswordEncoder encoder = new BCryptPasswordEncoder(); if ((oldPassword.length() > 0) && !encoder.matches(oldPassword, user.getPassword())) { response.setError( ErrorCodeEnum.PASSWORD_NOT_MATCH, "The old password and the original password does not match"); LOGGER.error("The old password and the original password does not match"); return response; } String encryptionPassword = encoder.encode(password); user.setPassword(encryptionPassword); userRepository.save(user); response.setSuccess(); response.setResponseMessage("Success!"); } catch (Exception e) { response.setError(ErrorCodeEnum.SQL_QUERY_ERROR, e.getMessage()); LOGGER.error(e.getMessage()); } return response; }
@Override public void onApplicationEvent(ContextRefreshedEvent event) { if (log.isInfoEnabled()) { log.info("importing data into database..."); } Long usersCount = userRepository.count(); if (usersCount == 0) { if (log.isDebugEnabled()) { log.debug("import users data into database..."); } userRepository.save( new User() .builder() .username("admin") .password(passwordEncoder.encode("test123")) .name("Administrator") .role("ADMIN") .build()); userRepository.save( new User() .builder() .username("testuser") .password(passwordEncoder.encode("test123")) .name("Test User") .role("USER") .build()); } }
@Override public void addUser(UserRoles userRoles) throws DataAccessException { try { if (userRoles.getId() == null) { /* em = em.getEntityManagerFactory().createEntityManager(); Session session = (Session) em.unwrap(Session.class);*/ userRoles.setTransactionDate(new Date()); // this is Temp fix for createdBy, TODO--> Based on admin Login if (userRoles.getCreatedBy() == null) { userRoles.setCreatedBy("*****@*****.**"); userRoles.setRole("ADMIN"); } if (userRoles.getUsers() != null) { String password = userRoles.getUsers().getPassword(); PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String hashedPassword = passwordEncoder.encode(password); userRoles.getUsers().setPassword(hashedPassword); logger.info(" user Encrypted Password", hashedPassword); } em.persist(userRoles); // Here the TransactionRequiredException happens. em.flush(); } else { em.merge(userRoles); } } catch (Exception e) { throw new RuntimeException(e); } }
@Override @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void updateUserPassword(User user) { PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String hashedPassword = passwordEncoder.encode(user.getPassword()); user.setPassword(hashedPassword); userDao.updateUser(user); }
@CacheEvict(value = "users", allEntries = true) public User updatePassword(PasswordUpdateRequest request, PasswordResetToken passwordResetToken) { User user = userRepository.findByIdForUpdate(request.getUserId()); if (user == null) { throw new IllegalArgumentException("The user does not exist"); } PasswordEncoder passwordEncoder = new StandardPasswordEncoder(); user.setLoginPassword(passwordEncoder.encode(request.getPassword())); user.setUpdatedAt(LocalDateTime.now()); user.setUpdatedBy(passwordResetToken.getUser().toString()); user = userRepository.saveAndFlush(user); passwordResetTokenRepository.delete(passwordResetToken); try { Blog blog = blogService.readBlogById(Blog.DEFAULT_ID); String blogTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage()); ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath(); if (blog.isMultiLanguage()) { builder.path("/{language}"); } builder.path("/login"); Map<String, Object> urlVariables = new LinkedHashMap<>(); urlVariables.put("language", request.getLanguage()); urlVariables.put("token", passwordResetToken.getToken()); String loginLink = builder.buildAndExpand(urlVariables).toString(); Context ctx = new Context(LocaleContextHolder.getLocale()); ctx.setVariable("passwordResetToken", passwordResetToken); ctx.setVariable("resetLink", loginLink); MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart message.setSubject( MessageFormat.format( messageSourceAccessor.getMessage( "PasswordChangedSubject", LocaleContextHolder.getLocale()), blogTitle)); message.setFrom(mailProperties.getProperties().get("mail.from")); message.setTo(passwordResetToken.getEmail()); String htmlContent = templateEngine.process("password-changed", ctx); message.setText(htmlContent, true); // true = isHtml mailSender.send(mimeMessage); } catch (MessagingException e) { throw new ServiceException(e); } return user; }
public static void main(String[] args) { PasswordEncoder enc = new BCryptPasswordEncoder(); Arrays.asList("root", "admin", "usuario") .stream() .forEach( pass -> { System.out.println( String.format( "'%s', '%s'", pass, StringUtils.strip(enc.encode(pass).substring(10)))); }); }
@CacheEvict(value = "users", allEntries = true) public User updatePassword(PasswordUpdateRequest request, AuthorizedUser updatedBy) { User user = userRepository.findByIdForUpdate(request.getUserId()); if (user == null) { throw new IllegalArgumentException("The user does not exist"); } PasswordEncoder passwordEncoder = new StandardPasswordEncoder(); user.setLoginPassword(passwordEncoder.encode(request.getPassword())); user.setUpdatedAt(LocalDateTime.now()); user.setUpdatedBy(updatedBy.toString()); return userRepository.saveAndFlush(user); }
@Override @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public Integer addUser(User user) throws UserAlreadyExistsException { if (userDao.findUserByUserName(user.getUsername()) != null) throw new UserAlreadyExistsException(user.getUsername()); else { PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String hashedPassword = passwordEncoder.encode(user.getPassword()); user.setPassword(hashedPassword); return userDao.addUser(user); } }
@Secured(value = {"ROLE_ADMIN", "ROLE_MANAGER", "ROLE_USER"}) @RequestMapping(method = RequestMethod.GET, value = "reset-password") public @ResponseBody ResponseEntity<Object> resetPassword( Principal principal, @RequestParam("oldpw") String oldPassword, @RequestParam("newpw") String newPassword) { PipUser user = PipUser.findPipUsersByEmailEquals(principal.getName()).getSingleResult(); if (!encoder.matches(oldPassword, user.getPassword())) return new ResponseEntity<Object>(HttpStatus.FORBIDDEN); user.setPassword(encoder.encode(newPassword)); user.merge(); return new ResponseEntity<Object>(HttpStatus.OK); }
@Transactional public void create(final Employee employee) { employee.setPwdExpiryDate( new DateTime().plusDays(applicationProperties.userPasswordExpiryInDays()).toDate()); employee.setPassword(passwordEncoder.encode(EisConstants.DEFAULT_EMPLOYEE_PWD)); // Following is added to prevent null values and empty assignment // objects getting persisted employee.setAssignments( employee .getAssignments() .parallelStream() .filter(assignment -> assignment.getPosition() != null) .collect(Collectors.toList())); for (final Assignment assign : employee.getAssignments()) { assign.setEmployee(employee); assign.setDepartment(assign.getDepartment()); for (final HeadOfDepartments hod : assign.getDeptSet()) hod.setAssignment(assign); } employee.setJurisdictions( employee .getJurisdictions() .parallelStream() .filter( Jurisdictions -> Jurisdictions.getBoundaryType() != null && Jurisdictions.getBoundary() != null) .collect(Collectors.toList())); for (final Jurisdiction jurisdiction : employee.getJurisdictions()) { jurisdiction.setEmployee(employee); jurisdiction.setBoundaryType(jurisdiction.getBoundaryType()); jurisdiction.setBoundary(jurisdiction.getBoundary()); } employee.getRoles().add(roleService.getRoleByName(EisConstants.ROLE_EMPLOYEE)); employeeRepository.save(employee); }
@Override public void changePassword(final String id, String oldPassword, final String newPassword) throws ScimResourceNotFoundException { if (oldPassword != null && !checkPasswordMatches(id, oldPassword)) { throw new BadCredentialsException("Old password is incorrect"); } if (checkPasswordMatches(id, newPassword)) { return; // we don't want to update the same password } final String encNewPassword = passwordEncoder.encode(newPassword); final String zoneId = IdentityZoneHolder.get().getId(); int updated = jdbcTemplate.update( CHANGE_PASSWORD_SQL, new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { Timestamp t = new Timestamp(System.currentTimeMillis()); ps.setTimestamp(1, t); ps.setString(2, encNewPassword); ps.setTimestamp(3, getPasswordLastModifiedTimestamp(t)); ps.setString(4, id); ps.setString(5, zoneId); } }); if (updated == 0) { throw new ScimResourceNotFoundException("User " + id + " does not exist"); } if (updated != 1) { throw new ScimResourceConstraintFailedException("User " + id + " duplicated"); } }
public void updateClientSecret(String clientId, String secret) throws NoSuchClientException { int count = jdbcTemplate.update(updateClientSecretSql, passwordEncoder.encode(secret), clientId); if (count != 1) { throw new NoSuchClientException("No client found with id = " + clientId); } }
@Test public void identifyUser_usesDAO() { when(userRepository.findOne(USER_A_NAME)).thenReturn(userAStored); when(passwordEncoder.matches(USER_A_PASSWORD, USER_A_PASSWORD_ENCODED)).thenReturn(true); communityServiceImpl.identifyUser(userA); verify(userRepository, times(1)).findOne(USER_A_NAME); }
public void changePassword(String password) { User currentUser = userRepository.findOneByLogin(SecurityUtils.getCurrentLogin()); String encryptedPassword = passwordEncoder.encode(password); currentUser.setPassword(encryptedPassword); userRepository.save(currentUser); log.debug("Changed password for User: {}", currentUser); }
@Test(expected = IllegalArgumentException.class) public void identifyUser_throwsIllegalArgumentException_002() { when(userRepository.findOne(USER_A_NAME)).thenReturn(userAStored); when(passwordEncoder.matches(USER_A_PASSWORD, USER_A_PASSWORD_ENCODED)).thenReturn(false); userA.setPassword(""); communityServiceImpl.identifyUser(userA); }
/** {@inheritDoc} */ @Override public User updatePassword( final String username, final String currentPassword, final String recoveryToken, final String newPassword, final String applicationUrl) throws UserExistsException { User user = getUserByUsername(username); if (isRecoveryTokenValid(user, recoveryToken)) { log.debug("Updating password from recovery token for user: "******"Password Updated"); return user; } else if (StringUtils.isNotBlank(currentPassword)) { if (passwordEncoder.matches(currentPassword, user.getPassword())) { log.debug("Updating password (providing current password) for user:" + username); user.setPassword(newPassword); user = saveUser(user); return user; } } // or throw exception return null; }
@Override public void checkLogin(int userId, String password) { User u = userRepository.findOne(userId); if (u == null || !passwordEncoder.matches(password, u.getPassword())) { throw new UserServiceException("Username or password isn't correct"); } }
@Override @Transactional public void onApplicationEvent(final ContextRefreshedEvent event) { if (alreadySetup) { return; } // == create initial privileges final Privilege readPrivilege = createPrivilegeIfNotFound("READ_PRIVILEGE"); final Privilege writePrivilege = createPrivilegeIfNotFound("WRITE_PRIVILEGE"); // == create initial roles final List<Privilege> adminPrivileges = Arrays.asList(readPrivilege, writePrivilege); createRoleIfNotFound("ROLE_ADMIN", adminPrivileges); createRoleIfNotFound("ROLE_USER", Arrays.asList(readPrivilege)); final Role adminRole = roleRepository.findByName("ROLE_ADMIN"); final User user = new User(); user.setFirstName("Test"); user.setLastName("Test"); user.setPassword(passwordEncoder.encode("test")); user.setEmail("*****@*****.**"); user.setRoles(Arrays.asList(adminRole)); user.setEnabled(true); userRepository.save(user); alreadySetup = true; }
public User createUserInformation( String login, String password, String firstName, String lastName, String email, String langKey) { User newUser = new User(); Authority authority = authorityRepository.findOne("ROLE_USER"); Set<Authority> authorities = new HashSet<>(); String encryptedPassword = passwordEncoder.encode(password); newUser.setLogin(login); // new user gets initially a generated password newUser.setPassword(encryptedPassword); newUser.setFirstName(firstName); newUser.setLastName(lastName); newUser.setEmail(email); newUser.setLangKey(langKey); // new user is not active newUser.setActivated(false); // new user gets registration key newUser.setActivationKey(RandomUtil.generateActivationKey()); authorities.add(authority); newUser.setAuthorities(authorities); userRepository.save(newUser); userSearchRepository.save(newUser); log.debug("Created Information for User: {}", newUser); return newUser; }
public User createUser(ManagedUserDTO managedUserDTO) { User user = new User(); user.setLogin(managedUserDTO.getLogin()); user.setFirstName(managedUserDTO.getFirstName()); user.setLastName(managedUserDTO.getLastName()); user.setEmail(managedUserDTO.getEmail()); if (managedUserDTO.getLangKey() == null) { user.setLangKey("en"); // default language is English } else { user.setLangKey(managedUserDTO.getLangKey()); } if (managedUserDTO.getAuthorities() != null) { Set<Authority> authorities = new HashSet<>(); managedUserDTO .getAuthorities() .stream() .forEach(authority -> authorities.add(authorityRepository.findOne(authority))); user.setAuthorities(authorities); } String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword()); user.setPassword(encryptedPassword); user.setResetKey(RandomUtil.generateResetKey()); user.setResetDate(ZonedDateTime.now()); user.setActivated(true); userRepository.save(user); log.debug("Created Information for User: {}", user); return user; }
@Secured(value = {"ROLE_ADMIN", "ROLE_MANAGER"}) @RequestMapping(method = RequestMethod.POST) public @ResponseBody void createUser(@RequestBody UserDto dto, Principal principal) { PipUser user = new PipUser(); user.setEmail(dto.getEmail()); Set<OrganisazionDto> organizations = dto.getOrganizations(); if (organizations.isEmpty()) { PipUser currentUser = PipUser.findPipUsersByEmailEquals(principal.getName()).getSingleResult(); List<Organisazion> organisazions = currentUser.getOrganisazions(); if (!organisazions.isEmpty()) { user.getOrganisazions().add(organisazions.get(0)); } } else { Organisazion organisazion = Organisazion.findOrganisazionsByName( new ArrayList<OrganisazionDto>(organizations).get(0).getName()) .getSingleResult(); user.getOrganisazions().add(organisazion); } String randomPassword = RandomStringUtils.randomAlphanumeric(6); user.setPassword(encoder.encode(randomPassword)); user.setRole(PipRole.USER.getName()); user.persist(); mailingUtil.sendCreationMail(user, randomPassword); }
/** * Used to create a user. Implements special logic by encoding the password. * * @param user * @return */ public void saveUser(User user) { LOG.trace("Trying to create a new user"); // encode the raw password using bcrypt final String pwHash = passwordEncoder.encode(user.getPassword()); user.setPassword(pwHash); dao.saveOrUpdate(user); LOG.info("Created the user " + user.getAccountName()); }
@Transactional @Override public User saveUserWithNewPassword(User user, String rawPassword) { validate(user, rawPassword); user.setPassword(passwordEncoder.encode(rawPassword)); user = saveUser(user); return user; }
@Override public Customer register(Customer customer, String rawPassword) { String password = passwordEncoder.encode(rawPassword); customer.setCustomerPass(password); customerRepository.insert(customer); return customer; }
private User createExistingUser(String login, String email, String firstName, String lastName) { User user = new User(); user.setLogin(login); user.setPassword(passwordEncoder.encode("password")); user.setEmail(email); user.setFirstName(firstName); user.setLastName(lastName); return userRepository.saveAndFlush(user); }
/** * Metodo que se va a utilizar para crear los usuarios * * @param userDto TODO: Queda por hacer el tema de los updates * @return */ @Override public UserDTO saveAndFlush(UserDTO userDto) { Role iniciado = roleRepository.findOne(1L); User u = userDto.toEntity(null, iniciado); u.setPassword(passwordEncoder.encode(userDto.getPassword())); u = userRepository.saveAndFlush(u); userDto.toDTO(u); return userDto; }
@Override public Authentication authenticate(Authentication req) throws AuthenticationException { logger.debug("Processing authentication request for " + req.getName()); if (req.getCredentials() == null) { BadCredentialsException e = new BadCredentialsException("No password supplied"); publish(new AuthenticationFailureBadCredentialsEvent(req, e)); throw e; } UaaUser user; try { user = userDatabase.retrieveUserByName(req.getName().toLowerCase(Locale.US)); } catch (UsernameNotFoundException e) { user = dummyUser; } final boolean passwordMatches = encoder.matches((CharSequence) req.getCredentials(), user.getPassword()); if (!accountLoginPolicy.isAllowed(user, req)) { logger.warn( "Login policy rejected authentication for " + user.getUsername() + ", " + user.getId() + ". Ignoring login request."); BadCredentialsException e = new BadCredentialsException("Login policy rejected authentication"); publish(new AuthenticationFailureLockedEvent(req, e)); throw e; } if (passwordMatches) { logger.debug("Password successfully matched"); Authentication success = new UaaAuthentication( new UaaPrincipal(user), user.getAuthorities(), (UaaAuthenticationDetails) req.getDetails()); publish(new UserAuthenticationSuccessEvent(user, success)); return success; } if (user == dummyUser) { logger.debug("No user named '" + req.getName() + "' was found"); publish(new UserNotFoundEvent(req)); } else { logger.debug("Password did not match for user " + req.getName()); publish(new UserAuthenticationFailureEvent(user, req)); } BadCredentialsException e = new BadCredentialsException("Bad credentials"); publish(new AuthenticationFailureBadCredentialsEvent(req, e)); throw e; }
@Test public void validateCurrentUserPassword() throws DatabaseException { MolgenisUser existingMolgenisUser = mock(MolgenisUser.class); when(existingMolgenisUser.getId()).thenReturn(1); when(existingMolgenisUser.getPassword()).thenReturn("encrypted-password"); when(existingMolgenisUser.getUsername()).thenReturn("username"); when(passwordEncoder.matches("password", "encrypted-password")).thenReturn(true); assertTrue(userAccountServiceImpl.validateCurrentUserPassword("password")); assertFalse(userAccountServiceImpl.validateCurrentUserPassword("wrong-password")); }
@Override public String checkLoginAndCalculateBasicAuth(UserDTO userDTO) { UserDTO user = findUserByEmailAndAlta(userDTO.getUsername()); if (user != null) { if (passwordEncoder.matches(userDTO.getPassword(), user.getPassword())) { return PasswordUtils.calculateBasicAuth(user.getEmail(), userDTO.getPassword()); } } return null; }