Created
September 24, 2011 11:09
-
-
Save cprieto/1239213 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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