Check user status when logging in

Asked

Viewed 564 times

-1

Hello, folks. I’m having a problem formulating my login screen and would like to ask your knowledge.

I’m using Eclipse Mars . 1 to program, Primefaces for visual components and Spring Security for user authentication and authorization.

The situation is as follows: On the login screen, I am asking the user to enter the email and password to login. The login is only done when the two information matches those in the database. So far, so good. But in my database there is a field called "status". This field is used to indicate if the user’s registration is in "active" or "inactive situation".

If the registration is "inactive" status, even if the email and password are correct, the user should not be allowed to log into the system. I’m having difficulty doing this treatment by the field "status".

I am posting the codes of the files that I believe are related to user authentication at the time of logging in.

Login.xhtml

Login

        <p:panel
             styleClass="grid-login">

            <p:graphicImage library="images" name="Rastrbov.png" />
            <h:panelGrid columns="2">
                <h:outputText value="Nome *" style="font-weight:bold;" />
                <p:inputText size="18" id="j_username" value="#{loginBean.nome}"
                    a:placeholder="&#128273;Usuario" />
                <h:outputText value="Senha *" style="font-weight:bold;" />
                <p:password size="18" id="j_password"
                    a:placeholder="&#128273;Senha" />
            </h:panelGrid>
            <h:panelGrid columns="4" width="100%" style="text-align:center">

                    <p:commandButton value="Entrar" action="#{loginBean.login}"
                        ajax="false" styleClass="botaoLogin" icon="ui-icon-circle-arrow-e"/>


                    <p:button value="Voltar" outcome="/Main.xhtml"
                        ajax="false" styleClass="botaoLogin" icon="ui-icon-home"/>
                    <br />


            </h:panelGrid>

                <h:panelGrid column="4" width="100%" style="text-align:center">
                        <h:panelGroup>
                            <p:commandLink style="text-decoration:underline;color:blue;"
                                value="Cadastre-se"
                                onclick="PF('varDialogCadastrarUsuario').show()" type="button" />
                            <br />
                            <p:commandLink style="text-decoration:underline;color:blue;"
                                value="Esqueci a senha"
                                onclick="PF('varDialogResetarSenha').show()" type="button" />
                        </h:panelGroup>
                </h:panelGrid>


        </p:panel>
    </h:form>
    <h:form>

        <p:dialog id="dialogResetarSenha" header="Recuperar Senha"
            widgetVar="varDialogResetarSenha" modal="true" showEffect="fade"
            resizable="false" hideEffect="fade">
            <p:panelGrid columns="1">

                <p:inputText value="#{usuarioLogadoMB.email}" required="true"
                    size="60" requiredMessage="O email é obrigatório"
                    id="emailRecuperaSenha" />
                <p:watermark value="Digite seu email" for="emailRecuperaSenha" />
            </p:panelGrid>
            <p:commandButton value="Enviar senha" icon="ui-icon-circle-check"
                actionListener="#{usuarioLogadoMB.solicitarNovaSenha}"
                oncomplete="if (!args.validationFailed){varDialogResetarSenha.hide()}" />
            <p:commandButton value="Cancelar" type="button"
                icon="ui-icon-circle-close" onclick="varDialogResetarSenha.hide()" />

        </p:dialog>
    </h:form>
    <h:form>

        <p:dialog id="dialogCadastrarUsuario" header="Cadastrar Usuario"
            widgetVar="varDialogCadastrarUsuario" modal="true" showEffect="fade"
            resizable="false" hideEffect="fade">
            <p:panelGrid columns="1">

                <p:inputText id="nome" size="60"
                    value="#{cadastroUsuarioTempBean.usuarioTemp.nome}" />
                <p:watermark value="Digite seu nome" for="nome" />



                <p:inputText id="email" size="60"
                    value="#{cadastroUsuarioTempBean.usuarioTemp.email}" />
                <p:watermark value="Digite seu email" for="email" />

                <p:password id="senha" size="60"
                    value="#{cadastroUsuarioTempBean.usuarioTemp.senha}" />
                <p:watermark value="Digite sua senha" for="senha" />

            </p:panelGrid>

            <p:commandButton value="Confirmar" icon="ui-icon-circle-check"
                actionListener="#{cadastroUsuarioTempBean.salvar}"
                oncomplete="PF('varDialogCadastrarUsuario').hide()" />

            <p:commandButton value="Cancelar" type="button"
                icon="ui-icon-circle-close"
                onclick="PF('varDialogCadastrarUsuario').hide()" />

        </p:dialog>
    </h:form>
