4fda312aac
- altri metodi tracciati - modifica json x prod - aggiunta Async vari
715 lines
24 KiB
C#
715 lines
24 KiB
C#
using GWMS.Data;
|
|
using GWMS.UI.Data;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Components;
|
|
using Microsoft.AspNetCore.Components.Authorization;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.JSInterop;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace GWMS.UI.Pages
|
|
{
|
|
[Authorize(Roles = "SuperAdmin, Admin")]
|
|
public partial class UserAdmin : ComponentBase, IDisposable
|
|
{
|
|
#region Public Fields
|
|
|
|
public const string ADMIN_ROLE = "SuperAdmin";
|
|
|
|
public const string STD_CLAIM = "None";
|
|
|
|
public const string STD_CLAIM_VAL = "0";
|
|
|
|
public const string UNDEF_ROLE = "Undef";
|
|
|
|
#endregion Public Fields
|
|
|
|
#region Public Properties
|
|
|
|
public string searchVal
|
|
{
|
|
get
|
|
{
|
|
return AppMService.SearchVal;
|
|
}
|
|
}
|
|
|
|
#endregion Public Properties
|
|
|
|
#region Public Methods
|
|
|
|
public List<string> ConvertClaim(List<System.Security.Claims.Claim> ClaimList)
|
|
{
|
|
List<string> answ = new List<string>();
|
|
|
|
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 "PlantId":
|
|
if (plantList != null)
|
|
{
|
|
var plantRec = plantList
|
|
.Where(x => x.PlantId.ToString() == splitClaim[1].Trim())
|
|
.FirstOrDefault();
|
|
if (plantRec != null)
|
|
{
|
|
answ.Add($"{splitClaim[0]}: {plantRec.PlantDesc}");
|
|
}
|
|
else
|
|
{
|
|
answ.Add($"{claim}");
|
|
}
|
|
}
|
|
break;
|
|
|
|
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;
|
|
|
|
case "None":
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
return answ;
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
AppMService.EA_SearchUpdated -= OnSeachUpdated;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Recupera elenco utenti
|
|
/// </summary>
|
|
public async Task GetUsers()
|
|
{
|
|
// clear any error messages
|
|
strError = "";
|
|
|
|
UsersAll = await DataService.UserDataGetFiltAsync(searchVal);
|
|
|
|
// filtro visualizzazione x tipo SE richeisto
|
|
if (FiltUserRole != "0")
|
|
{
|
|
UsersAll = UsersAll.Where(x => x.Roles.Contains(FiltUserRole)).ToList();
|
|
}
|
|
|
|
UsersList = UsersAll
|
|
.Skip(numRecord * (currPage - 1)).Take(numRecord)
|
|
.ToList();
|
|
}
|
|
|
|
public async void OnSeachUpdated()
|
|
{
|
|
await GetUsers();
|
|
StateHasChanged();
|
|
}
|
|
|
|
public string ShowClaims(List<System.Security.Claims.Claim> ClaimList)
|
|
{
|
|
//string answ = string.Join(",", ClaimList);
|
|
string answ = string.Join(",", ConvertClaim(ClaimList));
|
|
return answ;
|
|
}
|
|
|
|
public string ShowRoles(List<string> RoleList)
|
|
{
|
|
string answ = string.Join(",", RoleList);
|
|
return answ;
|
|
}
|
|
|
|
#endregion Public Methods
|
|
|
|
#region Protected Properties
|
|
|
|
[Inject]
|
|
protected RoleManager<IdentityRole> _RoleManager { get; set; }
|
|
|
|
[Inject]
|
|
protected UserManager<IdentityUser> _UserManager { get; set; }
|
|
|
|
[Inject]
|
|
protected MessageService AppMService { get; set; }
|
|
|
|
[Inject]
|
|
protected AuthenticationStateProvider AuthenticationStateProvider { get; set; }
|
|
|
|
[Inject]
|
|
protected GWMSDataService DataService { get; set; }
|
|
|
|
[Inject]
|
|
protected IJSRuntime JSRuntime { get; set; }
|
|
|
|
protected List<GWMS.Data.DatabaseModels.PlantDetailModel>? plantList { get; set; } = null;
|
|
|
|
protected List<GWMS.Data.DatabaseModels.SupplierModel>? suppList { get; set; } = null;
|
|
|
|
protected int totalCount
|
|
{
|
|
get
|
|
{
|
|
int answ = 0;
|
|
if (UsersAll != null)
|
|
{
|
|
answ = UsersAll.Count;
|
|
}
|
|
return answ;
|
|
}
|
|
}
|
|
|
|
protected List<GWMS.Data.DatabaseModels.TransporterModel>? transpList { get; set; } = null;
|
|
|
|
#endregion Protected Properties
|
|
|
|
#region Protected Methods
|
|
|
|
protected void ForceReload(int newNum)
|
|
{
|
|
numRecord = newNum;
|
|
}
|
|
|
|
protected void ForceReloadPage(int newNum)
|
|
{
|
|
currPage = newNum;
|
|
}
|
|
|
|
protected override async Task OnInitializedAsync()
|
|
{
|
|
AppMService.ShowSearch = true;
|
|
AppMService.PageName = "Gestione Utenti";
|
|
AppMService.PageIcon = "fas fa-users pr-2";
|
|
AppMService.EA_SearchUpdated += OnSeachUpdated;
|
|
// lettura dati
|
|
await GetUsers();
|
|
await CheckSuperAdmin();
|
|
}
|
|
|
|
#endregion Protected Methods
|
|
|
|
#region Private Fields
|
|
|
|
/// <summary>
|
|
/// Elenco CLAIMS da mostrare durante editing
|
|
/// </summary>
|
|
private List<string> ClaimsList = new List<string>() { STD_CLAIM, "PlantId", "SupplierId", "TransporterId" };
|
|
|
|
private Dictionary<string, string> ClaimValList = new Dictionary<string, string>();
|
|
|
|
/// <summary>
|
|
/// User corrente
|
|
/// </summary>
|
|
private IdentityUser objUser = new IdentityUser();
|
|
|
|
private string qrCodeVal = "";
|
|
|
|
/// <summary>
|
|
/// Collezione utenti
|
|
/// </summary>
|
|
private List<IdentityUser> RawList = new List<IdentityUser>();
|
|
|
|
/// <summary>
|
|
/// Elenco ROLES da mostrare in dropdown durante editing (1 solo? usare DB?!?)
|
|
/// </summary>
|
|
private List<string> RolesList = new List<string>() { "Undef", "ExtTransp", "ExtUser", "User", "Admin", "SuperAdmin" };
|
|
|
|
// To enable showing the Popup
|
|
private bool ShowPopup = false;
|
|
|
|
// To hold any possible errors
|
|
private string strError = "";
|
|
|
|
/// <summary>
|
|
/// Collezione utenti (totale)
|
|
/// </summary>
|
|
private List<UserData> UsersAll = new List<UserData>();
|
|
|
|
/// <summary>
|
|
/// Collezione utenti
|
|
/// </summary>
|
|
private List<UserData> UsersList = new List<UserData>();
|
|
|
|
#endregion Private Fields
|
|
|
|
#region Private Properties
|
|
|
|
private string _CurrClaimType { get; set; } = "None";
|
|
|
|
private int _currPage { get; set; } = 1;
|
|
|
|
private string _filtUserRole { get; set; } = "0";
|
|
|
|
private int _numRecord { get; set; } = 10;
|
|
|
|
[CascadingParameter]
|
|
private Task<AuthenticationState> authenticationStateTask { get; set; }
|
|
|
|
[Inject]
|
|
private IConfiguration Configuration { get; set; }
|
|
|
|
private System.Security.Claims.Claim CurrentUserClaim
|
|
{
|
|
get => new System.Security.Claims.Claim(CurrentUserClaimType, CurrentUserClaimVal);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Claim di default (Tipo)
|
|
/// </summary>
|
|
private string CurrentUserClaimType
|
|
{
|
|
get
|
|
{
|
|
return _CurrClaimType;
|
|
}
|
|
set
|
|
{
|
|
_CurrClaimType = value;
|
|
var pUpd = Task.Run(async () => await refreshClaimVal(value));
|
|
pUpd.Wait();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Claim di default (valore)
|
|
/// </summary>
|
|
private string CurrentUserClaimVal { get; set; } = "0";
|
|
|
|
/// <summary>
|
|
/// Ruolo di default (User!!!)
|
|
/// </summary>
|
|
private string CurrentUserRole { get; set; } = "User";
|
|
|
|
private int currPage
|
|
{
|
|
get => _currPage;
|
|
set
|
|
{
|
|
if (_currPage != value)
|
|
{
|
|
_currPage = value;
|
|
var pUpd = Task.Run(async () => await ReloadData());
|
|
pUpd.Wait();
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gestione filtraggio dati
|
|
/// </summary>
|
|
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 => _numRecord;
|
|
set
|
|
{
|
|
if (_numRecord != value)
|
|
{
|
|
_numRecord = value;
|
|
var pUpd = Task.Run(async () => await ReloadData());
|
|
pUpd.Wait();
|
|
}
|
|
}
|
|
}
|
|
|
|
#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 Task CheckSuperAdmin()
|
|
{
|
|
// se non ci fosse --> creo samuele come superadmin
|
|
string superUser = "samuele@steamware.net";
|
|
string superPwd = "viaDante16!";
|
|
var user = await _UserManager.FindByEmailAsync(superUser);
|
|
if (user == null)
|
|
{
|
|
// Insert new user
|
|
var NewUser =
|
|
new IdentityUser
|
|
{
|
|
UserName = superUser,
|
|
Email = superUser,
|
|
EmailConfirmed = true
|
|
};
|
|
var CreateResult = await _UserManager.CreateAsync(NewUser, superPwd);
|
|
if (CreateResult.Succeeded)
|
|
{
|
|
user = await _UserManager.FindByEmailAsync(superUser);
|
|
}
|
|
}
|
|
|
|
// verifico ruoli...
|
|
if (user != null)
|
|
{
|
|
// Gestione salvataggio ruoli... SE VARIATO...
|
|
var UserRoles = await _UserManager.GetRolesAsync(user);
|
|
if (UserRoles != null && UserRoles.Count > 0)
|
|
{
|
|
var oldRole = UserRoles.Where(x => x == ADMIN_ROLE).FirstOrDefault();
|
|
if (oldRole == null)
|
|
{
|
|
// aggiungo a ruolo admin
|
|
await _UserManager.AddToRoleAsync(user, ADMIN_ROLE);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task ClosePopup()
|
|
{
|
|
// Close the Popup
|
|
ShowPopup = false;
|
|
// Refresh Users
|
|
await GetUsers();
|
|
}
|
|
|
|
private async Task DeleteUser(IdentityUser _IdentityUser)
|
|
{
|
|
// 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);
|
|
}
|
|
// 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 UserRoles = await _UserManager.GetRolesAsync(user);
|
|
if (UserRoles != null)
|
|
{
|
|
CurrentUserRole = UserRoles.FirstOrDefault();
|
|
}
|
|
else
|
|
{
|
|
CurrentUserRole = UNDEF_ROLE;
|
|
}
|
|
|
|
// salvo claim
|
|
var UserClaims = await _UserManager.GetClaimsAsync(user);
|
|
if (UserClaims != null && UserClaims.Count > 0)
|
|
{
|
|
var CurrentUserClaim = UserClaims.FirstOrDefault();
|
|
CurrentUserClaimType = CurrentUserClaim.Type;
|
|
CurrentUserClaimVal = CurrentUserClaim.Value;
|
|
}
|
|
else
|
|
{
|
|
CurrentUserClaimType = STD_CLAIM;
|
|
CurrentUserClaimVal = "0";
|
|
}
|
|
|
|
string baseUrl = Configuration["RuntimeOpt:BaseUrl"];
|
|
string baseAppPath = Configuration["RuntimeOpt:BaseAppPath"];
|
|
string redirPage = Configuration["RuntimeOpt: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<string, string>();
|
|
// aggiorno elenco ClaimValList
|
|
switch (newType)
|
|
{
|
|
case "PlantId":
|
|
// elenco plant --> to dictionary!
|
|
var plantList = await DataService.PlantsListAsync();
|
|
if (plantList != null)
|
|
{
|
|
ClaimValList = plantList
|
|
.ToDictionary(x => $"{x.PlantId}", x => x.PlantDesc);
|
|
}
|
|
break;
|
|
|
|
case "SupplierId":
|
|
// elenco plant --> to dictionary!
|
|
var suppList = await DataService.SuppliersGetAllAsync();
|
|
if (suppList != null)
|
|
{
|
|
ClaimValList = suppList
|
|
.ToDictionary(x => $"{x.SupplierId}", x => x.SupplierDesc);
|
|
}
|
|
break;
|
|
|
|
case "TransporterId":
|
|
// elenco plant --> to dictionary!
|
|
var transpList = await DataService.TransportersGetAllAsync();
|
|
if (transpList != null)
|
|
{
|
|
ClaimValList = transpList
|
|
.ToDictionary(x => $"{x.TransporterId}", x => x.TransporterDesc);
|
|
}
|
|
break;
|
|
|
|
case "None":
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
|
|
private async Task refreshLists()
|
|
{
|
|
// effettuo refresh valori cache plants/suppliers/transp
|
|
if (plantList == null)
|
|
{
|
|
plantList = await DataService.PlantsListAsync();
|
|
}
|
|
if (suppList == null)
|
|
{
|
|
suppList = await DataService.SuppliersGetAllAsync();
|
|
}
|
|
if (transpList == null)
|
|
{
|
|
transpList = await DataService.TransportersGetAllAsync();
|
|
}
|
|
}
|
|
|
|
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 (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);
|
|
}
|
|
|
|
// gestione salvataggio Claims
|
|
var UserClaims = await _UserManager.GetClaimsAsync(user);
|
|
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
|
|
{
|
|
// 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 Users
|
|
await GetUsers();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
strError = ex.GetBaseException().Message;
|
|
}
|
|
}
|
|
|
|
#endregion Private Methods
|
|
}
|
|
} |