Innovenergy_trunk/csharp/App/Backend/Relations/Session.cs

42 lines
1.1 KiB
C#

using InnovEnergy.App.Backend.Database;
using InnovEnergy.App.Backend.DataTypes;
using SQLite;
namespace InnovEnergy.App.Backend.Relations;
public class Session : Relation<String, Int64>
{
public static TimeSpan MaxAge { get; } = TimeSpan.FromDays(7);
[Unique ] public String Token { get => Left ; init => Left = value;}
[Indexed] public Int64 UserId { get => Right; init => Right = value;}
[Indexed] public DateTime LastSeen { get; set; }
[Ignore] public Boolean Valid => DateTime.Now - LastSeen < MaxAge
&& (User) is not null;
[Ignore] public User User => _User ??= Db.GetUserById(UserId)!;
private User? _User;
[Obsolete("To be used only by deserializer")]
public Session()
{}
public Session(User user)
{
_User = user;
Token = CreateToken();
UserId = user.Id;
LastSeen = DateTime.Now;
}
private static String CreateToken()
{
var token = new Byte[24];
Random.Shared.NextBytes(token);
return Convert.ToBase64String(token).Replace("/","");
}
}