How to create a simple login system

1. Create an attribute for public actions.

    public class PublicActionAttribute : Attribute
    {
    }

2. Tag the Login action in your UserController (or similiar) with the attribute.

        [PublicAction]
        public IViewData Login()
        {
            return Render();
        }

        [PublicAction]
        public IActionResult LoginPost()
        {
            string userName = Form["username"];
            string password = Form["password"];
            string rememberMe = Form["rememberme"];

            // authenticate here.

            // create session
            WebSession.Create();
            WebSession.Current.UserId = 1;
            WebSession.Current.Status = UserStatus.SuperAdmin;


            return RedirectToUri("/user/welcome/");
        }

3. Override BeforeAction in your ApplicationController

        protected override HttpServer.Mvc.IActionResult BeforeAction(MethodInfo method)
        {
            bool isPublicMethod = false;

            // Check if action have been tagged with the public attribute.
            foreach (var attribute in method.GetCustomAttributes(true))
            {
                if (attribute is PublicActionAttribute)
                {
                    isPublicMethod = true;
                    break;
                }
            }

            // Check if our specified status is less then the required one.
            if (!isPublicMethod && WebSession.Current.Status < UserStatus.User)
                return new Redirect("/errors/accessdenied");

            return null;
        }

4. Done!

Last edited Mar 19, 2010 at 9:05 PM by jgauffin, version 1

Comments

jgauffin Mar 21, 2010 at 6:22 PM 
lol. sry. Forgot to commit those changes when I wrote the article =)

todd1814 Mar 21, 2010 at 4:41 PM 
I couldn't find the BeforeAction method in the latest source code. This is my implementation of BeforeAction which can be easily added:

HttpServer.Mvc.Controllers.Controller:

Add the following...

internal IActionResult InvokeBeforeAction(MethodInfo method)
{
return BeforeAction(method);
}

protected virtual IActionResult BeforeAction(MethodInfo method)
{
return null;
}

HttpServer.Mvc.Controllers.ControllerDirector:

Change the following line:

object result = method.Invoke(controller, null);

To:

object result = controller.InvokeBeforeAction(method) ?? method.Invoke(controller, null);

This example for logins works great otherwise! Just decorate you public methods with [PublicAction] and leave password protected ones without the attribute.

I also chose to return base.BeforeAction(method) rather than null in the overridden method. Not necessary, accomplishes the same thing as return null but allows any future code in the superclass to be called.