Problema com autenticacao de Usuarios

Pessoal seguinte, hj eu tenho alguns clientes, e os dados desses clientes como servidor q o banco de dados esta e o endereco do banco esta tudo dentro de um banco de dados chamado “Gestor”, a partir do endereco desse banco de dados eu entro no banco de dados do cliente, até ai tudo bem, estou utilizando JPA fiz 2 PU para isso e to fazendo a conexao correta, o meu problema é quando eu crio os filter para sessao do usuario . Quando eu entro no mozilla com o usuario X , eu fiz so uma pg de teste para ver se estava ok, voltando quando eu entro com o cliente X E abro a pagina de teste tudo ok , quando eu entro com o cliente Y em outro navegador e atualizo a pagina do cliente X, os dados do cliente Y como ex : Loja, estao para o cliente X, mas o nome do usuario nao muda, estou colocando toda a minha codigicação :

Segue Classe de Conexão :

`package DAO;

import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class Conexao {

private static EntityManagerFactory emf = Persistence.
		createEntityManagerFactory("GestorPU");

public static EntityManager getEntityManager(String PU, String Local) {
            
            if(PU.equals("0")){
                emf = Persistence.createEntityManagerFactory("GestorPU");
            }else{
                Properties props = new Properties();         
                props.setProperty("hibernate.connection.url", "jdbc:firebirdsql:localhost/3050:" + Local);
                emf = Persistence.createEntityManagerFactory(PU, props);
            }
            
            
	return emf.createEntityManager();
}
    public static EntityManager getEntity() {
	return emf.createEntityManager();
}

}
`

Segue minha Classe 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.Cadloj;
import Entity.Cadusr;
import Entity.Reljva;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
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 {

    Cadusr retorno;
    Cadgru cadgru;
    EntityManager gestorem;
    EntityTransaction gestortx;
    EntityManager mitryusem;
    EntityTransaction mitryustx;
    public static Cadusr usu = new Cadusr();

    public Reljva chamadaMitryus(String gr,String token) {
    gestorem = Conexao.getEntityManager(“0”, null);
    gestortx = gestorem.getTransaction();
    gestortx.begin();

     cadgru = gestorem.find(Cadgru.class, gr);
     gestortx.commit();
    
     gestorem.close();
     mitryusem = Conexao.getEntityManager("MitryusPU", cadgru.getEndfdb());
     mitryustx = mitryusem.getTransaction();
     mitryustx.begin();
     String jpql = "select a from Reljva a where a.TOKEN = :token";
     Query query = mitryusem.createQuery(jpql, Reljva.class);
     query.setParameter("token", token);
     return (Reljva) query.getSingleResult();
    

    }

    public Cadusr buscaPorId(String gr, String usr, String senha) {
    gestorem = Conexao.getEntityManager(“0”, null);
    gestortx = gestorem.getTransaction();
    gestortx.begin();

     cadgru = gestorem.find(Cadgru.class, gr);
     gestortx.commit();
    
     gestorem.close();
     if (cadgru != null) {
         mitryusem = Conexao.getEntityManager("MitryusPU", cadgru.getEndfdb());
         mitryustx = mitryusem.getTransaction();
         mitryustx.begin();
         String jpql = "select a from Cadusr a where a.nomusr = :nomusr and a.pasusr = :pasusr";
         Query query = mitryusem.createQuery(jpql, Cadusr.class);
         query.setParameter("nomusr", usr);
         query.setParameter("pasusr", senha);
         try {
             retorno = (Cadusr) query.getSingleResult();
             mitryustx.commit();
    
             mitryusem.close();
             if (retorno == null) {
                 gestorem = Conexao.getEntityManager("0", cadgru.getEndfdb());
                 gestortx = gestorem.getTransaction();
                 gestortx.begin();
    
             }
         } catch (NoResultException nre) {
    
         }
    
     } else {
         retorno = null;
     }
    
     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;
     }
    

    }

    public List lojas() {
    EntityManager em = Conexao.getEntity();
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    List lojas = new ArrayList<>();
    String jpql = “from Cadloj”;
    Query query = em.createQuery(jpql, Cadloj.class);
    lojas = query.getResultList();
    return lojas;

    }

}
`

Segue meu persistence :

`<?xml version="1.0" encoding="UTF-8"?>


