diff --git a/web/Helpdesk.Web/Api/ApiException.cs b/web/Helpdesk.Web/Api/ApiException.cs new file mode 100644 index 0000000..8072720 --- /dev/null +++ b/web/Helpdesk.Web/Api/ApiException.cs @@ -0,0 +1,71 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; + +namespace Helpdesk.Web.Api; + +/// +/// Neúspěšná odpověď API ve formátu ProblemDetails (RFC 9457). Nese stav, titulek +/// a u validačních chyb seznam chyb podle polí (klíče jsou názvy vlastností v camelCase). +/// +public sealed class ApiException(HttpStatusCode statusCode, string? title, IReadOnlyDictionary errors) + : Exception(title ?? $"API vrátilo stav {(int)statusCode}.") +{ + public HttpStatusCode StatusCode { get; } = statusCode; + public string? Title { get; } = title; + public IReadOnlyDictionary Errors { get; } = errors; + + /// Text pro uživatele. API píše titulky chyb česky, kromě odpovědí bez těla (např. 429). + public string UserMessage => StatusCode switch + { + HttpStatusCode.TooManyRequests => "Příliš mnoho pokusů. Zkuste to prosím za minutu.", + _ when !string.IsNullOrWhiteSpace(Title) => Title, + HttpStatusCode.Forbidden => "K této akci nemáte oprávnění.", + HttpStatusCode.NotFound => "Záznam nebyl nalezen.", + _ => "Požadavek se nepodařilo zpracovat. Zkuste to prosím znovu.", + }; + + public static async Task FromResponseAsync(HttpResponseMessage response, CancellationToken ct) + { + string? title = null; + Dictionary errors = new(StringComparer.OrdinalIgnoreCase); + + if (response.Content.Headers.ContentType?.MediaType is { } mediaType && mediaType.Contains("json", StringComparison.OrdinalIgnoreCase)) + { + try + { + var problem = await response.Content.ReadFromJsonAsync(ct); + title = problem?.Title; + if (problem?.Errors is { } fieldErrors) + { + foreach (var (field, messages) in fieldErrors) + errors[field] = messages; + } + } + catch (JsonException) + { + // Tělo není ProblemDetails – zůstane jen stavový kód. + } + } + + return new ApiException(response.StatusCode, title, errors); + } + + private sealed record ProblemBody(string? Title, Dictionary? Errors); +} + +internal static class ApiResponse +{ + public static async Task EnsureSuccessAsync(HttpResponseMessage response, CancellationToken ct) + { + if (!response.IsSuccessStatusCode) + throw await ApiException.FromResponseAsync(response, ct); + } + + public static async Task ReadAsync(HttpResponseMessage response, CancellationToken ct) + { + await EnsureSuccessAsync(response, ct); + return await response.Content.ReadFromJsonAsync(ct) + ?? throw new InvalidOperationException($"API vrátilo prázdnou odpověď místo {typeof(T).Name}."); + } +} diff --git a/web/Helpdesk.Web/Api/ApiModels.cs b/web/Helpdesk.Web/Api/ApiModels.cs new file mode 100644 index 0000000..b09772b --- /dev/null +++ b/web/Helpdesk.Web/Api/ApiModels.cs @@ -0,0 +1,47 @@ +namespace Helpdesk.Web.Api; + +// Kontrakt REST API /api/v1 tak, jak ho web používá. Web je tenký klient a na projekty +// backendu nemá referenci – DTO jsou zde zrcadlem dokumentace ve Swaggeru. + +public sealed record UserDto( + int Id, + string Email, + string FirstName, + string LastName, + string? Phone, + string Role, + bool EmailNotificationsEnabled) +{ + public string FullName => $"{FirstName} {LastName}"; +} + +public sealed record AuthResponse( + string AccessToken, + DateTimeOffset AccessTokenExpiresAt, + string RefreshToken, + DateTimeOffset RefreshTokenExpiresAt, + UserDto User) +{ + public TokenSet Tokens => new(AccessToken, AccessTokenExpiresAt, RefreshToken, RefreshTokenExpiresAt); +} + +/// Pár tokenů uložený v autentizační cookie webu. +public sealed record TokenSet( + string AccessToken, + DateTimeOffset AccessTokenExpiresAt, + string RefreshToken, + DateTimeOffset RefreshTokenExpiresAt); + +public sealed record LoginRequest(string Email, string Password); + +public sealed record RegisterRequest(string Email, string Password, string FirstName, string LastName); + +public sealed record RefreshTokenRequest(string RefreshToken); + +public sealed record EmailTokenRequest(string Token); + +public sealed record ForgotPasswordRequest(string Email); + +public sealed record ResetPasswordRequest(string Token, string NewPassword); + +public sealed record UpdateProfileRequest(string FirstName, string LastName, string? Phone, bool EmailNotificationsEnabled); diff --git a/web/Helpdesk.Web/Api/ApiOptions.cs b/web/Helpdesk.Web/Api/ApiOptions.cs new file mode 100644 index 0000000..89ab774 --- /dev/null +++ b/web/Helpdesk.Web/Api/ApiOptions.cs @@ -0,0 +1,11 @@ +namespace Helpdesk.Web.Api; + +/// Připojení k backendu (sekce Api). V Dockeru http://api:8080/. +public sealed class ApiOptions +{ + public const string Section = "Api"; + + public string BaseUrl { get; set; } = ""; + + public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(15); +} diff --git a/web/Helpdesk.Web/Api/AuthApiClient.cs b/web/Helpdesk.Web/Api/AuthApiClient.cs new file mode 100644 index 0000000..d1a4193 --- /dev/null +++ b/web/Helpdesk.Web/Api/AuthApiClient.cs @@ -0,0 +1,26 @@ +using System.Net; +using System.Net.Http.Json; + +namespace Helpdesk.Web.Api; + +/// +/// Anonymní endpointy /api/v1/auth. Záměrně bez : +/// obnova tokenu běží uvnitř ověřování cookie a čtení tokenu z cookie by se zacyklilo. +/// +public sealed class AuthApiClient(HttpClient http) +{ + public async Task LoginAsync(LoginRequest request, CancellationToken ct) + { + using var response = await http.PostAsJsonAsync("api/v1/auth/login", request, ct); + return await ApiResponse.ReadAsync(response, ct); + } + + /// Obnoví pár tokenů. Neplatný nebo už použitý refresh token → null. + public async Task RefreshAsync(string refreshToken, CancellationToken ct) + { + using var response = await http.PostAsJsonAsync("api/v1/auth/refresh", new RefreshTokenRequest(refreshToken), ct); + if (response.StatusCode == HttpStatusCode.Unauthorized) + return null; + return (await ApiResponse.ReadAsync(response, ct)).Tokens; + } +} diff --git a/web/Helpdesk.Web/Api/BearerTokenHandler.cs b/web/Helpdesk.Web/Api/BearerTokenHandler.cs new file mode 100644 index 0000000..d5e01d9 --- /dev/null +++ b/web/Helpdesk.Web/Api/BearerTokenHandler.cs @@ -0,0 +1,23 @@ +using System.Net.Http.Headers; +using Helpdesk.Web.Auth; +using Microsoft.AspNetCore.Authentication; + +namespace Helpdesk.Web.Api; + +/// +/// Přidá k požadavku na API access token přihlášeného uživatele z autentizační cookie. +/// Token je v té chvíli čerstvý – případnou obnovu už provedl . +/// +internal sealed class BearerTokenHandler(IHttpContextAccessor accessor) : DelegatingHandler +{ + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + if (accessor.HttpContext is { } httpContext && + await httpContext.GetTokenAsync(AuthCookie.AccessToken) is { Length: > 0 } token) + { + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + } + + return await base.SendAsync(request, cancellationToken); + } +} diff --git a/web/Helpdesk.Web/Api/HelpdeskApiClient.cs b/web/Helpdesk.Web/Api/HelpdeskApiClient.cs new file mode 100644 index 0000000..5b94b88 --- /dev/null +++ b/web/Helpdesk.Web/Api/HelpdeskApiClient.cs @@ -0,0 +1,14 @@ +using System.Net.Http.Json; + +namespace Helpdesk.Web.Api; + +/// Endpointy API pro přihlášeného uživatele; access token přidává . +public sealed class HelpdeskApiClient(HttpClient http) +{ + /// Odhlásí toto zařízení – API zneplatní aktuální access token i předaný refresh token. + public async Task LogoutAsync(string refreshToken, CancellationToken ct) + { + using var response = await http.PostAsJsonAsync("api/v1/auth/logout", new RefreshTokenRequest(refreshToken), ct); + await ApiResponse.EnsureSuccessAsync(response, ct); + } +} diff --git a/web/Helpdesk.Web/Auth/AuthCookie.cs b/web/Helpdesk.Web/Auth/AuthCookie.cs new file mode 100644 index 0000000..59a3b1a --- /dev/null +++ b/web/Helpdesk.Web/Auth/AuthCookie.cs @@ -0,0 +1,80 @@ +using System.Globalization; +using System.Security.Claims; +using Helpdesk.Web.Api; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; + +namespace Helpdesk.Web.Auth; + +/// +/// Autentizační cookie webu (kap. 9.4): identita uživatele pro Razor a tokeny pro volání API. +/// Cookie je HttpOnly a šifrovaná přes Data Protection – tokeny nejsou dostupné JavaScriptu. +/// +public static class AuthCookie +{ + public const string Name = "ntbug.auth"; + public const string AccessToken = "access_token"; + public const string AccessTokenExpiresAt = "access_token_expires_at"; + public const string RefreshToken = "refresh_token"; + public const string RefreshTokenExpiresAt = "refresh_token_expires_at"; + + public static async Task SignInAsync(HttpContext httpContext, AuthResponse auth, bool persistent) + { + var properties = new AuthenticationProperties { IsPersistent = persistent }; + StoreTokens(properties, auth.Tokens); + await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, CreatePrincipal(auth.User), properties); + } + + /// Přepíše identitu v cookie (např. po změně jména v profilu); tokeny zůstanou. + public static async Task UpdateUserAsync(HttpContext httpContext, UserDto user) + { + var result = await httpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme); + if (result.Succeeded) + await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, CreatePrincipal(user), result.Properties); + } + + public static ClaimsPrincipal CreatePrincipal(UserDto user) + { + var identity = new ClaimsIdentity( + [ + new Claim(ClaimTypes.NameIdentifier, user.Id.ToString(CultureInfo.InvariantCulture)), + new Claim(ClaimTypes.Name, user.FullName), + new Claim(ClaimTypes.Email, user.Email), + new Claim(ClaimTypes.Role, user.Role), + ], + CookieAuthenticationDefaults.AuthenticationScheme); + return new ClaimsPrincipal(identity); + } + + public static void StoreTokens(AuthenticationProperties properties, TokenSet tokens) + { + properties.StoreTokens( + [ + new AuthenticationToken { Name = AccessToken, Value = tokens.AccessToken }, + new AuthenticationToken { Name = AccessTokenExpiresAt, Value = tokens.AccessTokenExpiresAt.ToString("O", CultureInfo.InvariantCulture) }, + new AuthenticationToken { Name = RefreshToken, Value = tokens.RefreshToken }, + new AuthenticationToken { Name = RefreshTokenExpiresAt, Value = tokens.RefreshTokenExpiresAt.ToString("O", CultureInfo.InvariantCulture) }, + ]); + + // Trvalé přihlášení („zůstat přihlášen“) platí stejně dlouho jako refresh token. + if (properties.IsPersistent) + properties.ExpiresUtc = tokens.RefreshTokenExpiresAt; + } + + public static TokenSet? ReadTokens(AuthenticationProperties properties) + { + var access = properties.GetTokenValue(AccessToken); + var refresh = properties.GetTokenValue(RefreshToken); + if (string.IsNullOrEmpty(access) || string.IsNullOrEmpty(refresh) || + !TryParse(properties.GetTokenValue(AccessTokenExpiresAt), out var accessExpires) || + !TryParse(properties.GetTokenValue(RefreshTokenExpiresAt), out var refreshExpires)) + { + return null; + } + + return new TokenSet(access, accessExpires, refresh, refreshExpires); + } + + private static bool TryParse(string? value, out DateTimeOffset result) => + DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out result); +} diff --git a/web/Helpdesk.Web/Auth/HelpdeskCookieEvents.cs b/web/Helpdesk.Web/Auth/HelpdeskCookieEvents.cs new file mode 100644 index 0000000..160f163 --- /dev/null +++ b/web/Helpdesk.Web/Auth/HelpdeskCookieEvents.cs @@ -0,0 +1,67 @@ +using Helpdesk.Web.Api; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; + +namespace Helpdesk.Web.Auth; + +/// +/// Při každém požadavku zkontroluje tokeny v cookie. Access token (15 min) obnoví chvíli před +/// vypršením, takže volání API během požadavku už má platný token. Když API refresh token +/// odmítne (odhlášení jinde, změna role, změna hesla), uživatele odhlásí. +/// +public sealed partial class HelpdeskCookieEvents( + TokenRefresher refresher, + AuthApiClient authApi, + TimeProvider clock, + ILogger logger) : CookieAuthenticationEvents +{ + /// Jak dlouho před vypršením se access token obnoví. + internal static readonly TimeSpan RefreshMargin = TimeSpan.FromMinutes(1); + + public override async Task ValidatePrincipal(CookieValidatePrincipalContext context) + { + var tokens = context.Properties is { } properties ? AuthCookie.ReadTokens(properties) : null; + var now = clock.GetUtcNow(); + + if (tokens is null || tokens.RefreshTokenExpiresAt <= now) + { + await RejectAsync(context); + return; + } + + if (tokens.AccessTokenExpiresAt - now > RefreshMargin) + return; + + TokenSet? renewed; + try + { + // Sdílené volání nesmí zrušit odpojení prvního klienta – ostatní na výsledek čekají také. + renewed = await refresher.RefreshAsync(tokens.RefreshToken, token => authApi.RefreshAsync(token, CancellationToken.None)); + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or ApiException) + { + // API je dočasně nedostupné. Uživatele kvůli výpadku neodhlašujeme; požadavek + // dopadne chybovou stránkou a příští pokus obnovu zopakuje. + LogRefreshFailed(ex); + return; + } + + if (renewed is null) + { + await RejectAsync(context); + return; + } + + AuthCookie.StoreTokens(context.Properties!, renewed); + context.ShouldRenew = true; + } + + private static async Task RejectAsync(CookieValidatePrincipalContext context) + { + context.RejectPrincipal(); + await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); + } + + [LoggerMessage(Level = LogLevel.Warning, Message = "Obnova access tokenu selhala, API je nedostupné.")] + private partial void LogRefreshFailed(Exception ex); +} diff --git a/web/Helpdesk.Web/Auth/TokenRefresher.cs b/web/Helpdesk.Web/Auth/TokenRefresher.cs new file mode 100644 index 0000000..e6b1f64 --- /dev/null +++ b/web/Helpdesk.Web/Auth/TokenRefresher.cs @@ -0,0 +1,62 @@ +using System.Collections.Concurrent; +using System.Security.Cryptography; +using System.Text; +using Helpdesk.Web.Api; + +namespace Helpdesk.Web.Auth; + +/// +/// Sloučí souběžné obnovy téhož refresh tokenu do jednoho volání API. +/// +/// Refresh token jde použít jen jednou a druhé použití API vyhodnotí jako krádež – zneplatní +/// všechny tokeny uživatele (kap. 10.1). Prohlížeč přitom běžně pošle několik požadavků naráz +/// se stejnou cookie. Všechny proto čekají na jedno volání a dostanou stejný nový pár tokenů; +/// výsledek se drží ještě chvíli pro požadavky, které dorazí se starou cookie o něco později. +/// +/// Platí pro jednu instanci webu; při více instancích by se evidence přesunula do sdílené cache. +/// +public sealed class TokenRefresher(TimeProvider clock) +{ + internal static readonly TimeSpan ResultLifetime = TimeSpan.FromMinutes(1); + + private readonly ConcurrentDictionary _refreshes = new(); + + /// Refresh token z cookie. + /// Skutečné volání API; spustí se nejvýše jednou pro daný token. + /// Nový pár tokenů, nebo null, když API token odmítlo. + public async Task RefreshAsync(string refreshToken, Func> refresh) + { + RemoveExpired(); + + var key = Hash(refreshToken); + var entry = _refreshes.GetOrAdd(key, _ => new Entry( + new Lazy>(() => refresh(refreshToken)), + clock.GetUtcNow())); + + try + { + return await entry.Result.Value; + } + catch + { + // Dočasná chyba (API nedostupné) se nepamatuje – další požadavek to zkusí znovu. + _refreshes.TryRemove(new KeyValuePair(key, entry)); + throw; + } + } + + private void RemoveExpired() + { + var threshold = clock.GetUtcNow() - ResultLifetime; + foreach (var (key, entry) in _refreshes) + { + if (entry.CreatedAt < threshold && entry.Result.IsValueCreated && entry.Result.Value.IsCompleted) + _refreshes.TryRemove(new KeyValuePair(key, entry)); + } + } + + // Klíčem je hash, aby se refresh tokeny nedržely v paměti jako klíče slovníku. + private static string Hash(string token) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token))); + + private sealed record Entry(Lazy> Result, DateTimeOffset CreatedAt); +} diff --git a/web/Helpdesk.Web/Controllers/AccountController.cs b/web/Helpdesk.Web/Controllers/AccountController.cs new file mode 100644 index 0000000..df0eb32 --- /dev/null +++ b/web/Helpdesk.Web/Controllers/AccountController.cs @@ -0,0 +1,73 @@ +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 : "/"; +} diff --git a/web/Helpdesk.Web/Controllers/HomeController.cs b/web/Helpdesk.Web/Controllers/HomeController.cs index d9fe2cf..1a97a60 100644 --- a/web/Helpdesk.Web/Controllers/HomeController.cs +++ b/web/Helpdesk.Web/Controllers/HomeController.cs @@ -1,3 +1,4 @@ +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace Helpdesk.Web.Controllers; @@ -8,6 +9,7 @@ public sealed class HomeController : Controller public IActionResult Index() => View(); /// Chybová stránka pro neošetřené výjimky a stavové kódy (404, 403, …). + [AllowAnonymous] [Route("error/{statusCode:int?}")] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error(int? statusCode) diff --git a/web/Helpdesk.Web/Infrastructure/ApiExceptionFilter.cs b/web/Helpdesk.Web/Infrastructure/ApiExceptionFilter.cs new file mode 100644 index 0000000..cd5df3f --- /dev/null +++ b/web/Helpdesk.Web/Infrastructure/ApiExceptionFilter.cs @@ -0,0 +1,58 @@ +using System.Net; +using Helpdesk.Web.Api; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Mvc.ViewFeatures; + +namespace Helpdesk.Web.Infrastructure; + +/// +/// Společné zpracování chyb API, které kontroler sám neošetřil (validaci formulářů řeší kontrolery): +/// 401 → odhlásit a poslat na přihlášení, 403/404 → chybová stránka, nedostupné API → 503. +/// +internal sealed partial class ApiExceptionFilter( + ITempDataDictionaryFactory tempDataFactory, + ILogger logger) : IAsyncExceptionFilter +{ + public async Task OnExceptionAsync(ExceptionContext context) + { + var http = context.HttpContext; + + switch (context.Exception) + { + case ApiException { StatusCode: HttpStatusCode.Unauthorized }: + // Tokeny byly zneplatněny (odhlášení ze všech zařízení, změna role…). + await http.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); + tempDataFactory.GetTempData(http).SetError("Přihlášení vypršelo. Přihlaste se prosím znovu."); + var returnUrl = HttpMethods.IsGet(http.Request.Method) ? http.Request.Path + http.Request.QueryString : "/"; + context.Result = new RedirectToActionResult("Login", "Account", new { returnUrl }); + break; + + case ApiException { StatusCode: HttpStatusCode.Forbidden or HttpStatusCode.NotFound or HttpStatusCode.TooManyRequests } api: + context.Result = ErrorView((int)api.StatusCode); + break; + + case HttpRequestException or TaskCanceledException when !http.RequestAborted.IsCancellationRequested: + LogApiUnavailable(context.Exception); + context.Result = ErrorView(StatusCodes.Status503ServiceUnavailable); + break; + + default: + return; // ostatní chyby zpracuje globální exception handler (500) + } + + context.ExceptionHandled = true; + } + + private static ViewResult ErrorView(int statusCode) => new() + { + ViewName = "~/Views/Home/Error.cshtml", + StatusCode = statusCode, + ViewData = new ViewDataDictionary(new Microsoft.AspNetCore.Mvc.ModelBinding.EmptyModelMetadataProvider(), new()) { Model = statusCode }, + }; + + [LoggerMessage(Level = LogLevel.Error, Message = "Backend API je nedostupné.")] + private partial void LogApiUnavailable(Exception ex); +} diff --git a/web/Helpdesk.Web/Infrastructure/ModelStateExtensions.cs b/web/Helpdesk.Web/Infrastructure/ModelStateExtensions.cs new file mode 100644 index 0000000..aaa092d --- /dev/null +++ b/web/Helpdesk.Web/Infrastructure/ModelStateExtensions.cs @@ -0,0 +1,30 @@ +using System.Reflection; +using Helpdesk.Web.Api; +using Microsoft.AspNetCore.Mvc.ModelBinding; + +namespace Helpdesk.Web.Infrastructure; + +public static class ModelStateExtensions +{ + /// + /// Přenese chyby z API do formuláře: chyby polí k odpovídajícím vlastnostem view modelu + /// (API vrací názvy v camelCase), ostatní do souhrnu nad formulářem. + /// + public static void AddApiErrors(this ModelStateDictionary modelState, ApiException error, Type viewModelType) + { + var properties = viewModelType.GetProperties(BindingFlags.Public | BindingFlags.Instance) + .ToDictionary(p => p.Name, p => p.Name, StringComparer.OrdinalIgnoreCase); + + var anyFieldError = false; + foreach (var (field, messages) in error.Errors) + { + var key = properties.TryGetValue(field, out var property) ? property : string.Empty; + anyFieldError |= key.Length > 0; + foreach (var message in messages) + modelState.AddModelError(key, message); + } + + if (!anyFieldError) + modelState.AddModelError(string.Empty, error.UserMessage); + } +} diff --git a/web/Helpdesk.Web/Models/AccountModels.cs b/web/Helpdesk.Web/Models/AccountModels.cs new file mode 100644 index 0000000..64b90a5 --- /dev/null +++ b/web/Helpdesk.Web/Models/AccountModels.cs @@ -0,0 +1,19 @@ +using System.ComponentModel.DataAnnotations; + +namespace Helpdesk.Web.Models; + +public sealed class LoginViewModel +{ + [Required(ErrorMessage = "Zadejte e-mail.")] + [EmailAddress(ErrorMessage = "Zadejte platný e-mail.")] + [Display(Name = "E-mail")] + public string Email { get; set; } = ""; + + [Required(ErrorMessage = "Zadejte heslo.")] + [DataType(DataType.Password)] + [Display(Name = "Heslo")] + public string Password { get; set; } = ""; + + [Display(Name = "Zůstat přihlášen")] + public bool RememberMe { get; set; } +} diff --git a/web/Helpdesk.Web/Program.cs b/web/Helpdesk.Web/Program.cs index e9c3f83..c83134f 100644 --- a/web/Helpdesk.Web/Program.cs +++ b/web/Helpdesk.Web/Program.cs @@ -1,19 +1,68 @@ using System.Globalization; using System.Net; +using Helpdesk.Web.Api; +using Helpdesk.Web.Auth; using Helpdesk.Web.Infrastructure; +using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Authorization; +using Microsoft.Extensions.Options; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllersWithViews(options => { + // Všechny stránky vyžadují přihlášení, výjimky jsou označené [AllowAnonymous]. + options.Filters.Add(new AuthorizeFilter()); // Anti-forgery token u všech formulářů odesílaných metodou POST (CSRF, kap. 10). options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); + options.Filters.Add(); }); +// Klient REST API. Web nemá přístup k databázi – všechna data jdou přes API (kap. 9.4). +builder.Services.AddOptions() + .BindConfiguration(ApiOptions.Section) + .Validate(o => Uri.TryCreate(o.BaseUrl, UriKind.Absolute, out _), "Nastavte Api:BaseUrl na adresu backendu, např. http://api:8080/.") + .ValidateOnStart(); + +static void ConfigureApiClient(IServiceProvider services, HttpClient http) +{ + var options = services.GetRequiredService>().Value; + http.BaseAddress = new Uri(options.BaseUrl.EndsWith('/') ? options.BaseUrl : options.BaseUrl + "/"); + http.Timeout = options.Timeout; +} + +builder.Services.AddHttpContextAccessor(); +builder.Services.AddTransient(); +builder.Services.AddHttpClient(ConfigureApiClient); +builder.Services.AddHttpClient(ConfigureApiClient).AddHttpMessageHandler(); + +// Přihlášení: tokeny API v šifrované HttpOnly cookie, obnova access tokenu při ověření cookie. +builder.Services.AddSingleton(TimeProvider.System); +builder.Services.AddSingleton(); +builder.Services.AddScoped(); +builder.Services + .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) + .AddCookie(options => + { + options.Cookie.Name = AuthCookie.Name; + options.Cookie.HttpOnly = true; + options.Cookie.SameSite = SameSiteMode.Lax; + options.Cookie.SecurePolicy = builder.Environment.IsDevelopment() + ? CookieSecurePolicy.SameAsRequest + : CookieSecurePolicy.Always; + options.LoginPath = "/login"; + options.LogoutPath = "/logout"; + options.AccessDeniedPath = "/error/403"; + // Cookie nepřežije refresh token (14 dní); po jeho vypršení se uživatel přihlásí znovu. + options.ExpireTimeSpan = TimeSpan.FromDays(14); + options.SlidingExpiration = false; + options.EventsType = typeof(HelpdeskCookieEvents); + }); + // Klíče Data Protection šifrují autentizační cookie. Bez uložení na volume by // restart kontejneru odhlásil všechny uživatele (kap. 15.3). var dataProtection = builder.Services.AddDataProtection().SetApplicationName("Helpdesk.Web"); @@ -59,6 +108,7 @@ app.UseRequestLocalization(new RequestLocalizationOptions }); app.UseRouting(); +app.UseAuthentication(); app.UseAuthorization(); app.MapStaticAssets(); diff --git a/web/Helpdesk.Web/Views/Account/Login.cshtml b/web/Helpdesk.Web/Views/Account/Login.cshtml new file mode 100644 index 0000000..5d285ca --- /dev/null +++ b/web/Helpdesk.Web/Views/Account/Login.cshtml @@ -0,0 +1,30 @@ +@model LoginViewModel +@{ + ViewData["Title"] = "Přihlášení"; +} + +
+

