Can static classes and methods be used in ASP.NET MVC without problems between user sessions?

Asked

Viewed 136 times

1

I did a routine of login using cookies and as I’m always looking for this information, so you don’t have to be instantiating everywhere I use I left these static classes, my question is if there will be any problem when more than one user will do login.

Here is code from controller:

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Login(string email, string senha)
    {
        //Verifica se as credenciais estão validas, se não estão retorno a tela de login.
        if (!AutenticacaoHelper.AutenticarUsuario(email, senha, Session))
        {
            return RedirectToAction("Login", new { Erro = "0" });
        }

        //se esta logado, redireciono para a view carrinho
        return RedirectToAction("Carrinho", "Produto");
    }

Here is the code of AutenticacaoHelper

public static class AutenticacaoHelper
{
    public static bool AutenticarUsuario(string email, string senha, HttpSessionStateBase Session)
    {
        ClienteDAO _clienteDAO = new ClienteDAO();

        cliente Cliente = _clienteDAO.Autenticar(email, senha);

        if (Cliente == null)
        {
            return false;
        }
        else
        {
            GerarSessao(Session, Cliente);
            CarrinhoHelper.AtualizaClienteCarrinho(Cliente);
            return true;
        }
    }

    private static void GerarSessao(HttpSessionStateBase Session, cliente cliente)
    {
        //gero um token de sessao concatenando 2 tokens
        var tokenSessao = WindowsIdentity.GetCurrent().Token.ToString() + Session.SessionID.ToString();
        SessaoDAO _sessao = new SessaoDAO();
        _sessao.AdicionaSessao(cliente.id, tokenSessao);
        //Cria o cookie de sessao EFETIVAMENTE
        CookieHelper.RegistraCookieAutenticacao(tokenSessao, cliente.email);
    }
}

Here is the code of CookieHelper

public class CookieHelper
{
    public static void RegistraCookieAutenticacao(string tokenSessao, string email)
    {
        //Crio o token de sessao.
        HttpCookie CookieDeSessao = new HttpCookie("TokenDeSessao", tokenSessao);
        CookieDeSessao.Expires = DataHelper.DataAtual().AddMonths(3);

        //Crio o token com email
        HttpCookie CookieDeEmail = new HttpCookie("EmailDoCliente", email);
        CookieDeEmail.Expires = DataHelper.DataAtual().AddMonths(3);

        //Adiciono o cookie no contexto da aplicação
        HttpContext.Current.Response.Cookies.Add(CookieDeSessao);
        HttpContext.Current.Response.Cookies.Add(CookieDeEmail);
    }

    public static string BuscaCookieCarrinho()
    {
        try
        {
            return HttpContext.Current.Request.Cookies.Get("TokenDoCarrinho").Value;
        }
        catch (Exception)
        {
            return null;
        }
    }
}

Here the CarrinhoHelper

public static class CarrinhoHelper
{
    public static void AtualizaClienteCarrinho(cliente Cliente)
    {
        string tokenCarrinho = CookieHelper.BuscaCookieCarrinho();

        if(tokenCarrinho != null)
        {
            PedidoDAO _pedidoDAO = new PedidoDAO();

            _pedidoDAO.AtualizaClientePedido(tokenCarrinho, Cliente);
        }
    }
}

here is the Clientedao that does the customer search in the database

public cliente Autenticar(string email, string senha)
    {
        try
        {
            using (_contexto = new EnvidroEntidades())
            {
                //Busco o cliente
                var cliente = _contexto.cliente
                    .Where(u => u.email == email)
                    .FirstOrDefault();

                //Se o cliente não existe ou a senha criptografada não bate, não autentico o usuário
                if (cliente == null || !BCrypt.Net.BCrypt.Verify(senha, cliente.senha))
                {
                    return null;
                }
                else
                {
                    //criar a sessao do usuario
                    return cliente;
                }
            }
        }

And here is the class that updates the request that does not have id customer after logging in:

public void AtualizaClientePedido(string tokenCarrinho, cliente Cliente)
    {
        try
        {
            using (_contexto = new EnvidroEntidades())
            {
                var pedido = _contexto
                                    .pedido
                                    .Where(p => p.token_pedido == tokenCarrinho && p.situacao == "Carrinho")
                                    .FirstOrDefault();

                if (pedido != null && pedido.id_cliente == null)
                {
                    pedido.id_cliente = Cliente.id;
                    _contexto.Entry(pedido).State = EntityState.Modified;
                    _contexto.SaveChanges();
                }
            }
        }
        catch (Exception)
        {
            //api
        }
    }

1 answer

1


Of the form used has no problem, these classes exist for this very, create codes that will be called universally in the application. At least looking over doesn’t have to worry, you’re just delegating, I didn’t see details to say there could be problems, but if you do it won’t be because it’s static. I saw some things I’d probably do differently, but just.

  • Thanks, it was just that doubt really, just out of curiosity what would you do differently ? I like to know other ways of doing things, I believe it’s better than the way I’m doing things

Browser other questions tagged

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