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:com.abixen.platform.core.service.impl.LayoutServiceImpl.java

@Override
public Layout changeIcon(Long id, MultipartFile iconFile) throws IOException {
    Layout layout = findLayout(id);/*  w  ww  .  j  av  a2 s  . c o  m*/
    File currentAvatarFile = new File(platformResourceConfigurationProperties.getImageLibraryDirectory()
            + "/layout-miniature/" + layout.getIconFileName());
    if (currentAvatarFile.exists()) {
        if (!currentAvatarFile.delete()) {
            throw new FileExistsException();
        }
    }
    PasswordEncoder encoder = new BCryptPasswordEncoder();
    String newIconFileName = encoder.encode(iconFile.getName() + new Date().getTime()).replaceAll("\"", "s")
            .replaceAll("/", "a").replace(".", "sde");
    File newIconFile = new File(platformResourceConfigurationProperties.getImageLibraryDirectory()
            + "/layout-miniature/" + newIconFileName);
    FileOutputStream out = new FileOutputStream(newIconFile);
    out.write(iconFile.getBytes());
    out.close();
    layout.setIconFileName(newIconFileName);
    updateLayout(layout);
    return findLayout(id);
}

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

@Transactional(readOnly = false)
public void addPersonal(Personal p) {
    //temp password
    String tmpPassword = org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric(12);

    PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    String hashedPassword = passwordEncoder.encode(tmpPassword);
    //String hashedPassword = passwordEncoder.encode("bsc");

    //user//  w  ww .ja  va  2 s  . com
    Usuario u = p.getUsuario();

    u.setUsrActivationHash(java.util.UUID.randomUUID().toString().replace("-", ""));
    u.setUsrActive(false);
    u.setUsrCreationTimestamp(new Date());
    u.setUsrPassword(hashedPassword);

    u.setRole(rolDAO.getRol(p.getUsuario().getRol().getRolId()));

    //confirm email url
    String confirmUrl = "confirmEmail.xhtml?h=" + u.getUsrActivationHash() + "&c="
            + passwordEncoder.encode(u.getUsrCi());

    personalDAO.addPersonal(p);
    log.info("jfee: invoke email service start");
    emailService.sendAccountEmail(p.getUsuario(), p.getPsnNombre(), p.getPsnApellido(), tmpPassword, confirmUrl,
            FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath());
    log.info("jfee: invoke email service end");
}

From source file:com.restfiddle.controller.rest.UserController.java

@RequestMapping(value = "/api/users/change-password", method = RequestMethod.POST, headers = "Accept=application/json")
public @ResponseBody void changePassword(@RequestBody PasswordResetDTO passwordResetDTO) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Object principal = authentication.getPrincipal();

    if (principal != null && principal instanceof User) {
        User loggedInUser = (User) principal;
        User user = userRepository.findOne(loggedInUser.getId());
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        user.setPassword(passwordEncoder.encode(passwordResetDTO.getRetypedPassword()));
        userRepository.save(user);/*w w w.  j  a v  a 2  s.  c  o m*/
    }

}

From source file:com.chevres.rss.restapi.dao.impl.UserDAOImpl.java

@Override
public void updateUser(User oldUser, User newUser, boolean isUpdaterAdmin) {
    Session session = this.getSessionFactory().openSession();
    Transaction tx;// w  ww. j a  v  a  2s .c  o  m
    try {
        tx = session.beginTransaction();

        if (newUser.getUsername() != null) {
            oldUser.setUsername(newUser.getUsername());
        }
        if (newUser.getPassword() != null) {
            PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String hashedPassword = passwordEncoder.encode(newUser.getPassword());
            oldUser.setPassword(hashedPassword);
        }
        if (isUpdaterAdmin && newUser.getType() != null) {
            oldUser.setType(newUser.getType());
        }

        session.update(oldUser);
        tx.commit();
    } catch (Exception e) {
        throw e;
    } finally {
        session.close();
    }
}

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

@Override
public void updateUsuario(Usuario u) {
    Usuario old = usuarioDAO.getUsuario(u.getUsrCi());

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

        //confirm email url
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String confirmUrl = "confirmEmail.xhtml?h=" + u.getUsrActivationHash() + "&c="
                + passwordEncoder.encode(u.getUsrCi());
        emailService.sendConfirmationEmail(u, "usuario", "", confirmUrl,
                FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath());
    }/*from   ww  w.  j  av  a2s .com*/

    //TODO: verify if email already in use
    usuarioDAO.evictUsuario(old);
    usuarioDAO.updateUsuario(u);
}

