0

What I want is, In an application, if the user does not do anything for more than 2 mins, I want to redirect the page to the login page, stating that the session has expired. So for that, I tried something like below

In my HomeController

public class SessionTimeoutAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {            
        HttpContext ctx = HttpContext.Current;

        var strSession = HttpContext.Current.Session;
        if (strSession == null)
        {
            filterContext.Result = new RedirectResult("Login");                
        }
        base.OnActionExecuting(filterContext);
    }
}

and in every controller method i have added like this

[SessionTimeout]
public class AppController : Controller
{}

Also like this below

[HttpGet]
    public ActionResult Assign()
    {
        string validUser = "";
        string action = "";
        string controller = "";
        List<UMSLocationDetails> lstUMSLocationDetails = new List<UMSLocationDetails>();
        HomeController homeController = new HomeController();
        string assignUser = homeController.CheckRole(Convert.ToString(TempData["LoginUserName"]), Convert.ToString(TempData["strCurrentGroupName"]));

        if (Convert.ToString(TempData["strCurrentGroupName"]) != assignUser || Convert.ToString(TempData["strCurrentGroupName"]) == "" || Convert.ToString(TempData["strCurrentGroupName"]) == null)
        {
            return RedirectToAction("Login", "Home");
        }
        else
        {
            if (TempData["Location"] != null)
            {
                lstUMSLocationDetails = TempData["Location"] as List<UMSLocationDetails>;
                ViewBag.LocationDetails = lstUMSLocationDetails;
                TempData.Keep();
                //TempData.Remove("Location");
                ViewBag.LoginUserName = Convert.ToString(TempData["LoginUserName"]);
                //ViewBag.LoginUserName = Convert.ToString(Session["LoginUserName"]);  
                ViewBag.CurrentGroupName = Convert.ToString(TempData["strCurrentGroupName"]).Replace("_", " ");
                ViewBag.strReturnMessage = Convert.ToString(TempData["strReturnMessage"]);
                TempData.Remove("strReturnMessage");
                if (assignUser == strSapUserRole)
                {
                    validUser = "";
                    action = "Assign"; controller = "App";
                }
                else
                {
                    validUser = "1";
                    // return RedirectToAction("Login", "Home");
                    action = "Login"; controller = "Home";

                }
                //TempData.Remove("LoginUserName");
                //TempData.Remove("strCurrentGroupName");
            }
            if (validUser == "1")
            {
                return RedirectToAction("Login", "Home");
            }
            else
            {
                return View();
            }
        }

    }
    [HttpGet]
    public ActionResult Certify()
    {
        string validUser = "";
        string action = "";
        string controller = "";
        List<UMSLocationDetails> lstUMSLocationDetails = new List<UMSLocationDetails>();
        HomeController homeController = new HomeController();
        string certifyUser = homeController.CheckRole(Convert.ToString(TempData["LoginUserName"]), Convert.ToString(TempData["strCurrentGroupName"]));
        //  string certifyUser = "NEIQC_FIBER_ENGINEER";
        if (Convert.ToString(TempData["strCurrentGroupName"]) != certifyUser || Convert.ToString(TempData["strCurrentGroupName"]) == "" || Convert.ToString(TempData["strCurrentGroupName"]) == null)
        {
            return RedirectToAction("Login", "Home");
        }
        else
        {
            if (TempData["Location"] != null)
            {
                lstUMSLocationDetails = TempData["Location"] as List<UMSLocationDetails>;
                ViewBag.LocationDetails = lstUMSLocationDetails;
                TempData.Keep();
                //TempData.Remove("Location");
                ViewBag.LoginUserName = Convert.ToString(TempData["LoginUserName"]);
                ViewBag.CurrentGroupName = Convert.ToString(TempData["strCurrentGroupName"]).Replace("_", " ");
                TempData.Keep();
                if (certifyUser == strFEUserRole)
                {
                    validUser = "";
                    action = "Certify"; controller = "App";
                }
                else
                {
                    validUser = "1";
                    // return RedirectToAction("Login", "Home");
                    action = "Login"; controller = "Home";
                }
            }
            if (validUser == "1")
            {
                return RedirectToAction("Login", "Home");
            }
            else
            {
                return View();
            }
            // return View();
            // return RedirectToAction(action, controller);
        }
    }
    [HttpGet]
    public ActionResult Approver()
    {
        string validUser = "";
        string action = "";
        string controller = "";
        List<UMSLocationDetails> lstUMSLocationDetails = new List<UMSLocationDetails>();
        HomeController homeController = new HomeController();
        string aprroverUser = homeController.CheckRole(Convert.ToString(TempData["LoginUserName"]), Convert.ToString(TempData["strCurrentGroupName"]));
        if (Convert.ToString(TempData["strCurrentGroupName"]) != aprroverUser || Convert.ToString(TempData["strCurrentGroupName"]) == "" || Convert.ToString(TempData["strCurrentGroupName"]) == null)
        {
            return RedirectToAction("Login", "Home");
        }
        else
        {


            if (TempData["Location"] != null)
            {
                lstUMSLocationDetails = TempData["Location"] as List<UMSLocationDetails>;
                ViewBag.LocationDetails = lstUMSLocationDetails;
                TempData.Keep();
                //TempData.Remove("Location");
                ViewBag.LoginUserName = Convert.ToString(TempData["LoginUserName"]);
                ViewBag.CurrentGroupName = Convert.ToString(TempData["strCurrentGroupName"]).Replace("_", " ");
                if (aprroverUser == strCMMpUserRole)
                {
                    validUser = "";
                    action = "Certify"; controller = "App";
                }
                else
                {
                    validUser = "1";
                    // return RedirectToAction("Login", "Home");
                    action = "Login"; controller = "Home";

                }
            }
            if (validUser == "1")
            {
                return RedirectToAction("Login", "Home");
            }
            else
            {
                return View();
            }
            // return View();
            // return RedirectToAction(action, controller);
        }
    }

