Created
March 20, 2013 20:55
-
-
Save ChrisMcKee/5208336 to your computer and use it in GitHub Desktop.
FormsAuthentication class + AuthCookie
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
namespace xxx.Web.Auth | |
{ | |
using System; | |
using System.Security.Principal; | |
using xxx.Domain.Entities; | |
public class FormsAuthentication : IFormsAuthentication | |
{ | |
public void SetAuthCookie(string userId, RoleType roleType, string displayName, string email) | |
{ | |
var identityName = string.Format("{0}|{1}", userId, roleType); | |
var authCookie = new AuthCookie(identityName) | |
{ | |
DisplayName = displayName, | |
Email = email, | |
RoleType = roleType | |
}; | |
authCookie.Set(); | |
} | |
public AuthCookie GetAuthCookie() | |
{ | |
try | |
{ | |
return AuthCookie.Get(); | |
} | |
catch (Exception) | |
{ | |
} | |
return null; | |
} | |
public void SignOut() | |
{ | |
System.Web.Security.FormsAuthentication.SignOut(); | |
} | |
} | |
public static class IdentityExtensions | |
{ | |
internal class UserIdentity | |
{ | |
public UserIdentity(int userId, RoleType roleType) | |
{ | |
UserId = userId; | |
RoleType = roleType; | |
} | |
public int UserId { get; set; } | |
public RoleType RoleType { get; set; } | |
} | |
private static UserIdentity GetIdentity(this IIdentity identity) | |
{ | |
RoleType currentIdentityRole; | |
int currentIdentityUserId; | |
if (identity.Name == null) return null; | |
var split = identity.Name.Split('|'); | |
if (split.Length < 1) return null; | |
int.TryParse(split[0], out currentIdentityUserId); | |
Enum.TryParse(split[1], out currentIdentityRole); | |
return new UserIdentity(currentIdentityUserId, currentIdentityRole); | |
} | |
public static bool IsInRole(this IIdentity identity, RoleType role) | |
{ | |
var currenRole = identity.CurrentRole(); | |
return currenRole.HasValue && currenRole.Value.Equals(role); | |
} | |
public static RoleType? CurrentRole(this IIdentity identity) | |
{ | |
var role = identity.GetIdentity(); | |
if (role == null) | |
{ | |
System.Web.Security.FormsAuthentication.SignOut(); | |
return null; | |
} | |
return role.RoleType; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment