Files
limanapp/LiMan.UI/Components/UserMan.razor.cs
T

466 lines
15 KiB
C#

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;
namespace LiMan.UI.Components
{
public partial class UserMan : IDisposable
{
#region Public Methods
public void Dispose()
{
AppMService.EA_SearchUpdated -= AppMService_EA_SearchUpdated;
}
[Inject]
protected LiManDataService DataService { get; set; } = null!;
/// <summary>
/// Recupera elenco utenti
/// </summary>
public 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();
}
public string ShowRoles(List<AuthClaimModel> 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!;
protected int totalCount { get; set; } = 0;
#endregion Protected Properties
#region Protected Methods
protected void DoSelect(AuthUserModel? 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["RuntimeOpt:MultiRoleEnab"];
if (rawConf != null)
{
bool.TryParse(rawConf, out MultiRoleEnab);
}
AppMService.EA_SearchUpdated += AppMService_EA_SearchUpdated;
// lettura dati
await GetUsers();
await refreshLists();
}
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 = "Admin";
private const string UNDEF_ROLE = "Undef";
private string currSearch = "";
/// <summary>
/// Abilitazione gestione ROLES multipli
/// </summary>
private bool MultiRoleEnab = true;
/// <summary>
/// User corrente
/// </summary>
private IdentityUser objUser = new IdentityUser();
private string qrCodeVal = "";
/// <summary>
/// Elenco ROLES da mostrare in dropdown durante editing (usare DB?)
/// </summary>
private List<AuthRoleModel> RolesList = new List<AuthRoleModel>();
// To enable showing the Popup
private bool ShowPopup = false;
// To hold any possible errors
private string strError = "";
/// <summary>
/// Collezione utenti (totale)
/// </summary>
private List<AuthUserModel> UsersAll = new List<AuthUserModel>();
/// <summary>
/// Collezione utenti
/// </summary>
private List<AuthUserModel> UsersList = new List<AuthUserModel>();
#endregion Private Fields
#region Private Properties
private int _filtUserRole { get; set; } = 0;
[Inject]
private IConfiguration Configuration { get; set; } = null!;
/// <summary>
/// Ruolo di default (User!!!)
/// </summary>
private string CurrentUserRole { get; set; } = "User";
private int currPage { get; set; } = 1;
/// <summary>
/// Ruoli correnti utente
/// </summary>
private string[] CurrUserRoles { get; set; } = new string[] { "User" };
/// <summary>
/// Gestione filtraggio dati
/// </summary>
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 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(AuthUserModel _currRec)
{
#if false
// Close the Popup
ShowPopup = false;
if (!await JSRuntime.InvokeAsync<bool>("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(AuthUserModel _currRec)
{
// Open the Popup
ShowPopup = true;
}
private async Task refreshLists()
{
RolesList = await DataService.AuthRolesGetAll();
}
private async Task ReloadData()
{
isLoading = true;
await GetUsers();
isLoading = false;
}
private async Task SaveUser()
{
try
{
#if false
// 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();
#endif
// Refresh Users
await GetUsers();
}
catch (Exception ex)
{
strError = ex.GetBaseException().Message;
}
}
#endregion Private Methods
}
}