Example usage for org.springframework.security.crypto.password PasswordEncoder encode

List of usage examples for org.springframework.security.crypto.password PasswordEncoder encode

Introduction

In this page you can find the example usage for org.springframework.security.crypto.password PasswordEncoder encode.

Prototype

String encode(CharSequence rawPassword);

Source Link

Document

Encode the raw password.

Usage

From source file:ph.fingra.statisticsweb.security.FingraphUser.java

public FingraphUser(Member member, PasswordEncoder passwordEncoder) {
    setMemberid(member.getMemberid());/*from   w  ww. ja va 2s .  c o  m*/
    setEmail(member.getEmail());
    setName(member.getName());
    // encode password
    member.setPassword(passwordEncoder.encode(member.getPassword()));
    setPassword(member.getPassword());
    setDepartment(member.getDepartment());
    setPhone(member.getPhone());
    setStatus(member.getStatus());
    setJoinstatus(member.getJoinstatus());
    setLastlogin(member.getLastlogin());
    setRole(member.getRole());
    if (MemberStatus.valueOf(member.getStatus()) != MemberStatus.ACTIVE) {
        this.accountNonLocked = false;
        this.enabled = false;
    }
    // controlled by FingraphAnthenticationProvider.additionalAuthenticationChecks
    //if (MemberJoinstatus.valueOf(member.getJoinstatus()) != MemberJoinstatus.APPROVAL) {
    //    this.accountNonLocked = false;
    //    this.enabled = false;
    //}
}

From source file:io.dacopancm.jfee.sp.service.PersonalService.java

@Transactional(readOnly = false)
public void updatePersonal(Personal p) throws JfeeCustomException {
    Personal old = personalDAO.getPersonalById(p.getPsnId());

    if (!old.getUsuario().getUsrCi().equalsIgnoreCase(p.getUsuario().getUsrCi())) {
        //intenta actualizar cedula
        Personal old2 = personalDAO.getPersonalByCi(p.getUsuario().getUsrCi());
        if (old2.getPsnId().intValue() != p.getPsnId()) {
            //traemos usuario por CI, si ya existe quiere decir q el usuario q se esta actualizando
            //quiere usar una CI q ya esta registrada
            throw new io.dacopancm.jfee.exceptions.JfeeCustomException("Ya existe usuario con esa CI");
        }//from   w  w w. ja  v  a  2 s.  co m
        personalDAO.evictPersonal(old2);
    }

    if (!old.getUsuario().getUsrEmail().equalsIgnoreCase(p.getUsuario().getUsrEmail())) {
        p.getUsuario().setUsrActivationHash(java.util.UUID.randomUUID().toString().replace("-", ""));

        //confirm email url
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String confirmUrl = "confirmEmail.xhtml?h=" + p.getUsuario().getUsrActivationHash() + "&c="
                + passwordEncoder.encode(p.getUsuario().getUsrCi());
        emailService.sendConfirmationEmail(p.getUsuario(), p.getPsnNombre(), p.getPsnApellido(), confirmUrl,
                FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath());
    }

    //TODO: verify if email already in use
    p.getUsuario().setRole(rolDAO.getRol(p.getUsuario().getRol().getRolId()));
    personalDAO.evictPersonal(old);
    personalDAO.updatePersonal(p);
}

From source file:io.dacopancm.jfee.sp.service.SocioService.java

@Transactional(readOnly = false)
public void updateSocio(Socio p) throws JfeeCustomException {
    Socio old = socioDAO.getSocioById(p.getSocId());

    if (!old.getUsuario().getUsrCi().equalsIgnoreCase(p.getUsuario().getUsrCi())) {
        //intenta actualizar cedula
        Socio old2 = socioDAO.getSocioByCi(p.getUsuario().getUsrCi());
        if (old2.getSocId().intValue() != p.getSocId()) {
            //traemos usuario por CI, si ya existe quiere decir q el usuario q se esta actualizando
            //quiere usar una CI q ya esta registrada
            throw new io.dacopancm.jfee.exceptions.JfeeCustomException("Ya existe usuario con esa CI");
        }/*from  w w w  .  j a  va  2  s  .  c  o  m*/
        socioDAO.evictSocio(old2);
    }

    if (!old.getUsuario().getUsrEmail().equalsIgnoreCase(p.getUsuario().getUsrEmail())) {
        p.getUsuario().setUsrActivationHash(java.util.UUID.randomUUID().toString().replace("-", ""));

        //confirm email url
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String confirmUrl = "confirmEmail.xhtml?h=" + p.getUsuario().getUsrActivationHash() + "&c="
                + passwordEncoder.encode(p.getUsuario().getUsrCi());
        emailService.sendConfirmationEmail(p.getUsuario(), p.getSocNombre(), p.getSocApellido(), confirmUrl,
                FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath());
    }

    //TODO: verify if email already in use
    p.getUsuario().setRole(rolDAO.getRol(p.getUsuario().getRol().getRolId()));
    socioDAO.evictSocio(old);
    socioDAO.updateSocio(p);
}

