Files
NTBug/web/Helpdesk.Web/Controllers/AccountController.cs
T
PatTheEvil d3a1b1cb17 web: přihlášení přes API a automatická obnova tokenů
Typovaný klient REST API, tokeny v šifrované HttpOnly cookie, obnova access
tokenu před vypršením se sloučením souběžných obnov (ochrana proti
REUSE_DETECTED), odhlášení a společné zpracování chyb API.

Refs #21
2026-12-02 00:26:42 +01:00

74 lines
2.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Helpdesk.Web.Controllers;
/// <summary>Přihlášení a odhlášení. Stránky pro nepřihlášené jsou označené <see cref="AllowAnonymousAttribute"/>.</summary>
public sealed class AccountController(AuthApiClient authApi, HelpdeskApiClient api) : Controller
{
[AllowAnonymous]
[HttpGet("login")]
public IActionResult Login(string? returnUrl)
{
if (User.Identity?.IsAuthenticated == true)
return LocalRedirect(SafeReturnUrl(returnUrl));
ViewData["ReturnUrl"] = returnUrl;
return View(new LoginViewModel());
}
[AllowAnonymous]
[HttpPost("login")]
public async Task<IActionResult> Login(LoginViewModel model, string? returnUrl, CancellationToken ct)
{
ViewData["ReturnUrl"] = returnUrl;
if (!ModelState.IsValid)
return View(model);
try
{
var auth = await authApi.LoginAsync(new LoginRequest(model.Email.Trim(), model.Password), ct);
await AuthCookie.SignInAsync(HttpContext, auth, model.RememberMe);
return LocalRedirect(SafeReturnUrl(returnUrl));
}
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Unauthorized
or HttpStatusCode.Forbidden or HttpStatusCode.TooManyRequests)
{
// 401 špatné heslo / zamčený účet, 403 neověřený e-mail nebo deaktivovaný účet – API vrací český text.
ModelState.AddApiErrors(ex, typeof(LoginViewModel));
model.Password = "";
return View(model);
}
}
[HttpPost("logout")]
public async Task<IActionResult> Logout(CancellationToken ct)
{
if (await HttpContext.GetTokenAsync(AuthCookie.RefreshToken) is { Length: > 0 } refreshToken)
{
try
{
await api.LogoutAsync(refreshToken, ct);
}
catch (Exception ex) when (ex is ApiException or HttpRequestException)
{
// I když API zrovna nejde (nebo jsou tokeny už neplatné), lokální cookie smažeme.
}
}
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
TempData.SetSuccess("Byli jste odhlášeni.");
return RedirectToAction(nameof(Login));
}
private string SafeReturnUrl(string? returnUrl) =>
!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl) ? returnUrl : "/";
}