Skip to content

Instantly share code, notes, and snippets.

@cprieto
Created September 24, 2011 11:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cprieto/1239213 to your computer and use it in GitHub Desktop.
Save cprieto/1239213 to your computer and use it in GitHub Desktop.
using System;
using System.Security.Principal;
using System.Web.Mvc;
using System.Web.Security;
using MvcApplication7.Models;
namespace MvcApplication7.Controllers
{
public class CurrentUserFilter : IAuthorizationFilter
{
private readonly IUserRepository _repository;
public CurrentUserFilter(IUserRepository repository)
{
_repository = repository;
}
public void OnAuthorization(AuthorizationContext filterContext)
{
var authCookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null)
return;
var ticket = FormsAuthentication.Decrypt(authCookie.Value); // Contains userId from FormsAuthentication.SignUp(userId, true);
var userId = Convert.ToInt32(ticket.Name);
var user = _repository.GetUserById(userId);
var principal = new MyUserPrincipal(new MyUserIdentity(user.Id, user.Username, user.AvatarUrl));
filterContext.HttpContext.User = principal;
}
}
public class MyUserPrincipal : IPrincipal
{
private readonly MyUserIdentity _identity;
public MyUserPrincipal(MyUserIdentity identity)
{
_identity = identity;
}
public bool IsInRole(string role)
{
return true; // or you know, put your logic here mate!
}
public IIdentity Identity
{
get { return _identity; }
}
}
public class MyUserIdentity : IIdentity
{
public int UserId { get; set; }
public string Username { get; set; }
public string AvatarUrl { get; set; }
public MyUserIdentity(int userId, string username, string avatarUrl)
{
UserId = userId;
Username = username;
AvatarUrl = avatarUrl;
}
public string Name
{
get { return Username; }
}
public string AuthenticationType
{
get { return "Custom"; }
}
public bool IsAuthenticated
{
get { return string.IsNullOrWhiteSpace(Username) == false; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment