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; /// Přihlášení a odhlášení. Stránky pro nepřihlášené jsou označené . 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 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 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 : "/"; }