using System; using System.Collections.Generic; using System.Linq; namespace ln.identities { public class Identity { public static Identity Anonymous(IIdentityProvider identityProvider) => new Identity(identityProvider, Guid.Empty, null); private IIdentityProvider identityProvider; public IIdentityProvider IdentityProvider => identityProvider; public Guid UniqueID { get; private set; } public String IdentityName { get; set; } List secureAttributes = new List(); AssignedRoles assignedRoles; List cachedRoleAssignments; private Identity(IIdentityProvider identityProvider) { this.identityProvider = identityProvider; } private Identity(IIdentityProvider identityProvider,Guid uniqueID,string identityName) :this(identityProvider) { UniqueID = uniqueID; IdentityName = identityName; } public Identity(IIdentityProvider identityProvider,string identityName) : this(identityProvider,Guid.NewGuid(),identityName){} public void ResetCaches() { cachedRoleAssignments = null; } public SecureAttribute GetSecureAttribute(Guid uniqueID) { foreach (SecureAttribute secureAttribute in secureAttributes) { if (secureAttribute.UniqueID.Equals(uniqueID)) return secureAttribute; } throw new KeyNotFoundException(); } public SecureAttribute[] GetSecureAttributes() => secureAttributes.ToArray(); public SecureAttribute[] GetSecureAttributes(String secureAttributeTypeName) => secureAttributeTypeName == null ? GetSecureAttributes() : secureAttributes.Where((secureAttribute)=>secureAttribute.GetAttributeTypeName().Equals(secureAttributeTypeName)).ToArray(); public KeyValuePair[] GetChallenges() => GetChallenges(null); public KeyValuePair[] GetChallenges(String secureAttributeTypeName) { SecureAttribute[] sas = GetSecureAttributes(secureAttributeTypeName); KeyValuePair[] challenges = new KeyValuePair[sas.Length]; for (int n = 0; n < sas.Length; n++) { challenges[n] = new KeyValuePair(sas[n].UniqueID, sas[n].CreateChallenge()); } return challenges; } public void AddSecureAttribute(SecureAttribute secureAttribute) => secureAttributes.Add(secureAttribute); public void RemoveSecureAttribute(SecureAttribute secureAttribute) => secureAttributes.Remove(secureAttribute); public void ClearAssignedRolesCache() => assignedRoles = null; public AssignedRoles AssignedRoles { get { if (assignedRoles == null) { assignedRoles = IdentityProvider.GetAssignedRoles(this); } return assignedRoles; } } public IEnumerable RoleAssignments { get { if (cachedRoleAssignments == null) { cachedRoleAssignments = new List(IdentityProvider.GetRoleAssignments(this)); } return cachedRoleAssignments; } } public override bool Equals(object obj) => (obj is Identity other) && other.UniqueID.Equals(UniqueID); public override int GetHashCode() => UniqueID.GetHashCode(); public override string ToString() => String.Format("[Identity UniqueID={0} IdentityName={1}]",UniqueID,IdentityName); } }