JSF Session: login module

0

I have a problem, with my session, hj I make 2 connections, one in my manager database to get the ip and the location of the client database, and another in the client database with the ip and the location of the database, until then quiet, the problem is that I will have several users of several databases logged at the same time, I am trying to implement the session by filter, so q every time I enter a different account my previous account and replaced by the last one I entered .....

follow my DAO:

/*
 * 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 DAO;

import Entity.Cadgru;
import Entity.Cadusr;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.NoResultException;
import javax.persistence.Query;

/**
 *
 * @author Felipee
 */
@Stateless
public class GestorDAO implements Serializable{

    Cadusr retorno;
    public static Cadusr usu = new Cadusr();

    public Cadusr buscaPorId(String gr, String usr, String senha) {
        EntityManager em = Conexao.getEntityManager("0", null);
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        tx.commit();

        Cadgru cadgru = em.find(Cadgru.class, gr);
        if (cadgru != null) {
            em = Conexao.getEntityManager("MitryusPU", cadgru.getEndfdb());
            tx = em.getTransaction();
            tx.begin();
            String jpql = "select a from Cadusr a where a.nomusr = :nomusr and a.pasusr = :pasusr";
            Query query = em.createQuery(jpql, Cadusr.class);
            query.setParameter("nomusr", usr);
            query.setParameter("pasusr", senha);
            try {
                retorno =(Cadusr) query.getSingleResult() ;
                if (retorno == null) {
                    em = Conexao.getEntityManager("0", cadgru.getEndfdb());
                    tx = em.getTransaction();
                    tx.begin();

                }
            } catch (NoResultException nre) {

            }

        } else {
            retorno = null;
        }

        tx.commit();

        em.close();

        return retorno;
    }

    public String usuarioLogado() {
        String Usuario = usu.getCodusr() + "-" + usu.getNomusr();
        return Usuario;
    }

    private String convertStringToMd5(String valor) {
        MessageDigest mDigest;
        try {
            //Instanciamos o nosso HASH MD5, poderíamos usar outro como
            //SHA, por exemplo, mas optamos por MD5.
            mDigest = MessageDigest.getInstance("MD5");

            //Convert a String valor para um array de bytes em MD5
            byte[] valorMD5 = mDigest.digest(valor.getBytes("UTF-8"));

            //Convertemos os bytes para hexadecimal, assim podemos salvar
            //no banco para posterior comparação se senhas
            StringBuffer sb = new StringBuffer();
            for (byte b : valorMD5) {
                sb.append(Integer.toHexString((b & 0xFF) | 0x100).substring(1, 3));

            }

            return sb.toString();

        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

}

Follow my bean:

/*
 * 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 Controller;

import DAO.GestorDAO;
import Entity.Cadusr;
import Util.SessionContext;
import org.apache.log4j.Logger;
import javax.faces.bean.ManagedBean;

@ManagedBean

public class mbeanUsuario {

    private static Logger logger = Logger.getLogger(mbeanUsuario.class);
    private String Usuario;
    private String Grupo;
    private String senha;

    public GestorDAO gestor = new GestorDAO();

    public String Vusuario() {
        String retorno;
        Cadusr user = gestor.buscaPorId(getGrupo(), getUsuario(), getSenha());
        if (user != null) {
            logger.info("Tentando logar com usuário " + Usuario);
            SessionContext.getInstance().setAttribute("usuarioLogado", user);
            retorno = "index.xhtml";
        } else {
            retorno = null;
        }

        return retorno;

    }

    public String doLogout() {
        logger.info("Fazendo logout com usuário "
                + SessionContext.getInstance().getUsuarioLogado());
        SessionContext.getInstance().encerrarSessao();
        return "/login.xhtml?faces-redirect=true";
    }

    /**
     * @return the Usuario
     */
    public String getUsuario() {
        return Usuario;
    }

    /**
     * @param Usuario the Usuario to set
     */
    public void setUsuario(String Usuario) {
        this.Usuario = Usuario;
    }

    /**
     * @return the Grupo
     */
    public String getGrupo() {
        return Grupo;
    }

    /**
     * @param Grupo the Grupo to set
     */
    public void setGrupo(String Grupo) {
        this.Grupo = Grupo;
    }

    /**
     * @return the senha
     */
    public String getSenha() {
        return senha;
    }

    /**
     * @param senha the senha to set
     */
    public void setSenha(String senha) {
        this.senha = senha;
    }

    /**
     * @return the gr
     */
}

Follow my web.inf:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <filter> 
        <filter-name>LoginFilter</filter-name> 
        <filter-class>Util.LoginFilter</filter-class> 
    </filter> 
    <filter-mapping> 
        <filter-name>LoginFilter</filter-name> 
        <url-pattern>/restricted/*</url-pattern> 
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>faces/login.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

Here's my SessionContext:

/*
 * 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 Util;

import Entity.Cadusr;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Felipee
 */
public class SessionContext {

    private static SessionContext instance;

    public static SessionContext getInstance() {
        if (instance == null) {
            instance = new SessionContext();
        }
        return instance;
    }

    private SessionContext() {

    }

    private ExternalContext currentExternalContext() {
        if (FacesContext.getCurrentInstance() == null) {
            throw new RuntimeException("O FacesContext não pode ser chamado fora de uma requisição HTTP");
        } else {
            return FacesContext.getCurrentInstance().getExternalContext();
        }
    }

    public Cadusr getUsuarioLogado() {
        return (Cadusr) getAttribute("usuarioLogado");
    }

    public void setUsuarioLogado(Cadusr usuario) {
        setAttribute("usuarioLogado", usuario);
    }

    public void encerrarSessao() {
        currentExternalContext().invalidateSession();
    }

    public Object getAttribute(String nome) {
        return currentExternalContext().getSessionMap().get(nome);
    }

    public void setAttribute(String nome, Object valor) {
        currentExternalContext().getSessionMap().put(nome, valor);
    }

}

Follow my LoginFilter:

/*
 * 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 Util;

import Entity.Cadusr;
import static com.sun.corba.se.spi.presentation.rmi.StubAdapter.request;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Felipee
 */
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig fc) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        Cadusr user = null;
        HttpSession sess = ((HttpServletRequest) request).getSession(false);
        if (sess != null) {
            user = (Cadusr) sess.getAttribute("usuarioLogado");
        }
        if (user == null) {
            String contextPath = ((HttpServletRequest) request).getContextPath();
            ((HttpServletResponse) response).sendRedirect(contextPath + "/login.jsf");
        } else {
            chain.doFilter(request, response);
        }

    }

    @Override
    public void destroy() {
    }

}
    
asked by anonymous 19.02.2016 / 14:29

0 answers