backend + web: Add admin account lifecycle management

This commit is contained in:
GonnaHetzMe committed 2026-12-04 17:30:17 +01:00
1 parent fcf7cd0596
commit 91d0c06c83
25 files changed
+1148 -97

No files matched your search

+6
View File
@@ -52,6 +52,12 @@ public sealed record AdminUserDto(
public string FullName => $"{FirstName} {LastName}";
}
public sealed record AdminUserDetailsDto(int Id, string Email, string FirstName, string LastName, string? Phone,
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, bool? VerificationEmailSent = null);
public sealed record SaveAdminUserRequest(string Email, string FirstName, string LastName, string? Phone,
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, string? Password);
/// <summary>Stránkovaný seznam z API: <c>{ items, totalCount, page, pageSize }</c>.</summary>
public sealed record PagedResult<T>(IReadOnlyList<T> Items, int TotalCount, int Page, int PageSize)
{
+39 -2
View File
@@ -1,4 +1,5 @@
using System.Globalization;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using Microsoft.AspNetCore.WebUtilities;
@@ -42,16 +43,52 @@ public sealed class HelpdeskApiClient(HttpClient http)
public async Task ChangeUserRoleAsync(int id, string role, CancellationToken ct)
{
using var response = await http.PutAsJsonAsync($"admin/users/{id.ToString(CultureInfo.InvariantCulture)}/role", new { role }, ct);
using var response = await http.PutAsJsonAsync(AdminUserPath(id) + "/role", new { role }, ct);
await ApiResponse.EnsureSuccessAsync(response, ct);
}
public async Task SetUserActiveAsync(int id, bool isActive, CancellationToken ct)
{
using var response = await http.PutAsJsonAsync($"admin/users/{id.ToString(CultureInfo.InvariantCulture)}/active", new { isActive }, ct);
using var response = await http.PutAsJsonAsync(AdminUserPath(id) + "/active", new { isActive }, ct);
await ApiResponse.EnsureSuccessAsync(response, ct);
}
public async Task<AdminUserDetailsDto> GetAdminUserAsync(int id, CancellationToken ct)
{
using var response = await http.GetAsync(AdminUserPath(id), ct);
return await ApiResponse.ReadAsync<AdminUserDetailsDto>(response, ct);
}
public async Task<AdminUserDetailsDto?> SaveAdminUserAsync(int? id, SaveAdminUserRequest request, CancellationToken ct)
{
using var response = id is int userId
? await http.PutAsJsonAsync(AdminUserPath(userId), request, ct)
: await http.PostAsJsonAsync("admin/users", request, ct);
return response.StatusCode == HttpStatusCode.NoContent
? null
: await ApiResponse.ReadAsync<AdminUserDetailsDto>(response, ct);
}
public async Task SendAdminUserEmailConfirmationAsync(int id, CancellationToken ct)
{
using var response = await http.PostAsync(AdminUserPath(id) + "/email-confirmation", null, ct);
await ApiResponse.EnsureSuccessAsync(response, ct);
}
public async Task DeleteAdminUserAsync(int id, CancellationToken ct)
{
using var response = await http.DeleteAsync(AdminUserPath(id), ct);
await ApiResponse.EnsureSuccessAsync(response, ct);
}
public async Task UpdateAdminUsersAsync(int[] userIds, string action, string? role, CancellationToken ct)
{
using var response = await http.PostAsJsonAsync("admin/users/bulk", new { userIds, action, role }, ct);
await ApiResponse.EnsureSuccessAsync(response, ct);
}
private static string AdminUserPath(int id) => $"admin/users/{id.ToString(CultureInfo.InvariantCulture)}";
public async Task<PagedResult<IssueSummary>> GetIssuesAsync(IssueListQuery query, CancellationToken ct)
{
var parameters = new Dictionary<string, string?>
@@ -24,9 +24,95 @@ public sealed class AdminUsersController(HelpdeskApiClient api) : Controller
if (users.Items.Count == 0 && users.Page > 1)
return BackToList(new AdminUsersQuery(q, role, Math.Max(1, users.PageCount)));
int? currentUserId = int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier), CultureInfo.InvariantCulture, out var id)
? id : null;
return View(new AdminUsersViewModel(users, new AdminUsersQuery(q, role, users.Page), currentUserId));
return View(new AdminUsersViewModel(users, new AdminUsersQuery(q, role, users.Page), CurrentUserId));
}
[HttpGet("new")]
public IActionResult New([FromQuery] AdminUsersQuery query) => View("Form", new AdminUserForm { Query = query });
[HttpPost("new")]
public Task<IActionResult> New([FromForm] AdminUserForm model, [FromQuery] AdminUsersQuery query, CancellationToken ct) =>
SaveAsync(null, model, query, ct);
[HttpGet("{id:int}/edit")]
public async Task<IActionResult> Edit([FromRoute] int id, [FromQuery] AdminUsersQuery query, CancellationToken ct)
{
if (id == CurrentUserId)
return RedirectToAction("Index", "Profile");
var user = await api.GetAdminUserAsync(id, ct);
return View("Form", new AdminUserForm
{
Id = user.Id,
Query = query,
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
Phone = user.Phone,
Role = user.Role,
IsActive = user.IsActive,
EmailConfirmed = user.EmailConfirmed,
EmailNotificationsEnabled = user.EmailNotificationsEnabled,
});
}
[HttpPost("{id:int}/edit")]
public Task<IActionResult> Edit([FromRoute] int id, [FromForm] AdminUserForm model, [FromQuery] AdminUsersQuery query,
CancellationToken ct) => SaveAsync(id, model, query, ct);
[HttpPost("{id:int}/email-confirmation")]
public async Task<IActionResult> SendEmailConfirmation([FromRoute] int id, [FromQuery] AdminUsersQuery query, CancellationToken ct)
{
try
{
await api.SendAdminUserEmailConfirmationAsync(id, ct);
TempData.SetSuccess("Ověřovací e-mail byl odeslán.");
}
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.Conflict or HttpStatusCode.ServiceUnavailable)
{
TempData.SetError(ex.AllMessages);
}
return BackToEdit(id, query);
}
[HttpPost("{id:int}/delete")]
public async Task<IActionResult> Delete([FromRoute] int id, [FromForm] bool confirmDelete, [FromQuery] AdminUsersQuery query,
CancellationToken ct)
{
if (!confirmDelete)
{
TempData.SetError("Potvrďte smazání účtu.");
return BackToEdit(id, query);
}
return await UpdateAsync(query, () => api.DeleteAdminUserAsync(id, ct), "Účet byl smazán a jeho profil anonymizován.");
}
[HttpPost("bulk")]
public async Task<IActionResult> Bulk([FromForm] int[] userIds, [FromForm] string? action, [FromForm] string? newRole,
[FromForm] bool confirmDelete, [FromQuery] AdminUsersQuery query, CancellationToken ct)
{
if (!ModelState.IsValid || userIds is not { Length: >= 1 } ||
action is not ("activate" or "deactivate" or "role" or "delete"))
{
TempData.SetError("Označte účty a vyberte hromadnou akci.");
return BackToList(query);
}
if (action == "delete" && !confirmDelete)
{
TempData.SetError("Potvrďte smazání vybraných účtů.");
return BackToList(query);
}
if (action == "role" && (newRole is null || !UserRoles.All.Contains(newRole)))
{
TempData.SetError("Vyberte roli pro označené účty.");
return BackToList(query);
}
return await UpdateAsync(query, () => api.UpdateAdminUsersAsync(userIds, action, newRole, ct), "Hromadná akce byla provedena.");
}
[HttpPost("{id:int}/role")]
@@ -63,7 +149,7 @@ public sealed class AdminUsersController(HelpdeskApiClient api) : Controller
await update();
TempData.SetSuccess(success);
}
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict)
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict or HttpStatusCode.NotFound)
{
TempData.SetError(ex.AllMessages);
}
@@ -71,6 +157,44 @@ public sealed class AdminUsersController(HelpdeskApiClient api) : Controller
return BackToList(query);
}
private async Task<IActionResult> SaveAsync(int? id, AdminUserForm model, AdminUsersQuery query, CancellationToken ct)
{
if (id is not null && id == CurrentUserId)
return RedirectToAction("Index", "Profile");
model.Id = id;
model.Query = query;
if (id is null && string.IsNullOrWhiteSpace(model.Password))
ModelState.AddModelError(nameof(model.Password), "Zadejte počáteční heslo.");
if (ModelState.IsValid)
{
try
{
var result = await api.SaveAdminUserAsync(id, model.ToRequest(), ct);
var message = id is null ? "Účet byl založen." : "Změny účtu byly uloženy.";
TempData.SetSuccess(result?.VerificationEmailSent == true ? message + " Ověřovací e-mail byl odeslán." : message);
if (result is { VerificationEmailSent: false })
{
TempData.SetError("Ověřovací e-mail se nepodařilo odeslat. Můžete ho poslat znovu.");
return BackToEdit(result.Id, query);
}
return BackToList(query);
}
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict)
{
ModelState.AddApiErrors(ex, typeof(AdminUserForm));
}
}
return View("Form", model);
}
private int? CurrentUserId =>
int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier), CultureInfo.InvariantCulture, out var id) ? id : null;
private RedirectToActionResult BackToList(AdminUsersQuery query) =>
RedirectToAction(nameof(Index), new { q = query.Q, role = query.Role, page = query.Page });
private RedirectToActionResult BackToEdit(int id, AdminUsersQuery query) =>
RedirectToAction(nameof(Edit), new { id, q = query.Q, role = query.Role, page = query.Page });
}
@@ -1,5 +1,4 @@
using System.Security.Claims;
using Helpdesk.Web.Auth;
namespace Helpdesk.Web.Infrastructure;
@@ -21,7 +20,6 @@ public static class Navigation
new("Nástěnka", "Home", "Index"),
new("Nahlásit závadu", "Issues", "New"),
new("Moje hlášení", "Issues", "Index"),
new("Správa uživatelů", "AdminUsers", "Index", UserRoles.Admin),
];
public static IEnumerable<NavItem> For(ClaimsPrincipal user) => Items.Where(i => i.IsVisibleTo(user));
@@ -1,7 +1,50 @@
using System.ComponentModel.DataAnnotations;
using Helpdesk.Web.Api;
using Helpdesk.Web.Auth;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace Helpdesk.Web.Models;
public sealed record AdminUsersViewModel(PagedResult<AdminUserDto> Users, AdminUsersQuery Query, int? CurrentUserId);
public sealed record AdminUsersQuery(string? Q = null, string? Role = null, int Page = 1);
public sealed class AdminUserForm
{
[BindNever]
public int? Id { get; set; }
[BindNever]
public AdminUsersQuery Query { get; set; } = new();
[Display(Name = "Jméno"), Required(ErrorMessage = "Zadejte jméno."), StringLength(100)]
public string FirstName { get; set; } = "";
[Display(Name = "Příjmení"), Required(ErrorMessage = "Zadejte příjmení."), StringLength(100)]
public string LastName { get; set; } = "";
[Display(Name = "E-mail"), Required(ErrorMessage = "Zadejte e-mail."), EmailAddress(ErrorMessage = "Zadejte platný e-mail."), StringLength(254)]
public string Email { get; set; } = "";
[Display(Name = "Telefon"), StringLength(30)]
public string? Phone { get; set; }
[Display(Name = "Role"), Required(ErrorMessage = "Vyberte roli.")]
public string Role { get; set; } = UserRoles.Student;
[Display(Name = "Heslo"), DataType(DataType.Password)]
[StringLength(PasswordRules.MaxLength, MinimumLength = PasswordRules.MinLength, ErrorMessage = PasswordRules.LengthMessage)]
public string? Password { get; set; }
[Display(Name = "Aktivní účet")]
public bool IsActive { get; set; } = true;
[Display(Name = "E-mail je ověřený")]
public bool EmailConfirmed { get; set; }
[Display(Name = "E-mailové notifikace")]
public bool EmailNotificationsEnabled { get; set; } = true;
public SaveAdminUserRequest ToRequest() => new(Email.Trim(), FirstName.Trim(), LastName.Trim(), Phone,
Role, IsActive, EmailConfirmed, EmailNotificationsEnabled, Password);
}
@@ -0,0 +1,123 @@
@model AdminUserForm
@{
var isNew = Model.Id is null;
ViewData["Title"] = isNew ? "Založit účet" : "Upravit účet";
var query = Model.Query;
}
<section class="app-page-head">
<a class="app-back-link" asp-action="Index" asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@query.Page">Správa uživatelů</a>
<h1 class="mt-2 mb-0">@ViewData["Title"]</h1>
</section>
<div class="row g-4">
<div class="col-lg-8">
<div class="app-card">
<partial name="_FormErrors" />
<form method="post" asp-action="@(isNew ? "New" : "Edit")" asp-route-id="@Model.Id"
asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@query.Page" novalidate>
<div class="row g-3 mb-4">
<div class="col-sm-6">
<label asp-for="FirstName" class="form-label"></label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="invalid-feedback d-block"></span>
</div>
<div class="col-sm-6">
<label asp-for="LastName" class="form-label"></label>
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName" class="invalid-feedback d-block"></span>
</div>
<div class="col-sm-6">
<label asp-for="Email" class="form-label"></label>
<input asp-for="Email" class="form-control" data-admin-email="@(!isNew ? "" : null)" />
<span asp-validation-for="Email" class="invalid-feedback d-block"></span>
</div>
<div class="col-sm-6">
<label asp-for="Phone" class="form-label"></label>
<input asp-for="Phone" class="form-control" type="tel" />
<span asp-validation-for="Phone" class="invalid-feedback d-block"></span>
</div>
<div class="col-sm-6">
<label asp-for="Role" class="form-label"></label>
<select asp-for="Role" class="form-select">
@foreach (var role in UserRoles.All)
{
<option value="@role">@UserRoles.DisplayName(role)</option>
}
</select>
<span asp-validation-for="Role" class="invalid-feedback d-block"></span>
</div>
<div class="col-sm-6">
<label asp-for="Password" class="form-label">@(isNew ? "Počáteční heslo" : "Nové heslo")</label>
<input asp-for="Password" class="form-control" autocomplete="new-password" />
@if (!isNew)
{
<div class="form-text">Prázdné pole ponechá stávající heslo.</div>
}
<span asp-validation-for="Password" class="invalid-feedback d-block"></span>
</div>
</div>
<div class="form-check">
<input asp-for="IsActive" class="form-check-input" />
<label asp-for="IsActive" class="form-check-label"></label>
</div>
@if (isNew)
{
<fieldset class="mt-3 mb-3">
<legend class="form-label fs-6">Jak ověřit e-mail</legend>
<div class="form-check">
<input asp-for="EmailConfirmed" type="radio" value="false" id="verification-email" class="form-check-input" />
<label for="verification-email" class="form-check-label">Poslat ověřovací e-mail</label>
</div>
<div class="form-check">
<input asp-for="EmailConfirmed" type="radio" value="true" id="verification-direct" class="form-check-input" />
<label for="verification-direct" class="form-check-label">Ověřit e-mail ručně</label>
</div>
<p class="form-text mb-0">Ověřovací odkaz se odešle, pokud je účet aktivní. Při ručním ověření se aktivní uživatel může přihlásit hned.</p>
</fieldset>
}
else
{
<div class="form-check">
<input asp-for="EmailConfirmed" class="form-check-input" />
<label asp-for="EmailConfirmed" class="form-check-label"></label>
<p class="form-text mb-2">Při změně adresy se ověření obnoví. Aktivnímu účtu pošleme odkaz na novou adresu.</p>
</div>
}
<div class="form-check mb-4">
<input asp-for="EmailNotificationsEnabled" class="form-check-input" />
<label asp-for="EmailNotificationsEnabled" class="form-check-label"></label>
</div>
<button type="submit" class="btn btn-primary">@(isNew ? "Založit účet" : "Uložit změny")</button>
</form>
</div>
</div>
@if (!isNew)
{
<div class="col-lg-4">
@if (Model.IsActive && !Model.EmailConfirmed)
{
<section class="app-card mb-4">
<h2 class="h6 fw-bold">Ověření e-mailu</h2>
<form method="post" asp-action="SendEmailConfirmation" asp-route-id="@Model.Id"
asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@query.Page">
<button type="submit" class="btn btn-outline-primary">Poslat ověřovací e-mail</button>
</form>
</section>
}
<section class="app-card">
<h2 class="h6 fw-bold">Smazat účet</h2>
<p class="text-body-secondary">Účet ztratí přístup a jeho profil se nevratně anonymizuje. Historie hlášení a návrhů zůstane.</p>
<form method="post" asp-action="Delete" asp-route-id="@Model.Id"
asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@query.Page">
<div class="form-check mb-3">
<input id="confirm-delete" name="confirmDelete" type="checkbox" value="true" class="form-check-input" required />
<label for="confirm-delete" class="form-check-label">Potvrzuji smazání účtu</label>
</div>
<button type="submit" class="btn btn-outline-danger">Smazat účet</button>
</form>
</section>
</div>
}
</div>
+58 -3
View File
@@ -5,8 +5,10 @@
var query = Model.Query;
}
<section class="app-page-head">
<h1>Správa uživatelů</h1>
<section class="app-page-head d-flex flex-wrap justify-content-between align-items-center gap-2">
<h1 class="mb-0">Správa uživatelů</h1>
<a asp-action="New" asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@query.Page"
class="btn btn-primary">Založit účet</a>
</section>
<form method="get" asp-action="Index" class="app-card mb-4" role="search" aria-label="Vyhledávání uživatelů">
@@ -43,13 +45,63 @@
}
else
{
@if (result.Items.Any(user => user.Id != Model.CurrentUserId))
{
<form id="user-bulk" method="post" asp-action="Bulk"
asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@query.Page"
class="app-card mb-3 py-3" data-user-bulk>
<div class="d-flex flex-wrap gap-3 align-items-end">
<div class="form-check">
<input type="checkbox" class="form-check-input" id="select-page" data-user-select-page />
<label class="form-check-label" for="select-page">Vybrat vše na stránce</label>
<span class="d-block small text-body-secondary" data-user-count aria-live="polite"></span>
</div>
<div>
<label class="form-label" for="bulk-action">Hromadná akce</label>
<select class="form-select" id="bulk-action" name="action" required data-user-action>
<option value="">Vyberte akci</option>
<option value="activate">Aktivovat</option>
<option value="deactivate">Deaktivovat</option>
<option value="role">Změnit roli</option>
<option value="delete">Smazat</option>
</select>
</div>
<div data-user-bulk-role>
<label class="form-label" for="bulk-role">Nová role při změně role</label>
<select class="form-select" id="bulk-role" name="newRole">
<option value="">Vyberte roli</option>
@foreach (var role in UserRoles.All)
{
<option value="@role">@UserRoles.DisplayName(role)</option>
}
</select>
</div>
<button type="submit" class="btn btn-outline-primary">Provést akci</button>
</div>
<div class="mt-3" data-user-bulk-delete>
<div class="form-check">
<input name="confirmDelete" value="true" type="checkbox" class="form-check-input" id="confirm-bulk-delete" />
<label class="form-check-label" for="confirm-bulk-delete">Potvrzuji smazání vybraných účtů</label>
</div>
<p class="form-text mb-0">Účty ztratí přístup a jejich profily se anonymizují. Historie hlášení a návrhů zůstane.</p>
</div>
</form>
}
<ul class="list-unstyled d-grid gap-2 mb-0">
@foreach (var user in result.Items)
{
<li class="app-card px-3 px-sm-4 py-3">
<div class="row g-3 align-items-center">
<div class="col-12 col-lg-4">
<h2 class="h6 fw-bold text-break mb-1">@user.FullName</h2>
<div class="d-flex align-items-center gap-2">
@if (user.Id != Model.CurrentUserId)
{
<input name="userIds" value="@user.Id" type="checkbox" class="form-check-input mt-0"
form="user-bulk" aria-label="Označit účet @user.Email" />
}
<h2 class="h6 fw-bold text-break mb-1">@user.FullName</h2>
</div>
<div class="small text-body-secondary text-break">@user.Email</div>
</div>
<div class="col-12 col-sm-5 col-lg-3">
@@ -67,6 +119,9 @@ else
}
else
{
<a asp-action="Edit" asp-route-id="@user.Id" asp-route-q="@query.Q" asp-route-role="@query.Role"
asp-route-page="@query.Page" class="btn btn-sm btn-outline-primary"
aria-label="Upravit účet @user.Email">Upravit</a>
<form method="post" asp-action="ChangeRole" asp-route-id="@user.Id"
asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@query.Page"
class="d-flex flex-wrap align-items-center gap-2">
@@ -11,6 +11,7 @@
<li><a class="dropdown-item" asp-controller="Profile" asp-action="Index">Můj profil</a></li>
@if (User.IsInRole(UserRoles.Admin))
{
<li><a class="dropdown-item" asp-controller="AdminUsers" asp-action="Index">Správa uživatelů</a></li>
<li><a class="dropdown-item" href="~/swagger">Swagger API</a></li>
}
<li><hr class="dropdown-divider" /></li>
+44
View File
@@ -4,3 +4,47 @@
document.querySelectorAll("[data-autosubmit]").forEach((element) => {
element.addEventListener("change", () => element.form?.requestSubmit());
});
document.querySelectorAll("[data-user-bulk]").forEach((form) => {
const accounts = Array.from(form.elements).filter((element) => element.name === "userIds");
const selectPage = form.querySelector("[data-user-select-page]");
const count = form.querySelector("[data-user-count]");
const action = form.querySelector("[data-user-action]");
const role = form.querySelector("[data-user-bulk-role]");
const deletion = form.querySelector("[data-user-bulk-delete]");
const confirmDeletion = deletion.querySelector("input");
function updateSelection() {
const selected = accounts.filter((account) => account.checked).length;
selectPage.checked = selected === accounts.length;
selectPage.indeterminate = selected > 0 && selected < accounts.length;
count.textContent = `Vybráno ${selected} z ${accounts.length}`;
}
function updateAction() {
role.hidden = action.value !== "role";
deletion.hidden = action.value !== "delete";
confirmDeletion.required = !deletion.hidden;
if (deletion.hidden) confirmDeletion.checked = false;
}
selectPage.addEventListener("change", () => {
accounts.forEach((account) => { account.checked = selectPage.checked; });
updateSelection();
});
accounts.forEach((account) => account.addEventListener("change", updateSelection));
action.addEventListener("change", updateAction);
updateSelection();
updateAction();
});
document.querySelectorAll("[data-admin-email]").forEach((email) => {
const confirmed = email.form?.querySelector("#EmailConfirmed");
if (!confirmed) return;
email.addEventListener("change", () => {
if (email.value.trim().toLowerCase() !== email.defaultValue.trim().toLowerCase()) {
confirmed.checked = false;
}
});
});