Search:

Search all manuals
Search this manual
Manual
Membase and ASP.NET MVC 3 Tutorial
Additional Resources
Community Wiki
Community Forums
Couchbase SDKs
Parent Section
Membase and ASP.NET MVC 3 Tutorial
Chapter Sections
Chapters

6. Stage 5: Adding an authentication check

It is common in older style web applications to protect each action with a check to see whether the user is logged in (typically by checking if a cookie is valid) and redirecting them to a login page if not. This simple mechanism has been around for a long time. We're just going to go through and create one of these simple mechanisms using the fact that Membase keys can be set to expire automatically. Using an expiring key to keep a reference to the User record in means that if the key has expired, the application will need the user to reauthenticate in order to find the record again.

First, modify the Index method of HomeControler and add the bold face lines in Listing 11.

Listing 11: Modify the Index action.

public ActionResult Index()
 {
     var client = MvcApplication.MembaseClient;

     ViewData["Message"] = "I don't know you.";
     ViewData["IsLoggedIn"] = false;

     User user;
     if (!IsAuthenticated(client, out user))
         return RedirectToAction("Login");

     return View();
 }

Next, add the code in Listing 12 to the end of the HomeController class.

Listing 12: The IsAuthenticated method.

/// <summary>
/// Check that the user is authenticated, and if not, set some
/// view data to make sure a login form is shown.
/// </summary>
/// <param name="client"></param>
/// <param name="user">the user will be returned through
///   this out variable</param>
/// <returns></returns>
private bool IsAuthenticated(MembaseClient client, out User user)
{
    var cookie = ControllerContext.HttpContext
        .Request.Cookies["MEMBASE_SESSION"];
    if (cookie != null)
    {
        var sessionToken = cookie.Value;
        var userKey = client.Get<string>(sessionToken + AppSecret);

        if (userKey == null)
        {
            // User must have been idle too long and their session has
            // expired, so they'll need to log back in
            ViewData["Message"] = "You'll need to log in.";
        }
        else
        {
            var userId = client.Get<Guid>(userKey);
            user = client.Get<User>(userId.ToString());

            if (user == null)
            {
                ViewData["Message"] = "Unable to log in.";
            }
            else
            {
                ViewData["Message"] = "Welcome " + user.FullName;
                ViewData["IsLoggedIn"] = true;
                ViewData["User"] = user;

                // User is authenticated correctly so keep the session alive
                // by using the Touch operation which resets the timeout
                // for the key in the database.
                client.Touch(sessionToken + AppSecret,
                   TimeSpan.FromMinutes(SessionTimeoutMinutes));

                return true;
            }
        }
    }

    user = null;

    return false;
}

This method checks the request for a MEMBASE_SESSION cookie with a session token value that can be used to retrieve a userKey from the database. That user key can be used to retrieve the user's primary key and in turn get the stored user record, if it exists. This might seem overly complicated, but there is flexibility to design whatever data layout you wish within Membase. This is simply one layout that solved this particular problem, and you should feel free to create others.

Of special note is the use of the Touch method. If the user has correctly logged in, this operation will extend the expiry time of the session token whenever this method is hit. The Touch operation extends the expiry without actually getting the data. It is a method that the Enyim client library is using which exists in Membase servers from 1.7 and up. It will not work on 1.6 servers, so be aware of that.

Try the application out by hitting F5. The workflow of the application is fairly complete now. When you first hit the page, you will be asked to log in or create a new account. Afterwards, you remain logged in until you click the logout link, or until the session expires in 60 minutes.

The application needs more of a purpose, so let's quickly turn it into a simple online diary.