Day 22: Sprucing up Identity for Logged In Users

This is an installment in a 30 day series on Bootstrap and the MVC Framework. To see more, check out Day 0 for an index.

Typically you wouldn’t want the entirety of the internet adding and editing records at will without some form of authentication and authorization so that you can keep track of who’s editing your data, or so that your users can keep track of their own.

So, let’s continue with our project and build out some identity capabilities.

Okay, I’m Kidding. Just Press F5!

Great work, you’re all done!

As most folks are well aware, the default templates for Asp.Net applications now ship with a sample account administration implementation (reasonably good ones, at that). Users are able to register and log in using pre-built models, controllers and views. You can easily extend the template with 3rd party login capabilities, allowing folks with Microsoft, Facebook or Google accounts (and, and, and…) to log into your site as well. We’ve now got substantial improvements to identity management overall, with things like two-factor authentication, reductions in the leaky abstractions we’ve lived with, better testability, more flexibility in storage options, and more.

If you’re not familiar with these bits, it’s worth having a look, but this is a topic already well covered. Believe me, these are worth the reads:

But we’re here to do Bootstrappy things, right? So let’s spruce up that top bar a little for our logged in users with some MVC bits we build (HTML helpers) and some Bootstrap bits (image classes) that will take our site up a level.

Bootstrap Image Classes

The CSS library gives us a few easy-to-use helpers to make our images look consistent. Here’s a sample from the Bootstrap site:

image

The classes are as follows:

  • img-rounded – provides rounded corners to your rectangular images
  • img-circle – turns any image into a circle
  • img-thumbnail – makes your image look like a little Polaroid of itself

Making Members Feel Welcome

Today we’re just going to add a little touch to the navbar that our logged in users will see, keying in off of the default implementation of the Identity providers.  We’ll head in that direction by extending our HtmlHelper that generates Gravatar images, as we need to add a property for a CSS class to give us a nice round face on the page.  But first, we’ll have to add the following line of code to the GravatarOptions class:

public string CssClass { get; set; }
We’ll need to add that to the tag, so let’s revist the GravatarImage, likely located in the Helpers folder, to check for a value and add it to the tag if present. The full method should now look like this:
public static HtmlString GravatarImage(this HtmlHelper htmlHelper, string emailAddress, GravatarOptions options = null)
{
    if (options == null)
        options = GravatarOptions.GetDefaults();

    var imgTag = new TagBuilder("img");

    emailAddress = string.IsNullOrEmpty(emailAddress) ? string.Empty : emailAddress.Trim().ToLower();

    // <-- adding support for CSS
    if (!string.IsNullOrEmpty(options.CssClass))
    {
        imgTag.AddCssClass(options.CssClass);
    }
    // adding support for CSS  -->

    imgTag.Attributes.Add("src",
        string.Format("http://www.gravatar.com/avatar/{0}?s={1}{2}{3}",
            GetMd5Hash(emailAddress),
            options.Size,
            "&d=" + options.DefaultImageType,
            "&r=" + options.RatingLevel
            )
        );

    return new HtmlString(imgTag.ToString(TagRenderMode.SelfClosing));
}
Unfortunately there isn’t quite the exact Bootstrap class we need to make our image place and size well in the navbar, so we’ll need to open up our bootstrap.custom.css file and add the following structural class:

.navbar-image {
float: left;
padding: 10px 5px;
}

Finally, we’ll pop over to our _LoginPartial.cshtml (in Views\Shared) and modify the block of code displayed for logged in users.  Because I’m reusing the user’s name a couple of times (which is also their email address) I’m storing it in a variable first, and using that throughout the block. I also add a DIV as a container for our image, using the class that we just created. Last, I make a call to our GravatarImage helper, passing in the username (email!), an appropriate size for the toolbar (30px), and the Bootstrap class that gives us the shape we’re looking for (img-circle).

var username = User.Identity.GetUserName();
using (Html.BeginForm(“LogOff”, “Account”, FormMethod.Post, new { id = “logoutForm”, @class = “navbar-right” }))
{

@Html.AntiForgeryToken()

<div class=”navbar-image”>
@Html.GravatarImage(username, new GravatarOptions { Size = 30, CssClass = “img-circle” })
</div>

<ul class=”nav navbar-nav navbar-right”>
<li>
@Html.ActionLink(“Hello “ + username + “!”, “Manage”, “Account”, routeValues: null, htmlAttributes: new { title = “Manage” })
</li>
<li><a href=”javascript:document.getElementById(‘logoutForm’).submit()”>Log off</a></li>
</ul>
}

And now we’re rockin’ head shots in our navbar!

image

Next Steps

Perhaps you’ve modified your user profiles so that the username doesn’t have to be an email address. You could easily modify this example to read from a different property and generate the same type of effect.

What is sparkle without shine? Let’s give our users the ability to choose their own look-and-feel.  I mean, it worked for GeoCities, right?