using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Security.Principal; using FHT.Agency.CommonTypes; using FHT.Agency.Resources; using FHT.Utilities; namespace FHT.Agency.Web.Extensions { public static class UserIdentityExtensions { public static bool HasClaim(this IPrincipal user, FhtUserClaimType claim) { var claimsIdentity = (ClaimsIdentity)user.Identity; return claimsIdentity.Claims.Any(c => c.Type == "fhtuserclaimtype" && c.Value == ((int)claim).ToString()); } public static IEnumerable UserClaims(this IPrincipal user) { var claimsIdentity = (ClaimsIdentity)user.Identity; return claimsIdentity.Claims.Where(c => c.Type == "fhtuserclaimtype") .Select(c => (FhtUserClaimType)int.Parse(c.Value)) .ToList(); } public static FhtUserRoleType UserRole(this IPrincipal user) { var claimsIdentity = (ClaimsIdentity)user.Identity; return (FhtUserRoleType)int.Parse(claimsIdentity.Claims.Single(c => c.Type == "fhtuserroletype").Value); } public static bool HasRole(this IPrincipal user, FhtUserRoleType role) { return user.UserRole() == role; } public static string DescriptiveName(this IPrincipal user) { var claimsIdentity = (ClaimsIdentity)user.Identity; return claimsIdentity.Claims.Single(c => c.Type == "descriptivename").Value; } public static string AvatarUrl(this IPrincipal user) { var claimsIdentity = (ClaimsIdentity)user.Identity; string avatarUrl =claimsIdentity.Claims.Single(c =>c.Type == "avatarUrl").Value; return ImageConverter.ToAbsoluteUrl(avatarUrl); } public static string CompanyName(this IPrincipal user) { var claimsIdentity = (ClaimsIdentity)user.Identity; return claimsIdentity.Claims.Single(c => c.Type == "companyname").Value; } public static AgentType? AgentType(this IPrincipal user) { var claimsIdentity = (ClaimsIdentity)user.Identity; int? agentType = claimsIdentity.Claims.Single(c => c.Type == "agentleveltype") != null ? int.Parse(claimsIdentity.Claims.Single(c => c.Type == "agentleveltype").Value) : (int?)null; if (agentType.HasValue) { var t = (AgentType)agentType; if(!t.IsValid()) { throw new InvalidOperationException("agentType: " + agentType + " is not valid"); } return t; } return null; } } }