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

55 lines
2.2 KiB
C#

using InnovEnergy.App.Backend.Database;
using InnovEnergy.App.Backend.DataTypes;
using InnovEnergy.App.Backend.DataTypes.Methods;
using SQLite;
namespace InnovEnergy.App.Backend.Relations;
public class Session : Relation<String, Int64>
{
public static TimeSpan MaxAge { get; } = TimeSpan.FromDays(1);
[Unique ] public String Token { get => Left ; init => Left = value;}
[Indexed] public Int64 UserId { get => Right; init => Right = value;}
[Indexed] public DateTime LastSeen { get; set; }
public Boolean AccessToSalimax { get; set; } = false;
public Boolean AccessToSalidomo { get; set; } = false;
[Ignore] public Boolean Valid => DateTime.Now - LastSeen <=MaxAge ;
// Private backing field
private User? _User;
[Ignore] public User User
{
get => _User ??= Db.GetUserById(UserId)!;
set => _User =value;
}
[Obsolete("To be used only by deserializer")]
public Session()
{}
//We need to return a session object to the frontend. Only the public fields can be included.
//For this reason, we use the public User User. It is a public field but ignored, so it can be included to the object returned
//to the frontend but it will not get inserted to the database.
//When we initialize it like that: User = Db.GetUserById(user.Id)!, the set will be called and the private member will be initialized as well.
//What if the getSession method is called from another function of the controller?
//GetSession will retrieve a session object from the database, but this does not have the metadata included (the private fields and the ignored public fields)
//Thus, the get will be called and the private field _User will be initialized on the fly.
public Session(User user)
{
User = Db.GetUserById(user.Id)!;
Token = CreateToken();
UserId = user.Id;
LastSeen = DateTime.Now;
AccessToSalimax = user.AccessibleInstallations(product: 0).ToList().Count > 0;
AccessToSalidomo = user.AccessibleInstallations(product: 1).ToList().Count > 0;
}
private static String CreateToken()
{
return Guid.NewGuid().ToString("N");
}
}