I tried with above code but nothing is happening. Please suggest what should be the best possible way to achieve this.

UPDATE

[HttpPost]
    [ValidateInput(false)]
    public ActionResult ValidateUser()
    {
        string strUsername = Sanitizer.GetSafeHtmlFragment(Convert.ToString(Request.Form["txtUsername"]));
        string strPassword = Sanitizer.GetSafeHtmlFragment(Convert.ToString(Request.Form["txtPassword"]));            
        string strDbError = string.Empty;
        strUsername = strUsername.Trim();
        strPassword = strPassword.Trim();
        string strUserName = "";
        string strCurrentGroupName = "";
        int intCurrentGroupID = 0;
        string controller = "";
        string action = "";

        UserProviderClient ObjUMS = new UserProviderClient();
        bool result = false;            

        if (strUsername != "" || strPassword != "")
        {
            result = ObjUMS.AuthenticateUser(strUsername, strPassword, out strDbError);
            try
            {
                if (result == true)
                {
                    UMS ObjUMSDATA = new UMS();
                    //strUserName = System.Web.HttpContext.Current.User.Identity.Name.Split('\\')[1];
                    strUserName = strUsername;
                    _UMSUserName = strUserName;

                    if (!string.IsNullOrEmpty(strUserName))
                    {
                        List<UMSGroupDetails> lstUMSGroupDetails = null;
                        List<UMSLocationDetails> lstUMSLocationDetails = null;

                        ObjUMSDATA.GetUMSGroups(strUserName, out strCurrentGroupName, out intCurrentGroupID, out lstUMSLocationDetails, out lstUMSGroupDetails);
                        if (strCurrentGroupName != "" && intCurrentGroupID != 0)
                        {
                            ViewBag.LoginUserName = strUserName.ToUpper();
                            ViewBag.CurrentGroupName = strCurrentGroupName;
                            ViewBag.CurrentGroupID = intCurrentGroupID;
                            ViewBag.GroupDetails = lstUMSGroupDetails;
                            ViewBag.LocationDetails = lstUMSLocationDetails;
                            TempData["LoginUserName"] = strUsername.ToUpper();
                            TempData["Location"] = lstUMSLocationDetails;
                            TempData["strCurrentGroupName"] = strCurrentGroupName;
                            TempData.Keep();
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, "You are not registered. Please register first.");
                            return View("Login");
                        }
                    }
                }
                if (strCurrentGroupName == "SAP Executive")
                {
                    action = "Assign"; controller = "App";
                }
                else if (strCurrentGroupName == "Maintenance Lead")
                {
                    //return RedirectToAction("App", "Certify");
                    action = "Certify"; controller = "App";
                }
                else if (strCurrentGroupName == "NEIQC CMM")
                {
                    //return RedirectToAction("App", "Approver");
                    action = "Approver"; controller = "App";
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid Username and password");                        
                    return View("Login");                        
                }
            }
            catch (Exception ex)
            {   
                ApplicationLog.Error("Error", "ValidateUser", ex.Message);
            }
        }
        else
        {
            ModelState.AddModelError(string.Empty, "Invalid Username and password");                
            return View("Login");
        }

        //Session["isUserAuthenticated"] = result;            

        return RedirectToActionPermanent(action, controller);
    }
