ln.application/ApplicationSession.cs

92 lines
3.1 KiB
C#
Raw Normal View History

2019-11-15 13:46:08 +01:00
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; }
2019-11-26 12:22:09 +01:00
public Guid Secret { get; }
public DateTime Created { get; }
2019-11-15 13:46:08 +01:00
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();
2019-11-26 12:22:09 +01:00
Secret = Guid.NewGuid();
2019-11-15 13:46:08 +01:00
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;
2019-11-18 08:54:55 +01:00
return SessionIdentity;
2019-11-15 13:46:08 +01:00
}
else
{
2019-11-18 08:54:55 +01:00
SessionIdentity = null;
2019-11-15 13:46:08 +01:00
throw new ArgumentException();
}
}
return null;
}
public virtual void DeauthenticateUser()
{
SessionIdentity = null;
}
public virtual void Dispose()
{
Logging.Log(LogLevel.DEBUG, "ApplicationSession disposing: {0}", SessionID);
DeauthenticateUser();
}
}
}