Hello everyone. I'm having a problem in 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 this: On the login screen, I am asking the user to enter the email and password to login. The login is only made when the two information match those in the database. Up to this point, fine. But in my database there is a field called "status". This field is used to indicate whether the user's registry is in "active" or "inactive" status.
If the register is inactive, even if the email and password are correct, the user should not be allowed to login to the system. I'm having trouble doing this for the status field.
I'm posting the file codes that I believe are related to user authentication at login time.
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="🔑Usuario" />
<h:outputText value="Senha *" style="font-weight:bold;" />
<p:password size="18" id="j_password"
a:placeholder="🔑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>
User.java
@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;
}
}
Users.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;
}
}
UserSystem.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 starting lines as part of the imports.
If any files are missing, please let me know so you can add them immediately.
Thanks to all the opinions and suggestions posted.