ln.identities/ODBIdentityProvider.cs

92 lines
3.2 KiB
C#

using System;
using System.Collections.Generic;
using ln.types.odb.ng.storage;
using ln.types.odb.ng;
using System.Linq;
using ln.types.btree;
using ln.types.collections;
using System.Security.Principal;
using ln.types.odb.ng.mappings;
using System.Reflection;
namespace ln.identities
{
public class ODBIdentityProvider : BaseIdentityProvider
{
public IStorageContainer StorageContainer { get; }
Mapper mapper;
WeakValueDictionary<Guid, Identity> identityCache = new WeakValueDictionary<Guid, Identity>();
public ODBIdentityProvider(IStorageContainer storageContainer)
{
StorageContainer = storageContainer;
mapper = new Mapper(storageContainer);
ClassMapping identityClassMapping = new ClassMapping(
typeof(Identity),
(Mapper arg1, Document arg2) => new Identity(this,""),
(fieldInfo) => !fieldInfo.Name.Equals("identityProvider")
);
mapper.RegisterMapping(identityClassMapping.MappedType,identityClassMapping);
mapper.EnsureIndex<Identity>("UniqueID");
mapper.EnsureIndex<Identity>("IdentityName");
}
public override IEnumerable<KeyValuePair<Guid, string>> GetIdentities() => mapper.Load<Identity>().Select((identity) => new KeyValuePair<Guid, string>(identity.UniqueID, identity.IdentityName));
public override Identity GetIdentity(Guid uniqueID)
{
if (identityCache.ContainsKey(uniqueID))
return identityCache[uniqueID];
Identity identity = mapper.Load<Identity>(Query.Equals<Identity>("UniqueID", uniqueID)).FirstOrDefault();
if (identity != null)
{
identityCache.Add(identity.UniqueID,identity);
return identity;
}
throw new KeyNotFoundException();
}
public override Identity GetIdentity(string identityName)
{
Identity identity = mapper.Load<Identity>(Query.Equals<Identity>("IdentityName", identityName)).FirstOrDefault();
if (identity != null)
{
if (!identityCache.ContainsKey(identity.UniqueID))
identityCache.Add(identity.UniqueID, identity);
return identity;
}
throw new KeyNotFoundException();
}
public override Identity CreateIdentity(string identityName)
{
Identity identity = new Identity(this,identityName);
identityCache.Add(identity.UniqueID, identity);
return identity;
}
public override bool Save(Identity identity)
{
if (!identityCache.ContainsKey(identity.UniqueID))
throw new KeyNotFoundException();
Identity cachedIdentity = identityCache[identity.UniqueID];
if (!Object.ReferenceEquals(identity, cachedIdentity))
throw new ArgumentOutOfRangeException();
mapper.Save<Identity>(cachedIdentity);
return true;
}
public override IEnumerable<RoleAssignment> GetRoleAssignments(Identity identity)
{
throw new NotImplementedException();
}
}
}