Home > Software design >  ASP.NET MVC How to be logout when same user is logged in from different computer
ASP.NET MVC How to be logout when same user is logged in from different computer

Time:08-21

I did a lot of research but I couldn't find a clear solution. If logging in with the same user from a different computer, the old login must be logout.

My controller action code:

[HttpPost]
public ActionResult Index(User usr)
{
    var response = LoginManager.Login(usr);
    if (response != null)
    {
        Session.Add(Session.CurrentUser, response);
        return RedirectToAction("index", "Home");
    }
    return View();
}

LoginManager.Login code:

[HttpPost]
public static User Login(User usr)
{
    using (var db = new Entities())
    {
        var data = db.Users.FirstOrDefault(s => s.Email == usr.Email && s.Pass == 
        usr.Pass);
        if (data != null)
        {
             var ip = HttpContext.Current.Request.UserHostAddress;
             var addLog = new Log {UserID = data.Id, Date = DateTime.Now, IP = ip};
             db.Logs.Add(addLog)
             db.SaveChanges();

             return data;
        }
        return null;
    }
}

Session.CurrentUser code:

namespace ADMIN.Project
{
    public class Session
    {
        public const string CurrentUser = "CurrentUser";
    }
}

CodePudding user response:

Solution! it work fine.

Layout.cshtml Trigger

 var ip = HttpContext.Current.Request.UserHostAddress;
 var controlip= HomeManager.GetLogIP(loginuser.Id);
    if (controlip.IP != ip)
    {
        Session.Abandon();

        Response.Redirect("/Login/Index?msg=logged in from different computer");
    }

Manager GetLogIP

 public static Log GetLogIP(int id)
 {
   using (var db = new Entities())
   {
      var value = db.Logs.Where(x => x.UserID == id).ToList().Last();

      return value;
   }
 }

LoginController

 [HttpGet]
 public ActionResult Index(string msg)
 {
     ViewBag.Warning= msg;

     return View();
 }
  • Related