From source file:com.company.project.web.controller.service.CustomUserDetailsService.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    try {/*www . j av  a 2 s  .co  m*/
        //            Map<String, String> user = new HashMap<String, String>();
        //            user.put("username", "admin");
        //            user.put("password", "admin");
        //            user.put("role", "ROLE_ADMIN");
        //            users.put("admin", user);
        //            user = new HashMap<String, String>();
        //            user.put("username", "sadmin");
        //            user.put("password", "sadmin");
        //            user.put("role", "ROLE_SYS_ADMIN");
        //            users.put("sadmin", user);
        //            user = new HashMap<String, String>();
        //            user.put("username", "user");
        //            user.put("password", "user");
        //            user.put("role", "ROLE_USER");
        //            users.put("user", user);
        //            
        //            user = users.get(username);

        Map<String, Object> user = null;
        //user = userService.get(username);
        //user = userDao.get(username);
        user = userMapperImpl.get(username);
        if (user == null) {
            return null;
        }

        if (username.contains("admin")) {
            user.put("role", "ROLE_ADMIN");
        } else {
            user.put("role", "ROLE_USER");
        }

        List<GrantedAuthority> authorities = getAuthorities("" + user.get("role"));
        boolean enabled = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        // BCryptPasswordEncoder automatically generates a salt and concatenates it.
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodedPassword = passwordEncoder.encode("" + user.get("password"));

        return new User("" + user.get("username"), encodedPassword, enabled, accountNonExpired,
                credentialsNonExpired, accountNonLocked, authorities);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

@Transactional(readOnly = false)
public void addSocio(Socio s) throws JfeeCustomException {

    Socio old = socioDAO.getSocioByCi(s.getUsuario().getUsrCi());
    if (old != null) {
        socioDAO.evictSocio(old);//from  w ww .ja v  a 2s.c  om
        throw new JfeeCustomException("Ya existe un socio con esa CI");
    }

    //temp password
    String tmpPassword = org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric(12);

    PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    String hashedPassword = passwordEncoder.encode(tmpPassword);

    //user
    Usuario u = s.getUsuario();

    u.setUsrActivationHash(java.util.UUID.randomUUID().toString().replace("-", ""));
    u.setUsrActive(false);
    u.setUsrCreationTimestamp(new Date());
    u.setUsrPassword(hashedPassword);

    s.setSocEstado(Boolean.FALSE);

    //confirm email url
    String confirmUrl = "confirmEmail.xhtml?h=" + u.getUsrActivationHash() + "&c="
            + passwordEncoder.encode(u.getUsrCi());

    socioDAO.addSocio(s);
    emailService.sendAccountEmail(s.getUsuario(), s.getSocNombre(), s.getSocApellido(), tmpPassword, confirmUrl,
            FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath());
}

From source file:com.abixen.platform.core.application.service.LayoutManagementService.java

@PreAuthorize("hasPermission(#id, '" + AclClassName.Values.LAYOUT + "', '" + PermissionName.Values.LAYOUT_EDIT
        + "')")//from   www. j  a v  a 2  s.c  om
public LayoutDto changeLayoutIcon(final Long id, final MultipartFile iconFile) throws IOException {
    log.debug("changeLayoutIcon() - id: {}, iconFile: {}", id, iconFile);

    final Layout layout = layoutService.find(id);
    //FIXME - rename to thumbnail
    final File currentThumbnailFile = new File(
            platformResourceConfigurationProperties.getImageLibraryDirectory() + "/layout-miniature/"
                    + layout.getIconFileName());

    if (currentThumbnailFile.exists()) {
        if (!currentThumbnailFile.delete()) {
            throw new FileExistsException();
        }
    }

    final PasswordEncoder encoder = new BCryptPasswordEncoder();
    final String newIconFileName = encoder.encode(iconFile.getName() + new Date().getTime())
            .replaceAll("\"", "s").replaceAll("/", "a").replace(".", "sde");
    final File newIconFile = new File(platformResourceConfigurationProperties.getImageLibraryDirectory()
            + "/layout-miniature/" + newIconFileName);

    final FileOutputStream out = new FileOutputStream(newIconFile);
    out.write(iconFile.getBytes());
    out.close();

    layout.changeIconFileName(newIconFileName);
    final Layout updatedLayout = layoutService.update(layout);

    return layoutToLayoutDtoConverter.convert(updatedLayout);
}

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

@Override
public User changeUserAvatar(Long userId, MultipartFile avatarFile) throws IOException {
    User user = findUser(userId);//  www.j  a va2s.co m
    File currentAvatarFile = new File(platformResourceConfigurationProperties.getImageLibraryDirectory()
            + "/user-avatar/" + user.getAvatarFileName());
    if (currentAvatarFile.exists()) {
        if (!currentAvatarFile.delete()) {
            throw new FileExistsException();
        }
    }
    PasswordEncoder encoder = new BCryptPasswordEncoder();
    String newAvatarFileName = encoder.encode(avatarFile.getName() + new Date().getTime()).replaceAll("\"", "s")
            .replaceAll("/", "a").replace(".", "sde");
    File newAvatarFile = new File(platformResourceConfigurationProperties.getImageLibraryDirectory()
            + "/user-avatar/" + newAvatarFileName);
    FileOutputStream out = new FileOutputStream(newAvatarFile);
    out.write(avatarFile.getBytes());
    out.close();
    user.setAvatarFileName(newAvatarFileName);
    updateUser(user);
    return findUser(userId);
}

From source file:me.bulat.jivr.webmin.web.root.AppRootController.java

/**
 * Create new user by himself./*w ww.j  a  va  2  s.co  m*/
 *
 * @param userForm user form entered by user.
 * @param binding request.
 * @return redirect page.
 */
@RequestMapping(value = { "/registration" }, method = { RequestMethod.POST })
public String registerNewUser(@Valid @ModelAttribute("registerForm") UserForm userForm, BindingResult binding) {

    if (binding.hasErrors()) {
        return "redirect:/incorrect";
    }

    PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    User user = new User();
    user.setEmail(userForm.getEmail());
    user.setPassword(passwordEncoder.encode(userForm.getPassword()));
    user.setUserName(userForm.getUsername());
    user.setEnabled(true);
    Role role = new Role();
    role.setRole("ROLE_USER");
    List<Role> roles = new ArrayList<>();
    roles.add(role);
    user.setRoles(roles);
    loginService.saveUser(user);
    return "redirect:/success";
}