diff --git a/web/Helpdesk.Web/Api/AuthApiClient.cs b/web/Helpdesk.Web/Api/AuthApiClient.cs index d1a4193..1e6caa5 100644 --- a/web/Helpdesk.Web/Api/AuthApiClient.cs +++ b/web/Helpdesk.Web/Api/AuthApiClient.cs @@ -15,6 +15,32 @@ public sealed class AuthApiClient(HttpClient http) return await ApiResponse.ReadAsync(response, ct); } + /// Registrace. Roli (student / vyučující) určí API podle domény e-mailu. + public async Task RegisterAsync(RegisterRequest request, CancellationToken ct) + { + using var response = await http.PostAsJsonAsync("api/v1/auth/register", request, ct); + return await ApiResponse.ReadAsync(response, ct); + } + + public async Task ConfirmEmailAsync(string token, CancellationToken ct) + { + using var response = await http.PostAsJsonAsync("api/v1/auth/confirm-email", new EmailTokenRequest(token), ct); + await ApiResponse.EnsureSuccessAsync(response, ct); + } + + /// API odpoví stejně, ať účet existuje, nebo ne – stránka tak neprozradí registrované e-maily. + public async Task ForgotPasswordAsync(string email, CancellationToken ct) + { + using var response = await http.PostAsJsonAsync("api/v1/auth/forgot-password", new ForgotPasswordRequest(email), ct); + await ApiResponse.EnsureSuccessAsync(response, ct); + } + + public async Task ResetPasswordAsync(ResetPasswordRequest request, CancellationToken ct) + { + using var response = await http.PostAsJsonAsync("api/v1/auth/reset-password", request, ct); + await ApiResponse.EnsureSuccessAsync(response, ct); + } + /// Obnoví pár tokenů. Neplatný nebo už použitý refresh token → null. public async Task RefreshAsync(string refreshToken, CancellationToken ct) { diff --git a/web/Helpdesk.Web/Api/HelpdeskApiClient.cs b/web/Helpdesk.Web/Api/HelpdeskApiClient.cs index 5b94b88..2ac3395 100644 --- a/web/Helpdesk.Web/Api/HelpdeskApiClient.cs +++ b/web/Helpdesk.Web/Api/HelpdeskApiClient.cs @@ -5,6 +5,25 @@ namespace Helpdesk.Web.Api; /// Endpointy API pro přihlášeného uživatele; access token přidává . public sealed class HelpdeskApiClient(HttpClient http) { + public async Task GetMeAsync(CancellationToken ct) + { + using var response = await http.GetAsync("api/v1/users/me", ct); + return await ApiResponse.ReadAsync(response, ct); + } + + public async Task UpdateMeAsync(UpdateProfileRequest request, CancellationToken ct) + { + using var response = await http.PutAsJsonAsync("api/v1/users/me", request, ct); + return await ApiResponse.ReadAsync(response, ct); + } + + /// Odhlásí ze všech zařízení – API zneplatní všechny tokeny uživatele. + public async Task LogoutAllAsync(CancellationToken ct) + { + using var response = await http.PostAsync("api/v1/auth/logout-all", content: null, ct); + await ApiResponse.EnsureSuccessAsync(response, ct); + } + /// Odhlásí toto zařízení – API zneplatní aktuální access token i předaný refresh token. public async Task LogoutAsync(string refreshToken, CancellationToken ct) { diff --git a/web/Helpdesk.Web/Controllers/AccountController.cs b/web/Helpdesk.Web/Controllers/AccountController.cs index df0eb32..c56a35e 100644 --- a/web/Helpdesk.Web/Controllers/AccountController.cs +++ b/web/Helpdesk.Web/Controllers/AccountController.cs @@ -10,7 +10,10 @@ using Microsoft.AspNetCore.Mvc; namespace Helpdesk.Web.Controllers; -/// Přihlášení a odhlášení. Stránky pro nepřihlášené jsou označené . +/// +/// Přihlášení, registrace, ověření e-mailu a obnova hesla (FR-01 – FR-03). +/// Stránky pro nepřihlášené jsou označené . +/// public sealed class AccountController(AuthApiClient authApi, HelpdeskApiClient api) : Controller { [AllowAnonymous] @@ -48,6 +51,112 @@ public sealed class AccountController(AuthApiClient authApi, HelpdeskApiClient a } } + [AllowAnonymous] + [HttpGet("register")] + public IActionResult Register() => + User.Identity?.IsAuthenticated == true ? RedirectToAction("Index", "Home") : View(new RegisterViewModel()); + + [AllowAnonymous] + [HttpPost("register")] + public async Task Register(RegisterViewModel model, CancellationToken ct) + { + if (!ModelState.IsValid) + return View(model); + + try + { + var user = await authApi.RegisterAsync( + new RegisterRequest(model.Email.Trim(), model.Password, model.FirstName.Trim(), model.LastName.Trim()), ct); + return View("RegisterDone", user.Email); + } + catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict or HttpStatusCode.TooManyRequests) + { + // 400 cizí doména nebo validace, 409 účet už existuje. + ModelState.AddApiErrors(ex, typeof(RegisterViewModel)); + model.Password = model.ConfirmPassword = ""; + return View(model); + } + } + + /// Odkaz z registračního e-mailu. Token se spotřebuje až tlačítkem, ne samotným otevřením odkazu. + [AllowAnonymous] + [HttpGet("confirm-email")] + public IActionResult ConfirmEmail(string? token) => View(new EmailTokenViewModel { Token = token ?? "" }); + + [AllowAnonymous] + [HttpPost("confirm-email")] + public async Task ConfirmEmail(EmailTokenViewModel model, CancellationToken ct) + { + if (!ModelState.IsValid) + return View(model); + + try + { + await authApi.ConfirmEmailAsync(model.Token, ct); + TempData.SetSuccess("E-mail je ověřený. Teď se můžete přihlásit."); + return RedirectToAction(nameof(Login)); + } + catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.TooManyRequests) + { + ModelState.AddModelError(string.Empty, ex.UserMessage); + return View(model); + } + } + + [AllowAnonymous] + [HttpGet("forgot-password")] + public IActionResult ForgotPassword() => View(new ForgotPasswordViewModel()); + + [AllowAnonymous] + [HttpPost("forgot-password")] + public async Task ForgotPassword(ForgotPasswordViewModel model, CancellationToken ct) + { + if (!ModelState.IsValid) + return View(model); + + try + { + await authApi.ForgotPasswordAsync(model.Email.Trim(), ct); + return View("ForgotPasswordDone", model.Email.Trim()); + } + catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.TooManyRequests) + { + ModelState.AddApiErrors(ex, typeof(ForgotPasswordViewModel)); + return View(model); + } + } + + [AllowAnonymous] + [HttpGet("reset-password")] + public IActionResult ResetPassword(string? token) => View(new ResetPasswordViewModel { Token = token ?? "" }); + + [AllowAnonymous] + [HttpPost("reset-password")] + public async Task ResetPassword(ResetPasswordViewModel model, CancellationToken ct) + { + if (!ModelState.IsValid) + { + model.NewPassword = model.ConfirmPassword = ""; + return View(model); + } + + try + { + await authApi.ResetPasswordAsync(new ResetPasswordRequest(model.Token, model.NewPassword), ct); + } + catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.TooManyRequests) + { + ModelState.AddApiErrors(ex, typeof(ResetPasswordViewModel)); + model.NewPassword = model.ConfirmPassword = ""; + return View(model); + } + + // API po změně hesla zneplatnilo všechna přihlášení – i to v tomto prohlížeči. + await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); + TempData.SetSuccess("Heslo je změněné. Přihlaste se novým heslem."); + return RedirectToAction(nameof(Login)); + } + [HttpPost("logout")] public async Task Logout(CancellationToken ct) { diff --git a/web/Helpdesk.Web/Controllers/ProfileController.cs b/web/Helpdesk.Web/Controllers/ProfileController.cs new file mode 100644 index 0000000..de1c187 --- /dev/null +++ b/web/Helpdesk.Web/Controllers/ProfileController.cs @@ -0,0 +1,60 @@ +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; + +/// Profil přihlášeného uživatele a nastavení notifikací (FR-05). +[Route("profile")] +public sealed class ProfileController(HelpdeskApiClient api) : Controller +{ + [HttpGet("")] + public async Task Index(CancellationToken ct) => + View(ProfileViewModel.From(await api.GetMeAsync(ct))); + + [HttpPost("")] + public async Task 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)); + } + } + + /// Odhlášení ze všech zařízení – zneplatní tokeny i v mobilní aplikaci. + [HttpPost("logout-all")] + public async Task 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 WithReadOnlyFieldsAsync(ProfileViewModel model, CancellationToken ct) + { + var user = await api.GetMeAsync(ct); + model.Email = user.Email; + model.Role = user.Role; + return model; + } +} diff --git a/web/Helpdesk.Web/Models/AccountModels.cs b/web/Helpdesk.Web/Models/AccountModels.cs index 64b90a5..3d36ff1 100644 --- a/web/Helpdesk.Web/Models/AccountModels.cs +++ b/web/Helpdesk.Web/Models/AccountModels.cs @@ -2,6 +2,14 @@ using System.ComponentModel.DataAnnotations; namespace Helpdesk.Web.Models; +// Pravidla hesla odpovídají API: 8–64 znaků (BCrypt zpracuje nejvýše 72 bajtů). +internal static class PasswordRules +{ + public const int MinLength = 8; + public const int MaxLength = 64; + public const string LengthMessage = "Heslo musí mít 8 až 64 znaků."; +} + public sealed class LoginViewModel { [Required(ErrorMessage = "Zadejte e-mail.")] @@ -17,3 +25,67 @@ public sealed class LoginViewModel [Display(Name = "Zůstat přihlášen")] public bool RememberMe { get; set; } } + +public sealed class RegisterViewModel +{ + [Required(ErrorMessage = "Zadejte univerzitní e-mail.")] + [EmailAddress(ErrorMessage = "Zadejte platný e-mail.")] + [StringLength(254)] + [Display(Name = "Univerzitní e-mail")] + public string Email { get; set; } = ""; + + [Required(ErrorMessage = "Zadejte jméno.")] + [StringLength(100, ErrorMessage = "Jméno může mít nejvýše 100 znaků.")] + [Display(Name = "Jméno")] + public string FirstName { get; set; } = ""; + + [Required(ErrorMessage = "Zadejte příjmení.")] + [StringLength(100, ErrorMessage = "Příjmení může mít nejvýše 100 znaků.")] + [Display(Name = "Příjmení")] + public string LastName { get; set; } = ""; + + [Required(ErrorMessage = "Zadejte heslo.")] + [StringLength(PasswordRules.MaxLength, MinimumLength = PasswordRules.MinLength, ErrorMessage = PasswordRules.LengthMessage)] + [DataType(DataType.Password)] + [Display(Name = "Heslo")] + public string Password { get; set; } = ""; + + [Required(ErrorMessage = "Zadejte heslo znovu.")] + [Compare(nameof(Password), ErrorMessage = "Hesla se neshodují.")] + [DataType(DataType.Password)] + [Display(Name = "Heslo znovu")] + public string ConfirmPassword { get; set; } = ""; +} + +/// Stránka z odkazu v e-mailu – token se odešle až tlačítkem. +public sealed class EmailTokenViewModel +{ + [Required] + public string Token { get; set; } = ""; +} + +public sealed class ForgotPasswordViewModel +{ + [Required(ErrorMessage = "Zadejte e-mail.")] + [EmailAddress(ErrorMessage = "Zadejte platný e-mail.")] + [Display(Name = "E-mail")] + public string Email { get; set; } = ""; +} + +public sealed class ResetPasswordViewModel +{ + [Required] + public string Token { get; set; } = ""; + + [Required(ErrorMessage = "Zadejte nové heslo.")] + [StringLength(PasswordRules.MaxLength, MinimumLength = PasswordRules.MinLength, ErrorMessage = PasswordRules.LengthMessage)] + [DataType(DataType.Password)] + [Display(Name = "Nové heslo")] + public string NewPassword { get; set; } = ""; + + [Required(ErrorMessage = "Zadejte nové heslo znovu.")] + [Compare(nameof(NewPassword), ErrorMessage = "Hesla se neshodují.")] + [DataType(DataType.Password)] + [Display(Name = "Nové heslo znovu")] + public string ConfirmPassword { get; set; } = ""; +} diff --git a/web/Helpdesk.Web/Models/ProfileViewModel.cs b/web/Helpdesk.Web/Models/ProfileViewModel.cs new file mode 100644 index 0000000..f352f04 --- /dev/null +++ b/web/Helpdesk.Web/Models/ProfileViewModel.cs @@ -0,0 +1,39 @@ +using System.ComponentModel.DataAnnotations; +using Helpdesk.Web.Api; + +namespace Helpdesk.Web.Models; + +public sealed class ProfileViewModel +{ + // Jen pro zobrazení – e-mail a roli uživatel sám nemění. + public string Email { get; set; } = ""; + public string Role { get; set; } = ""; + + [Required(ErrorMessage = "Zadejte jméno.")] + [StringLength(100, ErrorMessage = "Jméno může mít nejvýše 100 znaků.")] + [Display(Name = "Jméno")] + public string FirstName { get; set; } = ""; + + [Required(ErrorMessage = "Zadejte příjmení.")] + [StringLength(100, ErrorMessage = "Příjmení může mít nejvýše 100 znaků.")] + [Display(Name = "Příjmení")] + public string LastName { get; set; } = ""; + + [StringLength(30, ErrorMessage = "Telefon může mít nejvýše 30 znaků.")] + [RegularExpression(@"^\+?[0-9 ]+$", ErrorMessage = "Telefon smí obsahovat jen číslice, mezery a úvodní +.")] + [Display(Name = "Telefon")] + public string? Phone { get; set; } + + [Display(Name = "Posílat upozornění e-mailem")] + public bool EmailNotificationsEnabled { get; set; } + + public static ProfileViewModel From(UserDto user) => new() + { + Email = user.Email, + Role = user.Role, + FirstName = user.FirstName, + LastName = user.LastName, + Phone = user.Phone, + EmailNotificationsEnabled = user.EmailNotificationsEnabled, + }; +} diff --git a/web/Helpdesk.Web/Views/Account/ConfirmEmail.cshtml b/web/Helpdesk.Web/Views/Account/ConfirmEmail.cshtml new file mode 100644 index 0000000..9c9ce25 --- /dev/null +++ b/web/Helpdesk.Web/Views/Account/ConfirmEmail.cshtml @@ -0,0 +1,27 @@ +@model EmailTokenViewModel +@{ + ViewData["Title"] = "Ověření e-mailu"; + var failed = !ViewData.ModelState.IsValid || string.IsNullOrEmpty(Model.Token); +} + +
+

