using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using DataModel.Models;
using Microsoft.AspNet.Identity;
namespace WebInterface.Security
{
///
/// Custom user identity for tracking user-related data
///
public sealed class UserIdentity : ClaimsIdentity
{
///
/// Constuctor
///
/// Claims for identity
/// Type of authentication for identity
public UserIdentity(IEnumerable claims, string authenticationType = DefaultAuthenticationTypes.ApplicationCookie)
: base(claims, authenticationType)
{
}
///
/// Constuctor
///
/// Identity to parse from
public UserIdentity(ClaimsIdentity claimsIdentity)
: base(claimsIdentity.Claims, claimsIdentity.AuthenticationType)
{
}
///
/// Extracts the keyed claims to generate LDAPEntry for user
///
/// LDAPEntry for current user
public LDAPEntry ToLDAPEntry()
{
return new LDAPEntry()
{
DN = GetClaimValue(ClaimTypes.NameIdentifier),
Username = GetClaimValue(ClaimTypes.WindowsAccountName),
FirstName = GetClaimValue(ClaimTypes.GivenName),
LastName = GetClaimValue(ClaimTypes.Surname),
Title = GetClaimValue(ClaimTypes.Role),
EmailAddress = GetClaimValue(ClaimTypes.Email)
};
}
///
/// Gets the value assigned to the designated claim
///
/// Type/ID of claim to get value for
/// Value of designed claim
private string GetClaimValue(string claimID)
{
Claim claim = Claims.FirstOrDefault(c => c.Type == claimID);
return claim == null ? string.Empty : claim.Value;
}
///
/// Generates user identify from LDAP entry
///
/// LDAP entry to get values for claims
/// User identity with claims for LDAP entry values
public static UserIdentity FromLDAPEntry(LDAPEntry ldapEntry)
{
//Create claims from LDAP entry values
List claims = new List {
new Claim(ClaimTypes.NameIdentifier, ldapEntry.DN),
new Claim(ClaimTypes.WindowsAccountName, ldapEntry.Username),
new Claim(ClaimTypes.GivenName, ldapEntry.FirstName),
new Claim(ClaimTypes.Surname, ldapEntry.LastName),
new Claim(ClaimTypes.Role, ldapEntry.Title),
new Claim(ClaimTypes.Email, ldapEntry.EmailAddress)
};
return new UserIdentity(claims);
}
}
}