Přihlášení

+

Přihlaste se univerzitním e-mailem.

+ +
+ +
+
+ + + +
+
+ + + +
+
+ + +
+ +
+
+
diff --git a/web/Helpdesk.Web/Views/Home/Error.cshtml b/web/Helpdesk.Web/Views/Home/Error.cshtml index 1d738d1..d3f3ed7 100644 --- a/web/Helpdesk.Web/Views/Home/Error.cshtml +++ b/web/Helpdesk.Web/Views/Home/Error.cshtml @@ -4,6 +4,8 @@ { 404 => ("Stránka nenalezena", "Stránka neexistuje, nebo byla přesunuta. Zkontrolujte adresu."), 403 => ("Přístup odepřen", "K této stránce nemáte oprávnění. Pokud si myslíte, že byste je mít měli, obraťte se na administrátora."), + 429 => ("Příliš mnoho požadavků", "Během krátké doby jste odeslali příliš mnoho požadavků. Zkuste to prosím za minutu."), + 503 => ("Služba je dočasně nedostupná", "Nepodařilo se spojit se serverem helpdesku. Zkuste to prosím za chvíli znovu."), _ => ("Něco se pokazilo", "Požadavek se nepodařilo zpracovat. Zkuste to prosím za chvíli znovu."), }; ViewData["Title"] = title; diff --git a/web/Helpdesk.Web/Views/Home/Index.cshtml b/web/Helpdesk.Web/Views/Home/Index.cshtml index 4467cd5..c852221 100644 --- a/web/Helpdesk.Web/Views/Home/Index.cshtml +++ b/web/Helpdesk.Web/Views/Home/Index.cshtml @@ -1,8 +1,9 @@ @{ ViewData["Title"] = "Nástěnka"; + var firstName = User.Identity?.Name?.Split(' ')[0]; }
-

