0

I'm following the next post which it really what I'm utilizing.

https://stackoverflow.com/a/15939899/1118485

As you see, this only is implemented in one of the methods of HomeController. To avoid rewrite code, I write a BaseController.

    protected new ViewResult View()
    {
        if (Session["sessionid"] == null )
        {
            //Session["sessionid"] = "empty";
            return base.View();
        }

        // check to see if your ID in the Logins table has LoggedIn = true - if so, continue, otherwise, redirect to Login page.
        if (OperationContext.IsYourLoginStillTrue(System.Web.HttpContext.Current.User.Identity.Name, Session["sessionid"].ToString()))
        {
            // check to see if your user ID is being used elsewhere under a different session ID
            if (!OperationContext.IsUserLoggedOnElsewhere(System.Web.HttpContext.Current.User.Identity.Name, Session["sessionid"].ToString()))
            {
                //return base.View();
            }
            else
            {
                // if it is being used elsewhere, update all their Logins records to LoggedIn = false, except for your session ID
                OperationContext.LogEveryoneElseOut(System.Web.HttpContext.Current.User.Identity.Name, Session["sessionid"].ToString());
                //return base.View();
            }
        }
        else
        {
            FormsAuthentication.SignOut();
            Attention("You have logged out because another user with the account has been connnected.");
            //return RedirectToAction("Login", "Account");
        }

        return base.View();
    }

But as you see, this only works when use View method, in my other controllers I used several Redirects or FileResult. So I need every ActionResult is executed, verify the above code. While I was investigated I supposed that I need to implement a custom ActionResultAttribute in all of my controllers, am I right?

If I'm right, can you show me a demo implementation about how can I use my custom ActionResultAttr to verify all the time the login. Or if am I wrong, what can I do?

Community
  • 1
  • 1
Darf Zon
  • 6,268
  • 20
  • 90
  • 149

1 Answers1

0

You can use OnAuthorization method of Controller class, which is executed before action.

public class BaseController : Controller
{
    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        if ( /*session is not valid*/)
        {
            filterContext.Result = RedirectToAction("SessionExpired", "Account");
        }
    }
}
LukLed
  • 31,452
  • 17
  • 82
  • 107
  • @DarfZon: How is user null? If user is logged in, it can't be null. That has to issue on your side. – LukLed Jun 02 '13 at 08:36