web: Add admin user management

This commit is contained in:
GonnaHetzMe committed 2026-12-04 16:49:05 +01:00
1 parent 232d48c7fc
commit fcf7cd0596
11 files changed
+410 -18

No files matched your search

+6
View File
@@ -46,6 +46,12 @@ public sealed record ResetPasswordRequest(string Token, string NewPassword);
public sealed record UpdateProfileRequest(string FirstName, string LastName, string? Phone, bool EmailNotificationsEnabled);
public sealed record AdminUserDto(
int Id, string Email, string FirstName, string LastName, string Role, bool IsActive, bool EmailConfirmed, DateTimeOffset CreatedAt)
{
public string FullName => $"{FirstName} {LastName}";
}
/// <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)
{
+24
View File
@@ -28,6 +28,30 @@ public sealed class HelpdeskApiClient(HttpClient http)
return await ApiResponse.ReadAsync<UserDto>(response, ct);
}
public async Task<PagedResult<AdminUserDto>> GetAdminUsersAsync(string? q, string? role, int page, CancellationToken ct)
{
var parameters = new Dictionary<string, string?>
{
["q"] = q,
["role"] = role,
["page"] = page.ToString(CultureInfo.InvariantCulture),
};
using var response = await http.GetAsync(QueryHelpers.AddQueryString("admin/users", parameters), ct);
return await ApiResponse.ReadAsync<PagedResult<AdminUserDto>>(response, ct);
}
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);
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);
await ApiResponse.EnsureSuccessAsync(response, ct);
}
public async Task<PagedResult<IssueSummary>> GetIssuesAsync(IssueListQuery query, CancellationToken ct)
{
var parameters = new Dictionary<string, string?>
+2
View File
@@ -9,6 +9,8 @@ public static class UserRoles
public const string Management = "MANAGEMENT";
public const string Admin = "ADMIN";
public static IReadOnlyList<string> All { get; } = [Student, Teacher, FacilityManager, Management, Admin];
public static string DisplayName(string? role) => role switch
{
Student => "Student",
@@ -0,0 +1,76 @@
using System.Globalization;
using System.Net;
using System.Security.Claims;
using Helpdesk.Web.Api;
using Helpdesk.Web.Auth;
using Helpdesk.Web.Infrastructure;
using Helpdesk.Web.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Helpdesk.Web.Controllers;
[Authorize(Roles = UserRoles.Admin)]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
[Route("admin/users")]
public sealed class AdminUsersController(HelpdeskApiClient api) : Controller
{
[HttpGet("")]
public async Task<IActionResult> Index([FromQuery] AdminUsersQuery query, CancellationToken ct)
{
var q = string.IsNullOrWhiteSpace(query.Q) ? null : query.Q.Trim();
var role = query.Role is { } filter && UserRoles.All.Contains(filter) ? filter : null;
var users = await api.GetAdminUsersAsync(q, role, Math.Max(1, query.Page), ct);
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));
}
[HttpPost("{id:int}/role")]
public async Task<IActionResult> ChangeRole([FromRoute] int id, [FromForm] string? newRole, [FromQuery] AdminUsersQuery query,
CancellationToken ct)
{
if (newRole is null || !UserRoles.All.Contains(newRole))
{
TempData.SetError("Vyberte platnou roli.");
return BackToList(query);
}
return await UpdateAsync(query, () => api.ChangeUserRoleAsync(id, newRole, ct), "Role uživatele byla uložena.");
}
[HttpPost("{id:int}/active")]
public async Task<IActionResult> SetActive([FromRoute] int id, [FromForm] bool? isActive, [FromQuery] AdminUsersQuery query,
CancellationToken ct)
{
if (isActive is not bool active)
{
TempData.SetError("Vyberte stav účtu.");
return BackToList(query);
}
return await UpdateAsync(query, () => api.SetUserActiveAsync(id, active, ct),
active ? "Účet byl aktivován." : "Účet byl deaktivován.");
}
private async Task<IActionResult> UpdateAsync(AdminUsersQuery query, Func<Task> update, string success)
{
try
{
await update();
TempData.SetSuccess(success);
}
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict)
{
TempData.SetError(ex.AllMessages);
}
return BackToList(query);
}
private RedirectToActionResult BackToList(AdminUsersQuery query) =>
RedirectToAction(nameof(Index), new { q = query.Q, role = query.Role, page = query.Page });
}
@@ -21,6 +21,7 @@ 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));
@@ -0,0 +1,7 @@
using Helpdesk.Web.Api;
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);
@@ -0,0 +1,117 @@
@model AdminUsersViewModel
@{
ViewData["Title"] = "Správa uživatelů";
var result = Model.Users;
var query = Model.Query;
}
<section class="app-page-head">
<h1>Správa uživatelů</h1>
</section>
<form method="get" asp-action="Index" class="app-card mb-4" role="search" aria-label="Vyhledávání uživatelů">
<div class="row g-3 align-items-end">
<div class="col-12 col-md-5">
<label for="q" class="form-label">Jméno nebo e-mail</label>
<input id="q" name="q" type="search" value="@query.Q" class="form-control" />
</div>
<div class="col-12 col-sm-6 col-md-3">
<label for="role" class="form-label">Role</label>
<select id="role" name="role" class="form-select">
<option value="">Všechny role</option>
@foreach (var role in UserRoles.All)
{
<option value="@role" selected="@(role == query.Role)">@UserRoles.DisplayName(role)</option>
}
</select>
</div>
<div class="col-12 col-sm-auto d-flex flex-wrap gap-2">
<button type="submit" class="btn btn-primary">Vyhledat</button>
@if (query.Q is not null || query.Role is not null)
{
<a asp-action="Index" class="btn btn-outline-secondary">Zrušit filtry</a>
}
</div>
</div>
</form>
@if (result.Items.Count == 0)
{
<div class="app-card app-empty-card">
<p class="mb-0">Žádní uživatelé k zobrazení.</p>
</div>
}
else
{
<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="small text-body-secondary text-break">@user.Email</div>
</div>
<div class="col-12 col-sm-5 col-lg-3">
<span class="status-badge @(user.IsActive ? "status-user-active" : "")">@(user.IsActive ? "Aktivní" : "Deaktivovaný")</span>
<div class="small text-body-secondary mt-1">@(user.EmailConfirmed ? "E-mail ověřený" : "E-mail neověřený")</div>
<div class="small text-body-secondary">
Založen <time datetime="@user.CreatedAt.ToString("O")">@DisplayTime.Format(user.CreatedAt)</time>
</div>
</div>
<div class="col-12 col-sm-7 col-lg-5 d-flex flex-wrap align-items-center gap-2">
@if (user.Id == Model.CurrentUserId)
{
<span class="badge app-role-badge">@UserRoles.DisplayName(user.Role)</span>
<span class="small text-body-secondary">Váš účet</span>
}
else
{
<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">
<label for="[email protected]" class="visually-hidden">Role účtu @user.Email</label>
<select id="[email protected]" name="newRole" class="form-select form-select-sm w-auto">
@foreach (var role in UserRoles.All)
{
<option value="@role" selected="@(role == user.Role)">@UserRoles.DisplayName(role)</option>
}
</select>
<button type="submit" class="btn btn-sm btn-outline-primary" aria-label="Uložit roli účtu @user.Email">Uložit roli</button>
</form>
<form method="post" asp-action="SetActive" asp-route-id="@user.Id"
asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@query.Page">
<input type="hidden" name="isActive" value="@(user.IsActive ? "false" : "true")" />
@if (user.IsActive)
{
<button type="submit" class="btn btn-sm btn-outline-danger" aria-label="Deaktivovat účet @user.Email">Deaktivovat</button>
}
else
{
<button type="submit" class="btn btn-sm btn-outline-primary" aria-label="Aktivovat účet @user.Email">Aktivovat</button>
}
</form>
}
</div>
</div>
</li>
}
</ul>
@if (result.PageCount > 1)
{
<nav aria-label="Stránkování uživatelů" class="mt-4">
<ul class="pagination flex-wrap justify-content-center">
@if (result.Page > 1)
{
<li class="page-item"><a class="page-link" asp-action="Index" asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@(result.Page - 1)">Předchozí</a></li>
}
<li class="page-item disabled"><span class="page-link" aria-current="page">Strana @result.Page z @result.PageCount</span></li>
@if (result.Page < result.PageCount)
{
<li class="page-item"><a class="page-link" asp-action="Index" asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@(result.Page + 1)">Další</a></li>
}
</ul>
</nav>
}
}
+1 -1
View File
@@ -165,7 +165,7 @@ body { min-height: 100vh; display: flex; flex-direction: column; }
.status-ASSIGNED { --status-color: var(--status-assigned); }
.status-IN_PROGRESS { --status-color: var(--status-in-progress); }
.status-PENDING_VERIFICATION, .status-UNDER_REVIEW { --status-color: var(--status-review); }
.status-RESOLVED, .status-ACCEPTED, .status-IMPLEMENTED { --status-color: var(--status-done); }
.status-RESOLVED, .status-ACCEPTED, .status-IMPLEMENTED, .status-user-active { --status-color: var(--status-done); }
.status-REJECTED { --status-color: var(--status-rejected); }
@media (prefers-reduced-motion: reduce) {