using LiMan.UI.Data; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Configuration; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System; using LiMan.DB.DBModels; using Microsoft.JSInterop; using StackExchange.Redis; using Microsoft.AspNetCore.Components.Authorization; using System.Data; using NLog.LayoutRenderers; using NLog.Filters; namespace LiMan.UI.Components { public partial class UserMan : IDisposable { #region Public Methods public void Dispose() { AppMService.EA_SearchUpdated -= AppMService_EA_SearchUpdated; } public string ShowRoles(List ClaimList) { string answ = ""; foreach (var item in ClaimList) { answ += $"{item.RoleNav.Ruolo}, "; } if (answ.Length > 2) { answ = answ.Substring(0, answ.Length - 2); } return answ; } #endregion Public Methods #region Protected Properties [Inject] protected MessageService AppMService { get; set; } = null!; [Inject] protected AuthenticationStateProvider AutheStateProvider { get; set; } = null!; [Inject] protected LiManDataService DataService { get; set; } = null!; [Inject] protected IJSRuntime JSRuntime { get; set; } = null!; protected int totalCount { get; set; } = 0; protected List UserClaims { get; set; } = new List(); #endregion Protected Properties #region Protected Methods /// /// Recupera elenco utenti /// protected async Task GetUsers() { // clear any error messages strError = ""; UsersAll = await DataService.AuthUserAll(); // filtro visualizzazione x tipo SE richeisto if (FiltUserRole > 0) { UsersAll = UsersAll.Where(x => x.Claims.Any(c => c.RoleID == FiltUserRole)).ToList(); } // se c'č search,,, if (!string.IsNullOrEmpty(currSearch)) { UsersAll = UsersAll .Where(x => x.Cognome.Contains(currSearch, StringComparison.CurrentCultureIgnoreCase) || x.Nome.Contains(currSearch, StringComparison.CurrentCultureIgnoreCase) || x.Username.Contains(currSearch, StringComparison.CurrentCultureIgnoreCase)) .ToList(); } totalCount = UsersAll.Count; UsersList = UsersAll .Skip(numRecord * (currPage - 1)).Take(numRecord) .ToList(); } protected override async Task OnInitializedAsync() { currSearch = ""; string rawConf = Configuration["RuntimeOpt:MultiRoleEnab"]; if (rawConf != null) { bool.TryParse(rawConf, out MultiRoleEnab); } AppMService.EA_SearchUpdated += AppMService_EA_SearchUpdated; // lettura dati await GetUsers(); await refreshLists(); await GetUserClaims(); } protected async Task SetNumRec(int newNum) { currPage = 1; numRecord = newNum; currPage = 1; await InvokeAsync(ReloadData); } protected async Task SetPage(int newNum) { currPage = newNum; EditUser(null); await InvokeAsync(ReloadData); } protected bool UserHasClaim(string ruolo) { bool answ = false; if (UserClaims != null && UserClaims.Count > 0) { answ = UserClaims.Where(x => x.RoleNav.Ruolo == ruolo).Any(); } return answ; } #endregion Protected Methods #region Private Fields private const string ADMIN_ROLE = "Admin"; private const string UNDEF_ROLE = "Undef"; private string currSearch = ""; /// /// User corrente /// private AuthUserModel? currUser = null; /// /// Abilitazione gestione ROLES multipli /// private bool MultiRoleEnab = true; private string qrCodeVal = ""; /// /// Elenco ROLES da mostrare in dropdown durante editing (usare DB?) /// private List RolesList = new List(); // To enable showing the Popup private bool ShowPopup = false; // To hold any possible errors private string strError = ""; private string userName = ""; /// /// Collezione utenti (totale) /// private List UsersAll = new List(); /// /// Collezione utenti /// private List UsersList = new List(); #endregion Private Fields #region Private Properties private int _filtUserRole { get; set; } = 0; [Inject] private IConfiguration Configuration { get; set; } = null!; /// /// 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 int 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 NewRoleId { get; set; } = 0; private int numRecord { get; set; } = 10; private List Roles2Add { get { List currRoles = new List(); foreach (var item in RolesList) { // solo se l'utente corrente lo possiede... if (UserClaims.Where(x => x.RoleID == item.RoleID).Any()) { // verifico no ci sia giā... if (!currUser.Claims.Where(x => x.RoleID == item.RoleID).Any()) { currRoles.Add(item); } } } return currRoles; } } #endregion Private Properties #region Private Methods private async Task AddSelRole() { if (NewRoleId > 0) { int userId = currUser.UserID; // creo nuovo ruolo... AuthClaimModel newClaim = new AuthClaimModel() { ClaimID = 0, UserID = currUser.UserID, RoleID = NewRoleId, DtIns = DateTime.Now, DtMod = DateTime.Now }; await DataService.AuthClaimUpsert(newClaim); // Refresh Users await ReloadData(); currUser = UsersAll.Find(x => x.UserID == userId); } } 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 DeleteRole(AuthClaimModel currClaim) { if (!await JSRuntime.InvokeAsync("confirm", "Sicuro di voler eliminare il Ruolo utente selezionato?")) return; int userId = currUser.UserID; await DataService.AuthClaimRemove(currClaim); // Refresh Users await ReloadData(); currUser = UsersAll.Find(x => x.UserID == userId); } private async Task DeleteUser(AuthUserModel _currRec) { if (!await JSRuntime.InvokeAsync("confirm", "Sicuro di voler eliminare i Ruoli per l'utente selezionato? Il record rimarrā ma inattivo.")) return; await DataService.AuthRoleResetUser(_currRec.UserID); // Close the Popup ShowPopup = false; // Refresh Users await ReloadData(); } private void EditUser(AuthUserModel _currRec) { // Open the Popup currUser = _currRec; NewRoleId = 0; ShowPopup = true; } private async Task GetUserClaims() { var authState = await AutheStateProvider.GetAuthenticationStateAsync(); var user = authState.User; if (user.Identity.IsAuthenticated) { userName = $"{user.Identity.Name}"; } UserClaims = await DataService.AuthClaimByUserName(userName); } private async Task refreshLists() { RolesList = await DataService.AuthRolesGetAll(); } private async Task ReloadData() { isLoading = true; await GetUsers(); isLoading = false; } private async Task SaveUser() { try { // chiamo update! await DataService.AuthUserUpsert(currUser); ShowPopup = false; // Refresh Users await GetUsers(); } catch (Exception ex) { strError = ex.GetBaseException().Message; } } #endregion Private Methods } }