This commit is contained in:
Ondur
2026-11-11 16:53:32 +01:00
parent 1506bfcf09
commit 257fd7481a
4 changed files with 115 additions and 70 deletions

View File

@@ -1,14 +1,19 @@
@page "/admin/administratori"
@layout Web_Jarmark.Components.Layout.Admin.AdminLayout
@rendermode InteractiveServer
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Identity
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.EntityFrameworkCore
@using Web_Jarmark.Data
@inject UserManager<ApplicationUser> UserManager
@inject RoleManager<IdentityRole> RoleManager
@inject AuthenticationStateProvider AuthenticationStateProvider
@attribute [Authorize(Roles = "Admin")]
<PageTitle>Registrovaní uživatelé</PageTitle>
<div class="ap">
@@ -17,7 +22,7 @@
<div class="ap-hero-row">
<div>
<h1>Uživatelé</h1>
<p class="ap-sub">Správa registrovaných účtů.</p>
<p class="ap-sub">Správa registrovaných účtů a administrátorských oprávnění.</p>
</div>
</div>
</header>
@@ -53,13 +58,13 @@
<th>Potvrzený</th>
<th>Admin</th>
<th>Stav</th>
<th></th>
<th>Akce</th>
</tr>
</thead>
<tbody>
@foreach (var u in users)
{
<tr>
<tr @key="u.Id">
<td class="ap-name">@u.Email</td>
<td>
<span class="ap-status @(u.EmailConfirmed ? "is-on" : "is-off")">
@@ -83,6 +88,7 @@
@onclick="() => ToggleAdminAsync(u)">
@(u.IsAdmin ? "Odebrat admin" : "Udělat admin")
</button>
<button type="button"
class="ap-btn ap-btn-ghost"
disabled="@busy"
@@ -118,7 +124,14 @@
{
if (!await RoleManager.RoleExistsAsync(AdminRole))
{
await RoleManager.CreateAsync(new IdentityRole(AdminRole));
var result = await RoleManager.CreateAsync(
new IdentityRole(AdminRole));
if (!result.Succeeded)
{
message = "Nepodařilo se vytvořit roli Admin: "
+ string.Join(", ", result.Errors.Select(e => e.Description));
}
}
}
@@ -134,7 +147,9 @@
foreach (var user in list)
{
var roles = await UserManager.GetRolesAsync(user);
var isLocked = user.LockoutEnd.HasValue && user.LockoutEnd > DateTimeOffset.UtcNow;
var isLocked = user.LockoutEnd.HasValue
&& user.LockoutEnd > DateTimeOffset.UtcNow;
users.Add(new UserRow(
user.Id,
@@ -147,34 +162,82 @@
private async Task ToggleAdminAsync(UserRow row)
{
if (busy)
return;
busy = true;
message = null;
try
{
var user = await UserManager.FindByIdAsync(row.Id);
if (user is null)
{
message = "Uživatel nebyl nalezen.";
return;
}
if (!await RoleManager.RoleExistsAsync(AdminRole))
{
var createRoleResult = await RoleManager.CreateAsync(
new IdentityRole(AdminRole));
if (!createRoleResult.Succeeded)
{
message = "Nepodařilo se vytvořit roli Admin: "
+ string.Join(", ", createRoleResult.Errors.Select(e => e.Description));
return;
}
}
if (row.IsAdmin)
{
await UserManager.RemoveFromRoleAsync(user, AdminRole);
message = $"Role Admin odebrána: {row.Email}";
var admins = await UserManager.GetUsersInRoleAsync(AdminRole);
if (admins.Count <= 1)
{
message = "Nelze odebrat roli poslednímu administrátorovi.";
return;
}
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var currentUserId = UserManager.GetUserId(authState.User);
if (currentUserId == user.Id)
{
message = "Nemůžeš odebrat administrátorskou roli sám sobě.";
return;
}
}
IdentityResult result;
if (row.IsAdmin)
{
result = await UserManager.RemoveFromRoleAsync(user, AdminRole);
}
else
{
await UserManager.AddToRoleAsync(user, AdminRole);
message = $"Role Admin přidělena: {row.Email}";
result = await UserManager.AddToRoleAsync(user, AdminRole);
}
if (!result.Succeeded)
{
message = "Změna role se nepodařila: "
+ string.Join(", ", result.Errors.Select(e => e.Description));
return;
}
message = row.IsAdmin
? $"Administrátorská role byla odebrána: {row.Email}"
: $"Administrátorská role byla přidána: {row.Email}";
await LoadUsersAsync();
}
catch (Exception ex)
{
message = "Chyba: " + ex.Message;
message = "Chyba při změně role: " + ex.Message;
}
finally
{
@@ -184,30 +247,59 @@
private async Task ToggleLockAsync(UserRow row)
{
if (busy)
return;
busy = true;
message = null;
try
{
var user = await UserManager.FindByIdAsync(row.Id);
if (user is null)
{
message = "Uživatel nebyl nalezen.";
return;
}
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var currentUserId = UserManager.GetUserId(authState.User);
if (currentUserId == user.Id)
{
message = "Nemůžeš zamknout vlastní účet.";
return;
}
IdentityResult result;
if (row.IsLocked)
{
await UserManager.SetLockoutEndDateAsync(user, null);
message = $"Účet odemčen: {row.Email}";
result = await UserManager.SetLockoutEndDateAsync(user, null);
}
else
{
await UserManager.SetLockoutEnabledAsync(user, true);
await UserManager.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddYears(100));
message = $"Účet zamčen: {row.Email}";
result = await UserManager.SetLockoutEnabledAsync(user, true);
if (result.Succeeded)
{
result = await UserManager.SetLockoutEndDateAsync(
user, DateTimeOffset.UtcNow.AddYears(100));
}
}
if (!result.Succeeded)
{
message = "Změna stavu účtu se nepodařila: "
+ string.Join(", ", result.Errors.Select(e => e.Description));
return;
}
message = row.IsLocked
? $"Účet byl odemčen: {row.Email}"
: $"Účet byl zamčen: {row.Email}";
await LoadUsersAsync();
}
catch (Exception ex)

View File

@@ -46,69 +46,22 @@ builder.Services.AddSingleton<IEmailSender<ApplicationUser>, IdentityNoOpEmailSe
builder.Services.AddHttpContextAccessor();
var app = builder.Build();
// Vytvoření role Admin, pokud ještě neexistuje
using (var scope = app.Services.CreateScope())
{
var userManager = scope.ServiceProvider
.GetRequiredService<UserManager<ApplicationUser>>();
var roleManager = scope.ServiceProvider
.GetRequiredService<RoleManager<IdentityRole>>();
const string adminEmail = "markus@bumbus.cz";
// Vytvoření role Admin, pokud ještě neexistuje
if (!await roleManager.RoleExistsAsync("Admin"))
{
await roleManager.CreateAsync(new IdentityRole("Admin"));
}
var result = await roleManager.CreateAsync(new IdentityRole("Admin"));
// Vyhledání administrátorského účtu
var adminUser = await userManager.FindByEmailAsync(adminEmail);
if (adminUser != null)
{
if (!await userManager.IsInRoleAsync(adminUser, "Admin"))
if (!result.Succeeded)
{
await userManager.AddToRoleAsync(adminUser, "Admin");
}
}
else
{
throw new Exception(
$"Administrátorský účet {adminEmail} nebyl nalezen.");
}
}
// Vytvoření rolí a nastavení administrátora
using (var scope = app.Services.CreateScope())
{
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
if (!await roleManager.RoleExistsAsync("Admin"))
{
await roleManager.CreateAsync(new IdentityRole("Admin"));
}
if (!await roleManager.RoleExistsAsync("User"))
{
await roleManager.CreateAsync(new IdentityRole("User"));
}
var adminEmail = app.Configuration["InitialAdmin:Email"];
if (!string.IsNullOrWhiteSpace(adminEmail))
{
var admin = await userManager.FindByEmailAsync(adminEmail);
if (admin != null && !await userManager.IsInRoleAsync(admin, "Admin"))
{
var result = await userManager.AddToRoleAsync(admin, "Admin");
if (!result.Succeeded)
{
throw new InvalidOperationException(
string.Join(", ", result.Errors.Select(e => e.Description)));
}
throw new InvalidOperationException(
"Nepodařilo se vytvořit roli Admin: "
+ string.Join(", ", result.Errors.Select(e => e.Description)));
}
}
}

Binary file not shown.

Binary file not shown.