ln.application/ApplicationSession.cs

92 lines
3.1 KiB
C#

using System;
using System.Threading;
using ln.identities;
using ln.types.rpc;
using System.Collections.Generic;
using ln.logging;
using ln.json;
using ln.json.mapping;
namespace ln.application
{
public class ApplicationSession : IDisposable
{
static ThreadLocal<ApplicationSession> currentApplicationSession = new ThreadLocal<ApplicationSession>();
public static void SetCurrentSession(ApplicationSession applicationSession) => currentApplicationSession.Value = applicationSession;
public static void ClearCurrentSession() => currentApplicationSession.Value = null;
public static ApplicationSession CurrentSession => currentApplicationSession.Value;
public Guid SessionID { get; }
public Guid Secret { get; }
public DateTime Created { get; }
public DateTime LastAccess { get; protected set; }
public TimeSpan Age => LastAccess - Created;
public TimeSpan Untouched => DateTime.Now - LastAccess;
public Application Application { get; }
public Identity SessionIdentity { get; protected set; }
public ApplicationSession(Application application)
{
SessionID = Guid.NewGuid();
Secret = Guid.NewGuid();
Created = DateTime.Now;
LastAccess = Created;
Application = application;
SessionIdentity = null;
Logging.Log(LogLevel.DEBUG, "ApplicationSession created: {0}",SessionID);
}
protected void UpdateLastAccess()
{
LastAccess = DateTime.Now;
}
public virtual object ProcessMessage(object message)
{
if (message is RPCCall rpcCall)
{
return Application.RPCContainer.Invoke(rpcCall);
} else if (message is AuthenticationRequest authenticationRequest)
{
Identity identity = Application.IdentityProvider.GetIdentity(authenticationRequest.IdentityName);
SecureAttribute[] secureAttributes = identity.GetSecureAttributes(authenticationRequest.SecureAttributeTypeName);
AuthenticationChallenges authenticationChallenges = new AuthenticationChallenges(secureAttributes);
return authenticationChallenges;
} else if (message is AuthenticationProve authenticationProve)
{
Identity identity = Application.IdentityProvider.GetIdentity(authenticationProve.IdentityName);
SecureAttribute secureAttribute = identity.GetSecureAttribute(authenticationProve.SecureAttributeUniqueID);
if (secureAttribute.Authenticate(authenticationProve.Challenge, authenticationProve.Prove))
{
SessionIdentity = identity;
return SessionIdentity;
}
else
{
SessionIdentity = null;
throw new ArgumentException();
}
}
return null;
}
public virtual void DeauthenticateUser()
{
SessionIdentity = null;
}
public virtual void Dispose()
{
Logging.Log(LogLevel.DEBUG, "ApplicationSession disposing: {0}", SessionID);
DeauthenticateUser();
}
}
}