Ověření e-mailu

+
+ @if (failed) + { + +

Odkaz je neplatný, už byl použit, nebo vypršel. Pokud jste e-mail už ověřili, stačí se přihlásit.

+ } + else + { +

Dokončete registraci potvrzením svého e-mailu.

+
+ + +
+ } +
+ +
diff --git a/web/Helpdesk.Web/Views/Account/ForgotPassword.cshtml b/web/Helpdesk.Web/Views/Account/ForgotPassword.cshtml new file mode 100644 index 0000000..48d5fcb --- /dev/null +++ b/web/Helpdesk.Web/Views/Account/ForgotPassword.cshtml @@ -0,0 +1,25 @@ +@model ForgotPasswordViewModel +@{ + ViewData["Title"] = "Zapomenuté heslo"; +} + +
+

Zapomenuté heslo

+

Pošleme vám odkaz, kterým si nastavíte nové heslo.

+ +
+ +
+
+ + + +
+ +
+
+ + +
diff --git a/web/Helpdesk.Web/Views/Account/ForgotPasswordDone.cshtml b/web/Helpdesk.Web/Views/Account/ForgotPasswordDone.cshtml new file mode 100644 index 0000000..02ae132 --- /dev/null +++ b/web/Helpdesk.Web/Views/Account/ForgotPasswordDone.cshtml @@ -0,0 +1,15 @@ +@model string +@{ + ViewData["Title"] = "Zkontrolujte e-mail"; +} + +
+

