using MagMan.Core.Services; using MagMan.Data.Admin; using MagMan.Data.Admin.DbModels; using MagMan.Data.Admin.Services; using MagMan.Data.Tenant.DbModels; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Identity; using Microsoft.Data.SqlClient; using Microsoft.JSInterop; using System.Collections.Generic; using System.Linq; using System.Security.Claims; namespace MagMan.UI.Components { public partial class UserMan : IDisposable { #region Public Methods public List ConvertClaim(List ClaimList) { List answ = new List(); var pUpd = Task.Run(async () => { await refreshLists(); }); pUpd.Wait(); // ciclo sui claims foreach (var claim in ClaimList) { string claimStr = claim.ToString(); // verifico che in OGNI claim ci siaun valore ammissibile... if (claimStr.Contains(":")) { // splitto chiave/valore var splitClaim = claimStr.Split(':'); switch (splitClaim[0]) { case "CustomerID": if (customList != null) { var plantRec = customList .Where(x => $"{x.CustomerID}" == splitClaim[1].Trim()) .FirstOrDefault(); if (plantRec != null) { answ.Add($"{splitClaim[0]}: {plantRec.Name}"); } else { answ.Add($"{claim}"); } } break; #if false case "SupplierId": if (suppList != null) { var plantRec = suppList .Where(x => x.SupplierId.ToString() == splitClaim[1].Trim()) .FirstOrDefault(); if (plantRec != null) { answ.Add($"{splitClaim[0]}: {plantRec.SupplierDesc}"); } else { answ.Add($"{claim}"); } } break; case "TransporterId": if (transpList != null) { var plantRec = transpList .Where(x => x.TransporterId.ToString() == splitClaim[1].Trim()) .FirstOrDefault(); if (plantRec != null) { answ.Add($"{splitClaim[0]}: {plantRec.TransporterDesc}"); } else { answ.Add($"{claim}"); } } break; #endif case "None": default: break; } } } return answ; } public void Dispose() { AppMService.EA_SearchUpdated -= AppMService_EA_SearchUpdated; } /// /// Recupera elenco utenti /// public async Task GetUsers() { // clear any error messages strError = ""; UsersAll = await MTService.UserDataGetFilt(currSearch); // filtro visualizzazione x tipo SE richeisto if (FiltUserRole != "0") { UsersAll = UsersAll.Where(x => x.Roles.Contains(FiltUserRole)).ToList(); } totalCount = UsersAll.Count; UsersList = UsersAll .Skip(numRecord * (currPage - 1)).Take(numRecord) .ToList(); } public string ShowClaims(List ClaimList) { string answ = string.Join(",", ConvertClaim(ClaimList)); return answ; } public string ShowRoles(List RoleList) { string answ = string.Join(",", RoleList); return answ; } #endregion Public Methods #region Protected Properties [Inject] protected UserManager _UserManager { get; set; } = null!; [Inject] protected MessageService AppMService { get; set; } = null!; protected List? customList { get; set; } = null; [Inject] protected MTAdminService MTService { get; set; } = null!; protected int totalCount { get; set; } = 0; #endregion Protected Properties #region Protected Methods protected void DoSelect(UserData? selItem) { #if false if (selItem != null) { ProjDbId = selItem.ProjDbId; } else { ProjDbId = 0; } E_ProjSel.InvokeAsync(selItem); #endif } protected override async Task OnInitializedAsync() { currSearch = ""; string rawConf = Configuration["OptConf:MultiRoleEnab"]; if (rawConf != null) { bool.TryParse(rawConf, out MultiRoleEnab); } rawConf = Configuration["OptConf:MultiClaimEnab"]; if (rawConf != null) { bool.TryParse(rawConf, out MultiClaimEnab); } AppMService.EA_SearchUpdated += AppMService_EA_SearchUpdated; // lettura dati await GetUsers(); } protected async Task SetNumRec(int newNum) { numRecord = newNum; currPage = 1; await InvokeAsync(ReloadData); } protected async Task SetPage(int newNum) { currPage = newNum; DoSelect(null); await InvokeAsync(ReloadData); } #endregion Protected Methods #region Private Fields private const string ADMIN_ROLE = "SuperAdmin"; private const string STD_CLAIM = "None"; private const string STD_CLAIM_VAL = "0"; private const string UNDEF_ROLE = "Undef"; /// /// Elenco CLAIMS da mostrare durante editing /// private List ClaimsList = new List() { STD_CLAIM, "CustomerID" }; //private List ClaimsList = new List() { STD_CLAIM, "CustomerID", "SupplierId", "TransporterId" }; private Dictionary ClaimValList = new Dictionary(); private string currSearch = ""; /// /// Abilitazoine gestione CLAIM multipli /// private bool MultiClaimEnab = false; /// /// Abilitazoine gestione ROLES multipli /// private bool MultiRoleEnab = false; /// /// User corrente /// private IdentityUser objUser = new IdentityUser(); private string qrCodeVal = ""; /// /// Elenco ROLES da mostrare in dropdown durante editing (1 solo? usare DB?!?) /// private List RolesList = new List() { "Undef", "User", "SuperUser", "Admin", "SuperAdmin" }; // To enable showing the Popup private bool ShowPopup = false; // To hold any possible errors private string strError = ""; /// /// Collezione utenti (totale) /// private List UsersAll = new List(); /// /// Collezione utenti /// private List UsersList = new List(); #endregion Private Fields #region Private Properties private string _CurrClaimType { get; set; } = "None"; private string _filtUserRole { get; set; } = "0"; [Inject] private IConfiguration Configuration { get; set; } = null!; private Claim CurrentUserClaim { get => new Claim(CurrentUserClaimType, CurrentUserClaimVal); } /// /// Claims attuali utente /// private List CurrentUserClaims { get; set; } = new List(); /// /// Claim di default (Tipo) /// private string CurrentUserClaimType { get { return _CurrClaimType; } set { _CurrClaimType = value; var pUpd = Task.Run(async () => await refreshClaimVal(value)); pUpd.Wait(); } } /// /// Claim di default (valore) /// private string CurrentUserClaimVal { get; set; } = "0"; /// /// Ruolo di default (User!!!) /// private string CurrentUserRole { get; set; } = "User"; private int currPage { get; set; } = 1; /// /// Ruoli correnti utente /// private string[] CurrUserRoles { get; set; } = new string[] { "User" }; /// /// Gestione filtraggio dati /// private string FiltUserRole { get { return _filtUserRole; } set { if (_filtUserRole != value) { _filtUserRole = value; var pUpd = Task.Run(async () => await ReloadData()); pUpd.Wait(); } } } private bool isLoading { get; set; } = false; private int numRecord { get; set; } = 10; #endregion Private Properties #region Private Methods private void AddNewUser() { // Make new user objUser = new IdentityUser(); objUser.PasswordHash = "*****"; // Set Id to blank so we know it is a new record objUser.Id = ""; // Open the Popup ShowPopup = true; } private async void AppMService_EA_SearchUpdated() { currSearch = AppMService.SearchVal; await ReloadData(); } private async Task ClosePopup() { // Close the Popup ShowPopup = false; // Refresh Users await GetUsers(); } private async Task DeleteUser(IdentityUser _IdentityUser) { #if false // Close the Popup ShowPopup = false; if (!await JSRuntime.InvokeAsync("confirm", "Sicuro di voler eliminare l'utente selezionato??")) return; // Get the user var user = await _UserManager.FindByIdAsync(_IdentityUser.Id); if (user != null) { // Delete the user await _UserManager.DeleteAsync(user); } #endif // Refresh Users await GetUsers(); } private void EditUser(IdentityUser _IdentityUser) { // selezione come current user objUser = _IdentityUser; var pUpd = Task.Run(async () => { // Get the user var user = await _UserManager.FindByIdAsync(objUser.Id); if (user != null) { // salvo role var rawRoles = await _UserManager.GetRolesAsync(user); CurrUserRoles = rawRoles.ToArray(); if (!MultiRoleEnab) { if (CurrUserRoles != null) { CurrentUserRole = CurrUserRoles.FirstOrDefault(); } else { CurrentUserRole = UNDEF_ROLE; } } // salvo claim var UserClaims = await _UserManager.GetClaimsAsync(user); CurrentUserClaims.Clear(); if (UserClaims != null) { int idx = 1; foreach (var item in UserClaims) { CurrentUserClaims.Add(new ClaimRec(item, idx++)); } } if (!MultiClaimEnab) { if (CurrentUserClaims != null && CurrentUserClaims.Count > 0) { var CurrentUserClaim = UserClaims.FirstOrDefault(); CurrentUserClaimType = CurrentUserClaim.Type; CurrentUserClaimVal = CurrentUserClaim.Value; } else { CurrentUserClaimType = STD_CLAIM; CurrentUserClaimVal = "0"; } } string baseUrl = Configuration["OptConf:BaseAddr"]; string baseAppPath = Configuration["OptConf:BaseAppPath"]; string redirPage = Configuration["OptConf:QrRedirPage"]; if (!string.IsNullOrEmpty(baseAppPath)) { if (baseUrl.EndsWith("/")) { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } baseUrl = $"{baseUrl}{baseAppPath}"; } qrCodeVal = $"{baseUrl}Identity/Account/LogIn?uid={user.Id}&uem={user.Email}&pag={redirPage}"; } }); pUpd.Wait(); // Open the Popup ShowPopup = true; } private async Task refreshClaimVal(string newType) { // init vuoto ClaimValList = new Dictionary(); // aggiorno elenco ClaimValList switch (newType) { case "CustomerID": // elenco plant --> to dictionary! var customList = await MTService.CustomerGetAll(); if (customList != null) { ClaimValList = customList .ToDictionary(x => $"{x.CustomerID}", x => x.Name); } break; #if false case "SupplierId": // elenco plant --> to dictionary! var suppList = await DataService.SuppliersGetAll(); if (suppList != null) { ClaimValList = suppList .ToDictionary(x => $"{x.SupplierId}", x => x.SupplierDesc); } break; case "TransporterId": // elenco plant --> to dictionary! var transpList = await DataService.TransportersGetAll(); if (transpList != null) { ClaimValList = transpList .ToDictionary(x => $"{x.TransporterId}", x => x.TransporterDesc); } break; #endif case "None": default: break; } } private async Task refreshLists() { // effettuo refresh valori cache plants/suppliers/transp if (customList == null) { customList = await MTService.CustomerGetAll(); } } private async Task ReloadData() { isLoading = true; await GetUsers(); isLoading = false; } private async Task SaveUser() { try { // Is this an existing user? if (objUser.Id != "") { // Get the user var user = await _UserManager.FindByIdAsync(objUser.Id); // Update Email + check email user.Email = objUser.Email; user.EmailConfirmed = objUser.EmailConfirmed; // Update the user await _UserManager.UpdateAsync(user); // Only update password if the current value is not the default value if (objUser.PasswordHash != "*****") { var resetToken = await _UserManager.GeneratePasswordResetTokenAsync(user); var passworduser = await _UserManager.ResetPasswordAsync( user, resetToken, objUser.PasswordHash); if (!passworduser.Succeeded) { if (passworduser.Errors.FirstOrDefault() != null) { strError = passworduser .Errors .FirstOrDefault() .Description; } else { strError = "Password error"; } // Keep the popup opened return; } } // Gestione salvataggio ruoli... SE VARIATO... var UserRoles = await _UserManager.GetRolesAsync(user); if (!MultiRoleEnab) { if (UserRoles != null && UserRoles.Count > 0) { var oldRole = UserRoles.FirstOrDefault(); if (!CurrentUserRole.Equals(oldRole)) { // recupero il ruolo attuale e lo rimuovo await _UserManager.RemoveFromRoleAsync(user, oldRole); } // aggiungo il nuovo ruolo await _UserManager.AddToRoleAsync(user, CurrentUserRole); } else { // aggiungo il nuovo ruolo await _UserManager.AddToRoleAsync(user, CurrentUserRole); } } else { // verifico ruoli costanti... var listOk = UserRoles.Intersect(CurrUserRoles).ToList(); var list2del = UserRoles.Except(listOk).ToList(); var list2add = CurrUserRoles.Except(listOk).ToList(); // elimino foreach (var item in list2del) { await _UserManager.RemoveFromRoleAsync(user, item); } // aggiungo foreach (var item in list2add) { await _UserManager.AddToRoleAsync(user, item); } } // gestione salvataggio Claims var UserClaims = await _UserManager.GetClaimsAsync(user); if (!MultiClaimEnab) { if (UserClaims != null && UserClaims.Count > 0) { var oldClaim = UserClaims.FirstOrDefault(); if (!oldClaim.Equals(CurrentUserClaim)) { // recupero il ruolo attuale e lo rimuovo await _UserManager.RemoveClaimAsync(user, oldClaim); } // aggiungo il nuovo ruolo await _UserManager.AddClaimAsync(user, CurrentUserClaim); } else { // aggiungo il nuovo ruolo await _UserManager.AddClaimAsync(user, CurrentUserClaim); } } else { // elimino i vecchi claims non presenti nel nuovo... var listClaimsMod = CurrentUserClaims.Select(x => new Claim(x.Type, x.Value)).ToList(); var listOk = UserClaims.Intersect(listClaimsMod).ToList(); var list2del = UserClaims.Except(listOk).ToList(); var list2add = listClaimsMod.Except(listOk).ToList(); // elimino foreach (var item in list2del) { await _UserManager.RemoveClaimAsync(user, item); } // aggiungo foreach (var item in list2add) { await _UserManager.AddClaimAsync(user, item); } } } else { // Insert new user var NewUser = new IdentityUser { UserName = objUser.Email, Email = objUser.Email }; var CreateResult = await _UserManager.CreateAsync(NewUser, objUser.PasswordHash); if (!CreateResult.Succeeded) { if (CreateResult .Errors .FirstOrDefault() != null) { strError = CreateResult .Errors .FirstOrDefault() .Description; } else { strError = "Create error"; } // Keep the popup opened return; } else { // aggiungo a ruolo undef await _UserManager.AddToRoleAsync(NewUser, UNDEF_ROLE); // aggiungo claim undef... await _UserManager.AddClaimAsync(NewUser, CurrentUserClaim); } } // Close the Popup ShowPopup = false; // refresh cache... await MTService.ResetUserDataCache(); // Refresh Users await GetUsers(); } catch (Exception ex) { strError = ex.GetBaseException().Message; } } #endregion Private Methods #if false protected async Task AddClaim(string rawClaim) { // splitto ed aggiungo... if (rawClaim.Contains(":")) { CurrentUserClaims.Add(rawClaim); await InvokeAsync(StateHasChanged); } } protected async Task RemClaim(string rawClaim) { // splitto ed aggiungo... if (rawClaim.Contains(":")) { if (CurrentUserClaims.Contains(rawClaim)) { CurrentUserClaims.Remove(rawClaim); await InvokeAsync(StateHasChanged); } } } #endif } }