60 lines
2.3 KiB
C#
60 lines
2.3 KiB
C#
using System.Net;
|
||||
|
|
using Helpdesk.Web.Api;
|
|||
|
|
using Helpdesk.Web.Auth;
|
|||
|
|
using Helpdesk.Web.Infrastructure;
|
|||
|
|
using Helpdesk.Web.Models;
|
|||
|
|
using Microsoft.AspNetCore.Authentication;
|
|||
|
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
|||
|
|
using Microsoft.AspNetCore.Mvc;
|
|||
|
|
|
|||
|
|
namespace Helpdesk.Web.Controllers;
|
|||
|
|
|
|||
|
|
/// <summary>Profil přihlášeného uživatele a nastavení notifikací (FR-05).</summary>
|
|||
|
|
[Route("profile")]
|
|||
|
|
public sealed class ProfileController(HelpdeskApiClient api) : Controller
|
|||
|
|
{
|
|||
|
|
[HttpGet("")]
|
|||
|
|
public async Task<IActionResult> Index(CancellationToken ct) =>
|
|||
|
|
View(ProfileViewModel.From(await api.GetMeAsync(ct)));
|
|||
|
|
|
|||
|
|
[HttpPost("")]
|
|||
|
|
public async Task<IActionResult> Index(ProfileViewModel model, CancellationToken ct)
|
|||
|
|
{
|
|||
|
|
if (!ModelState.IsValid)
|
|||
|
|
return View(await WithReadOnlyFieldsAsync(model, ct));
|
|||
|
|
|
|||
|
|
try
|
|||
|
|
{
|
|||
|
|
var user = await api.UpdateMeAsync(
|
|||
|
|
new UpdateProfileRequest(model.FirstName.Trim(), model.LastName.Trim(), model.Phone, model.EmailNotificationsEnabled), ct);
|
|||
|
|
// Jméno je i v cookie (menu, pozdrav na nástěnce) – přepíšeme ho.
|
|||
|
|
await AuthCookie.UpdateUserAsync(HttpContext, user);
|
|||
|
|
TempData.SetSuccess("Profil je uložený.");
|
|||
|
|
return RedirectToAction(nameof(Index));
|
|||
|
|
}
|
|||
|
|
catch (ApiException ex) when (ex.StatusCode == HttpStatusCode.BadRequest)
|
|||
|
|
{
|
|||
|
|
ModelState.AddApiErrors(ex, typeof(ProfileViewModel));
|
|||
|
|
return View(await WithReadOnlyFieldsAsync(model, ct));
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// <summary>Odhlášení ze všech zařízení – zneplatní tokeny i v mobilní aplikaci.</summary>
|
|||
|
|
[HttpPost("logout-all")]
|
|||
|
|
public async Task<IActionResult> LogoutAll(CancellationToken ct)
|
|||
|
|
{
|
|||
|
|
await api.LogoutAllAsync(ct);
|
|||
|
|
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
|||
|
|
TempData.SetSuccess("Byli jste odhlášeni ze všech zařízení.");
|
|||
|
|
return RedirectToAction("Login", "Account");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// E-mail a role se formulářem neposílají; při opakovaném zobrazení je doplníme z API.
|
|||
|
|
private async Task<ProfileViewModel> WithReadOnlyFieldsAsync(ProfileViewModel model, CancellationToken ct)
|
|||
|
|
{
|
|||
|
|
var user = await api.GetMeAsync(ct);
|
|||
|
|
model.Email = user.Email;
|
|||
|
|
model.Role = user.Role;
|
|||
|
|
return model;
|
|||
|
|
}
|
|||
|
|
}
|