Zkontrolujte e-mail

+
+

Pokud k adrese @Model existuje účet, poslali jsme na ni odkaz pro nastavení nového hesla.

+

Odkaz platí 1 hodinu a jde použít jen jednou.

+
+ +
diff --git a/web/Helpdesk.Web/Views/Account/Login.cshtml b/web/Helpdesk.Web/Views/Account/Login.cshtml index 5d285ca..5bbdf45 100644 --- a/web/Helpdesk.Web/Views/Account/Login.cshtml +++ b/web/Helpdesk.Web/Views/Account/Login.cshtml @@ -27,4 +27,9 @@ + + diff --git a/web/Helpdesk.Web/Views/Account/Register.cshtml b/web/Helpdesk.Web/Views/Account/Register.cshtml new file mode 100644 index 0000000..57178bb --- /dev/null +++ b/web/Helpdesk.Web/Views/Account/Register.cshtml @@ -0,0 +1,48 @@ +@model RegisterViewModel +@{ + ViewData["Title"] = "Registrace"; +} + +
+

Registrace

+

Studenti a vyučující se registrují univerzitním e-mailem. Roli určí doména e-mailu.

+ +
+ +
+
+ + + +
+
+
+ + + +
+
+ + + +
+
+
+ + +
8 až 64 znaků.
+ +
+
+ + + +
+ +
+
+ + +
diff --git a/web/Helpdesk.Web/Views/Account/RegisterDone.cshtml b/web/Helpdesk.Web/Views/Account/RegisterDone.cshtml new file mode 100644 index 0000000..26f20c4 --- /dev/null +++ b/web/Helpdesk.Web/Views/Account/RegisterDone.cshtml @@ -0,0 +1,15 @@ +@model string +@{ + ViewData["Title"] = "Ověřte e-mail"; +} + +
+

