Prevent user from being logged in twice

Asked

Viewed 1,270 times

2

In my project, I have a login module that works perfectly. Until then quiet, but the way it is I can not bar the same user logged in twice. That is, I can log in with the same user twice, and that’s not what I want. Because I may have problems with this.

How can I stop this operation ? I mean, do a check at the moment of login in my application and if by chance the user is logged in to the application, bar this new attempt while the same user is logged in to my application ?

The code of my login:

public ActionResult Index()
{
    return View();
}
[HttpPost]
public ActionResult Index(String Login, String Senha)
{
    //verificando login pelo usuario do banco de dados ...
    Usuario login = db.Usuarios.Where(x => x.Login == Login && x.Senha == Senha).FirstOrDefault();
    if (login != null)
    {
        FormsAuthentication.SetAuthCookie(Login, false);
        Session.Add(".PermissionCookie", login.Perfil);
        return RedirectToAction("Index", "Home"); //pagina padrao para todos os usuarios...
    }
    return RedirectToAction("Index");
}

1 answer

2


1. Place properties on the user who controls whether he is logged in or not

public class Usuario 
{
    ...
    public bool Logado { get; set; }
    pubic string SessionId { get; set; }
    public DateTime UltimoLogin { get; set; }
    ...
}

2. Implement a ActionFilter to check if a session is already open

namespace SeuProjeto.Filters 
{
    public class UniqueSessionActionFilter : ActionFilterAttribute, IActionFilter
    {
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            var contexto = new MeuProjetoContext();
            // Recupero a Id do Usuário logado aqui.
            // Não sei como você está fazendo, então inventei um método
            var idDoUsuario = RecuperarIdDoUsuarioLogado();

            var usuario = contexto.Usuarios.FirstOrDefault(u => u.Id == idDoUsuario && u.Logado && u.SessionId != filterContext.HttpContext.Session.SessionID);

            if (usuario != null) {
                // Se o último login foi feito dentro do período de um dia
                if (usuario.UltimoLogin.AddDays(1) > DateTime.Now) {
                    // Usuário logado em outro lugar.
                    usuario.Logado = false;
                    contexto.Entry(usuario).State = EntityState.Modified;
                    contexto.SaveChanges();
                    // Destrua aqui a Session do Usuário se houver uma.
                } else {
                    // O login do Usuário expirou.
                    var controller = (MeuControllerBase) filterContext.Controller;
                    filterContext.Result = controller.RedirectToAction("Index", "Login");
                }
            }

            this.OnActionExecuting(filterContext);
        }
    }
}

Only that RedirectToAction is protected in the Controller. You’ll have to make one Controller reintroduced base RedirectToAction to use it inside the ActionFilter:

public class MeuControllerBase: Controller 
{
    public new RedirectToRouteResult RedirectToAction(string action, string controller)
    {
        return base.RedirectToAction(action, controller);
    }
}

3. When creating the Authentication Ticket, fill in Logado, SessionId and UltimoLogin

[HttpPost]
public ActionResult Index(String Login, String Senha)
{
    //verificando login pelo usuario do banco de dados ...
    Usuario login = db.Usuarios.Where(x => x.Login == Login && x.Senha == Senha).FirstOrDefault();
    if (login != null)
    {
        FormsAuthentication.SetAuthCookie(Login, false);
        Session.Add(".PermissionCookie", login.Perfil);

        login.Logado = true;
        login.UltimoLogin = DateTime.Now;
        login.SessionId = HttpContext.Current.Session.SessionID;

        db.Entry(login).State = EntityState.Modified;
        db.SaveChanges();

        return RedirectToAction("Index", "Home"); //pagina padrao para todos os usuarios...
    }
    return RedirectToAction("Index");
}

Browser other questions tagged

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