com.cfs.backingbean.AlterarSenha.java Source code

Java tutorial

Introduction

Here is the source code for com.cfs.backingbean.AlterarSenha.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cfs.backingbean;

import com.cfs.controller.UsersDAO;
import com.cfs.model.Users;
import com.cfs.util.DAOException;
import com.cfs.util.HashSenha;
import com.cfs.util.JSFUtil;
import com.cfs.util.Utilities;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCrypt;

/**
 *
 * @author cfsbs_000
 */
@ManagedBean(name = "MBAlterarSenha")
@ViewScoped
public class AlterarSenha implements Serializable {

    private String senhaAtual;
    private String senhaNova;
    private UsersDAO usersDao = new UsersDAO();
    private Users user = new Users();

    public void alterarSenha() {
        user = new Users();
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication()
                .getPrincipal();

        user = usersDao.buscaUsuarioPorUSERNAME(userDetails.getUsername());

        if (user == null) {
            System.out.println(Utilities.getInstance().getLineNumber() + "user null");
            return;
        }

        if (!BCrypt.checkpw(senhaAtual, user.getPassword())) {
            JSFUtil.addErrorMessage("Senha atual incorreta.");
            return;
        }

        user.setPassword(HashSenha.hash(senhaNova));

        try {
            usersDao.salvar(user);

        } catch (DAOException ex) {
            Logger.getLogger(AlterarSenha.class.getName()).log(Level.SEVERE, null, ex);
            JSFUtil.addErrorMessage("Erro senha no alterada.");
        }
        JSFUtil.addInfoMessage("Senha alterada com sucesso!");
        limpar();
    }

    public void limpar() {
        user = new Users();
        senhaAtual = null;
        senhaNova = null;

    }

    public String getSenhaAtual() {
        return senhaAtual;
    }

    public void setSenhaAtual(String senhaAtual) {
        this.senhaAtual = senhaAtual;
    }

    public String getSenhaNova() {
        return senhaNova;
    }

    public void setSenhaNova(String senhaNova) {
        this.senhaNova = senhaNova;
    }

}