</div>

Java user.

@Entity
@SequenceGenerator(name ="usuario_sequence", sequenceName = "usuario_sequence")
@Table(name = "usuario")
public class Usuario implements Serializable{


private static final long serialVersionUID = 1L;

private Long id;
private String nome;
private String senha;
private String status;
private String cpf;
private String rg;
private String email;
private String telefone;
private String celular;
private String endereco;
private Estado estado;
private Cidade cidade;
private String cep;
private List<Grupo> grupos = new ArrayList<>();

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "usuario_sequence")
public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

@NotNull
@Column(nullable = false, length = 60)
public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

@NotNull
@Column(nullable = false, length = 6)
public String getSenha() {
    return senha;
}

public void setSenha(String senha) {
    this.senha = senha;
}

@NotNull
@Column(nullable = false, length = 14, unique=true)
public String getCpf(){
    return cpf;
}

public void setCpf(String cpf){
    this.cpf = cpf;
}

@NotNull
@Column(nullable = false, length = 20)
public String getRg(){
    return rg;
}

public void setRg(String rg){
    this.rg = rg;
}

@NotNull
@Column(nullable = false, length = 50)
public String getEmail(){
    return email;
}

public void setEmail(String email){
    this.email = email;
}

@NotNull
@Column(nullable = false, length = 14)
public String getTelefone(){
    return telefone;
}

public void setTelefone(String telefone){
    this.telefone = telefone;
}

@NotNull
@Column(nullable = false, length = 14)
public String getCelular() {
    return celular;
}

public void setCelular(String celular) {
    this.celular = celular;
}

@NotNull
@Column(nullable = false, length = 200)
public String getEndereco(){
    return endereco;
}

public void setEndereco(String endereco){
    this.endereco = endereco;
}

@NotNull
@Column(nullable = false, length = 9)
public String getCep(){
    return cep;
}

public void setCep(String cep){
    this.cep = cep;
}

@ManyToOne
@JoinColumn(name = "estado_sigla")
public Estado getEstado(){
    return estado;
}

public void setEstado(Estado estado){
    this.estado = estado;
}

@ManyToOne
@JoinColumn(name = "cidadeNome")
public Cidade getCidade() {
    return cidade;
}

public void setCidade(Cidade cidade) {
    this.cidade = cidade;
}

@NotNull
@Column(nullable = false, length = 7)
public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Usuario other = (Usuario) obj;
    if (id == null) {
        if (other.id != null)
            return false;
    } else if (!id.equals(other.id))
        return false;
    return true;
}

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "usuario_grupo", joinColumns = @JoinColumn(name="usuario_id"),
        inverseJoinColumns = @JoinColumn(name = "grupo_id"))
public List<Grupo> getGrupos() {
    return grupos;
}

public void setGrupos(List<Grupo> grupos) {
    this.grupos = grupos;
}

}

Usuariosrep.java