Univerzitní helpdesk

+

Dobrý den, @firstName

Nahlaste závadu v budově, na vybavení nebo ve službách a sledujte, jak se řeší. Podejte návrh na zlepšení univerzity a hlasujte pro návrhy ostatních.

diff --git a/web/Helpdesk.Web/Views/Shared/_FormErrors.cshtml b/web/Helpdesk.Web/Views/Shared/_FormErrors.cshtml new file mode 100644 index 0000000..09bc433 --- /dev/null +++ b/web/Helpdesk.Web/Views/Shared/_FormErrors.cshtml @@ -0,0 +1,22 @@ +@* Chyby, které nepatří ke konkrétnímu poli (např. „Neplatný e-mail nebo heslo.“). *@ +@{ + var errors = ViewData.ModelState.TryGetValue(string.Empty, out var entry) ? entry.Errors : null; +} +@if (errors is { Count: > 0 }) +{ + +} diff --git a/web/Helpdesk.Web/Views/Shared/_UserMenu.cshtml b/web/Helpdesk.Web/Views/Shared/_UserMenu.cshtml index 22d3f71..f686c77 100644 --- a/web/Helpdesk.Web/Views/Shared/_UserMenu.cshtml +++ b/web/Helpdesk.Web/Views/Shared/_UserMenu.cshtml @@ -8,5 +8,11 @@ diff --git a/web/Helpdesk.Web/Views/_ViewImports.cshtml b/web/Helpdesk.Web/Views/_ViewImports.cshtml index bf4797d..853a494 100644 --- a/web/Helpdesk.Web/Views/_ViewImports.cshtml +++ b/web/Helpdesk.Web/Views/_ViewImports.cshtml @@ -2,4 +2,5 @@ @using Helpdesk.Web @using Helpdesk.Web.Auth @using Helpdesk.Web.Infrastructure +@using Helpdesk.Web.Models @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers diff --git a/web/Helpdesk.Web/wwwroot/css/site.css b/web/Helpdesk.Web/wwwroot/css/site.css index f72a9a6..bf4e5ec 100644 --- a/web/Helpdesk.Web/wwwroot/css/site.css +++ b/web/Helpdesk.Web/wwwroot/css/site.css @@ -76,6 +76,7 @@ body { min-height: 100vh; display: flex; flex-direction: column; } .app-auth { max-width: 26rem; margin: 1rem auto 0; } .app-auth h1 { font-size: 1.5rem; font-weight: 700; margin-bottom: .25rem; } .app-auth .app-card { padding: 1.75rem; } +.input-validation-error { border-color: var(--bs-form-invalid-border-color); } .app-auth-links { display: flex; flex-wrap: wrap; justify-content: space-between; gap: .5rem; margin-top: 1rem; font-size: .925rem; } /* prázdné a chybové stavy */