451 lines
16 KiB
C#
451 lines
16 KiB
C#
using GPW.CORE.Data.Controllers;
|
|
using GPW.CORE.Data.DbModels;
|
|
using GPW.CORE.Data.DTO;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.Logging;
|
|
using Newtonsoft.Json;
|
|
using NLog;
|
|
using StackExchange.Redis;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
using System.Linq;
|
|
using System.Reflection.PortableExecutable;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace GPW.CORE.Data.Services
|
|
{
|
|
public class AppAuthService : IDisposable
|
|
{
|
|
#region Public Fields
|
|
|
|
// diritti (cablòato)
|
|
public const string RoleSuperAdmin = "MoonPro_SuperAdmin";
|
|
|
|
public List<string> Lingue = new List<string>();
|
|
|
|
#endregion Public Fields
|
|
|
|
#region Public Constructors
|
|
|
|
public AppAuthService(IConfiguration configuration, IConnectionMultiplexer redisConnMult)
|
|
{
|
|
_configuration = configuration;
|
|
|
|
// cod app
|
|
CodApp = _configuration.GetValue<string>("ServerConf:CodApp") ?? "GPW.ADM";
|
|
Modulo = _configuration.GetValue<string>("ServerConf:Modulo") ?? "GPW";
|
|
|
|
// Conf cache
|
|
redisConn = redisConnMult;
|
|
redisDb = this.redisConn.GetDatabase();
|
|
|
|
// json serializer... FIX errore loop circolare https://www.ryadel.com/en/jsonserializationexception-self-referencing-loop-detected-error-fix-entity-framework-asp-net-core/
|
|
JSSettings = new JsonSerializerSettings()
|
|
{
|
|
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
|
|
};
|
|
|
|
// conf DB
|
|
string connStr = _configuration.GetConnectionString("GPW.DB") ?? "";
|
|
if (string.IsNullOrEmpty(connStr))
|
|
{
|
|
Log.Error("ConnString empty!");
|
|
}
|
|
else
|
|
{
|
|
dbController = new AppAuthController(configuration);
|
|
GpwDbController = new GPWController(configuration);
|
|
userController = new AppUserController(configuration);
|
|
Log.Info("DbController OK");
|
|
}
|
|
}
|
|
|
|
#endregion Public Constructors
|
|
|
|
#region Public Properties
|
|
|
|
public static AppAuthController dbController { get; set; } = null!;
|
|
public static GPWController GpwDbController { get; set; } = null!;
|
|
public static AppUserController userController { get; set; } = null!;
|
|
|
|
#endregion Public Properties
|
|
|
|
#region Public Methods
|
|
|
|
public async Task<List<AnagKeyValueModel>> AnagKeyValList()
|
|
{
|
|
List<AnagKeyValueModel> dbResult = new List<AnagKeyValueModel>();
|
|
Stopwatch stopWatch = new Stopwatch();
|
|
stopWatch.Start();
|
|
dbResult = GpwDbController.AnagKeyValGetAll();
|
|
stopWatch.Stop();
|
|
TimeSpan ts = stopWatch.Elapsed;
|
|
Log.Trace($"Effettuata lettura da DB per AnagKeyValList: {ts.TotalMilliseconds} ms");
|
|
return await Task.FromResult(dbResult);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Elenco diritti dato utente
|
|
/// </summary>
|
|
/// <param name="UserName"></param>
|
|
/// <returns></returns>
|
|
public async Task<List<UserDirittiModel>> DirittiGetByUser(string UserName)
|
|
{
|
|
string source = "DB";
|
|
List<UserDirittiModel>? dbResult = new List<UserDirittiModel>();
|
|
string currKey = $"{rKeyDirittiUser}:{UserName}";
|
|
Stopwatch sw = new Stopwatch();
|
|
sw.Start();
|
|
string? rawData = await redisDb.StringGetAsync(currKey);
|
|
if (!string.IsNullOrEmpty(rawData) && rawData.Length > 2)
|
|
{
|
|
source = "REDIS";
|
|
var tempResult = JsonConvert.DeserializeObject<List<UserDirittiModel>>(rawData);
|
|
dbResult = tempResult ?? new List<UserDirittiModel>();
|
|
}
|
|
else
|
|
{
|
|
// recupero diritti utente
|
|
dbResult = userController.DirittiUtente(UserName, Modulo);
|
|
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
|
|
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
|
|
}
|
|
if (dbResult == null)
|
|
{
|
|
dbResult = new List<UserDirittiModel>();
|
|
}
|
|
sw.Stop();
|
|
Log.Debug($"DirittiGetByUser | {source} | {sw.ElapsedMilliseconds} ms");
|
|
return dbResult;
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
// Clear database controller
|
|
dbController.Dispose();
|
|
GpwDbController.Dispose();
|
|
}
|
|
|
|
public async Task FlushRedisCache()
|
|
{
|
|
RedisValue pattern = new RedisValue($"{redisBaseAddr}:*");
|
|
bool answ = await ExecFlushRedisPattern(pattern);
|
|
// reset in RAM
|
|
Vocabolario = new Dictionary<string, string>();
|
|
CheckVoc();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Menu pagine abilitate dato utente
|
|
/// </summary>
|
|
/// <param name="UserName"></param>
|
|
/// <returns></returns>
|
|
public async Task<List<MenuItemDTO>> MenuUtente(string UserName, string UserLang)
|
|
{
|
|
string source = "DB";
|
|
List<MenuItemDTO>? dbResult = new List<MenuItemDTO>();
|
|
string currKey = $"{rKeyMenuUser}:{UserName}:{UserLang}";
|
|
Stopwatch sw = new Stopwatch();
|
|
sw.Start();
|
|
string? rawData = await redisDb.StringGetAsync(currKey);
|
|
if (!string.IsNullOrEmpty(rawData))
|
|
{
|
|
source = "REDIS";
|
|
var tempResult = JsonConvert.DeserializeObject<List<MenuItemDTO>>(rawData);
|
|
if (tempResult == null)
|
|
{
|
|
dbResult = new List<MenuItemDTO>();
|
|
}
|
|
else
|
|
{
|
|
dbResult = tempResult;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// verifica preliminare vocabolario
|
|
CheckVoc();
|
|
// recupero permessi utente...
|
|
List<PermessiModel> userRightList = await PermessiGetByUser(UserName);
|
|
// converto in voce menù
|
|
dbResult = userRightList
|
|
// solo le vere voci di menù x parametri gruppo/numero
|
|
.Where(x => x.Numero > 0 && x.Gruppo < 999)
|
|
.OrderBy(g => g.Gruppo)
|
|
.ThenBy(n => n.Numero)
|
|
.Select(x => new MenuItemDTO
|
|
{
|
|
Url = x.Url,
|
|
Title = Traduci(x.Nome ?? x.Url, UserLang),
|
|
Descript = Traduci(x.Descrizione ?? "", UserLang),
|
|
Group = x.Gruppo ?? 0,
|
|
Num = x.Numero ?? 0
|
|
})
|
|
.ToList();
|
|
// salvo in redis...
|
|
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
|
|
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
|
|
}
|
|
if (dbResult == null)
|
|
{
|
|
dbResult = new List<MenuItemDTO>();
|
|
}
|
|
sw.Stop();
|
|
Log.Debug($"MenuUtente | {source} | {sw.ElapsedMilliseconds} ms");
|
|
return dbResult;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Elenco permessi dato utente
|
|
/// </summary>
|
|
/// <param name="UserName"></param>
|
|
/// <returns></returns>
|
|
public async Task<List<PermessiModel>> PermessiGetByUser(string UserName)
|
|
{
|
|
string source = "DB";
|
|
List<PermessiModel>? dbResult = new List<PermessiModel>();
|
|
string currKey = $"{rKeyPermUser}:{UserName}";
|
|
Stopwatch sw = new Stopwatch();
|
|
sw.Start();
|
|
string? rawData = await redisDb.StringGetAsync(currKey);
|
|
if (!string.IsNullOrEmpty(rawData))
|
|
{
|
|
source = "REDIS";
|
|
var tempResult = JsonConvert.DeserializeObject<List<PermessiModel>>(rawData);
|
|
if (tempResult == null)
|
|
{
|
|
dbResult = new List<PermessiModel>();
|
|
}
|
|
else
|
|
{
|
|
dbResult = tempResult;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// recupero diritti utente
|
|
var userRightList = userController.DirittiUtente(UserName, Modulo);
|
|
// proietto come funzioni...
|
|
var ListFunc = userRightList.Select(x => x.Funzione).ToList();
|
|
// trasformo i permessi utente
|
|
if (ListFunc == null)
|
|
{
|
|
ListFunc = new List<string>();
|
|
}
|
|
dbResult = dbController.PermessiGetByFunc(ListFunc);
|
|
rawData = JsonConvert.SerializeObject(dbResult, JSSettings);
|
|
await redisDb.StringSetAsync(currKey, rawData, UltraLongCache);
|
|
}
|
|
if (dbResult == null)
|
|
{
|
|
dbResult = new List<PermessiModel>();
|
|
}
|
|
sw.Stop();
|
|
Log.Debug($"PermessiGetByUser | {source} | {sw.ElapsedMilliseconds} ms");
|
|
return dbResult;
|
|
}
|
|
|
|
public string Traduci(string lemma, string lingua = "IT")
|
|
{
|
|
string answ = $"__{lemma}__";
|
|
string keyReq = $"{lingua}#{lemma}";
|
|
CheckVoc();
|
|
// cerco in vocabolario...
|
|
if (Vocabolario.ContainsKey(keyReq))
|
|
{
|
|
answ = Vocabolario[keyReq];
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
#endregion Public Methods
|
|
|
|
#region Protected Methods
|
|
|
|
protected void CheckVoc()
|
|
{
|
|
if (Vocabolario.Count == 0)
|
|
{
|
|
string source = "DB";
|
|
string currKey = "";
|
|
string? rawData = "";
|
|
Stopwatch sw = new Stopwatch();
|
|
sw.Start();
|
|
// lingue
|
|
currKey = $"{redisBaseAddr}:MP:LANG";
|
|
rawData = redisDb.StringGet(currKey);
|
|
if (!string.IsNullOrEmpty(rawData) && rawData.Length > 2)
|
|
{
|
|
var tempResult = JsonConvert.DeserializeObject<List<string>>(rawData);
|
|
Lingue = tempResult ?? new List<string>();
|
|
}
|
|
else
|
|
{
|
|
Lingue = dbController
|
|
.LingueGetAll()
|
|
.Select(x => x.Lingua)
|
|
.ToList();
|
|
rawData = JsonConvert.SerializeObject(Lingue);
|
|
redisDb.StringSet(currKey, rawData, UltraLongCache);
|
|
}
|
|
|
|
// vocabolario
|
|
currKey = $"{redisBaseAddr}:MP:VOCAB";
|
|
rawData = redisDb.StringGet(currKey);
|
|
if (!string.IsNullOrEmpty(rawData) && rawData.Length > 2)
|
|
{
|
|
source = "REDIS";
|
|
var tempResult = JsonConvert.DeserializeObject<Dictionary<string, string>>(rawData);
|
|
Vocabolario = tempResult ?? new Dictionary<string, string>();
|
|
}
|
|
else
|
|
{
|
|
Vocabolario = dbController
|
|
.VocabolarioGetAll()
|
|
.ToDictionary(x => $"{x.Lingua}#{x.Lemma}", x => x.Traduzione);
|
|
rawData = JsonConvert.SerializeObject(Vocabolario);
|
|
redisDb.StringSet(currKey, rawData, UltraLongCache);
|
|
}
|
|
sw.Stop();
|
|
Log.Trace($"Rilettura Vocabolario | {source} | {sw.ElapsedMilliseconds} ms");
|
|
}
|
|
}
|
|
|
|
#endregion Protected Methods
|
|
|
|
#region Private Fields
|
|
|
|
// gestione key Redis
|
|
private const string redisBaseAddr = "GPW:ADM";
|
|
|
|
private const string rKeyDirittiUser = $"{redisBaseAddr}:DIR_USER";
|
|
|
|
private const string rKeyMenuUser = $"{redisBaseAddr}:MENU_USER";
|
|
private const string rKeyPermUser = $"{redisBaseAddr}:PERM_USER";
|
|
private static JsonSerializerSettings? JSSettings;
|
|
private static Logger Log = LogManager.GetCurrentClassLogger();
|
|
private static string Modulo = "";
|
|
|
|
/// <summary>
|
|
/// Durata cache lunga IN SECONDI
|
|
/// </summary>
|
|
private int cacheTtlLong = 60 * 5;
|
|
|
|
/// <summary>
|
|
/// Durata cache breve IN SECONDI
|
|
/// </summary>
|
|
private int cacheTtlShort = 60 * 1;
|
|
|
|
/// <summary>
|
|
/// Oggetto per connessione a REDIS
|
|
/// </summary>
|
|
private IConnectionMultiplexer redisConn;
|
|
|
|
//ISubscriber sub = redis.GetSubscriber();
|
|
/// <summary>
|
|
/// Oggetto DB redis da impiegare x chiamate R/W
|
|
/// </summary>
|
|
private IDatabase redisDb = null!;
|
|
|
|
private Random rnd = new Random();
|
|
private Dictionary<string, string> Vocabolario = new Dictionary<string, string>();
|
|
|
|
#endregion Private Fields
|
|
|
|
#region Private Properties
|
|
|
|
private static IConfiguration _configuration { get; set; } = null!;
|
|
private string CodApp { get; set; } = "";
|
|
|
|
/// <summary>
|
|
/// Durata cache lunga (+ perturbazione percentuale +/-10%)
|
|
/// </summary>
|
|
private TimeSpan FastCache
|
|
{
|
|
get => TimeSpan.FromSeconds(cacheTtlShort * rnd.Next(900, 1100) / 1000);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Durata cache lunga (+ perturbazione percentuale +/-10%)
|
|
/// </summary>
|
|
private TimeSpan LongCache
|
|
{
|
|
get => TimeSpan.FromSeconds(cacheTtlLong * rnd.Next(900, 1100) / 1000);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Durata cache lunga (+ perturbazione percentuale +/-10%)
|
|
/// </summary>
|
|
private TimeSpan UltraLongCache
|
|
{
|
|
get => TimeSpan.FromSeconds(cacheTtlLong * 10 * rnd.Next(900, 1100) / 1000);
|
|
}
|
|
|
|
#endregion Private Properties
|
|
|
|
#region Private Methods
|
|
|
|
/// <summary>
|
|
/// Esegue flush memoria redis dato pat2Flush
|
|
/// </summary>
|
|
/// <param name="pat2Flush"></param>
|
|
/// <returns></returns>
|
|
private async Task<bool> ExecFlushRedisPattern(RedisValue pat2Flush)
|
|
{
|
|
bool answ = false;
|
|
var masterEndpoint = redisConn.GetEndPoints()
|
|
.Where(ep => redisConn.GetServer(ep).IsConnected && !redisConn.GetServer(ep).IsReplica)
|
|
.FirstOrDefault();
|
|
|
|
// sepattern è "*" elimino intero DB...
|
|
if (masterEndpoint != null && (pat2Flush.Equals(new RedisValue("*")) || pat2Flush == RedisValue.Null))
|
|
{
|
|
redisConn.GetServer(masterEndpoint).FlushDatabase(database: redisDb.Database);
|
|
}
|
|
else
|
|
{
|
|
var server = redisConn.GetServer(masterEndpoint);
|
|
var keys = server.Keys(database: redisDb.Database, pattern: pat2Flush, pageSize: 1000);
|
|
|
|
var deleteTasks = new List<Task>();
|
|
foreach (var key in keys)
|
|
{
|
|
deleteTasks.Add(redisDb.KeyDeleteAsync(key));
|
|
if (deleteTasks.Count >= 1000)
|
|
{
|
|
await Task.WhenAll(deleteTasks);
|
|
deleteTasks.Clear();
|
|
}
|
|
}
|
|
if (deleteTasks.Count > 0)
|
|
{
|
|
await Task.WhenAll(deleteTasks);
|
|
}
|
|
}
|
|
answ = true;
|
|
#if false
|
|
var listEndpoints = redisConn.GetEndPoints();
|
|
foreach (var endPoint in listEndpoints)
|
|
{
|
|
//var server = redisConnAdmin.GetServer(listEndpoints[0]);
|
|
var server = redisConn.GetServer(endPoint);
|
|
if (server != null)
|
|
{
|
|
var keyList = server.Keys(redisDb.Database, pattern);
|
|
foreach (var item in keyList)
|
|
{
|
|
await redisDb.KeyDeleteAsync(item);
|
|
}
|
|
answ = true;
|
|
}
|
|
}
|
|
#endif
|
|
|
|
return answ;
|
|
}
|
|
|
|
#endregion Private Methods
|
|
}
|
|
} |