Nad
  • 4,605
  • 11
  • 71
  • 160
  • you know that if user doesn't do anything on your page, your C# code will never be executed, right? – vasily.sib Mar 18 '20 at 08:28
  • @vasily.sib: yes, but remaining idle should process something to logout ? – Nad Mar 18 '20 at 08:29
  • I mean, your `SessionTimeoutAttribute` doesn't do anything with `Timeout`. It just redirects to Login if you have no session yet. Maybe you should store `LoginAt` value in your session, and check for this value in your `SessionTimeoutAttribute`? – vasily.sib Mar 18 '20 at 08:34
  • @vasily.sib: can you help me out with some code so that I can try – Nad Mar 18 '20 at 08:36
  • It depends on how do you login your users? Do you have some kind of `UsersController.Login()` action? – vasily.sib Mar 18 '20 at 08:40
  • @vasily.sib: Yes, I have updated my question for more reference. Please check – Nad Mar 18 '20 at 08:43
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/209828/discussion-between-nkb-and-vasily-sib). – Nad Mar 18 '20 at 08:50

2 Answers2

0

If you are trying to check the user session then why not use the Authorized filter instead?

[Authorized]
public class AppController : Controller
{}

More usages can be found here: Authorize attribute in ASP.NET MVC

Update: The Authorized attribute would do the same as your code:

var strSession = HttpContext.Current.Session;
if (strSession == null)
{
    filterContext.Result = new RedirectResult("Login");                
}

i.e. checks the session and if it is lost it would redirect to the login page.

Rahatur
  • 3,147
  • 3
  • 33
  • 49
  • 1
    some useful links and code would be highly recommended while posting the answer – Nad Mar 18 '20 at 08:30
  • i dont want to authenticate, i want to handle the timeout functionality. The authentication is working – Nad Mar 18 '20 at 09:28
0

You almost there. Look at your ValidateUser() code, there is a commented line at the end:

//Session["isUserAuthenticated"] = result;

This is how you store some data in your session. Add this line just beneath that comment:

Session["UserLoginAt"] = DateTime.Now;

Then, in your SessionTimeoutAttribute you need to get this value:

var timeout = TimeSpan.FromMinutes(2) // lets say you have a 2 minutes timeout

var userLoginAt = filterContext.HttpContext.Session["UserLoginAt"] as DateTime?;
if (userLoginAt.HasValue && userLoginAt.Value < DateTime.Now.Subtract(timeout))
    // redirect to logOUT page if we are timed out
    filterContext.Result = new RedirectResult("Logout");

Please note, that all above code was not checked.

vasily.sib
  • 3,871
  • 2
  • 23
  • 26