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 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))); 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 New([FromForm] AdminUserForm model, [FromQuery] AdminUsersQuery query, CancellationToken ct) => SaveAsync(null, model, query, ct); [HttpGet("{id:int}/edit")] public async Task 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, RowVersion = user.RowVersion, 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 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 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 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 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")] public async Task 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 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 UpdateAsync(AdminUsersQuery query, Func update, string success) { try { await update(); TempData.SetSuccess(success); } catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict or HttpStatusCode.NotFound) { TempData.SetError(ex.AllMessages); } return BackToList(query); } private async Task SaveAsync(int? id, AdminUserForm model, AdminUsersQuery query, CancellationToken ct) { if (id is not null && id == CurrentUserId) return RedirectToAction("Index", "Profile"); if (id is int userId && model.RowVersion is null or < 0) { TempData.SetError("Formulář nemá platnou verzi účtu. Změny zadejte znovu."); return BackToEdit(userId, query); } 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 (id is int editedUserId && ex is { StatusCode: HttpStatusCode.Conflict, ProblemType: "urn:ntbug:account-version-conflict" }) { TempData.SetError(ex.UserMessage); return BackToEdit(editedUserId, 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 }); }