Ověřte svůj e-mail

+
+

Na adresu @Model jsme poslali odkaz pro ověření e-mailu. Platí 24 hodin.

+

Po ověření se budete moct přihlásit. Pokud e-mail nevidíte, podívejte se i do nevyžádané pošty.

+
+ +
diff --git a/web/Helpdesk.Web/Views/Account/ResetPassword.cshtml b/web/Helpdesk.Web/Views/Account/ResetPassword.cshtml new file mode 100644 index 0000000..3f9e8e3 --- /dev/null +++ b/web/Helpdesk.Web/Views/Account/ResetPassword.cshtml @@ -0,0 +1,39 @@ +@model ResetPasswordViewModel +@{ + ViewData["Title"] = "Nové heslo"; +} + +
+

Nové heslo

+ +
+ @if (string.IsNullOrEmpty(Model.Token)) + { +

Odkaz je neúplný. Otevřete ho prosím znovu z e-mailu, nebo si pošlete nový.

+ } + else + { + +
+ +
+ + +
8 až 64 znaků. Po změně budete odhlášeni na všech zařízeních.
+ +
+
+ + + +
+ +
+ } +
+ + +
diff --git a/web/Helpdesk.Web/Views/Profile/Index.cshtml b/web/Helpdesk.Web/Views/Profile/Index.cshtml new file mode 100644 index 0000000..f44018d --- /dev/null +++ b/web/Helpdesk.Web/Views/Profile/Index.cshtml @@ -0,0 +1,59 @@ +@model ProfileViewModel +@{ + ViewData["Title"] = "Můj profil"; +} + +
+

Můj profil

+
+ +
+
+
+
+
E-mail
+
@Model.Email
+
Role
+
@UserRoles.DisplayName(Model.Role)
+
+ + +
+
+
+ + + +
+
+ + + +
+
+
+ + +
Nepovinné. Na serveru se ukládá šifrovaně.
+ +
+
+ + +
Upozornění v aplikaci dostáváte vždy.
+
+ +
+
+
+ +
+
+

Přihlášená zařízení

+

Odhlásí vás ve všech prohlížečích i v mobilní aplikaci. Hodí se, když jste se přihlásili na cizím počítači.

+
+ +
+
+
+
diff --git a/web/Helpdesk.Web/Views/Shared/_UserMenu.cshtml b/web/Helpdesk.Web/Views/Shared/_UserMenu.cshtml index f686c77..b272d1e 100644 --- a/web/Helpdesk.Web/Views/Shared/_UserMenu.cshtml +++ b/web/Helpdesk.Web/Views/Shared/_UserMenu.cshtml @@ -8,6 +8,7 @@