185 lines
6.8 KiB
C#
185 lines
6.8 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.Authorization;
|
||
using Microsoft.AspNetCore.Mvc;
|
||
|
||
namespace Helpdesk.Web.Controllers;
|
||
|
||
/// <summary>
|
||
/// Přihlášení, registrace, ověření e-mailu a obnova hesla (FR-01 – FR-03).
|
||
/// 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)
|
||
{
|
||
ModelState.AddApiErrors(ex, typeof(LoginViewModel));
|
||
model.Password = "";
|
||
return View(model);
|
||
}
|
||
}
|
||
|
||
[AllowAnonymous]
|
||
[HttpGet("register")]
|
||
public IActionResult Register() =>
|
||
User.Identity?.IsAuthenticated == true ? RedirectToAction("Index", "Home") : View(new RegisterViewModel());
|
||
|
||
[AllowAnonymous]
|
||
[HttpPost("register")]
|
||
public async Task<IActionResult> Register(RegisterViewModel model, CancellationToken ct)
|
||
{
|
||
if (!ModelState.IsValid)
|
||
return View(model);
|
||
|
||
try
|
||
{
|
||
var user = await authApi.RegisterAsync(
|
||
new RegisterRequest(model.Email.Trim(), 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));
|
||
return View(model);
|
||
}
|
||
}
|
||
|
||
/// <summary>Odkaz z ověřovacího e-mailu. Token se spotřebuje při uložení hesla.</summary>
|
||
[AllowAnonymous]
|
||
[HttpGet("confirm-email")]
|
||
public IActionResult ConfirmEmail(string? token) => View(new EmailPasswordViewModel { Token = token ?? "" });
|
||
|
||
[AllowAnonymous]
|
||
[HttpPost("confirm-email")]
|
||
public async Task<IActionResult> ConfirmEmail(EmailPasswordViewModel model, CancellationToken ct)
|
||
{
|
||
if (!ModelState.IsValid)
|
||
{
|
||
model.NewPassword = model.ConfirmPassword = "";
|
||
return View(model);
|
||
}
|
||
|
||
try
|
||
{
|
||
await authApi.ConfirmEmailAsync(new ConfirmEmailRequest(model.Token, model.NewPassword), ct);
|
||
TempData.SetSuccess("E-mail je ověřený. Teď se můžete přihlásit nastaveným heslem.");
|
||
return RedirectToAction(nameof(Login));
|
||
}
|
||
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.TooManyRequests)
|
||
{
|
||
ModelState.AddApiErrors(ex, typeof(EmailPasswordViewModel));
|
||
model.NewPassword = model.ConfirmPassword = "";
|
||
return View(model);
|
||
}
|
||
}
|
||
|
||
[AllowAnonymous]
|
||
[HttpGet("forgot-password")]
|
||
public IActionResult ForgotPassword() => View(new ForgotPasswordViewModel());
|
||
|
||
[AllowAnonymous]
|
||
[HttpPost("forgot-password")]
|
||
public async Task<IActionResult> 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 EmailPasswordViewModel { Token = token ?? "" });
|
||
|
||
[AllowAnonymous]
|
||
[HttpPost("reset-password")]
|
||
public async Task<IActionResult> ResetPassword(EmailPasswordViewModel 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(EmailPasswordViewModel));
|
||
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<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 : "/";
|
||
}
|