Example usage for org.springframework.security.crypto.bcrypt BCryptPasswordEncoder BCryptPasswordEncoder

List of usage examples for org.springframework.security.crypto.bcrypt BCryptPasswordEncoder BCryptPasswordEncoder

Introduction

In this page you can find the example usage for org.springframework.security.crypto.bcrypt BCryptPasswordEncoder BCryptPasswordEncoder.

Prototype

public BCryptPasswordEncoder() 

Source Link

Usage

From source file:hu.petabyte.redflags.web.cfg.SecurityRoles.java

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
}

From source file:com.formkiq.core.service.UserServiceImplTest.java

/**
 * Before./*  ww  w .  j  a va  2s  .com*/
 */
@Before
public void before() {
    ReflectionTestUtils.setField(this.service, "passwordEncoder", new BCryptPasswordEncoder());
}

From source file:com.tamnd.app.rest.controller.AccountController.java

@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<AccountResource> createAccount(@RequestBody AccountResource sentAccount) {
    try {//from  w ww.  ja va2s  . com
        //Encode BCrypt password
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String hashedPassword = passwordEncoder.encode(sentAccount.getPassword());
        sentAccount.setPassword(hashedPassword);

        Account newAccount = sentAccount.toAccount();
        Set<AccountRole> roles = new HashSet(0);
        roles.add(new AccountRole(newAccount, "ROLE_USER"));
        newAccount.setUserRole(roles);

        Account account = accountService.createAccount(newAccount);
        AccountResource res = new AccountResourceAsm().toResource(account);
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(URI.create(res.getLink("self").getHref()));
        return new ResponseEntity<>(res, headers, HttpStatus.CREATED);
    } catch (AccountExistsException ex) {
        throw new ConflictException(ex);
    }
}

From source file:org.oncoblocks.centromere.web.test.security.SecurityTests.java

@Before
public void setup() {

    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).addFilter(springSecurityFilterChain)
            .build();//from ww  w.  j av a2 s . c  o  m

    if (isConfigured)
        return;

    userRepository.deleteAll();

    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    Set<String> roles = new HashSet<>();
    roles.add("USER");
    User user = new User();
    user.setName("User");
    user.setUsername("user");
    user.setPassword(encoder.encode("user"));
    user.setEmail("user@email.com");
    user.setRegistrationDate(new Date());
    user.setRoles(roles);

    userRepository.insert(user);

    roles.add("ADMIN");

    User admin = new User();
    admin.setName("Admin");
    admin.setUsername("admin");
    admin.setPassword(encoder.encode("admin"));
    admin.setEmail("admin@email.com");
    admin.setRegistrationDate(new Date());
    admin.setRoles(roles);

    userRepository.insert(admin);

    isConfigured = true;

}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.root.ForgottenPasswordController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException bindException) throws Exception {
    ForgottenPasswordCommand fpc = (ForgottenPasswordCommand) command;

    Person user = personDao.getPerson(fpc.getUsername());

    log.debug("Creating new mail object");
    SimpleMailMessage mail = new SimpleMailMessage(mailMessage);

    String recipient = user.getEmail();
    log.debug("Composing e-mail - TO: " + recipient);
    mail.setTo(recipient);/*from   w w  w.jav  a2  s  .c  o  m*/

    String subject = mail.getSubject() + " - Password reset";
    log.debug("Composing e-mail - SUBJECT: " + subject);
    mail.setSubject(subject);

    String password = ControllerUtils.getRandomPassword();
    String text = "Your password for EEGbase portal was reset. Your new password (within brackets) is ["
            + password + "]\n\n" + "Please change the password after logging into system.";
    log.debug("Composing e-mail - TEXT: " + text);
    mail.setText(text);

    String mavName = getSuccessView();
    try {
        log.debug("Sending e-mail message");
        mailSender.send(mail);
        log.debug("E-mail message sent successfully");

        log.debug("Updating new password into database");
        user.setPassword(new BCryptPasswordEncoder().encode(password));
        personDao.update(user);
        log.debug("Password updated");
    } catch (MailException e) {
        log.debug("E-mail message was NOT sent");
        log.debug("Password was NOT changed");
        mavName = getFailedView();
    }

    log.debug("Returning MAV");
    ModelAndView mav = new ModelAndView(mavName);
    return mav;
}

From source file:ch.wisv.areafiftylan.IntegrationTest.java

private User makeOutsider() {
    User outsider = new User("outsider", new BCryptPasswordEncoder().encode("password"), "outsider@gmail.com");
    outsider.getProfile().setAllFields("Nottin", "Todoeo Witit", "Lookinin", Gender.FEMALE, "LoserStreet 1",
            "2826GJ", "China", "0906-3928", null);

    return userRepository.saveAndFlush(outsider);
}

From source file:cz.muni.fi.pa165.legomanager.services.impl.UserDetailsServiceImpl.java

@Override
@Transactional/* w  w w  .  j  a v a2s .  c om*/
public void updateUser(UserTO user) {
    if (user == null)
        throw new IllegalArgumentException();
    String hash = getUser(user.getAccountName()).getPassword();
    if (!user.getPassword().equals(hash)) {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        user.setPassword(passwordEncoder.encode(user.getPassword()));
    }
    userDao.updateUser(mapper.map(user, User.class));
}

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");
        }/* w  ww . jav  a 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: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  va  2s.c  o 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:au.aurin.org.controller.RestController.java

@RequestMapping(method = RequestMethod.GET, value = "/getUser", produces = "application/json")
@ResponseStatus(HttpStatus.OK)/*from ww w.j a v a  2 s. c  om*/
public @ResponseBody userData getUser(@RequestHeader("X-AURIN-USER-ID") final String roleId,
        @RequestHeader("user") final String user, @RequestHeader("password") final String password,
        final HttpServletRequest request) {

    if (!roleId.equals(adminUser.getAdminUsername())) {
        logger.info("Incorrect X-AURIN-USER-ID passed: {}.", roleId);
        return null;
    }

    logger.info("*******>> Rest-getUser for Project user ={} and pass={} ", user, password);
    userData myuser = new userData();

    try {

        final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        myuser = geodataFinder.getUser(user);
        if (myuser != null) {
            final boolean isMatch = passwordEncoder.matches(password, myuser.getPassword());

            if (isMatch == true) {
                // final HttpSession session = request.getSession(true);
                // session.setAttribute("user_id", "1");
                // session.setAttribute("user_name", "Alireza Shamakhy");
                // session.setAttribute("user_org", "Maroondah");
                myuser.setPassword("");
                return myuser;
            } else {
                return null;
            }
        } else {
            return null;
        }

    } catch (final Exception e) {
        logger.info(e.toString());
        logger.info("*******>> Error in Rest-getUser for  user ={}  ", user);

    }
    return null;
}