org.hibernate.ejb.HibernatePersistence
Entity.Cadgru
true









org.hibernate.ejb.HibernatePersistence
Entity.Cadusr
Entity.Cadloj
Entity.Cadfun
Entity.Tipcli
Entity.Tipven
Entity.Vendas
Entity.Venda_Sintetico
Entity.CodigoPin
Entity.Codloc
Entity.VendaEvolucao
Entity.Reljva

<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
  <property name="hibernate.connection.driver_class" value="org.firebirdsql.jdbc.FBDriver"/>
  <property name="hibernate.connection.username" value="SYSDBA"/>
  <property name="hibernate.connection.password" value="masterkey"/>
  <property name="hibernate.dialect" value="org.hibernate.dialect.FirebirdDialect"/>
</properties>
`

Segue meu LoginAuth :
`/*

  • 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 filtro;

import Entity.Cadusr;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
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.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
*

  • @author Felipee
    */
    @WebFilter(filterName = “loginAuth”, urlPatterns = {"/seguranca/login.jsf"})
    public class LoginAuth implements Filter {

    private static final boolean debug = true;

    // The filter configuration object we are associated with. If
    // this value is null, this filter instance is not currently
    // configured.
    private FilterConfig filterConfig = null;

    public LoginAuth() {
    }

    private void doBeforeProcessing(ServletRequest request, ServletResponse response)
    throws IOException, ServletException {

    }

    private void doAfterProcessing(ServletRequest request, ServletResponse response)
    throws IOException, ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain)
    throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    HttpSession session = (HttpSession) req.getSession();
    Cadusr user = (Cadusr) session.getAttribute(“usuario”);
    if (user == null) {
    chain.doFilter(request, response);
    } else {
    res.sendRedirect(req.getContextPath() + “/app/index.jsf”);

     }
    

    }

    /**

    • Return the filter configuration object for this filter.
      */
      public FilterConfig getFilterConfig() {
      return (this.filterConfig);
      }

    /**

    • Set the filter configuration object for this filter.
    • @param filterConfig The filter configuration object
      */
      public void setFilterConfig(FilterConfig filterConfig) {
      this.filterConfig = filterConfig;
      }

    /**

    • Destroy method for this filter
      */
      public void destroy() {
      }

    /**

    • Init method for this filter
      */
      public void init(FilterConfig filterConfig) {

    }

    /**

    • Return a String representation of this object.
      */
      @Override
      public String toString() {
      if (filterConfig == null) {
      return (“NovoFilter()”);
      }
      StringBuffer sb = new StringBuffer(“NovoFilter(”);
      sb.append(filterConfig);
      sb.append(")");
      return (sb.toString());
      }

    private void sendProcessingError(Throwable t, ServletResponse response) {
    String stackTrace = getStackTrace(t);

     if (stackTrace != null && !stackTrace.equals("")) {
         try {
             response.setContentType("text/html");
             PrintStream ps = new PrintStream(response.getOutputStream());
             PrintWriter pw = new PrintWriter(ps);
             pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n"); //NOI18N
    
             // PENDING! Localize this for next official release
             pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
             pw.print(stackTrace);
             pw.print("</pre></body>\n</html>"); //NOI18N
             pw.close();
             ps.close();
             response.getOutputStream().close();
         } catch (Exception ex) {
         }
     } else {
         try {
             PrintStream ps = new PrintStream(response.getOutputStream());
             t.printStackTrace(ps);
             ps.close();
             response.getOutputStream().close();
         } catch (Exception ex) {
         }
     }
    

    }

    public static String getStackTrace(Throwable t) {
    String stackTrace = null;
    try {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    t.printStackTrace(pw);
    pw.close();
    sw.close();
    stackTrace = sw.getBuffer().toString();
    } catch (Exception ex) {
    }
    return stackTrace;
    }

    public void log(String msg) {
    filterConfig.getServletContext().log(msg);
    }

}
`

Segue meu 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.Cadloj;
import Entity.Cadusr;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

/**
*

  • @author Felipee
    */
    @ManagedBean
    @SessionScoped
    public class Bean implements Serializable{

    private String Usuario;
    private String Grupo;
    private String senha;
    private List lojas;
    private GestorDAO gestor = new GestorDAO();

    public String Vusuario() {
    Cadusr user = getGestor().buscaPorId(getGrupo(), getUsuario(), getSenha());

     if ( user != null) {
          HttpSession sess = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
          sess.setAttribute("usuario", user);
          return  "/app/index.xhtml?faces-redirect=true";
     }else{
         return  "/seguranca/login.xhtml?faces-redirect=true";
     }
    

    }
    public String sair(){
    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    return “/seguranca/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 lojas
      */
      public List getLojas() {

      lojas = new GestorDAO().lojas();
      return lojas;
      }

    /**

    • @param lojas the lojas to set
      */
      public void setLojas(List lojas) {
      this.lojas = lojas;
      }

    /**

    • @return the gestor
      */
      public GestorDAO getGestor() {
      return gestor;
      }

    /**

    • @param gestor the gestor to set
      */
      public void setGestor(GestorDAO gestor) {
      this.gestor = gestor;
      }

}
`

