247 lines
7.5 KiB
C#
247 lines
7.5 KiB
C#
using MP.Data.DTO;
|
|
using Newtonsoft.Json;
|
|
using NLog;
|
|
using StackExchange.Redis;
|
|
using System.Diagnostics;
|
|
|
|
namespace MP.INVE.Data
|
|
{
|
|
public class LoginService : IDisposable
|
|
{
|
|
#region Public Constructors
|
|
|
|
public LoginService(IConfiguration configuration, ILogger<LoginService> logger, HttpClient httpClient,
|
|
IHttpContextAccessor httpContextAccessor)
|
|
{
|
|
this.HttpClient = httpClient;
|
|
HttpContextAccessor = httpContextAccessor;
|
|
|
|
_logger = logger;
|
|
_logger.LogInformation("Starting LoginService INIT");
|
|
_configuration = configuration;
|
|
|
|
// setup compoenti REDIS
|
|
redisConn = ConnectionMultiplexer.Connect(_configuration.GetConnectionString("Redis"));
|
|
redisConnAdmin = ConnectionMultiplexer.Connect(_configuration.GetConnectionString("RedisAdmin"));
|
|
redisDb = redisConn.GetDatabase();
|
|
|
|
// leggo cache lungo periodo
|
|
int.TryParse(_configuration.GetValue<string>("ServerConf:redisLongTimeCache"), out redisLongTimeCache);
|
|
|
|
_logger.LogInformation("Redis LoginService INIT");
|
|
}
|
|
|
|
#endregion Public Constructors
|
|
|
|
#region Public Events
|
|
|
|
public event Action EA_LogIn = null!;
|
|
|
|
public event Action EA_LogOut = null!;
|
|
|
|
#endregion Public Events
|
|
|
|
#region Public Properties
|
|
|
|
public string Cognome
|
|
{
|
|
get
|
|
{
|
|
string answ = "NA";
|
|
if (matrOpr > 0 && !string.IsNullOrEmpty(authKey))
|
|
{
|
|
var currUser = UserDTO(matrOpr, authKey);
|
|
if (currUser != null)
|
|
{
|
|
answ = currUser.Cognome;
|
|
}
|
|
}
|
|
return answ;
|
|
}
|
|
}
|
|
|
|
public int matrOpr
|
|
{
|
|
get
|
|
{
|
|
int answ = 0;
|
|
if (HttpContextAccessor.HttpContext != null)
|
|
{
|
|
var token = HttpContextAccessor.HttpContext.Request.Cookies["userId_token"];
|
|
if (token != null)
|
|
{
|
|
int.TryParse(token, out answ);
|
|
}
|
|
}
|
|
return answ;
|
|
}
|
|
set
|
|
{
|
|
CookieOptions options = new CookieOptions();
|
|
options.Expires = DateTime.Now.AddDays(1);
|
|
if (HttpContextAccessor.HttpContext != null)
|
|
{
|
|
HttpContextAccessor.HttpContext.Response.Cookies.Append("userId_token", $"{value}", options);
|
|
}
|
|
}
|
|
}
|
|
|
|
public string Nome
|
|
{
|
|
get
|
|
{
|
|
string answ = "NA";
|
|
if (matrOpr > 0 && !string.IsNullOrEmpty(authKey))
|
|
{
|
|
var currUser = UserDTO(matrOpr, authKey);
|
|
if (currUser != null)
|
|
{
|
|
answ = currUser.Nome;
|
|
}
|
|
}
|
|
return answ;
|
|
}
|
|
}
|
|
|
|
#endregion Public Properties
|
|
|
|
#region Public Methods
|
|
|
|
public void Dispose()
|
|
{
|
|
}
|
|
|
|
public void LogOut()
|
|
{
|
|
OperatoreDTO resetData = new OperatoreDTO();
|
|
UserDTOSave(resetData);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Ricerca su REDIS dell'utente loggato
|
|
/// NB: da rifare con unico JWT che contenga tutto
|
|
/// </summary>
|
|
/// <param name="matrOpr"></param>
|
|
/// <param name="authKey"></param>
|
|
/// <returns></returns>
|
|
public OperatoreDTO? UserDTO(int matrOpr, string authKey)
|
|
{
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
OperatoreDTO? result = null;
|
|
string source = "REDIS";
|
|
// cerco in redis...
|
|
RedisValue rawData = redisDb.StringGet($"{redisUserSession}:{matrOpr}");
|
|
if (!string.IsNullOrEmpty($"{rawData}"))
|
|
{
|
|
try
|
|
{
|
|
result = JsonConvert.DeserializeObject<OperatoreDTO>($"{rawData}");
|
|
}
|
|
catch
|
|
{ }
|
|
}
|
|
#if false
|
|
else
|
|
{
|
|
result = await Task.FromResult(dbController.AnagStatiComm());
|
|
// serializzo e salvo...
|
|
rawData = JsonConvert.SerializeObject(result);
|
|
await redisDb.StringSetAsync(redisUserSession, rawData, getRandTOut(redisLongTimeCache));
|
|
source = "DB";
|
|
}
|
|
#endif
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Debug($"LoggedUser Read from {source}: {ts.TotalMilliseconds}ms");
|
|
// restituisco
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Salva su REDIS dati dell'utente loggato
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public bool UserDTOSave(OperatoreDTO userData)
|
|
{
|
|
bool fatto = false;
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
string source = "REDIS";
|
|
// cerco in redis...
|
|
string rawData = JsonConvert.SerializeObject(userData);
|
|
fatto = redisDb.StringSet($"{redisUserSession}:{userData.MatrOpr}", rawData, TimeSpan.FromMinutes(60));
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Debug($"UserDTO write to {source}: {ts.TotalMilliseconds}ms");
|
|
// restituisco
|
|
return fatto;
|
|
}
|
|
|
|
#endregion Public Methods
|
|
|
|
#region Protected Properties
|
|
|
|
protected string authKey
|
|
{
|
|
get
|
|
{
|
|
string answ = "";
|
|
if (HttpContextAccessor.HttpContext != null)
|
|
{
|
|
var token = HttpContextAccessor.HttpContext.Request.Cookies["authKey_token"];
|
|
if (token != null)
|
|
{
|
|
answ = token;
|
|
}
|
|
}
|
|
return answ;
|
|
}
|
|
set
|
|
{
|
|
CookieOptions options = new CookieOptions();
|
|
options.Expires = DateTime.Now.AddDays(1);
|
|
|
|
if (HttpContextAccessor.HttpContext != null)
|
|
{
|
|
HttpContextAccessor.HttpContext.Response.Cookies.Append("authKey_token", value, options);
|
|
}
|
|
}
|
|
}
|
|
|
|
protected HttpClient HttpClient { get; set; }
|
|
protected IHttpContextAccessor HttpContextAccessor { get; set; }
|
|
|
|
#endregion Protected Properties
|
|
|
|
#region Private Fields
|
|
|
|
private const string redisBaseAddr = "MP:INVE";
|
|
|
|
private const string redisUserSession = redisBaseAddr + ":User:";
|
|
private static IConfiguration _configuration = null!;
|
|
|
|
private static ILogger<LoginService> _logger = null!;
|
|
|
|
private static Logger Log = LogManager.GetCurrentClassLogger();
|
|
|
|
/// <summary>
|
|
/// Oggetto per connessione a REDIS
|
|
/// </summary>
|
|
private ConnectionMultiplexer redisConn = null!;
|
|
|
|
/// <summary>
|
|
/// Oggetto per connessione a REDIS modalità admin (ex flux dati)
|
|
/// </summary>
|
|
private ConnectionMultiplexer redisConnAdmin = null!;
|
|
|
|
/// <summary>
|
|
/// Oggetto DB redis da impiegare x chiamate R/W
|
|
/// </summary>
|
|
private IDatabase redisDb = null!;
|
|
|
|
private int redisLongTimeCache = 5;
|
|
|
|
#endregion Private Fields
|
|
}
|
|
} |