Prevent user from being logged in twice

2

In my project, I have a login module that works perfectly. So 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 can have problems with that.

How can I stop this operation? I mean, do I check in on the login in my application and if the user is logged in to the application, will it prevent this new attempt while the same user is logged into my application?

My login code:

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");
}
    
asked by anonymous 30.11.2014 / 01:37

1 answer

2

1. Put properties on the user that control whether they are 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 that checks for an already open session

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 RedirectToAction is protected not Controller . You will have to% base% reintroducing Controller to use it within RedirectToAction :

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

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

[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");
}
    
30.11.2014 / 20:38