public class UsuariosRep implements Serializable {

private static final long serialVersionUID = 1L;
@Inject
private EntityManager manager;

public Usuario guardar(Usuario usuario) {
    EntityTransaction trx = manager.getTransaction();

    trx.begin();

    usuario = manager.merge(usuario);

    trx.commit();

    return usuario;
}

/*public Usuario porNome(String nome) 
{
    return manager.find(Usuario.class, nome);
}*/

public Usuario porNome(String nome) {
    Usuario usuario = null;

    try{
    usuario = this.manager.createQuery("from Usuario where lower(nome) = :nome", Usuario.class)
            .setParameter("nome", nome.toLowerCase()).getSingleResult();
    }catch (NoResultException e){
        // Nenhum usuario encontrado com o nome informado.
    }
    return usuario;
}

public Usuario porId(Long id)
{
    return manager.find(Usuario.class, id);
}

public List<Usuario> listaDeUsu() 
{
    return manager.createQuery("from Usuario", Usuario.class).getResultList();
}

public List<Usuario> raizes()
{
    return  manager.createQuery("from Usuario",Usuario.class).getResultList(); 
}

@SuppressWarnings("unchecked")
public List<Usuario> filtrados(UsuarioFilter filtro) {

    Session session = manager.unwrap(Session.class);

    Criteria criteria = session.createCriteria(Usuario.class);

    if (filtro.getNome() != "") 
    {
        System.out.println(filtro.getNome());
        criteria.add(Restrictions.eq("nome", filtro.getNome()));
    }

    if (filtro.getStatus() != null)
    {
        criteria.add(Restrictions.eq("status", filtro.getStatus()));
    }

    // orderBy do SQL
    return criteria.addOrder(Order.asc("id")).list();
}

public void remover(Usuario usuario) {
    this.manager.remove(usuario);
    EntityTransaction trx = manager.getTransaction();
    trx.begin();
    manager.flush();
    trx.commit();
}

public Usuario porEmail(String email) {
    Usuario usuario = null;

    try{
        usuario = this.manager.createQuery("from Usuario where lower(email) = :email", Usuario.class)
                .setParameter("email", email.toLowerCase()).getSingleResult();
    }
    catch (NoResultException e){
        FacesUtil.addErrorMessage("Nenhum usuário encontrado");
    }
    return usuario;
}
}

Appuserdetailservice.java

public class AppUserDetailsService implements UserDetailsService{


@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
    UsuariosRep usuariosRep = CDIServiceLocator.getBean(UsuariosRep.class);
    Usuario usuario = usuariosRep.porEmail(email);
    UsuarioSistema user = null;

    if(usuario != null){
        user = new UsuarioSistema(usuario, getGrupos(usuario));
    }
    return user;
}


private Collection<? extends GrantedAuthority> getGrupos(Usuario usuario) {
    List<SimpleGrantedAuthority> authorities = new ArrayList<>();

    for(Grupo grupo : usuario.getGrupos()){
        authorities.add(new SimpleGrantedAuthority(grupo.getNome().toUpperCase()));
    }

    return authorities;
}

}

Usuariosistema.java

//a classe User pertence ao Spring Security
public class UsuarioSistema extends User {
private static final long serialVersionUID = 1L;
private Usuario usuario;

public UsuarioSistema(Usuario usuario, Collection<? extends GrantedAuthority> authorities) {
    super(usuario.getEmail(), usuario.getSenha(), authorities);
    this.usuario = usuario;
}

public Usuario getUsuario() {
    return usuario;
}
}

To shorten the codes, I removed some initial lines as part of the Imports.

In case any file is missing, please let me know so I can add them immediately.

I thank all the opinions and suggestions posted.

1 answer

0

From what I understand of your system, you would have to make a change in your class AppUserDetailService.java, by inserting the condition of status. Make a check if the usuario returns other than null and case the status be equal to ativo, thus: usuario.getStaus().equals("ativo"). Then I’d stay that way:

if(usuario != null){
     if(usuario.getStaus().equals("ativo")){
          user = new UsuarioSistema(usuario, getGrupos(usuario));
     }
} 

Or you can put in the same if using && which would be equivalent:

if(usuario != null && usuario.getStaus().equals("ativo")){
     user = new UsuarioSistema(usuario, getGrupos(usuario));
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.