Bom… olhando superficialmente seu código (muito código), reparei que na sua classe DAO você manipula 2 objetos que não são private.

Cadusr retorno;
Cadgru cadgru;

São estes objetos que contém os dados que estão sendo apresentados em comum?

isso , o Cadgru tem os dados de onde o banco de dados esta, com esses dados eu entro no Cadusr para pegar as informacoes de usuario e senha

Experimentou defini-los como private?

siim, nada tbmm

Não analisei com muito detalhe mas aposto que esse static aí tem a culpa…

bom uma imagem pode explicar melhor, ta ai quando eu abro no chome e no explorer, se eu abro primeiro no chome e depois no explorer, e volto pro chome e do um f5 , o usuario continua o mesmo , agora a a parte do selecione ali, ele pega os dados do cliente do explorer , eu nao tenho q fazer algo com o filter pra passar junto os dados ?? nao somente o usuario ?

eu tirei o static tbm nao é , e tbm coloquei como private

E de onde é que vêm os dados dessa combo?

do public List lojas() , ele pega as lojas do banco de dados do cliente

Pelo que percebo tu vais ter uma base de dados “dinamica” segundo o utilizador mas tens a factory static. Isso quer dizer que só vai existir um único objeto emf em toda a aplicação, partilhado por todos os utilizadores.
Assim, dependendo da última vez em toda a aplicação que foi chamado método getEntityManager, assim será a tua Factory.

provavel q seja isso mesmo , sera se eu tirar o static do factory funciona ?

Bom amigo consegue, so nao sei se e a maneira correta, eu peguei o usuario da sessao no list de lojas e fiz a conexao no banco correto , o problema é q eu abro o banco toda hr q eu vou fazer uma pesquisa, esta correto isso ?

public List lojas() {
UsuarioSessao usuario = (UsuarioSessao) getSession().getAttribute(“usuario”);
gestorem = Conexao.getEntityManager(“0”, null);
gestortx = gestorem.getTransaction();
gestortx.begin();
cadgru = gestorem.find(Cadgru.class, usuario.getGrupo());
gestortx.commit();
gestorem.close();
mitryusem = Conexao.getEntityManager(“MitryusPU”, cadgru.getEndfdb());
mitryustx = mitryusem.getTransaction();
mitryustx.begin();
List lojas = new ArrayList<>();
String jpql = “from Cadloj”;
Query query = mitryusem.createQuery(jpql, Cadloj.class);
lojas = query.getResultList();
mitryustx.commit();

    mitryusem.close();
    return lojas;

}

Tens de guardar os entitymanager em alguma estrutura (map) e só inicializar quando ainda não exista.

tem algum ex ?

Feito no joelho, mas algo assim

public class Conexao {

    private static EntityManager mainEM = Persistence.createEntityManagerFactory("GestorPU").createEntityManager();

    private static Map<String, EntityManager> userEM = new ConcurrentHashMap<>();


    public static EntityManager getUserEntityManager(String PU, String Local) {
        if (userEM.get(local)==null){
              Properties props = new Properties();         
              props.setProperty("hibernate.connection.url", "jdbc:firebirdsql:localhost/3050:" + Local);
              userEM.put(local,Persistence.createEntityManagerFactory(PU, props).createEntityManager());
         }

    	return userEM.get(local);
    }

    public static EntityManager getMainEntityManager(){
         return mainEM;
    }
}

amigo resolvi o problema, passei o emf por session e deu boa , obrigado pela ajuda