From source file:org.web4thejob.security.SpringSecurityService.java

@Override
public String encodePassword(UserIdentity userIdentity, String value) {
    PasswordEncoder passwordEncoder;

    try {//from   w w  w .  ja  va  2  s .c  o  m
        passwordEncoder = ContextUtil.getBean(PasswordEncoder.class);
    } catch (NoSuchBeanDefinitionException e) {
        return value;
    }

    return passwordEncoder.encode(value);
}

From source file:com.abixen.platform.core.domain.model.User.java

public void changeAvatar(String imageLibraryDirectory, MultipartFile avatarFile) throws IOException {
    final File currentAvatarFile = new File(imageLibraryDirectory + "/user-avatar/" + getAvatarFileName());
    if (currentAvatarFile.exists()) {
        if (!currentAvatarFile.delete()) {
            throw new FileExistsException();
        }/*from w  ww  . j  a v  a 2  s. c o  m*/
    }
    final PasswordEncoder encoder = new BCryptPasswordEncoder();
    final String newAvatarFileName = encoder.encode(avatarFile.getName() + new Date().getTime())
            .replaceAll("\"", "s").replaceAll("/", "a").replace(".", "sde");
    final File newAvatarFile = new File(imageLibraryDirectory + "/user-avatar/" + newAvatarFileName);
    final FileOutputStream out = new FileOutputStream(newAvatarFile);
    out.write(avatarFile.getBytes());
    out.close();
    setAvatarFileName(newAvatarFileName);
}

From source file:org.taverna.server.master.identity.StrippedDownAuthProvider.java

/**
 * Sets the PasswordEncoder instance to be used to encode and validate
 * passwords./* w w w. j a  va 2 s .  c om*/
 */
@Required
public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
    if (passwordEncoder == null)
        throw new IllegalArgumentException("passwordEncoder cannot be null");

    this.passwordEncoder = passwordEncoder;
    this.userNotFoundEncodedPassword = passwordEncoder.encode(USER_NOT_FOUND_PASSWORD);
}

From source file:com.abixen.platform.core.service.impl.UserServiceImpl.java

@Override
public UserChangePasswordForm changeUserPassword(User user, UserChangePasswordForm userChangePasswordForm) {
    log.info("changeUserPassword()");

    PasswordEncoder encoder = new BCryptPasswordEncoder();
    String password = userChangePasswordForm.getCurrentPassword();
    if (!encoder.matches(password, user.getPassword())) {
        throw new UsernameNotFoundException("Wrong username and / or password.");
    }/*from   w  ww.  j av a  2s .com*/

    user.setPassword(encoder.encode(userChangePasswordForm.getNewPassword()));
    updateUser(user);

    return userChangePasswordForm;
}

From source file:org.wallride.service.UserService.java

@CacheEvict(value = WallRideCacheConfiguration.USER_CACHE, allEntries = true)
public User updatePassword(PasswordUpdateRequest request, AuthorizedUser updatedBy) {
    User user = userRepository.findOneForUpdateById(request.getUserId());
    if (user == null) {
        throw new IllegalArgumentException("The user does not exist");
    }//w  w w .  j  a  v  a  2 s.c om
    PasswordEncoder passwordEncoder = new StandardPasswordEncoder();
    user.setLoginPassword(passwordEncoder.encode(request.getPassword()));
    user.setUpdatedAt(LocalDateTime.now());
    user.setUpdatedBy(updatedBy.toString());
    return userRepository.saveAndFlush(user);
}

From source file:org.wallride.service.UserService.java

@CacheEvict(value = WallRideCacheConfiguration.USER_CACHE, allEntries = true)
public User updatePassword(PasswordUpdateRequest request, PasswordResetToken passwordResetToken) {
    User user = userRepository.findOneForUpdateById(request.getUserId());
    if (user == null) {
        throw new IllegalArgumentException("The user does not exist");
    }/*  w  w w . j  av  a  2 s.c o m*/
    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.getBlogById(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;
}

From source file:com.abixen.platform.core.domain.model.User.java

public void changePassword(String currentPassword, String newPassword) {
    final PasswordEncoder encoder = new BCryptPasswordEncoder();
    if (!encoder.matches(currentPassword, getPassword())) {
        throw new UsernameNotFoundException("Wrong username and / or password.");
    }// w w  w  .  j av a 2s . c  om

    setPassword(encoder.encode(newPassword));
}