Compare commits
28
Commits
6208fd3baf
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a61e7a0f99 | ||
|
|
722d318898 | ||
|
|
e9782a1413 | ||
|
|
9fe713fc10 | ||
|
|
0215af0749 | ||
|
|
52fb8af684 | ||
|
|
5470818841 | ||
|
|
4f95c8a379 | ||
|
|
ee5f1d3d10 | ||
|
|
bd8eb65e56 | ||
|
|
91d0c06c83 | ||
|
|
fcf7cd0596 | ||
|
|
232d48c7fc | ||
|
|
0865831746 | ||
|
|
1550c0343b | ||
|
|
ea3de2e444 | ||
|
|
34f2d57bd3 | ||
|
|
eddf5837eb | ||
|
|
d8de714481 | ||
|
|
ac3ec6aff7 | ||
|
|
32bc5a4691 | ||
|
|
ce04c8beb3 | ||
|
|
def23d306e | ||
|
|
fd37986f5e | ||
|
|
483bb10fbd | ||
|
|
5d8b71c435 | ||
|
|
946ff5ce12 | ||
|
|
2fe939ba5c |
No files matched your search
@@ -30,7 +30,7 @@ Potřeba je jen Docker Desktop.
|
|||||||
docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build
|
docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build
|
||||||
```
|
```
|
||||||
|
|
||||||
3. Webová aplikace: <http://localhost:8081> · Swagger UI: <http://localhost:8080/swagger> · stav a verze schématu: <http://localhost:8080/health>
|
3. Webová aplikace: <http://localhost:8081> · Swagger UI po přihlášení administrátora: <http://localhost:8081/swagger> · stav a verze schématu: <http://localhost:8080/health>
|
||||||
|
|
||||||
Lokálně bez reverse proxy nastavte `PUBLIC_BASE_URL=http://localhost:8081`, aby odkazy pro ověření e-mailu a obnovu hesla vedly na web v Dockeru.
|
Lokálně bez reverse proxy nastavte `PUBLIC_BASE_URL=http://localhost:8081`, aby odkazy pro ověření e-mailu a obnovu hesla vedly na web v Dockeru.
|
||||||
|
|
||||||
@@ -38,9 +38,9 @@ Při prvním startu se vytvoří účet administrátora, pokud vyplníte `ADMIN_
|
|||||||
|
|
||||||
Pro nasazení nastavte v `deploy/.env` režim `Production`, veřejnou HTTPS adresu webu v `PUBLIC_BASE_URL` a skutečné univerzitní domény v `STUDENT_EMAIL_DOMAIN` a `TEACHER_EMAIL_DOMAIN`. Pro Email Profi vyplňte `SMTP_MAILBOX` celou adresou schránky a nastavte `SMTP_PASSWORD`. API odesílá přes `smtp.seznam.cz:465` s TLS.
|
Pro nasazení nastavte v `deploy/.env` režim `Production`, veřejnou HTTPS adresu webu v `PUBLIC_BASE_URL` a skutečné univerzitní domény v `STUDENT_EMAIL_DOMAIN` a `TEACHER_EMAIL_DOMAIN`. Pro Email Profi vyplňte `SMTP_MAILBOX` celou adresou schránky a nastavte `SMTP_PASSWORD`. API odesílá přes `smtp.seznam.cz:465` s TLS.
|
||||||
|
|
||||||
Reverse proxy ukončuje HTTPS a předává požadavky přes HTTP na adresu `PROXY_UPSTREAM_BIND_ADDRESS`: `/api/*` a `/swagger` na port `API_HTTP_PORT` (výchozí `8080`), ostatní na web na port `WEB_HTTP_PORT` (výchozí `8081`). Výchozí adresa `127.0.0.1` odpovídá proxy běžící přímo na stejném hostiteli.
|
Reverse proxy ukončuje HTTPS a předává požadavky přes HTTP na adresu `PROXY_UPSTREAM_BIND_ADDRESS`: `/api/*` na port `API_HTTP_PORT` (výchozí `8080`) a ostatní cesty včetně `/swagger` na web na port `WEB_HTTP_PORT` (výchozí `8081`). Výchozí adresa `127.0.0.1` odpovídá proxy běžící přímo na stejném hostiteli. Swagger UI ověřuje administrátorskou relaci webu. Funkce **Try it out** vyžaduje, aby stejná adresa přes proxy směrovala i `/api/*`, a chráněná volání autorizuje access tokenem.
|
||||||
|
|
||||||
Pro zpracování `X-Forwarded-For` a `X-Forwarded-Proto` nastavte `TRUSTED_REVERSE_PROXY_IP` na IP bezprostředního protějšku, kterou vidí API a web. Tato IP se může při průchodu Docker sítí lišit od adresy, na kterou je API vázáno.
|
Serverová reverse proxy předává IP klienta v `X-Forwarded-For` a schéma v `X-Forwarded-Proto`. Nastavte `TRUSTED_REVERSE_PROXY_IP` na IP bezprostředního protějšku, kterou vidí API a web. Tato IP se může při průchodu Docker sítí lišit od adresy, na kterou je API vázáno. Compose automaticky nastaví privátní síť a důvěryhodnou adresu webu, přes kterou web předává IP klienta dál do API.
|
||||||
|
|
||||||
S nakonfigurovaným SMTP odesílá backend i e-mailové notifikace z databázové fronty. Pro mobilní push nastavte `FIREBASE_SERVICE_ACCOUNT_JSON` na jednořádkový JSON klíče servisního účtu Firebase.
|
S nakonfigurovaným SMTP odesílá backend i e-mailové notifikace z databázové fronty. Pro mobilní push nastavte `FIREBASE_SERVICE_ACCOUNT_JSON` na jednořádkový JSON klíče servisního účtu Firebase.
|
||||||
|
|
||||||
@@ -64,10 +64,31 @@ Testy webové aplikace:
|
|||||||
dotnet test --solution web/Helpdesk.Web.sln
|
dotnet test --solution web/Helpdesk.Web.sln
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Integrační testy backendu
|
||||||
|
|
||||||
|
Vyžadují .NET SDK 10 a spuštěný Docker. Testcontainers vytvoří dočasnou MariaDB 11.4 a testy spustí skutečné migrace.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dotnet run --project backend/tests/Helpdesk.IntegrationTests/Helpdesk.IntegrationTests.csproj
|
||||||
|
```
|
||||||
|
|
||||||
|
Pokrytí backendu integračními testy se ukládá jako Cobertura XML do `TestResults` ve výstupu testovacího projektu.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dotnet run --project backend/tests/Helpdesk.IntegrationTests/Helpdesk.IntegrationTests.csproj -- \
|
||||||
|
--coverage --coverage-output-format cobertura --coverage-output backend-coverage.cobertura.xml \
|
||||||
|
--coverage-settings "$PWD/backend/tests/Helpdesk.IntegrationTests/coverage.settings.xml"
|
||||||
|
```
|
||||||
|
|
||||||
## Verzování databáze
|
## Verzování databáze
|
||||||
|
|
||||||
Schéma se mění výhradně novými číslovanými skripty `db/migrations/V{NNN}__{popis}.sql`. Provedený skript se nikdy neupravuje. Migrace spouští DbUp (`Helpdesk.Migrator`) před startem API a eviduje je v tabulce `schema_version`.
|
Schéma se mění výhradně novými číslovanými skripty `db/migrations/V{NNN}__{popis}.sql`. Provedený skript se nikdy neupravuje. Migrace spouští DbUp (`Helpdesk.Migrator`) před startem API a eviduje je v tabulce `schema_version`.
|
||||||
|
|
||||||
|
## Verzování webové aplikace
|
||||||
|
|
||||||
|
- **Verze API:** web volá REST API `/api/v1`. Verze je na jednom místě, `ApiOptions.ApiVersion` v `web/Helpdesk.Web/Api/ApiOptions.cs`. Klienti API používají jen relativní cesty (`issues`, `auth/login`), takže přechod na `/api/v2` znamená změnit tuto konstantu a upravit DTO, která se ve v2 změnila.
|
||||||
|
- **Verze webu:** `<Version>` v `web/Helpdesk.Web/Helpdesk.Web.csproj` podle semver – před vydáním 1.0 zvyšujeme MINOR za novou část aplikace (závady, návrhy, …) a PATCH za opravy. Verze se zobrazuje v patičce webu spolu s krátkým hashem commitu, ze kterého byl web sestaven.
|
||||||
|
|
||||||
## Technologie
|
## Technologie
|
||||||
|
|
||||||
Backend C# / ASP.NET Core Web API · EF Core + Pomelo (MariaDB) · DbUp · JWT (RFC 7519) · Swagger · Web ASP.NET Core MVC · Mobil Kotlin + Jetpack Compose · Docker
|
Backend C# / ASP.NET Core Web API · EF Core + Pomelo (MariaDB) · DbUp · JWT (RFC 7519) · Swagger · Web ASP.NET Core MVC · Mobil Kotlin + Jetpack Compose · Docker
|
||||||
|
|||||||
@@ -15,14 +15,17 @@
|
|||||||
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="10.0.14" />
|
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="10.0.14" />
|
||||||
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.14" />
|
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.14" />
|
||||||
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.14" />
|
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.14" />
|
||||||
<PackageVersion Include="Swashbuckle.AspNetCore" Version="10.3.1" />
|
<PackageVersion Include="Swashbuckle.AspNetCore.SwaggerGen" Version="10.3.1" />
|
||||||
<PackageVersion Include="BCrypt.Net-Next" Version="4.2.0" />
|
<PackageVersion Include="BCrypt.Net-Next" Version="4.2.0" />
|
||||||
<PackageVersion Include="MailKit" Version="5.0.0" />
|
<PackageVersion Include="MailKit" Version="5.0.0" />
|
||||||
<PackageVersion Include="FirebaseAdmin" Version="3.7.1" />
|
<PackageVersion Include="FirebaseAdmin" Version="3.7.1" />
|
||||||
<PackageVersion Include="FluentValidation" Version="12.2.0" />
|
<PackageVersion Include="FluentValidation" Version="12.2.0" />
|
||||||
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" />
|
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" />
|
||||||
<!-- testy -->
|
<!-- testy -->
|
||||||
|
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.14" />
|
||||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
|
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
|
||||||
|
<PackageVersion Include="Microsoft.Testing.Extensions.CodeCoverage" Version="18.12.0" />
|
||||||
|
<PackageVersion Include="Testcontainers.MariaDb" Version="4.16.0" />
|
||||||
<PackageVersion Include="xunit.v3" Version="4.0.2" />
|
<PackageVersion Include="xunit.v3" Version="4.0.2" />
|
||||||
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
|
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.Migrator", "src\He
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.UnitTests", "tests\Helpdesk.UnitTests\Helpdesk.UnitTests.csproj", "{AB40F473-EB15-47C7-B179-A8EB066325EC}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.UnitTests", "tests\Helpdesk.UnitTests\Helpdesk.UnitTests.csproj", "{AB40F473-EB15-47C7-B179-A8EB066325EC}"
|
||||||
EndProject
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.IntegrationTests", "tests\Helpdesk.IntegrationTests\Helpdesk.IntegrationTests.csproj", "{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}"
|
||||||
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
@@ -97,6 +99,18 @@ Global
|
|||||||
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x64.Build.0 = Release|Any CPU
|
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x64.Build.0 = Release|Any CPU
|
||||||
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.ActiveCfg = Release|Any CPU
|
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.Build.0 = Release|Any CPU
|
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x86.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
|
|||||||
@@ -22,6 +22,53 @@ public sealed class AdminUsersController(UserService users, ICurrentUser current
|
|||||||
CancellationToken ct = default) =>
|
CancellationToken ct = default) =>
|
||||||
users.SearchAsync(q, role, page, pageSize, ct);
|
users.SearchAsync(q, role, page, pageSize, ct);
|
||||||
|
|
||||||
|
[HttpGet("{id:int}")]
|
||||||
|
public Task<AdminUserDetailsDto> Get(int id, CancellationToken ct) => users.GetAdminAsync(id, ct);
|
||||||
|
|
||||||
|
[HttpPost]
|
||||||
|
[ProducesResponseType<AdminUserDetailsDto>(StatusCodes.Status201Created)]
|
||||||
|
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
|
public async Task<ActionResult<AdminUserDetailsDto>> Create(SaveAdminUserRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var user = await users.CreateAsync(currentUser, request, ct);
|
||||||
|
return CreatedAtAction(nameof(Get), new { id = user.Id }, user);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPut("{id:int}")]
|
||||||
|
[ProducesResponseType<AdminUserDetailsDto>(StatusCodes.Status200OK)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
|
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||||
|
public async Task<IActionResult> Update(int id, SaveAdminUserRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var result = await users.UpdateAsync(currentUser, id, request, ct);
|
||||||
|
return result is null ? NoContent() : Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/email-confirmation")]
|
||||||
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
|
public async Task<IActionResult> SendEmailConfirmation(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await users.SendEmailConfirmationAsync(id, ct);
|
||||||
|
return NoContent();
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpDelete("{id:int}")]
|
||||||
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
|
public async Task<IActionResult> Delete(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await users.DeleteAsync(currentUser, id, ct);
|
||||||
|
return NoContent();
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("bulk")]
|
||||||
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
|
public async Task<IActionResult> Bulk(BulkAdminUsersRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await users.BulkUpdateAsync(currentUser, request, ct);
|
||||||
|
return NoContent();
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Změna role – uživatel bude odhlášen a po přihlášení dostane token s novou rolí.</summary>
|
/// <summary>Změna role – uživatel bude odhlášen a po přihlášení dostane token s novou rolí.</summary>
|
||||||
[HttpPut("{id:int}/role")]
|
[HttpPut("{id:int}/role")]
|
||||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
@@ -36,6 +83,7 @@ public sealed class AdminUsersController(UserService users, ICurrentUser current
|
|||||||
/// <summary>Aktivace / deaktivace účtu. Deaktivace zneplatní všechny tokeny uživatele.</summary>
|
/// <summary>Aktivace / deaktivace účtu. Deaktivace zneplatní všechny tokeny uživatele.</summary>
|
||||||
[HttpPut("{id:int}/active")]
|
[HttpPut("{id:int}/active")]
|
||||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
|
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||||
public async Task<IActionResult> SetActive(int id, SetActiveRequest request, CancellationToken ct)
|
public async Task<IActionResult> SetActive(int id, SetActiveRequest request, CancellationToken ct)
|
||||||
|
|||||||
@@ -15,8 +15,8 @@ namespace Helpdesk.Api.Controllers;
|
|||||||
[Produces("application/json")]
|
[Produces("application/json")]
|
||||||
public sealed class AuthController(AuthService auth) : ControllerBase
|
public sealed class AuthController(AuthService auth) : ControllerBase
|
||||||
{
|
{
|
||||||
/// <summary>Registrace e-mailem a heslem. Role (student / vyučující) se určí podle domény e-mailu.</summary>
|
/// <summary>Registrace e-mailem. Role (student / vyučující) se určí podle domény e-mailu.</summary>
|
||||||
/// <remarks>Po registraci přijde e-mail s odkazem pro ověření; bez ověření se nelze přihlásit.</remarks>
|
/// <remarks>Heslo se nastavuje až po otevření ověřovacího odkazu z e-mailu.</remarks>
|
||||||
[HttpPost("register")]
|
[HttpPost("register")]
|
||||||
[ProducesResponseType<UserDto>(StatusCodes.Status201Created)]
|
[ProducesResponseType<UserDto>(StatusCodes.Status201Created)]
|
||||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
@@ -28,11 +28,11 @@ public sealed class AuthController(AuthService auth) : ControllerBase
|
|||||||
return Created($"/{ApiRoutes.V1}/users/me", user);
|
return Created($"/{ApiRoutes.V1}/users/me", user);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Ověření e-mailu tokenem z registračního e-mailu (jednorázový).</summary>
|
/// <summary>Ověří e-mail jednorázovým tokenem a nastaví heslo k účtu.</summary>
|
||||||
[HttpPost("confirm-email")]
|
[HttpPost("confirm-email")]
|
||||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
public async Task<IActionResult> ConfirmEmail(EmailTokenRequest request, CancellationToken ct)
|
public async Task<IActionResult> ConfirmEmail(ConfirmEmailRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
await auth.ConfirmEmailAsync(request, ct);
|
await auth.ConfirmEmailAsync(request, ct);
|
||||||
return NoContent();
|
return NoContent();
|
||||||
@@ -42,8 +42,15 @@ public sealed class AuthController(AuthService auth) : ControllerBase
|
|||||||
[HttpPost("login")]
|
[HttpPost("login")]
|
||||||
[ProducesResponseType<AuthResponse>(StatusCodes.Status200OK)]
|
[ProducesResponseType<AuthResponse>(StatusCodes.Status200OK)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status429TooManyRequests)]
|
||||||
public Task<AuthResponse> Login(LoginRequest request, CancellationToken ct) => auth.LoginAsync(request, ct);
|
public async Task<ActionResult<AuthResponse>> Login(LoginRequest request, [FromServices] LoginRateLimiter limiter, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (!limiter.TryAcquire(HttpContext, request.Email))
|
||||||
|
return Problem(statusCode: StatusCodes.Status429TooManyRequests,
|
||||||
|
title: "Příliš mnoho pokusů o přihlášení. Zkuste to za chvíli.");
|
||||||
|
|
||||||
|
return await auth.LoginAsync(request, ct);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Výměna refresh tokenu za nový pár tokenů. Použitý refresh token se zneplatní.</summary>
|
/// <summary>Výměna refresh tokenu za nový pár tokenů. Použitý refresh token se zneplatní.</summary>
|
||||||
/// <remarks>Opakované použití už vyměněného refresh tokenu zneplatní všechny tokeny uživatele.</remarks>
|
/// <remarks>Opakované použití už vyměněného refresh tokenu zneplatní všechny tokeny uživatele.</remarks>
|
||||||
@@ -62,7 +69,7 @@ public sealed class AuthController(AuthService auth) : ControllerBase
|
|||||||
return NoContent();
|
return NoContent();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Odhlášení ze všech zařízení – zneplatní všechny tokeny uživatele.</summary>
|
/// <summary>Odhlášení ze všech zařízení. Zneplatní tokeny a odstraní registrace pro push.</summary>
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[HttpPost("logout-all")]
|
[HttpPost("logout-all")]
|
||||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ public sealed class IssuesController(IssueService issues) : ControllerBase
|
|||||||
[RequestSizeLimit(AttachmentLimits.MaxRequestBytes)]
|
[RequestSizeLimit(AttachmentLimits.MaxRequestBytes)]
|
||||||
[RequestFormLimits(MultipartBodyLengthLimit = AttachmentLimits.MaxRequestBytes)]
|
[RequestFormLimits(MultipartBodyLengthLimit = AttachmentLimits.MaxRequestBytes)]
|
||||||
[ProducesResponseType<IssueDetail>(StatusCodes.Status201Created)]
|
[ProducesResponseType<IssueDetail>(StatusCodes.Status201Created)]
|
||||||
|
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status413PayloadTooLarge)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status413PayloadTooLarge)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status415UnsupportedMediaType)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status415UnsupportedMediaType)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status429TooManyRequests)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status429TooManyRequests)]
|
||||||
@@ -55,7 +56,7 @@ public sealed class IssuesController(IssueService issues) : ControllerBase
|
|||||||
var form = await ReadFormAsync(ct);
|
var form = await ReadFormAsync(ct);
|
||||||
request = new CreateIssueRequest(
|
request = new CreateIssueRequest(
|
||||||
form["title"].ToString(), form["description"].ToString(),
|
form["title"].ToString(), form["description"].ToString(),
|
||||||
ReadId(form, "categoryId") ?? throw new BadRequestException("Kategorie je povinná."),
|
ReadId(form, "categoryId") ?? 0,
|
||||||
ReadId(form, "buildingId"), form["locationDetail"].ToString());
|
ReadId(form, "buildingId"), form["locationDetail"].ToString());
|
||||||
uploads = ReadUploads(form.Files);
|
uploads = ReadUploads(form.Files);
|
||||||
}
|
}
|
||||||
@@ -87,6 +88,7 @@ public sealed class IssuesController(IssueService issues) : ControllerBase
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpPut("{id:int}")]
|
[HttpPut("{id:int}")]
|
||||||
|
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
public Task<IssueDetail> Edit(int id, EditIssueRequest request, CancellationToken ct) =>
|
public Task<IssueDetail> Edit(int id, EditIssueRequest request, CancellationToken ct) =>
|
||||||
issues.EditAsync(id, request, ct);
|
issues.EditAsync(id, request, ct);
|
||||||
|
|
||||||
@@ -160,16 +162,16 @@ public sealed class IssuesController(IssueService issues) : ControllerBase
|
|||||||
if (string.IsNullOrWhiteSpace(value))
|
if (string.IsNullOrWhiteSpace(value))
|
||||||
return null;
|
return null;
|
||||||
if (!int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var id))
|
if (!int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var id))
|
||||||
throw new BadRequestException($"Neplatná hodnota {key}.");
|
throw new FieldValidationException(key, "Zadejte platné ID.");
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static AttachmentUpload[] ReadUploads(IFormFileCollection files)
|
private static AttachmentUpload[] ReadUploads(IFormFileCollection files)
|
||||||
{
|
{
|
||||||
if (files.Count > AttachmentLimits.MaxFiles)
|
if (files.Count > AttachmentLimits.MaxFiles)
|
||||||
throw new BadRequestException("Najednou lze přiložit nejvýše pět souborů.");
|
throw new FieldValidationException("files", "Najednou lze přiložit nejvýše pět souborů.");
|
||||||
if (files.Any(file => file.Name != "files"))
|
if (files.Any(file => file.Name != "files"))
|
||||||
throw new BadRequestException("Přílohy patří do pole files.");
|
throw new FieldValidationException("files", "Přílohy patří do pole files.");
|
||||||
|
|
||||||
return files.Select(file => new AttachmentUpload(file.FileName, file.Length, file.OpenReadStream)).ToArray();
|
return files.Select(file => new AttachmentUpload(file.FileName, file.Length, file.OpenReadStream)).ToArray();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ public sealed class ProposalsController(ProposalService proposals) : ControllerB
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("{id:int}/status")]
|
[HttpPost("{id:int}/status")]
|
||||||
[Authorize(Roles = Roles.Management)]
|
[Authorize(Roles = Roles.ManagementOrAdmin)]
|
||||||
[RequestSizeLimit(1024 * 1024)]
|
[RequestSizeLimit(1024 * 1024)]
|
||||||
public Task<ProposalDetail> ChangeStatus(int id, ChangeProposalStatusRequest request, CancellationToken ct) =>
|
public Task<ProposalDetail> ChangeStatus(int id, ChangeProposalStatusRequest request, CancellationToken ct) =>
|
||||||
proposals.ChangeStatusAsync(id, request, ct);
|
proposals.ChangeStatusAsync(id, request, ct);
|
||||||
|
|||||||
@@ -6,9 +6,9 @@ using Microsoft.AspNetCore.Mvc;
|
|||||||
|
|
||||||
namespace Helpdesk.Api.Controllers;
|
namespace Helpdesk.Api.Controllers;
|
||||||
|
|
||||||
/// <summary>Statistiky pro vedení školy. Období v UTC zahrnuje začátek a vylučuje konec.</summary>
|
/// <summary>Statistiky pro vedení školy a administrátory. Období v UTC zahrnuje začátek a vylučuje konec.</summary>
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Authorize(Roles = Roles.Management)]
|
[Authorize(Roles = Roles.ManagementOrAdmin)]
|
||||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||||
[Route(ApiRoutes.V1 + "/statistics")]
|
[Route(ApiRoutes.V1 + "/statistics")]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ public sealed class UsersController(UserService users, ICurrentUser currentUser,
|
|||||||
|
|
||||||
/// <summary>Aktivní řešitelé s počtem otevřených závad.</summary>
|
/// <summary>Aktivní řešitelé s počtem otevřených závad.</summary>
|
||||||
[HttpGet("assignable")]
|
[HttpGet("assignable")]
|
||||||
[Authorize(Roles = Roles.Management)]
|
[Authorize(Roles = Roles.ManagementOrAdmin)]
|
||||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
||||||
public Task<IReadOnlyList<AssignableUserDto>> GetAssignable(CancellationToken ct) => issues.GetAssignableAsync(ct);
|
public Task<IReadOnlyList<AssignableUserDto>> GetAssignable(CancellationToken ct) => issues.GetAssignableAsync(ct);
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" />
|
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -20,7 +20,7 @@ internal sealed class AppExceptionHandler(IProblemDetailsService problemDetails)
|
|||||||
Status = StatusCodes.Status400BadRequest,
|
Status = StatusCodes.Status400BadRequest,
|
||||||
Title = "Neplatná vstupní data.",
|
Title = "Neplatná vstupní data.",
|
||||||
},
|
},
|
||||||
AppException app => new ProblemDetails { Status = app.StatusCode, Title = app.Message },
|
AppException app => new ProblemDetails { Status = app.StatusCode, Title = app.Message, Type = app.ProblemType },
|
||||||
BadHttpRequestException request => new ProblemDetails { Status = request.StatusCode },
|
BadHttpRequestException request => new ProblemDetails { Status = request.StatusCode },
|
||||||
_ => null,
|
_ => null,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -43,4 +43,10 @@ public static class RateLimitPolicies
|
|||||||
{
|
{
|
||||||
public const string Auth = "auth";
|
public const string Auth = "auth";
|
||||||
public const string IssueWrites = "issue-writes";
|
public const string IssueWrites = "issue-writes";
|
||||||
|
|
||||||
|
public static string ClientIp(HttpContext context)
|
||||||
|
{
|
||||||
|
var address = context.Connection.RemoteIpAddress;
|
||||||
|
return (address is { IsIPv4MappedToIPv6: true } ? address.MapToIPv4() : address)?.ToString() ?? "unknown";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
using System.Threading.RateLimiting;
|
||||||
|
using Helpdesk.Domain.Users;
|
||||||
|
|
||||||
|
namespace Helpdesk.Api.Infrastructure;
|
||||||
|
|
||||||
|
public sealed class LoginRateLimiter : IDisposable
|
||||||
|
{
|
||||||
|
private readonly PartitionedRateLimiter<(string, string)> attempts =
|
||||||
|
PartitionedRateLimiter.Create<(string, string), (string, string)>(key =>
|
||||||
|
RateLimitPartition.GetFixedWindowLimiter(key,
|
||||||
|
_ => new FixedWindowRateLimiterOptions { PermitLimit = 5, Window = TimeSpan.FromMinutes(1) }));
|
||||||
|
|
||||||
|
public bool TryAcquire(HttpContext context, string? email)
|
||||||
|
{
|
||||||
|
var trimmed = email?.Trim();
|
||||||
|
var normalized = trimmed is { Length: > 0 and <= 254 } ? User.NormalizeEmail(trimmed) : string.Empty;
|
||||||
|
using var lease = attempts.AttemptAcquire((RateLimitPolicies.ClientIp(context), normalized));
|
||||||
|
return lease.IsAcquired;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose() => attempts.Dispose();
|
||||||
|
}
|
||||||
@@ -8,4 +8,5 @@ public static class Roles
|
|||||||
public const string FacilityManager = "FACILITY_MANAGER";
|
public const string FacilityManager = "FACILITY_MANAGER";
|
||||||
public const string Management = "MANAGEMENT";
|
public const string Management = "MANAGEMENT";
|
||||||
public const string Admin = "ADMIN";
|
public const string Admin = "ADMIN";
|
||||||
|
public const string ManagementOrAdmin = Management + "," + Admin;
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,7 @@ using Microsoft.OpenApi;
|
|||||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||||
using Helpdesk.Api.Controllers;
|
using Helpdesk.Api.Controllers;
|
||||||
using Helpdesk.Application.Issues;
|
using Helpdesk.Application.Issues;
|
||||||
|
using Helpdesk.Application.Users;
|
||||||
|
|
||||||
namespace Helpdesk.Api.Infrastructure;
|
namespace Helpdesk.Api.Infrastructure;
|
||||||
|
|
||||||
@@ -9,7 +10,7 @@ public static class SwaggerSetup
|
|||||||
{
|
{
|
||||||
private const string SchemeId = "Bearer";
|
private const string SchemeId = "Bearer";
|
||||||
|
|
||||||
/// <summary>Swagger UI na <c>/swagger</c> včetně přihlášení access tokenem (NFR-04).</summary>
|
/// <summary>Generování OpenAPI dokumentu pro administrátorské Swagger UI (NFR-04).</summary>
|
||||||
public static IServiceCollection AddHelpdeskSwagger(this IServiceCollection services)
|
public static IServiceCollection AddHelpdeskSwagger(this IServiceCollection services)
|
||||||
{
|
{
|
||||||
services.AddEndpointsApiExplorer();
|
services.AddEndpointsApiExplorer();
|
||||||
@@ -34,6 +35,7 @@ public static class SwaggerSetup
|
|||||||
[new OpenApiSecuritySchemeReference(SchemeId, document)] = [],
|
[new OpenApiSecuritySchemeReference(SchemeId, document)] = [],
|
||||||
});
|
});
|
||||||
options.OperationFilter<IssueRequestBody>();
|
options.OperationFilter<IssueRequestBody>();
|
||||||
|
options.SchemaFilter<UserStateRequestSchema>();
|
||||||
|
|
||||||
var xml = Path.Combine(AppContext.BaseDirectory, "Helpdesk.Api.xml");
|
var xml = Path.Combine(AppContext.BaseDirectory, "Helpdesk.Api.xml");
|
||||||
if (File.Exists(xml))
|
if (File.Exists(xml))
|
||||||
@@ -43,6 +45,30 @@ public static class SwaggerSetup
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal sealed class UserStateRequestSchema : ISchemaFilter
|
||||||
|
{
|
||||||
|
public void Apply(IOpenApiSchema schema, SchemaFilterContext context)
|
||||||
|
{
|
||||||
|
string[] fields = context.Type switch
|
||||||
|
{
|
||||||
|
var type when type == typeof(UpdateProfileRequest) => ["emailNotificationsEnabled"],
|
||||||
|
var type when type == typeof(SetActiveRequest) => ["isActive"],
|
||||||
|
var type when type == typeof(SaveAdminUserRequest) => ["isActive", "emailConfirmed", "emailNotificationsEnabled"],
|
||||||
|
_ => [],
|
||||||
|
};
|
||||||
|
if (fields.Length == 0 || schema is not OpenApiSchema { Properties: { } properties } request)
|
||||||
|
return;
|
||||||
|
|
||||||
|
request.Required ??= new HashSet<string>();
|
||||||
|
foreach (var field in fields)
|
||||||
|
{
|
||||||
|
request.Required.Add(field);
|
||||||
|
if (properties[field] is OpenApiSchema property)
|
||||||
|
property.Type = JsonSchemaType.Boolean;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
internal sealed class IssueRequestBody : IOperationFilter
|
internal sealed class IssueRequestBody : IOperationFilter
|
||||||
{
|
{
|
||||||
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
||||||
|
|||||||
@@ -30,27 +30,31 @@ builder.Services.AddProblemDetails();
|
|||||||
builder.Services.AddExceptionHandler<AppExceptionHandler>();
|
builder.Services.AddExceptionHandler<AppExceptionHandler>();
|
||||||
builder.Services.AddHelpdeskSwagger();
|
builder.Services.AddHelpdeskSwagger();
|
||||||
|
|
||||||
var trustedProxy = builder.Configuration["ReverseProxy:TrustedIp"];
|
var trustedProxies = new[] { "ReverseProxy:TrustedIp", "ReverseProxy:TrustedWebIp" }
|
||||||
if (!string.IsNullOrWhiteSpace(trustedProxy))
|
.Where(key => !string.IsNullOrWhiteSpace(builder.Configuration[key]))
|
||||||
{
|
.Select(key => IPAddress.TryParse(builder.Configuration[key], out var address) ? address
|
||||||
if (!IPAddress.TryParse(trustedProxy, out var proxyAddress))
|
: throw new InvalidOperationException($"Nastavte platnou IP adresu v {key}."))
|
||||||
throw new InvalidOperationException("Nastavte platnou IP adresu důvěryhodné reverse proxy.");
|
.ToArray();
|
||||||
|
|
||||||
|
if (trustedProxies.Length > 0)
|
||||||
|
{
|
||||||
builder.Services.Configure<ForwardedHeadersOptions>(options =>
|
builder.Services.Configure<ForwardedHeadersOptions>(options =>
|
||||||
{
|
{
|
||||||
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
|
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
|
||||||
options.KnownIPNetworks.Clear();
|
options.KnownIPNetworks.Clear();
|
||||||
options.KnownProxies.Clear();
|
options.KnownProxies.Clear();
|
||||||
options.KnownProxies.Add(proxyAddress);
|
foreach (var address in trustedProxies)
|
||||||
|
options.KnownProxies.Add(address);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ochrana přihlášení a zápisů závad proti zahlcení (kap. 10).
|
// Ochrana přihlášení a zápisů závad proti zahlcení (kap. 10).
|
||||||
|
builder.Services.AddSingleton<LoginRateLimiter>();
|
||||||
builder.Services.AddRateLimiter(options =>
|
builder.Services.AddRateLimiter(options =>
|
||||||
{
|
{
|
||||||
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||||
options.AddPolicy(RateLimitPolicies.Auth, http => RateLimitPartition.GetFixedWindowLimiter(
|
options.AddPolicy(RateLimitPolicies.Auth, http => RateLimitPartition.GetFixedWindowLimiter(
|
||||||
http.Connection.RemoteIpAddress?.ToString() ?? "unknown",
|
RateLimitPolicies.ClientIp(http),
|
||||||
_ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) }));
|
_ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) }));
|
||||||
options.AddPolicy(RateLimitPolicies.IssueWrites, http => RateLimitPartition.GetSlidingWindowLimiter(
|
options.AddPolicy(RateLimitPolicies.IssueWrites, http => RateLimitPartition.GetSlidingWindowLimiter(
|
||||||
http.User.FindFirst(JwtRegisteredClaimNames.Sub)?.Value ?? "unknown",
|
http.User.FindFirst(JwtRegisteredClaimNames.Sub)?.Value ?? "unknown",
|
||||||
@@ -64,23 +68,18 @@ builder.Services.AddRateLimiter(options =>
|
|||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(trustedProxy))
|
if (trustedProxies.Length > 0)
|
||||||
app.UseForwardedHeaders();
|
app.UseForwardedHeaders();
|
||||||
|
|
||||||
app.UseExceptionHandler();
|
app.UseExceptionHandler();
|
||||||
app.UseStatusCodePages();
|
app.UseStatusCodePages();
|
||||||
|
|
||||||
app.UseSwagger();
|
|
||||||
app.UseSwaggerUI(options =>
|
|
||||||
{
|
|
||||||
options.SwaggerEndpoint("/swagger/v1/swagger.json", "Helpdesk API v1");
|
|
||||||
options.DocumentTitle = "Helpdesk API";
|
|
||||||
});
|
|
||||||
|
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
app.UseRateLimiter();
|
app.UseRateLimiter();
|
||||||
|
|
||||||
|
app.MapSwagger(ApiRoutes.V1 + "/admin/openapi/{documentName}.json")
|
||||||
|
.RequireAuthorization(policy => policy.RequireRole(Roles.Admin));
|
||||||
app.MapControllers();
|
app.MapControllers();
|
||||||
|
|
||||||
app.Run();
|
app.Run();
|
||||||
|
|||||||
@@ -30,7 +30,8 @@ public interface IAppDbContext
|
|||||||
DbSet<PushDevice> PushDevices { get; }
|
DbSet<PushDevice> PushDevices { get; }
|
||||||
|
|
||||||
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
|
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
|
||||||
Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct);
|
Task<IDbContextTransaction> BeginWriteAsync(CancellationToken ct);
|
||||||
|
Task<User?> LockUserAsync(int id, CancellationToken ct);
|
||||||
Task<Proposal?> LockProposalAsync(int id, CancellationToken ct);
|
Task<Proposal?> LockProposalAsync(int id, CancellationToken ct);
|
||||||
Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct);
|
Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct);
|
||||||
}
|
}
|
||||||
@@ -38,7 +39,7 @@ public interface IAppDbContext
|
|||||||
public interface IPasswordHasher
|
public interface IPasswordHasher
|
||||||
{
|
{
|
||||||
string Hash(string password);
|
string Hash(string password);
|
||||||
bool Verify(string password, string passwordHash);
|
bool Verify(string password, string? passwordHash);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Vydaný JWT: serializovaný token a záznam pro tabulku <c>auth_token</c>.</summary>
|
/// <summary>Vydaný JWT: serializovaný token a záznam pro tabulku <c>auth_token</c>.</summary>
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
|
using System.Text;
|
||||||
using FluentValidation;
|
using FluentValidation;
|
||||||
using Helpdesk.Application.Users;
|
using Helpdesk.Application.Users;
|
||||||
|
|
||||||
namespace Helpdesk.Application.Auth;
|
namespace Helpdesk.Application.Auth;
|
||||||
|
|
||||||
public sealed record RegisterRequest(string Email, string Password, string FirstName, string LastName);
|
public sealed record RegisterRequest(string Email, string FirstName, string LastName);
|
||||||
|
|
||||||
public sealed record LoginRequest(string Email, string Password);
|
public sealed record LoginRequest(string Email, string Password);
|
||||||
|
|
||||||
/// <summary>Refresh token – pro <c>/auth/refresh</c> i <c>/auth/logout</c>.</summary>
|
/// <summary>Refresh token – pro <c>/auth/refresh</c> i <c>/auth/logout</c>.</summary>
|
||||||
public sealed record RefreshTokenRequest(string RefreshToken);
|
public sealed record RefreshTokenRequest(string RefreshToken);
|
||||||
|
|
||||||
/// <summary>Token z odkazu v e-mailu (ověření e-mailu).</summary>
|
public sealed record ConfirmEmailRequest(string Token, string NewPassword);
|
||||||
public sealed record EmailTokenRequest(string Token);
|
|
||||||
|
|
||||||
public sealed record ForgotPasswordRequest(string Email);
|
public sealed record ForgotPasswordRequest(string Email);
|
||||||
|
|
||||||
@@ -26,11 +26,15 @@ public sealed record AuthResponse(
|
|||||||
|
|
||||||
internal static class PasswordRules
|
internal static class PasswordRules
|
||||||
{
|
{
|
||||||
public const int MinLength = 8;
|
private const int MinLength = 8;
|
||||||
public const int MaxLength = 64; // BCrypt zpracuje nejvýše 72 bajtů
|
private const int MaxLength = 64;
|
||||||
|
private const int MaxUtf8Bytes = 72;
|
||||||
|
|
||||||
public static IRuleBuilderOptions<T, string> ValidPassword<T>(this IRuleBuilder<T, string> rule) =>
|
public static IRuleBuilderOptions<T, string?> ValidPassword<T>(this IRuleBuilderInitial<T, string?> rule) =>
|
||||||
rule.NotEmpty().MinimumLength(MinLength).MaximumLength(MaxLength);
|
rule.Cascade(CascadeMode.Stop)
|
||||||
|
.NotEmpty().MinimumLength(MinLength).MaximumLength(MaxLength)
|
||||||
|
.Must(password => Encoding.UTF8.GetByteCount(password!) <= MaxUtf8Bytes)
|
||||||
|
.WithMessage("Heslo může mít nejvýše 72 bajtů v UTF-8.");
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class RegisterRequestValidator : AbstractValidator<RegisterRequest>
|
public sealed class RegisterRequestValidator : AbstractValidator<RegisterRequest>
|
||||||
@@ -38,12 +42,20 @@ public sealed class RegisterRequestValidator : AbstractValidator<RegisterRequest
|
|||||||
public RegisterRequestValidator()
|
public RegisterRequestValidator()
|
||||||
{
|
{
|
||||||
RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(254);
|
RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(254);
|
||||||
RuleFor(x => x.Password).ValidPassword();
|
|
||||||
RuleFor(x => x.FirstName).NotEmpty().MaximumLength(100);
|
RuleFor(x => x.FirstName).NotEmpty().MaximumLength(100);
|
||||||
RuleFor(x => x.LastName).NotEmpty().MaximumLength(100);
|
RuleFor(x => x.LastName).NotEmpty().MaximumLength(100);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public sealed class ConfirmEmailRequestValidator : AbstractValidator<ConfirmEmailRequest>
|
||||||
|
{
|
||||||
|
public ConfirmEmailRequestValidator()
|
||||||
|
{
|
||||||
|
RuleFor(x => x.Token).NotEmpty();
|
||||||
|
RuleFor(x => x.NewPassword).ValidPassword();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public sealed class LoginRequestValidator : AbstractValidator<LoginRequest>
|
public sealed class LoginRequestValidator : AbstractValidator<LoginRequest>
|
||||||
{
|
{
|
||||||
public LoginRequestValidator()
|
public LoginRequestValidator()
|
||||||
|
|||||||
@@ -17,8 +17,8 @@ public sealed class AuthService(
|
|||||||
TokenRevocationService revocation,
|
TokenRevocationService revocation,
|
||||||
IEmailSender emailSender,
|
IEmailSender emailSender,
|
||||||
IOptions<RegistrationOptions> registrationOptions,
|
IOptions<RegistrationOptions> registrationOptions,
|
||||||
TimeProvider clock,
|
|
||||||
IValidator<RegisterRequest> registerValidator,
|
IValidator<RegisterRequest> registerValidator,
|
||||||
|
IValidator<ConfirmEmailRequest> confirmEmailValidator,
|
||||||
IValidator<LoginRequest> loginValidator,
|
IValidator<LoginRequest> loginValidator,
|
||||||
IValidator<ResetPasswordRequest> resetPasswordValidator)
|
IValidator<ResetPasswordRequest> resetPasswordValidator)
|
||||||
{
|
{
|
||||||
@@ -29,61 +29,65 @@ public sealed class AuthService(
|
|||||||
await registerValidator.ValidateAndThrowAsync(request, ct);
|
await registerValidator.ValidateAndThrowAsync(request, ct);
|
||||||
|
|
||||||
var role = _registration.ResolveRole(request.Email)
|
var role = _registration.ResolveRole(request.Email)
|
||||||
?? throw new BadRequestException("Registrace je možná jen s univerzitním e-mailem.");
|
?? throw new FieldValidationException(nameof(request.Email), "Registrace je možná jen s univerzitním e-mailem.");
|
||||||
|
|
||||||
var normalized = User.NormalizeEmail(request.Email);
|
var normalized = User.NormalizeEmail(request.Email);
|
||||||
var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized, ct);
|
var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized, ct);
|
||||||
if (user is null)
|
if (user is null)
|
||||||
{
|
{
|
||||||
user = User.Create(request.Email, passwordHasher.Hash(request.Password), request.FirstName, request.LastName, role);
|
user = User.Create(request.Email, "", request.FirstName, request.LastName, role);
|
||||||
db.Users.Add(user);
|
db.Users.Add(user);
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
}
|
}
|
||||||
else if (!user.IsActive || user.EmailConfirmed || !passwordHasher.Verify(request.Password, user.PasswordHash))
|
else if (!user.IsActive || user.EmailConfirmed)
|
||||||
{
|
{
|
||||||
throw new ConflictException("Účet s tímto e-mailem už existuje.");
|
throw new ConflictException("Účet s tímto e-mailem už existuje.");
|
||||||
}
|
}
|
||||||
|
|
||||||
await SendEmailTokenAsync(user, TokenType.EmailConfirm, ct);
|
await SendEmailConfirmationAsync(user, ct);
|
||||||
return UserDto.From(user);
|
return UserDto.From(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task ConfirmEmailAsync(EmailTokenRequest request, CancellationToken ct)
|
internal Task<bool> SendEmailConfirmationAsync(User user, CancellationToken ct) =>
|
||||||
|
SendEmailTokenAsync(user, TokenType.EmailConfirm, ct);
|
||||||
|
|
||||||
|
public async Task ConfirmEmailAsync(ConfirmEmailRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
|
await confirmEmailValidator.ValidateAndThrowAsync(request, ct);
|
||||||
|
|
||||||
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
var user = await ConsumeEmailTokenAsync(request.Token, TokenType.EmailConfirm, ct);
|
var user = await ConsumeEmailTokenAsync(request.Token, TokenType.EmailConfirm, ct);
|
||||||
|
var revoked = await StageDisconnectAsync(user.Id, RevokeReason.PasswordChanged, ct);
|
||||||
|
user.ChangePasswordHash(passwordHasher.Hash(request.NewPassword));
|
||||||
user.ConfirmEmail();
|
user.ConfirmEmail();
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
|
revocation.Publish(revoked);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<AuthResponse> LoginAsync(LoginRequest request, CancellationToken ct)
|
public async Task<AuthResponse> LoginAsync(LoginRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
await loginValidator.ValidateAndThrowAsync(request, ct);
|
await loginValidator.ValidateAndThrowAsync(request, ct);
|
||||||
|
|
||||||
var now = clock.GetUtcNow().UtcDateTime;
|
|
||||||
var normalized = User.NormalizeEmail(request.Email);
|
var normalized = User.NormalizeEmail(request.Email);
|
||||||
var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized, ct);
|
var account = await db.Users.Where(u => u.EmailNormalized == normalized && u.IsActive && !u.IsDeleted && u.EmailConfirmed)
|
||||||
|
.Select(u => new { u.Id, u.EmailNormalized, u.PasswordHash }).SingleOrDefaultAsync(ct);
|
||||||
|
|
||||||
// Neexistující účet a špatné heslo vracejí stejnou chybu – nelze tak zjišťovat registrované e-maily.
|
|
||||||
const string invalidCredentials = "Neplatný e-mail nebo heslo.";
|
const string invalidCredentials = "Neplatný e-mail nebo heslo.";
|
||||||
if (user is null)
|
var passwordHash = account?.EmailNormalized == normalized ? account.PasswordHash : null;
|
||||||
|
if (!passwordHasher.Verify(request.Password, passwordHash) || account is null)
|
||||||
throw new UnauthorizedException(invalidCredentials);
|
throw new UnauthorizedException(invalidCredentials);
|
||||||
if (user.IsLockedOut(now))
|
|
||||||
throw new UnauthorizedException("Účet je po opakovaných neúspěšných pokusech dočasně zamčen. Zkuste to později.");
|
|
||||||
|
|
||||||
if (!passwordHasher.Verify(request.Password, user.PasswordHash))
|
// Po ověření hesla ověříme pod zámkem, že se účet mezitím nezměnil.
|
||||||
{
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
user.RegisterFailedLogin(now);
|
var user = await db.LockUserAsync(account.Id, ct);
|
||||||
await db.SaveChangesAsync(ct);
|
if (user is not { IsActive: true, IsDeleted: false, EmailConfirmed: true } ||
|
||||||
|
user.EmailNormalized != normalized || user.PasswordHash != passwordHash)
|
||||||
throw new UnauthorizedException(invalidCredentials);
|
throw new UnauthorizedException(invalidCredentials);
|
||||||
}
|
|
||||||
|
|
||||||
if (!user.IsActive)
|
var response = await IssueTokenPairAsync(user, ct);
|
||||||
throw new ForbiddenException("Účet je deaktivován.");
|
await transaction.CommitAsync(ct);
|
||||||
if (!user.EmailConfirmed)
|
return response;
|
||||||
throw new ForbiddenException("E-mail ještě nebyl ověřen. Použijte odkaz z registračního e-mailu.");
|
|
||||||
|
|
||||||
user.RegisterSuccessfulLogin();
|
|
||||||
return await IssueTokenPairAsync(user, ct);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -95,17 +99,23 @@ public sealed class AuthService(
|
|||||||
var token = await tokens.ValidateAsync(request.RefreshToken, TokenType.Refresh)
|
var token = await tokens.ValidateAsync(request.RefreshToken, TokenType.Refresh)
|
||||||
?? throw new UnauthorizedException("Neplatný refresh token.");
|
?? throw new UnauthorizedException("Neplatný refresh token.");
|
||||||
|
|
||||||
if (!await revocation.TryConsumeAsync(token.Jti, TokenType.Refresh, ct))
|
// Stejný zámek účtu používá jeho správa, takže během zneplatnění nevznikne nová relace.
|
||||||
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
|
var user = await db.LockUserAsync(token.UserId, ct);
|
||||||
|
if (user is null || !user.IsActive || !user.EmailConfirmed)
|
||||||
|
throw new UnauthorizedException("Účet neexistuje, je deaktivován nebo nemá ověřený e-mail.");
|
||||||
|
|
||||||
|
if (await revocation.TryConsumeAsync(token.Jti, TokenType.Refresh, ct))
|
||||||
{
|
{
|
||||||
await revocation.RevokeAllAsync(token.UserId, RevokeReason.ReuseDetected, ct);
|
var response = await IssueTokenPairAsync(user, ct);
|
||||||
throw new UnauthorizedException("Refresh token už byl použit. Přihlaste se znovu.");
|
await transaction.CommitAsync(ct);
|
||||||
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
var user = await db.Users.SingleOrDefaultAsync(u => u.Id == token.UserId, ct);
|
var revoked = await StageDisconnectAsync(user.Id, RevokeReason.ReuseDetected, ct);
|
||||||
if (user is null || !user.IsActive)
|
await transaction.CommitAsync(ct);
|
||||||
throw new UnauthorizedException("Účet neexistuje nebo je deaktivován.");
|
revocation.Publish(revoked);
|
||||||
|
throw new UnauthorizedException("Refresh token už byl použit. Přihlaste se znovu.");
|
||||||
return await IssueTokenPairAsync(user, ct);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Odhlášení jednoho zařízení – zneplatní aktuální access token a k němu předaný refresh token.</summary>
|
/// <summary>Odhlášení jednoho zařízení – zneplatní aktuální access token a k němu předaný refresh token.</summary>
|
||||||
@@ -120,8 +130,15 @@ public sealed class AuthService(
|
|||||||
await revocation.RevokeAsync(currentUser.Id, jtis, RevokeReason.Logout, ct);
|
await revocation.RevokeAsync(currentUser.Id, jtis, RevokeReason.Logout, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task LogoutAllAsync(ICurrentUser currentUser, CancellationToken ct) =>
|
public async Task LogoutAllAsync(ICurrentUser currentUser, CancellationToken ct)
|
||||||
revocation.RevokeAllAsync(currentUser.Id, RevokeReason.LogoutAll, ct);
|
{
|
||||||
|
var userId = currentUser.Id;
|
||||||
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
|
await db.LockUserAsync(userId, ct);
|
||||||
|
var revoked = await StageDisconnectAsync(userId, RevokeReason.LogoutAll, ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
|
revocation.Publish(revoked);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Vždy uspěje, i pro neexistující e-mail – odpověď neprozradí, zda účet existuje.</summary>
|
/// <summary>Vždy uspěje, i pro neexistující e-mail – odpověď neprozradí, zda účet existuje.</summary>
|
||||||
public async Task ForgotPasswordAsync(ForgotPasswordRequest request, CancellationToken ct)
|
public async Task ForgotPasswordAsync(ForgotPasswordRequest request, CancellationToken ct)
|
||||||
@@ -145,12 +162,22 @@ public sealed class AuthService(
|
|||||||
{
|
{
|
||||||
await resetPasswordValidator.ValidateAndThrowAsync(request, ct);
|
await resetPasswordValidator.ValidateAndThrowAsync(request, ct);
|
||||||
|
|
||||||
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
var user = await ConsumeEmailTokenAsync(request.Token, TokenType.PasswordReset, ct);
|
var user = await ConsumeEmailTokenAsync(request.Token, TokenType.PasswordReset, ct);
|
||||||
|
var revoked = await StageDisconnectAsync(user.Id, RevokeReason.PasswordChanged, ct);
|
||||||
// Nejdřív zneplatnit stará přihlášení – kdyby uložení hesla selhalo, nic se tím neotevře.
|
|
||||||
await revocation.RevokeAllAsync(user.Id, RevokeReason.PasswordChanged, ct);
|
|
||||||
user.ChangePasswordHash(passwordHasher.Hash(request.NewPassword));
|
user.ChangePasswordHash(passwordHasher.Hash(request.NewPassword));
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
|
revocation.Publish(revoked);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Volat v transakci se zámkem účtu, který používá i registrace zařízení.
|
||||||
|
private async Task<List<TokenRevocationService.RevokedAccessToken>> StageDisconnectAsync(
|
||||||
|
int userId, RevokeReason reason, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var revoked = await revocation.StageRevokeAllAsync([userId], reason, ct);
|
||||||
|
await db.PushDevices.Where(device => device.UserId == userId).ExecuteDeleteAsync(ct);
|
||||||
|
return revoked;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<AuthResponse> IssueTokenPairAsync(User user, CancellationToken ct)
|
private async Task<AuthResponse> IssueTokenPairAsync(User user, CancellationToken ct)
|
||||||
@@ -166,21 +193,33 @@ public sealed class AuthService(
|
|||||||
UserDto.From(user));
|
UserDto.From(user));
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task SendEmailTokenAsync(User user, TokenType type, CancellationToken ct)
|
private async Task<bool> SendEmailTokenAsync(User user, TokenType type, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var issued = tokens.Issue(user, type);
|
IssuedToken issued;
|
||||||
|
await using (var transaction = await db.BeginWriteAsync(ct))
|
||||||
|
{
|
||||||
|
await db.LockUserAsync(user.Id, ct);
|
||||||
|
var current = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == user.Id, ct);
|
||||||
|
if (current is null || !current.IsActive || current.EmailNormalized != user.EmailNormalized ||
|
||||||
|
(type == TokenType.EmailConfirm && current.EmailConfirmed))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
issued = tokens.Issue(current, type);
|
||||||
db.AuthTokens.Add(issued.Record);
|
db.AuthTokens.Add(issued.Record);
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
|
}
|
||||||
|
|
||||||
var baseUrl = _registration.WebBaseUrl.TrimEnd('/');
|
var baseUrl = _registration.WebBaseUrl.TrimEnd('/');
|
||||||
var (subject, path, text) = type switch
|
var (subject, path, text) = type switch
|
||||||
{
|
{
|
||||||
TokenType.EmailConfirm => ("Ověření e-mailu", "confirm-email", "Pro dokončení registrace ověřte svůj e-mail"),
|
TokenType.EmailConfirm => ("Ověření e-mailu", "confirm-email", "Ověřte svůj e-mail a nastavte heslo k účtu"),
|
||||||
TokenType.PasswordReset => ("Obnova hesla", "reset-password", "Nové heslo nastavíte"),
|
TokenType.PasswordReset => ("Obnova hesla", "reset-password", "Nové heslo nastavíte"),
|
||||||
_ => throw new ArgumentOutOfRangeException(nameof(type)),
|
_ => throw new ArgumentOutOfRangeException(nameof(type)),
|
||||||
};
|
};
|
||||||
var link = $"{baseUrl}/{path}?token={Uri.EscapeDataString(issued.Token)}";
|
var link = $"{baseUrl}/{path}?token={Uri.EscapeDataString(issued.Token)}";
|
||||||
await emailSender.SendAsync(user.Email, subject, $"{text} na adrese:\n{link}", ct);
|
await emailSender.SendAsync(user.Email, subject, $"{text} na adrese:\n{link}", ct);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<User> ConsumeEmailTokenAsync(string token, TokenType type, CancellationToken ct)
|
private async Task<User> ConsumeEmailTokenAsync(string token, TokenType type, CancellationToken ct)
|
||||||
@@ -188,10 +227,11 @@ public sealed class AuthService(
|
|||||||
const string invalid = "Odkaz je neplatný, už byl použit nebo vypršel.";
|
const string invalid = "Odkaz je neplatný, už byl použit nebo vypršel.";
|
||||||
|
|
||||||
var validated = await tokens.ValidateAsync(token ?? "", type) ?? throw new BadRequestException(invalid);
|
var validated = await tokens.ValidateAsync(token ?? "", type) ?? throw new BadRequestException(invalid);
|
||||||
if (!await revocation.TryConsumeAsync(validated.Jti, type, ct))
|
var user = await db.LockUserAsync(validated.UserId, ct);
|
||||||
|
if (user is null || !user.IsActive || (type == TokenType.EmailConfirm && user.EmailConfirmed) ||
|
||||||
|
!await revocation.TryConsumeAsync(validated.Jti, type, ct))
|
||||||
throw new BadRequestException(invalid);
|
throw new BadRequestException(invalid);
|
||||||
|
|
||||||
return await db.Users.SingleOrDefaultAsync(u => u.Id == validated.UserId && u.IsActive, ct)
|
return user;
|
||||||
?? throw new BadRequestException(invalid);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -31,35 +31,37 @@ public sealed class TokenRevocationService(IAppDbContext db, IRevokedTokenStore
|
|||||||
.ExecuteUpdateAsync(s => s
|
.ExecuteUpdateAsync(s => s
|
||||||
.SetProperty(t => t.RevokedAt, now)
|
.SetProperty(t => t.RevokedAt, now)
|
||||||
.SetProperty(t => t.RevokeReason, reason), ct);
|
.SetProperty(t => t.RevokeReason, reason), ct);
|
||||||
await AddRevokedAccessTokensToStoreAsync(userId, now, ct);
|
Publish(await LoadRevokedAccessTokensAsync([userId], now, ct));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Zneplatní všechny platné tokeny uživatele – jeden UPDATE (kap. 10.1).</summary>
|
internal async Task<List<RevokedAccessToken>> StageRevokeAllAsync(int[] userIds, RevokeReason reason, CancellationToken ct)
|
||||||
public async Task RevokeAllAsync(int userId, RevokeReason reason, CancellationToken ct)
|
|
||||||
{
|
{
|
||||||
var now = Now();
|
var now = Now();
|
||||||
await db.AuthTokens
|
await db.AuthTokens
|
||||||
.Where(t => t.UserId == userId && t.RevokedAt == null)
|
.Where(t => userIds.Contains(t.UserId) && t.RevokedAt == null)
|
||||||
.ExecuteUpdateAsync(s => s
|
.ExecuteUpdateAsync(s => s
|
||||||
.SetProperty(t => t.RevokedAt, now)
|
.SetProperty(t => t.RevokedAt, now)
|
||||||
.SetProperty(t => t.RevokeReason, reason), ct);
|
.SetProperty(t => t.RevokeReason, reason), ct);
|
||||||
await AddRevokedAccessTokensToStoreAsync(userId, now, ct);
|
return await LoadRevokedAccessTokensAsync(userIds, now, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Access tokeny se ověřují proti paměťové evidenci, aby API nemuselo při každém
|
// Access tokeny se ověřují proti paměťové evidenci, aby API nemuselo při každém
|
||||||
// požadavku dotazovat DB. Zneplatněné řádky poznáme podle právě zapsaného revoked_at.
|
// požadavku dotazovat DB. Zneplatněné řádky poznáme podle právě zapsaného revoked_at.
|
||||||
private async Task AddRevokedAccessTokensToStoreAsync(int userId, DateTime revokedAt, CancellationToken ct)
|
private Task<List<RevokedAccessToken>> LoadRevokedAccessTokensAsync(int[] userIds, DateTime revokedAt, CancellationToken ct) =>
|
||||||
{
|
db.AuthTokens
|
||||||
var revoked = await db.AuthTokens
|
|
||||||
.AsNoTracking()
|
.AsNoTracking()
|
||||||
.Where(t => t.UserId == userId && t.TokenType == TokenType.Access && t.RevokedAt == revokedAt)
|
.Where(t => userIds.Contains(t.UserId) && t.TokenType == TokenType.Access && t.RevokedAt == revokedAt)
|
||||||
.Select(t => new { t.Jti, t.ExpiresAt })
|
.Select(t => new RevokedAccessToken(t.Jti, t.ExpiresAt))
|
||||||
.ToListAsync(ct);
|
.ToListAsync(ct);
|
||||||
|
|
||||||
|
internal void Publish(IEnumerable<RevokedAccessToken> revoked)
|
||||||
|
{
|
||||||
foreach (var token in revoked)
|
foreach (var token in revoked)
|
||||||
store.Add(token.Jti, token.ExpiresAt);
|
store.Add(token.Jti, token.ExpiresAt);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal sealed record RevokedAccessToken(string Jti, DateTime ExpiresAt);
|
||||||
|
|
||||||
// DATETIME(6) má přesnost na mikrosekundy – zaokrouhlením zajistíme, že hodnota
|
// DATETIME(6) má přesnost na mikrosekundy – zaokrouhlením zajistíme, že hodnota
|
||||||
// zapsaná do DB je stejná jako ta, podle které pak hledáme.
|
// zapsaná do DB je stejná jako ta, podle které pak hledáme.
|
||||||
private DateTime Now()
|
private DateTime Now()
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
|
using FluentValidation;
|
||||||
|
using FluentValidation.Results;
|
||||||
|
|
||||||
namespace Helpdesk.Application.Common;
|
namespace Helpdesk.Application.Common;
|
||||||
|
|
||||||
/// <summary>Chyba aplikační vrstvy; API ji převádí na ProblemDetails s odpovídajícím HTTP stavem.</summary>
|
/// <summary>Chyba aplikační vrstvy; API ji převádí na ProblemDetails s odpovídajícím HTTP stavem.</summary>
|
||||||
public abstract class AppException(string message) : Exception(message)
|
public abstract class AppException(string message, string? problemType = null) : Exception(message)
|
||||||
{
|
{
|
||||||
public abstract int StatusCode { get; }
|
public abstract int StatusCode { get; }
|
||||||
|
public string? ProblemType { get; } = problemType;
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class NotFoundException(string message) : AppException(message)
|
public sealed class NotFoundException(string message) : AppException(message)
|
||||||
@@ -11,7 +15,13 @@ public sealed class NotFoundException(string message) : AppException(message)
|
|||||||
public override int StatusCode => 404;
|
public override int StatusCode => 404;
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class ConflictException(string message) : AppException(message)
|
public sealed class ConflictException(string message, string? problemType = null) : AppException(message, problemType)
|
||||||
|
{
|
||||||
|
public override int StatusCode => 409;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class AccountVersionConflictException()
|
||||||
|
: AppException("Účet se mezitím změnil. Načtěte jeho aktuální údaje a změny zadejte znovu.", "urn:ntbug:account-version-conflict")
|
||||||
{
|
{
|
||||||
public override int StatusCode => 409;
|
public override int StatusCode => 409;
|
||||||
}
|
}
|
||||||
@@ -31,8 +41,13 @@ public sealed class BadRequestException(string message) : AppException(message)
|
|||||||
public override int StatusCode => 400;
|
public override int StatusCode => 400;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public sealed class FieldValidationException(string field, string message)
|
||||||
|
: ValidationException([new ValidationFailure(field, message)])
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
public sealed class EmailDeliveryException(string reason, bool retryable)
|
public sealed class EmailDeliveryException(string reason, bool retryable)
|
||||||
: AppException("E-mail se nepodařilo odeslat. Zkuste požadavek později.")
|
: AppException("E-mail se nepodařilo odeslat. Zkuste požadavek později.", "urn:ntbug:email-delivery-failed")
|
||||||
{
|
{
|
||||||
public string Reason { get; } = reason;
|
public string Reason { get; } = reason;
|
||||||
public bool Retryable { get; } = retryable;
|
public bool Retryable { get; } = retryable;
|
||||||
|
|||||||
@@ -80,10 +80,11 @@ public sealed partial class IssueService
|
|||||||
public async Task<IReadOnlyList<AssignableUserDto>> GetAssignableAsync(CancellationToken ct)
|
public async Task<IReadOnlyList<AssignableUserDto>> GetAssignableAsync(CancellationToken ct)
|
||||||
{
|
{
|
||||||
var actor = await GetActorAsync(ct);
|
var actor = await GetActorAsync(ct);
|
||||||
if (actor.Role != UserRole.Management)
|
if (!Issue.CanAssign(actor.Role))
|
||||||
throw new ForbiddenException("Přehled řešitelů je určen vedení.");
|
throw new ForbiddenException("Přehled řešitelů je určen vedení a administrátorům.");
|
||||||
|
|
||||||
var users = await db.Users.Where(u => u.IsActive && (u.Role == UserRole.Management || u.Role == UserRole.FacilityManager))
|
var users = await db.Users.Where(u => u.IsActive &&
|
||||||
|
(u.Role == UserRole.Management || u.Role == UserRole.FacilityManager || u.Role == UserRole.Admin))
|
||||||
.OrderBy(u => u.LastName).ThenBy(u => u.FirstName).ThenBy(u => u.Id)
|
.OrderBy(u => u.LastName).ThenBy(u => u.FirstName).ThenBy(u => u.Id)
|
||||||
.Select(u => new
|
.Select(u => new
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
|
using FluentValidation;
|
||||||
|
using FluentValidation.Results;
|
||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
using Helpdesk.Application.Common;
|
using Helpdesk.Application.Common;
|
||||||
using Helpdesk.Application.Notifications;
|
using Helpdesk.Application.Notifications;
|
||||||
@@ -44,16 +46,22 @@ public sealed partial class IssueService(
|
|||||||
CheckVersion(issue, request.RowVersion);
|
CheckVersion(issue, request.RowVersion);
|
||||||
var assignee = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == request.AssigneeId && u.IsActive, ct);
|
var assignee = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == request.AssigneeId && u.IsActive, ct);
|
||||||
if (assignee is null || !Issue.CanBeAssigned(assignee.Role))
|
if (assignee is null || !Issue.CanBeAssigned(assignee.Role))
|
||||||
throw new BadRequestException("Vyberte aktivního správce budov nebo člena vedení.");
|
throw new FieldValidationException(nameof(request.AssigneeId), "Vyberte aktivního správce budov, člena vedení nebo administrátora.");
|
||||||
if (issue.AssigneeId == assignee.Id)
|
if (issue.AssigneeId == assignee.Id)
|
||||||
throw new ConflictException("Závada je již přiřazena tomuto řešiteli.");
|
throw new ConflictException("Závada je již přiřazena tomuto řešiteli.");
|
||||||
|
|
||||||
IssuePriority? priority = request.Priority is null ? null : ParseCode<IssuePriority>(request.Priority);
|
IssuePriority? priority = null;
|
||||||
|
if (request.Priority is { } code)
|
||||||
|
{
|
||||||
|
if (!EnumCode.TryParse<IssuePriority>(code, out var selected))
|
||||||
|
throw new FieldValidationException(nameof(request.Priority), "Vyberte platnou prioritu.");
|
||||||
|
priority = selected;
|
||||||
|
}
|
||||||
var from = issue.Status;
|
var from = issue.Status;
|
||||||
issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority);
|
issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority);
|
||||||
AddEvent(issue, IssueEventType.Assigned, from, actor, assignee.FullName);
|
AddEvent(issue, IssueEventType.Assigned, from, actor, assignee.FullName);
|
||||||
await notificationWriter.ForIssueAsync(issue, actor.Id, [assignee.Id], NotificationType.IssueAssigned, "Závada byla přiřazena", ct);
|
await notificationWriter.ForIssueAsync(issue, actor.Id, [assignee.Id], NotificationType.IssueAssigned, "Závada byla přiřazena", ct);
|
||||||
if (from == IssueStatus.Received && issue.ReporterId != assignee.Id)
|
if (from != issue.Status && issue.ReporterId != assignee.Id)
|
||||||
await notificationWriter.ForIssueAsync(issue, actor.Id, [issue.ReporterId], NotificationType.IssueStatusChanged, "Závada byla přiřazena", ct);
|
await notificationWriter.ForIssueAsync(issue, actor.Id, [issue.ReporterId], NotificationType.IssueStatusChanged, "Závada byla přiřazena", ct);
|
||||||
|
|
||||||
await SaveAsync(ct);
|
await SaveAsync(ct);
|
||||||
@@ -65,8 +73,8 @@ public sealed partial class IssueService(
|
|||||||
var (issue, actor) = await LoadActionAsync(id, action, ct);
|
var (issue, actor) = await LoadActionAsync(id, action, ct);
|
||||||
CheckVersion(issue, version);
|
CheckVersion(issue, version);
|
||||||
note = action is IssueAction.Reopen or IssueAction.Reject
|
note = action is IssueAction.Reopen or IssueAction.Reject
|
||||||
? RequiredText(note, "Důvod", MaxTextBytes)
|
? RequiredText(note, nameof(IssueReasonRequest.Reason), "Důvod")
|
||||||
: OptionalText(note, "Poznámka", MaxTextBytes);
|
: OptionalText(note, nameof(VerifyIssueRequest.Note), "Poznámka");
|
||||||
|
|
||||||
var from = issue.Status;
|
var from = issue.Status;
|
||||||
issue.Transition(action, actor.Id, actor.Role, note);
|
issue.Transition(action, actor.Id, actor.Role, note);
|
||||||
@@ -87,7 +95,7 @@ public sealed partial class IssueService(
|
|||||||
public async Task<IssueEventDto> CommentAsync(int id, CommentRequest request, CancellationToken ct)
|
public async Task<IssueEventDto> CommentAsync(int id, CommentRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var (issue, actor) = await LoadActionAsync(id, IssueAction.Comment, ct);
|
var (issue, actor) = await LoadActionAsync(id, IssueAction.Comment, ct);
|
||||||
var text = RequiredText(request.Text, "Komentář", MaxTextBytes);
|
var text = RequiredText(request.Text, nameof(request.Text), "Komentář");
|
||||||
issue.RecordParticipation(IssueAction.Comment, actor.Id, actor.Role);
|
issue.RecordParticipation(IssueAction.Comment, actor.Id, actor.Role);
|
||||||
var entry = AddEvent(issue, IssueEventType.Commented, null, actor, text);
|
var entry = AddEvent(issue, IssueEventType.Commented, null, actor, text);
|
||||||
int[] recipients = issue.AssigneeId is int assignee ? [issue.ReporterId, assignee] : [issue.ReporterId];
|
int[] recipients = issue.AssigneeId is int assignee ? [issue.ReporterId, assignee] : [issue.ReporterId];
|
||||||
@@ -102,7 +110,7 @@ public sealed partial class IssueService(
|
|||||||
var (issue, actor) = await LoadActionAsync(id, IssueAction.AddAttachments, ct);
|
var (issue, actor) = await LoadActionAsync(id, IssueAction.AddAttachments, ct);
|
||||||
var uploads = await readUploads(ct);
|
var uploads = await readUploads(ct);
|
||||||
if (uploads.Length == 0)
|
if (uploads.Length == 0)
|
||||||
throw new BadRequestException("Vyberte alespoň jeden soubor.");
|
throw new FieldValidationException("files", "Vyberte alespoň jeden soubor.");
|
||||||
|
|
||||||
issue.RecordParticipation(IssueAction.AddAttachments, actor.Id, actor.Role);
|
issue.RecordParticipation(IssueAction.AddAttachments, actor.Id, actor.Role);
|
||||||
var attachments = await SaveWithAttachmentsAsync(issue, uploads, ct);
|
var attachments = await SaveWithAttachmentsAsync(issue, uploads, ct);
|
||||||
@@ -113,7 +121,7 @@ public sealed partial class IssueService(
|
|||||||
Issue issue, IReadOnlyList<AttachmentUpload> uploads, CancellationToken ct)
|
Issue issue, IReadOnlyList<AttachmentUpload> uploads, CancellationToken ct)
|
||||||
{
|
{
|
||||||
if (uploads.Count > AttachmentLimits.MaxFiles)
|
if (uploads.Count > AttachmentLimits.MaxFiles)
|
||||||
throw new BadRequestException("Najednou lze přiložit nejvýše pět souborů.");
|
throw new FieldValidationException("files", "Najednou lze přiložit nejvýše pět souborů.");
|
||||||
|
|
||||||
var attachments = new List<Attachment>(uploads.Count);
|
var attachments = new List<Attachment>(uploads.Count);
|
||||||
var saving = false;
|
var saving = false;
|
||||||
@@ -172,18 +180,31 @@ public sealed partial class IssueService(
|
|||||||
|
|
||||||
private async Task ValidateDetailsAsync(CreateIssueRequest request, Issue? original, CancellationToken ct)
|
private async Task ValidateDetailsAsync(CreateIssueRequest request, Issue? original, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var title = RequiredText(request.Title, "Název", MaxTextBytes);
|
var errors = new List<ValidationFailure>();
|
||||||
RequiredText(request.Description, "Popis", MaxTextBytes);
|
var title = request.Title?.Trim();
|
||||||
if (title.Length > 200 || request.LocationDetail?.Trim().Length > 255)
|
if (string.IsNullOrEmpty(title))
|
||||||
throw new BadRequestException("Název smí mít nejvýše 200 znaků a upřesnění místa 255 znaků.");
|
errors.Add(new(nameof(request.Title), "Zadejte název."));
|
||||||
|
else if (title.Length > 200)
|
||||||
|
errors.Add(new(nameof(request.Title), "Název může mít nejvýše 200 znaků."));
|
||||||
|
|
||||||
|
var description = request.Description?.Trim();
|
||||||
|
if (string.IsNullOrEmpty(description))
|
||||||
|
errors.Add(new(nameof(request.Description), "Popište závadu."));
|
||||||
|
else if (Encoding.UTF8.GetByteCount(description) > MaxTextBytes)
|
||||||
|
errors.Add(new(nameof(request.Description), "Popis je příliš dlouhý."));
|
||||||
|
if (request.LocationDetail?.Trim().Length > 255)
|
||||||
|
errors.Add(new(nameof(request.LocationDetail), "Upřesnění místa může mít nejvýše 255 znaků."));
|
||||||
|
|
||||||
if (original?.CategoryId != request.CategoryId &&
|
if (original?.CategoryId != request.CategoryId &&
|
||||||
!await db.IssueCategories.AnyAsync(c => c.Id == request.CategoryId && c.IsActive, ct))
|
!await db.IssueCategories.AnyAsync(c => c.Id == request.CategoryId && c.IsActive, ct))
|
||||||
throw new BadRequestException("Vyberte aktivní kategorii závady.");
|
errors.Add(new(nameof(request.CategoryId), "Vyberte aktivní kategorii závady."));
|
||||||
|
|
||||||
if (request.BuildingId is int buildingId && original?.BuildingId != buildingId &&
|
if (request.BuildingId is int buildingId && original?.BuildingId != buildingId &&
|
||||||
!await db.Buildings.AnyAsync(b => b.Id == buildingId && b.IsActive, ct))
|
!await db.Buildings.AnyAsync(b => b.Id == buildingId && b.IsActive, ct))
|
||||||
throw new BadRequestException("Vyberte aktivní budovu.");
|
errors.Add(new(nameof(request.BuildingId), "Vyberte aktivní budovu."));
|
||||||
|
|
||||||
|
if (errors.Count > 0)
|
||||||
|
throw new ValidationException(errors);
|
||||||
}
|
}
|
||||||
|
|
||||||
private IssueEvent AddEvent(Issue issue, IssueEventType type, IssueStatus? fromStatus, User actor, string? note)
|
private IssueEvent AddEvent(Issue issue, IssueEventType type, IssueStatus? fromStatus, User actor, string? note)
|
||||||
@@ -201,30 +222,33 @@ public sealed partial class IssueService(
|
|||||||
}
|
}
|
||||||
catch (DbUpdateConcurrencyException)
|
catch (DbUpdateConcurrencyException)
|
||||||
{
|
{
|
||||||
throw new ConflictException("Závada se mezitím změnila. Načtěte aktuální stav.");
|
throw IssueVersionConflict();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void CheckVersion(Issue issue, int? supplied)
|
private static void CheckVersion(Issue issue, int? supplied)
|
||||||
{
|
{
|
||||||
if (supplied is null or < 0)
|
if (supplied is null or < 0)
|
||||||
throw new BadRequestException("Zadejte platnou hodnotu rowVersion.");
|
throw new FieldValidationException(nameof(IssueVersionRequest.RowVersion), "Zadejte platnou verzi závady.");
|
||||||
if (issue.RowVersion != supplied)
|
if (issue.RowVersion != supplied)
|
||||||
throw new ConflictException("Závada se mezitím změnila. Načtěte aktuální stav.");
|
throw IssueVersionConflict();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static ConflictException IssueVersionConflict() =>
|
||||||
|
new("Závada se mezitím změnila. Načtěte aktuální stav.", "urn:ntbug:issue-version-conflict");
|
||||||
|
|
||||||
private const int MaxTextBytes = 65_535;
|
private const int MaxTextBytes = 65_535;
|
||||||
|
|
||||||
private static string RequiredText(string? input, string name, int maxBytes) =>
|
private static string RequiredText(string? input, string field, string label) =>
|
||||||
OptionalText(input, name, maxBytes) ?? throw new BadRequestException($"{name}: hodnota je povinná.");
|
OptionalText(input, field, label) ?? throw new FieldValidationException(field, $"{label}: hodnota je povinná.");
|
||||||
|
|
||||||
private static string? OptionalText(string? input, string name, int maxBytes)
|
private static string? OptionalText(string? input, string field, string label)
|
||||||
{
|
{
|
||||||
var text = input?.Trim();
|
var text = input?.Trim();
|
||||||
if (string.IsNullOrEmpty(text))
|
if (string.IsNullOrEmpty(text))
|
||||||
return null;
|
return null;
|
||||||
if (Encoding.UTF8.GetByteCount(text) > maxBytes)
|
if (Encoding.UTF8.GetByteCount(text) > MaxTextBytes)
|
||||||
throw new BadRequestException($"{name}: hodnota je příliš dlouhá.");
|
throw new FieldValidationException(field, $"{label}: hodnota je příliš dlouhá.");
|
||||||
return text;
|
return text;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ public sealed class NotificationService(IAppDbContext db, ICurrentUser currentUs
|
|||||||
private IQueryable<Notification> Inbox()
|
private IQueryable<Notification> Inbox()
|
||||||
{
|
{
|
||||||
var userId = currentUser.Id;
|
var userId = currentUser.Id;
|
||||||
return db.Notifications.Where(n => n.UserId == userId);
|
return NotificationVisibility.VisibleToRecipients(db).Where(n => n.UserId == userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Task<int> MarkUnreadRowsAsync(IQueryable<Notification> query, CancellationToken ct)
|
private Task<int> MarkUnreadRowsAsync(IQueryable<Notification> query, CancellationToken ct)
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
using Helpdesk.Application.Abstractions;
|
||||||
|
using Helpdesk.Domain.Issues;
|
||||||
|
using Helpdesk.Domain.Notifications;
|
||||||
|
using Helpdesk.Domain.Users;
|
||||||
|
|
||||||
|
namespace Helpdesk.Application.Notifications;
|
||||||
|
|
||||||
|
public static class NotificationVisibility
|
||||||
|
{
|
||||||
|
internal static readonly UserRole[] ReadAllIssueRoles = Enum.GetValues<UserRole>().Where(Issue.CanReadAll).ToArray();
|
||||||
|
|
||||||
|
public static IQueryable<Notification> VisibleToRecipients(IAppDbContext db) =>
|
||||||
|
db.Notifications.Where(n => db.Users.Any(u => u.Id == n.UserId && u.IsActive && !u.IsDeleted &&
|
||||||
|
(n.IssueId == null || ReadAllIssueRoles.Contains(u.Role) ||
|
||||||
|
db.Issues.Any(issue => issue.Id == n.IssueId && issue.ReporterId == u.Id))));
|
||||||
|
}
|
||||||
@@ -14,8 +14,7 @@ public sealed class NotificationWriter(IAppDbContext db, TimeProvider clock)
|
|||||||
CancellationToken ct)
|
CancellationToken ct)
|
||||||
{
|
{
|
||||||
var reporterId = issue.ReporterId;
|
var reporterId = issue.ReporterId;
|
||||||
var eligibleUsers = db.Users.Where(u =>
|
var eligibleUsers = db.Users.Where(u => u.Id == reporterId || NotificationVisibility.ReadAllIssueRoles.Contains(u.Role));
|
||||||
u.Id == reporterId || u.Role == UserRole.FacilityManager || u.Role == UserRole.Management);
|
|
||||||
return QueueAsync(eligibleUsers, actorId, recipientIds,
|
return QueueAsync(eligibleUsers, actorId, recipientIds,
|
||||||
id => new Notification(issue, id, type, title, issue.Title), ct);
|
id => new Notification(issue, id, type, title, issue.Title), ct);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,27 @@
|
|||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
using Helpdesk.Application.Common;
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Domain.Auth;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
namespace Helpdesk.Application.Notifications;
|
namespace Helpdesk.Application.Notifications;
|
||||||
|
|
||||||
public sealed class PushDeviceService(IAppDbContext db, ICurrentUser currentUser)
|
public sealed class PushDeviceService(IAppDbContext db, ICurrentUser currentUser)
|
||||||
{
|
{
|
||||||
public Task RegisterAsync(string token, CancellationToken ct)
|
public async Task RegisterAsync(string token, CancellationToken ct)
|
||||||
{
|
{
|
||||||
ValidateToken(token);
|
ValidateToken(token);
|
||||||
return db.RegisterPushDeviceAsync(currentUser.Id, token, ct);
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
|
var user = await db.LockUserAsync(currentUser.Id, ct);
|
||||||
|
if (user is not { IsActive: true, IsDeleted: false })
|
||||||
|
throw new UnauthorizedException("Účet není aktivní.");
|
||||||
|
|
||||||
|
// Po čekání na zámek mohl správce relaci odhlásit a odstranit všechna její zařízení.
|
||||||
|
if (!await db.AuthTokens.AnyAsync(t => t.Jti == currentUser.TokenId && t.UserId == user.Id &&
|
||||||
|
t.TokenType == TokenType.Access && t.RevokedAt == null, ct))
|
||||||
|
throw new UnauthorizedException("Přihlášení vypršelo. Přihlaste se znovu.");
|
||||||
|
|
||||||
|
await db.RegisterPushDeviceAsync(user.Id, token, ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task UnregisterAsync(string token, CancellationToken ct)
|
public async Task UnregisterAsync(string token, CancellationToken ct)
|
||||||
|
|||||||
@@ -28,20 +28,20 @@ public sealed partial class ProposalService(
|
|||||||
|
|
||||||
public async Task<ProposalDetail> EditAsync(int id, SaveProposalRequest request, CancellationToken ct)
|
public async Task<ProposalDetail> EditAsync(int id, SaveProposalRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
await GetActorRoleAsync(ct);
|
var role = await GetActorRoleAsync(ct);
|
||||||
var (title, description) = ValidateDetails(request);
|
var (title, description) = ValidateDetails(request);
|
||||||
await using (var transaction = await db.BeginProposalWriteAsync(ct))
|
await using (var transaction = await db.BeginWriteAsync(ct))
|
||||||
{
|
{
|
||||||
var proposal = await LockProposalAsync(id, ct);
|
var proposal = await LockProposalAsync(id, ct);
|
||||||
if (!proposal.IsAuthor(currentUser.Id))
|
if (!proposal.CanEditAs(currentUser.Id, role))
|
||||||
throw new ForbiddenException("Návrh může upravit jen jeho autor.");
|
throw new ForbiddenException("Návrh může upravit jeho autor nebo administrátor.");
|
||||||
if (!proposal.IsEditable)
|
if (!proposal.IsEditable)
|
||||||
throw new ConflictException("Návrh lze upravit jen ve stavu Podán.");
|
throw new ConflictException("Návrh lze upravit jen ve stavu Podán.");
|
||||||
|
|
||||||
if (proposal.CategoryId != request.CategoryId)
|
if (proposal.CategoryId != request.CategoryId)
|
||||||
await RequireActiveCategoryAsync(request.CategoryId, ct);
|
await RequireActiveCategoryAsync(request.CategoryId, ct);
|
||||||
|
|
||||||
proposal.Edit(currentUser.Id, title, description, request.CategoryId);
|
proposal.Edit(currentUser.Id, role, title, description, request.CategoryId);
|
||||||
AddEvent(proposal, ProposalEventType.Updated);
|
AddEvent(proposal, ProposalEventType.Updated);
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
await transaction.CommitAsync(ct);
|
await transaction.CommitAsync(ct);
|
||||||
@@ -53,8 +53,8 @@ public sealed partial class ProposalService(
|
|||||||
public async Task<ProposalDetail> ChangeStatusAsync(int id, ChangeProposalStatusRequest request, CancellationToken ct)
|
public async Task<ProposalDetail> ChangeStatusAsync(int id, ChangeProposalStatusRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var role = await GetActorRoleAsync(ct);
|
var role = await GetActorRoleAsync(ct);
|
||||||
if (role != UserRole.Management)
|
if (!Proposal.CanReview(role))
|
||||||
throw new ForbiddenException("Stav návrhu může změnit jen vedení školy.");
|
throw new ForbiddenException("Stav návrhu může změnit vedení školy nebo administrátor.");
|
||||||
|
|
||||||
var target = ParseStatus(request.Status);
|
var target = ParseStatus(request.Status);
|
||||||
var note = string.IsNullOrWhiteSpace(request.Note) ? null : request.Note.Trim();
|
var note = string.IsNullOrWhiteSpace(request.Note) ? null : request.Note.Trim();
|
||||||
@@ -63,7 +63,7 @@ public sealed partial class ProposalService(
|
|||||||
if (note is not null && Encoding.UTF8.GetByteCount(note) > MaxTextBytes)
|
if (note is not null && Encoding.UTF8.GetByteCount(note) > MaxTextBytes)
|
||||||
throw new BadRequestException("Vyjádření je příliš dlouhé.");
|
throw new BadRequestException("Vyjádření je příliš dlouhé.");
|
||||||
|
|
||||||
await using (var transaction = await db.BeginProposalWriteAsync(ct))
|
await using (var transaction = await db.BeginWriteAsync(ct))
|
||||||
{
|
{
|
||||||
var proposal = await LockProposalAsync(id, ct);
|
var proposal = await LockProposalAsync(id, ct);
|
||||||
var previous = proposal.Status;
|
var previous = proposal.Status;
|
||||||
@@ -94,7 +94,7 @@ public sealed partial class ProposalService(
|
|||||||
{
|
{
|
||||||
await GetActorRoleAsync(ct);
|
await GetActorRoleAsync(ct);
|
||||||
var actorId = currentUser.Id;
|
var actorId = currentUser.Id;
|
||||||
await using var transaction = await db.BeginProposalWriteAsync(ct);
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
var proposal = await LockProposalAsync(id, ct);
|
var proposal = await LockProposalAsync(id, ct);
|
||||||
if (proposal.IsAuthor(actorId))
|
if (proposal.IsAuthor(actorId))
|
||||||
throw new ForbiddenException("Autor nemůže hlasovat o vlastním návrhu.");
|
throw new ForbiddenException("Autor nemůže hlasovat o vlastním návrhu.");
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using FluentValidation;
|
using FluentValidation;
|
||||||
|
using Helpdesk.Application.Auth;
|
||||||
using Helpdesk.Domain;
|
using Helpdesk.Domain;
|
||||||
using Helpdesk.Domain.Users;
|
using Helpdesk.Domain.Users;
|
||||||
|
|
||||||
@@ -18,7 +19,7 @@ public sealed record UserDto(
|
|||||||
user.Id, user.Email, user.FirstName, user.LastName, user.Phone, user.Role.ToCode(), user.EmailNotificationsEnabled);
|
user.Id, user.Email, user.FirstName, user.LastName, user.Phone, user.Role.ToCode(), user.EmailNotificationsEnabled);
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed record UpdateProfileRequest(string FirstName, string LastName, string? Phone, bool EmailNotificationsEnabled);
|
public sealed record UpdateProfileRequest(string FirstName, string LastName, string? Phone, bool? EmailNotificationsEnabled);
|
||||||
|
|
||||||
public sealed class UpdateProfileRequestValidator : AbstractValidator<UpdateProfileRequest>
|
public sealed class UpdateProfileRequestValidator : AbstractValidator<UpdateProfileRequest>
|
||||||
{
|
{
|
||||||
@@ -28,6 +29,7 @@ public sealed class UpdateProfileRequestValidator : AbstractValidator<UpdateProf
|
|||||||
RuleFor(x => x.LastName).NotEmpty().MaximumLength(100);
|
RuleFor(x => x.LastName).NotEmpty().MaximumLength(100);
|
||||||
RuleFor(x => x.Phone).MaximumLength(30).Matches(@"^\+?[0-9 ]+$").When(x => !string.IsNullOrWhiteSpace(x.Phone))
|
RuleFor(x => x.Phone).MaximumLength(30).Matches(@"^\+?[0-9 ]+$").When(x => !string.IsNullOrWhiteSpace(x.Phone))
|
||||||
.WithMessage("Telefon smí obsahovat jen číslice, mezery a úvodní +.");
|
.WithMessage("Telefon smí obsahovat jen číslice, mezery a úvodní +.");
|
||||||
|
RuleFor(x => x.EmailNotificationsEnabled).NotNull().WithMessage("Uveďte, zda mají být e-mailové notifikace zapnuté.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,4 +46,38 @@ public sealed record AdminUserDto(
|
|||||||
|
|
||||||
public sealed record ChangeRoleRequest(string Role);
|
public sealed record ChangeRoleRequest(string Role);
|
||||||
|
|
||||||
public sealed record SetActiveRequest(bool IsActive);
|
public sealed record SetActiveRequest(bool? IsActive);
|
||||||
|
|
||||||
|
public sealed class SetActiveRequestValidator : AbstractValidator<SetActiveRequest>
|
||||||
|
{
|
||||||
|
public SetActiveRequestValidator()
|
||||||
|
{
|
||||||
|
RuleFor(x => x.IsActive).NotNull().WithMessage("Uveďte, zda má být účet aktivní.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record AdminUserDetailsDto(int Id, string Email, string FirstName, string LastName, string? Phone,
|
||||||
|
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, int RowVersion,
|
||||||
|
bool? VerificationEmailSent = null)
|
||||||
|
{
|
||||||
|
public static AdminUserDetailsDto From(User user) => new(user.Id, user.Email, user.FirstName, user.LastName, user.Phone,
|
||||||
|
user.Role.ToCode(), user.IsActive, user.EmailConfirmed, user.EmailNotificationsEnabled, user.RowVersion);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record SaveAdminUserRequest(string Email, string FirstName, string LastName, string? Phone,
|
||||||
|
string Role, bool? IsActive, bool? EmailConfirmed, bool? EmailNotificationsEnabled, string? Password, int? RowVersion = null);
|
||||||
|
|
||||||
|
public sealed class SaveAdminUserRequestValidator : AbstractValidator<SaveAdminUserRequest>
|
||||||
|
{
|
||||||
|
public SaveAdminUserRequestValidator()
|
||||||
|
{
|
||||||
|
RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(254);
|
||||||
|
RuleFor(x => x.Role).NotEmpty();
|
||||||
|
RuleFor(x => x.IsActive).NotNull().WithMessage("Uveďte, zda má být účet aktivní.");
|
||||||
|
RuleFor(x => x.EmailConfirmed).NotNull().WithMessage("Uveďte, zda má být e-mail ověřený.");
|
||||||
|
RuleFor(x => x.EmailNotificationsEnabled).NotNull().WithMessage("Uveďte, zda mají být e-mailové notifikace zapnuté.");
|
||||||
|
RuleFor(x => x.Password).ValidPassword().When(x => x.Password is not null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record BulkAdminUsersRequest(int[] UserIds, string Action, string? Role);
|
||||||
@@ -13,7 +13,11 @@ namespace Helpdesk.Application.Users;
|
|||||||
public sealed class UserService(
|
public sealed class UserService(
|
||||||
IAppDbContext db,
|
IAppDbContext db,
|
||||||
TokenRevocationService revocation,
|
TokenRevocationService revocation,
|
||||||
IValidator<UpdateProfileRequest> profileValidator)
|
AuthService auth,
|
||||||
|
IValidator<UpdateProfileRequest> profileValidator,
|
||||||
|
IValidator<SaveAdminUserRequest> adminUserValidator,
|
||||||
|
IValidator<SetActiveRequest> activeValidator,
|
||||||
|
IPasswordHasher passwordHasher)
|
||||||
{
|
{
|
||||||
public async Task<UserDto> GetMeAsync(ICurrentUser currentUser, CancellationToken ct) =>
|
public async Task<UserDto> GetMeAsync(ICurrentUser currentUser, CancellationToken ct) =>
|
||||||
UserDto.From(await GetAsync(currentUser.Id, ct));
|
UserDto.From(await GetAsync(currentUser.Id, ct));
|
||||||
@@ -22,9 +26,13 @@ public sealed class UserService(
|
|||||||
{
|
{
|
||||||
await profileValidator.ValidateAndThrowAsync(request, ct);
|
await profileValidator.ValidateAndThrowAsync(request, ct);
|
||||||
|
|
||||||
var user = await GetAsync(currentUser.Id, ct);
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
user.UpdateProfile(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled);
|
var user = RequireAccount(await db.LockUserAsync(currentUser.Id, ct), currentUser.Id);
|
||||||
|
if (!user.IsActive)
|
||||||
|
throw new UnauthorizedException("Účet není aktivní.");
|
||||||
|
user.UpdateProfile(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled!.Value);
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
return UserDto.From(user);
|
return UserDto.From(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,7 +41,7 @@ public sealed class UserService(
|
|||||||
page = Math.Max(page, 1);
|
page = Math.Max(page, 1);
|
||||||
pageSize = Math.Clamp(pageSize, 1, 100);
|
pageSize = Math.Clamp(pageSize, 1, 100);
|
||||||
|
|
||||||
var query = db.Users.AsNoTracking();
|
var query = db.Users.AsNoTracking().Where(u => !u.IsDeleted);
|
||||||
if (!string.IsNullOrWhiteSpace(q))
|
if (!string.IsNullOrWhiteSpace(q))
|
||||||
{
|
{
|
||||||
var term = q.Trim();
|
var term = q.Trim();
|
||||||
@@ -46,9 +54,13 @@ public sealed class UserService(
|
|||||||
}
|
}
|
||||||
|
|
||||||
var total = await query.CountAsync(ct);
|
var total = await query.CountAsync(ct);
|
||||||
|
var offset = (long)(page - 1) * pageSize;
|
||||||
|
if (offset >= total)
|
||||||
|
return new PagedResult<AdminUserDto>([], total, page, pageSize);
|
||||||
|
|
||||||
var users = await query
|
var users = await query
|
||||||
.OrderBy(u => u.LastName).ThenBy(u => u.FirstName).ThenBy(u => u.Id)
|
.OrderBy(u => u.LastName).ThenBy(u => u.FirstName).ThenBy(u => u.Id)
|
||||||
.Skip((page - 1) * pageSize).Take(pageSize)
|
.Skip((int)offset).Take(pageSize)
|
||||||
.ToListAsync(ct);
|
.ToListAsync(ct);
|
||||||
|
|
||||||
var items = users
|
var items = users
|
||||||
@@ -58,39 +70,214 @@ public sealed class UserService(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Změna role zneplatní tokeny uživatele – po novém přihlášení dostane token s novou rolí.</summary>
|
/// <summary>Změna role zneplatní tokeny uživatele – po novém přihlášení dostane token s novou rolí.</summary>
|
||||||
public async Task ChangeRoleAsync(ICurrentUser admin, int userId, ChangeRoleRequest request, CancellationToken ct)
|
public Task ChangeRoleAsync(ICurrentUser admin, int userId, ChangeRoleRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var role = ParseRole(request.Role);
|
var role = ParseRole(request.Role);
|
||||||
if (userId == admin.Id)
|
return UpdateAccountsAsync(admin, [userId], user => ChangeRole(user, role), ct);
|
||||||
throw new ConflictException("Administrátor nemůže změnit roli sám sobě.");
|
|
||||||
|
|
||||||
var user = await GetAsync(userId, ct);
|
|
||||||
if (user.Role == role)
|
|
||||||
return;
|
|
||||||
|
|
||||||
await revocation.RevokeAllAsync(user.Id, RevokeReason.RoleChanged, ct);
|
|
||||||
user.ChangeRole(role);
|
|
||||||
await db.SaveChangesAsync(ct);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task SetActiveAsync(ICurrentUser admin, int userId, SetActiveRequest request, CancellationToken ct)
|
public async Task SetActiveAsync(ICurrentUser admin, int userId, SetActiveRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
if (userId == admin.Id && !request.IsActive)
|
await activeValidator.ValidateAndThrowAsync(request, ct);
|
||||||
throw new ConflictException("Administrátor nemůže deaktivovat sám sebe.");
|
var isActive = request.IsActive!.Value;
|
||||||
|
if (userId == admin.Id && isActive)
|
||||||
var user = await GetAsync(userId, ct);
|
|
||||||
if (user.IsActive == request.IsActive)
|
|
||||||
return;
|
return;
|
||||||
|
await UpdateAccountsAsync(admin, [userId], user => SetActive(user, isActive), ct);
|
||||||
|
}
|
||||||
|
|
||||||
if (!request.IsActive)
|
public async Task<AdminUserDetailsDto> GetAdminAsync(int id, CancellationToken ct) =>
|
||||||
await revocation.RevokeAllAsync(user.Id, RevokeReason.AccountDeactivated, ct);
|
AdminUserDetailsDto.From(await GetAsync(id, ct));
|
||||||
user.SetActive(request.IsActive);
|
|
||||||
|
public async Task<AdminUserDetailsDto> CreateAsync(ICurrentUser admin, SaveAdminUserRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await ValidateAsync(request, ct);
|
||||||
|
var confirmed = request.EmailConfirmed!.Value;
|
||||||
|
if (confirmed && string.IsNullOrWhiteSpace(request.Password))
|
||||||
|
throw new BadRequestException("Při ručním ověření e-mailu zadejte počáteční heslo.");
|
||||||
|
var role = ParseRole(request.Role);
|
||||||
|
var passwordHash = confirmed ? passwordHasher.Hash(request.Password!) : "";
|
||||||
|
var user = User.Create(request.Email, passwordHash, request.FirstName, request.LastName, role);
|
||||||
|
ApplyProfile(user, request, confirmed);
|
||||||
|
user.SetActive(request.IsActive!.Value);
|
||||||
|
|
||||||
|
await using (var transaction = await db.BeginWriteAsync(ct))
|
||||||
|
{
|
||||||
|
RequireAdministrator(await db.LockUserAsync(admin.Id, ct));
|
||||||
|
db.Users.Add(user);
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
|
}
|
||||||
|
return await AccountSavedAsync(user, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<AdminUserDetailsDto?> UpdateAsync(ICurrentUser admin, int userId, SaveAdminUserRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await ValidateAsync(request, ct);
|
||||||
|
if (request.RowVersion is null or < 0)
|
||||||
|
throw new BadRequestException("Zadejte platnou verzi účtu (rowVersion).");
|
||||||
|
|
||||||
|
var role = ParseRole(request.Role);
|
||||||
|
var passwordHash = request.Password is null ? null : passwordHasher.Hash(request.Password);
|
||||||
|
var sendLink = false;
|
||||||
|
var updated = await UpdateAccountsAsync(admin, [userId], user =>
|
||||||
|
{
|
||||||
|
if (user.RowVersion != request.RowVersion)
|
||||||
|
throw new AccountVersionConflictException();
|
||||||
|
|
||||||
|
var emailChanged = user.EmailNormalized != User.NormalizeEmail(request.Email);
|
||||||
|
var confirmed = !emailChanged && request.EmailConfirmed!.Value;
|
||||||
|
if (confirmed && passwordHash is null && user.PasswordHash.Length == 0)
|
||||||
|
throw new BadRequestException("Při ručním ověření e-mailu zadejte počáteční heslo.");
|
||||||
|
var confirmationChanged = user.EmailConfirmed != confirmed;
|
||||||
|
var roleChanged = ChangeRole(user, role);
|
||||||
|
var activeChanged = SetActive(user, request.IsActive!.Value);
|
||||||
|
ApplyProfile(user, request, confirmed);
|
||||||
|
sendLink = emailChanged && user.IsActive;
|
||||||
|
if (passwordHash is not null)
|
||||||
|
{
|
||||||
|
user.ChangePasswordHash(passwordHash);
|
||||||
|
return RevokeReason.PasswordChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (emailChanged || confirmationChanged)
|
||||||
|
return RevokeReason.LogoutAll;
|
||||||
|
return roleChanged ?? activeChanged;
|
||||||
|
}, ct);
|
||||||
|
return sendLink ? await AccountSavedAsync(updated.Single(), ct) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task SendEmailConfirmationAsync(int userId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var user = await GetAsync(userId, ct);
|
||||||
|
if (!user.IsActive || user.EmailConfirmed)
|
||||||
|
throw new ConflictException("Ověřovací odkaz lze poslat pouze aktivnímu účtu s neověřeným e-mailem.");
|
||||||
|
|
||||||
|
if (!await auth.SendEmailConfirmationAsync(user, ct))
|
||||||
|
throw new ConflictException("Účet se mezitím změnil. Obnovte jeho detail.");
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task DeleteAsync(ICurrentUser admin, int userId, CancellationToken ct) =>
|
||||||
|
UpdateAccountsAsync(admin, [userId], Delete, ct);
|
||||||
|
|
||||||
|
public Task BulkUpdateAsync(ICurrentUser admin, BulkAdminUsersRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (request.UserIds is not { Length: >= 1 and <= 100 } || request.UserIds.Any(id => id <= 0))
|
||||||
|
throw new BadRequestException("Vyberte 1 až 100 uživatelů.");
|
||||||
|
|
||||||
|
var role = request.Action == "role" ? ParseRole(request.Role ?? "") : default;
|
||||||
|
return request.Action switch
|
||||||
|
{
|
||||||
|
"activate" => UpdateAccountsAsync(admin, request.UserIds, user => SetActive(user, true), ct),
|
||||||
|
"deactivate" => UpdateAccountsAsync(admin, request.UserIds, user => SetActive(user, false), ct),
|
||||||
|
"role" => UpdateAccountsAsync(admin, request.UserIds, user => ChangeRole(user, role), ct),
|
||||||
|
"delete" => UpdateAccountsAsync(admin, request.UserIds, Delete, ct),
|
||||||
|
_ => throw new BadRequestException("Vyberte platnou hromadnou akci."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<List<User>> UpdateAccountsAsync(ICurrentUser admin, int[] ids, Func<User, RevokeReason?> update, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (ids.Contains(admin.Id))
|
||||||
|
throw new ConflictException("Vlastní účet upravujte v nastavení profilu.");
|
||||||
|
|
||||||
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
|
var users = new List<User>();
|
||||||
|
// Stejné pořadí při překryvu výběrů. Zámek správce brání souběžnému odebrání role.
|
||||||
|
foreach (var id in ids.Append(admin.Id).Distinct().Order())
|
||||||
|
{
|
||||||
|
var user = await db.LockUserAsync(id, ct);
|
||||||
|
if (id == admin.Id)
|
||||||
|
RequireAdministrator(user);
|
||||||
|
else
|
||||||
|
users.Add(RequireAccount(user, id));
|
||||||
|
}
|
||||||
|
|
||||||
|
var changes = new List<(int Id, RevokeReason Reason)>();
|
||||||
|
foreach (var user in users)
|
||||||
|
{
|
||||||
|
if (update(user) is { } reason)
|
||||||
|
changes.Add((user.Id, reason));
|
||||||
|
}
|
||||||
|
|
||||||
|
var revoked = new List<TokenRevocationService.RevokedAccessToken>();
|
||||||
|
foreach (var group in changes.GroupBy(change => change.Reason))
|
||||||
|
revoked.AddRange(await revocation.StageRevokeAllAsync(group.Select(change => change.Id).ToArray(), group.Key, ct));
|
||||||
|
var disconnectedIds = users.Where(user => user.IsDeleted).Select(user => user.Id)
|
||||||
|
.Concat(changes.Where(change => change.Reason == RevokeReason.PasswordChanged).Select(change => change.Id))
|
||||||
|
.ToArray();
|
||||||
|
if (disconnectedIds.Length > 0)
|
||||||
|
await db.PushDevices.Where(device => disconnectedIds.Contains(device.UserId)).ExecuteDeleteAsync(ct);
|
||||||
|
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
|
revocation.Publish(revoked);
|
||||||
|
return users;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<AdminUserDetailsDto> AccountSavedAsync(User user, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var result = AdminUserDetailsDto.From(user);
|
||||||
|
if (!user.IsActive || user.EmailConfirmed)
|
||||||
|
return result;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return result with { VerificationEmailSent = await auth.SendEmailConfirmationAsync(user, ct) };
|
||||||
|
}
|
||||||
|
catch (EmailDeliveryException)
|
||||||
|
{
|
||||||
|
// Účet je již uložený a ověřovací e-mail lze poslat znovu.
|
||||||
|
return result with { VerificationEmailSent = false };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ValidateAsync(SaveAdminUserRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await adminUserValidator.ValidateAndThrowAsync(request, ct);
|
||||||
|
await profileValidator.ValidateAndThrowAsync(
|
||||||
|
new UpdateProfileRequest(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled), ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ApplyProfile(User user, SaveAdminUserRequest request, bool confirmed)
|
||||||
|
{
|
||||||
|
user.UpdateProfile(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled!.Value);
|
||||||
|
user.ChangeEmail(request.Email);
|
||||||
|
user.SetEmailConfirmed(confirmed);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static RevokeReason? ChangeRole(User user, UserRole role)
|
||||||
|
{
|
||||||
|
if (user.Role == role)
|
||||||
|
return null;
|
||||||
|
user.ChangeRole(role);
|
||||||
|
return RevokeReason.RoleChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static RevokeReason? SetActive(User user, bool active)
|
||||||
|
{
|
||||||
|
var wasActive = user.IsActive;
|
||||||
|
user.SetActive(active);
|
||||||
|
return wasActive && !active ? RevokeReason.AccountDeactivated : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static RevokeReason? Delete(User user)
|
||||||
|
{
|
||||||
|
user.Delete();
|
||||||
|
return RevokeReason.AccountDeactivated;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<User> GetAsync(int id, CancellationToken ct) =>
|
private async Task<User> GetAsync(int id, CancellationToken ct) =>
|
||||||
await db.Users.SingleOrDefaultAsync(u => u.Id == id, ct)
|
RequireAccount(await db.Users.SingleOrDefaultAsync(u => u.Id == id, ct), id);
|
||||||
?? throw new NotFoundException($"Uživatel {id} neexistuje.");
|
|
||||||
|
private static User RequireAccount(User? user, int id) => user is { IsDeleted: false }
|
||||||
|
? user
|
||||||
|
: throw new NotFoundException($"Uživatel {id} neexistuje.");
|
||||||
|
|
||||||
|
private static void RequireAdministrator(User? user)
|
||||||
|
{
|
||||||
|
if (user is not { Role: UserRole.Admin, IsActive: true, IsDeleted: false })
|
||||||
|
throw new ForbiddenException("K této akci potřebujete aktivní účet administrátora.");
|
||||||
|
}
|
||||||
|
|
||||||
private static UserRole ParseRole(string code) =>
|
private static UserRole ParseRole(string code) =>
|
||||||
EnumCode.TryParse<UserRole>(code, out var role)
|
EnumCode.TryParse<UserRole>(code, out var role)
|
||||||
|
|||||||
@@ -31,9 +31,11 @@ public sealed class Issue : IHasCreatedAt
|
|||||||
public int RowVersion { get; private set; }
|
public int RowVersion { get; private set; }
|
||||||
public DateTime CreatedAt { get; set; }
|
public DateTime CreatedAt { get; set; }
|
||||||
|
|
||||||
public static bool CanReadAll(UserRole role) => role is UserRole.FacilityManager or UserRole.Management;
|
public static bool CanReadAll(UserRole role) => role == UserRole.FacilityManager || CanAssign(role);
|
||||||
|
|
||||||
public static bool CanBeAssigned(UserRole role) => role is UserRole.FacilityManager or UserRole.Management;
|
public static bool CanAssign(UserRole role) => role is UserRole.Management or UserRole.Admin;
|
||||||
|
|
||||||
|
public static bool CanBeAssigned(UserRole role) => role is UserRole.FacilityManager or UserRole.Management or UserRole.Admin;
|
||||||
|
|
||||||
public bool CanRead(int userId, UserRole role) => CanReadAll(role) || ReporterId == userId;
|
public bool CanRead(int userId, UserRole role) => CanReadAll(role) || ReporterId == userId;
|
||||||
|
|
||||||
@@ -42,14 +44,15 @@ public sealed class Issue : IHasCreatedAt
|
|||||||
var reporter = ReporterId == actorId;
|
var reporter = ReporterId == actorId;
|
||||||
var assignee = AssigneeId == actorId && CanBeAssigned(role);
|
var assignee = AssigneeId == actorId && CanBeAssigned(role);
|
||||||
var management = role == UserRole.Management;
|
var management = role == UserRole.Management;
|
||||||
|
var admin = role == UserRole.Admin;
|
||||||
|
|
||||||
var authorized = action switch
|
var authorized = action switch
|
||||||
{
|
{
|
||||||
IssueAction.Edit or IssueAction.Confirm or IssueAction.Reopen => reporter,
|
IssueAction.Edit or IssueAction.Confirm or IssueAction.Reopen => admin || reporter,
|
||||||
IssueAction.Assign => management,
|
IssueAction.Assign => CanAssign(role),
|
||||||
IssueAction.StartWork or IssueAction.SubmitForVerification => assignee,
|
IssueAction.StartWork or IssueAction.SubmitForVerification => admin || assignee,
|
||||||
IssueAction.Reject => assignee || (management && AssigneeId is null),
|
IssueAction.Reject => admin || assignee || (management && AssigneeId is null),
|
||||||
IssueAction.Comment or IssueAction.AddAttachments => reporter || assignee,
|
IssueAction.Comment or IssueAction.AddAttachments => admin || reporter || assignee,
|
||||||
_ => false,
|
_ => false,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -64,8 +67,8 @@ public sealed class Issue : IHasCreatedAt
|
|||||||
IssueAction.SubmitForVerification => Status == IssueStatus.InProgress,
|
IssueAction.SubmitForVerification => Status == IssueStatus.InProgress,
|
||||||
IssueAction.Confirm or IssueAction.Reopen => Status == IssueStatus.PendingVerification,
|
IssueAction.Confirm or IssueAction.Reopen => Status == IssueStatus.PendingVerification,
|
||||||
IssueAction.Reject => Status == IssueStatus.Received
|
IssueAction.Reject => Status == IssueStatus.Received
|
||||||
? management
|
? admin || management
|
||||||
: assignee && Status is (IssueStatus.Assigned or IssueStatus.InProgress),
|
: (admin || assignee) && Status is (IssueStatus.Assigned or IssueStatus.InProgress),
|
||||||
IssueAction.Comment or IssueAction.AddAttachments => Status is not (IssueStatus.Resolved or IssueStatus.Rejected),
|
IssueAction.Comment or IssueAction.AddAttachments => Status is not (IssueStatus.Resolved or IssueStatus.Rejected),
|
||||||
_ => false,
|
_ => false,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -26,9 +26,11 @@ public sealed class Proposal : IHasCreatedAt
|
|||||||
public bool IsAuthor(int userId) => AuthorId == userId;
|
public bool IsAuthor(int userId) => AuthorId == userId;
|
||||||
public bool IsEditable => Status == ProposalStatus.Submitted;
|
public bool IsEditable => Status == ProposalStatus.Submitted;
|
||||||
public bool IsVotingOpen => Status is ProposalStatus.Submitted or ProposalStatus.UnderReview;
|
public bool IsVotingOpen => Status is ProposalStatus.Submitted or ProposalStatus.UnderReview;
|
||||||
public bool CanEdit(int userId) => IsAuthor(userId) && IsEditable;
|
public bool CanEditAs(int userId, UserRole role) => role == UserRole.Admin || IsAuthor(userId);
|
||||||
public bool CanVote(int userId) => !IsAuthor(userId) && IsVotingOpen;
|
public bool CanVote(int userId) => !IsAuthor(userId) && IsVotingOpen;
|
||||||
|
|
||||||
|
public static bool CanReview(UserRole role) => role is UserRole.Management or UserRole.Admin;
|
||||||
|
|
||||||
public bool CanTransitionTo(ProposalStatus target) => Status switch
|
public bool CanTransitionTo(ProposalStatus target) => Status switch
|
||||||
{
|
{
|
||||||
ProposalStatus.Submitted => target is ProposalStatus.UnderReview or ProposalStatus.Accepted or ProposalStatus.Rejected,
|
ProposalStatus.Submitted => target is ProposalStatus.UnderReview or ProposalStatus.Accepted or ProposalStatus.Rejected,
|
||||||
@@ -37,9 +39,9 @@ public sealed class Proposal : IHasCreatedAt
|
|||||||
_ => false,
|
_ => false,
|
||||||
};
|
};
|
||||||
|
|
||||||
public void Edit(int actorId, string title, string description, int categoryId)
|
public void Edit(int actorId, UserRole role, string title, string description, int categoryId)
|
||||||
{
|
{
|
||||||
if (!CanEdit(actorId))
|
if (!CanEditAs(actorId, role) || !IsEditable)
|
||||||
throw new InvalidOperationException("Návrh nelze upravit.");
|
throw new InvalidOperationException("Návrh nelze upravit.");
|
||||||
|
|
||||||
SetDetails(title, description, categoryId);
|
SetDetails(title, description, categoryId);
|
||||||
@@ -47,7 +49,7 @@ public sealed class Proposal : IHasCreatedAt
|
|||||||
|
|
||||||
public void ChangeStatus(ProposalStatus target, UserRole role, string? note)
|
public void ChangeStatus(ProposalStatus target, UserRole role, string? note)
|
||||||
{
|
{
|
||||||
if (role != UserRole.Management || !CanTransitionTo(target))
|
if (!CanReview(role) || !CanTransitionTo(target))
|
||||||
throw new InvalidOperationException("Stav návrhu nelze změnit.");
|
throw new InvalidOperationException("Stav návrhu nelze změnit.");
|
||||||
if (target == ProposalStatus.Rejected && string.IsNullOrWhiteSpace(note))
|
if (target == ProposalStatus.Rejected && string.IsNullOrWhiteSpace(note))
|
||||||
throw new ArgumentException("Zamítnutí vyžaduje vyjádření.", nameof(note));
|
throw new ArgumentException("Zamítnutí vyžaduje vyjádření.", nameof(note));
|
||||||
|
|||||||
@@ -6,9 +6,6 @@ namespace Helpdesk.Domain.Users;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class User : IHasCreatedAt
|
public sealed class User : IHasCreatedAt
|
||||||
{
|
{
|
||||||
public const int MaxFailedLogins = 5;
|
|
||||||
public static readonly TimeSpan LockoutDuration = TimeSpan.FromMinutes(15);
|
|
||||||
|
|
||||||
private User() { } // EF Core
|
private User() { } // EF Core
|
||||||
|
|
||||||
public int Id { get; private set; }
|
public int Id { get; private set; }
|
||||||
@@ -21,10 +18,10 @@ public sealed class User : IHasCreatedAt
|
|||||||
public string? Phone { get; private set; }
|
public string? Phone { get; private set; }
|
||||||
public UserRole Role { get; private set; }
|
public UserRole Role { get; private set; }
|
||||||
public bool IsActive { get; private set; } = true;
|
public bool IsActive { get; private set; } = true;
|
||||||
|
public bool IsDeleted { get; private set; }
|
||||||
public bool EmailConfirmed { get; private set; }
|
public bool EmailConfirmed { get; private set; }
|
||||||
public bool EmailNotificationsEnabled { get; private set; } = true;
|
public bool EmailNotificationsEnabled { get; private set; } = true;
|
||||||
public int FailedLoginCount { get; private set; }
|
public int RowVersion { get; private set; }
|
||||||
public DateTime? LockoutUntil { get; private set; }
|
|
||||||
public DateTime CreatedAt { get; set; }
|
public DateTime CreatedAt { get; set; }
|
||||||
|
|
||||||
public string FullName => $"{FirstName} {LastName}";
|
public string FullName => $"{FirstName} {LastName}";
|
||||||
@@ -41,33 +38,18 @@ public sealed class User : IHasCreatedAt
|
|||||||
|
|
||||||
public static string NormalizeEmail(string email) => email.Trim().ToUpperInvariant();
|
public static string NormalizeEmail(string email) => email.Trim().ToUpperInvariant();
|
||||||
|
|
||||||
public bool IsLockedOut(DateTime now) => LockoutUntil is { } until && until > now;
|
|
||||||
|
|
||||||
/// <summary>Neúspěšné přihlášení; po <see cref="MaxFailedLogins"/> pokusech se účet na 15 minut zamkne.</summary>
|
|
||||||
public void RegisterFailedLogin(DateTime now)
|
|
||||||
{
|
|
||||||
FailedLoginCount++;
|
|
||||||
if (FailedLoginCount >= MaxFailedLogins)
|
|
||||||
{
|
|
||||||
LockoutUntil = now + LockoutDuration;
|
|
||||||
FailedLoginCount = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void RegisterSuccessfulLogin()
|
|
||||||
{
|
|
||||||
FailedLoginCount = 0;
|
|
||||||
LockoutUntil = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void ConfirmEmail() => EmailConfirmed = true;
|
public void ConfirmEmail() => EmailConfirmed = true;
|
||||||
|
|
||||||
public void ChangePasswordHash(string passwordHash)
|
public void SetEmailConfirmed(bool confirmed) => EmailConfirmed = confirmed;
|
||||||
|
|
||||||
|
public void ChangeEmail(string email)
|
||||||
{
|
{
|
||||||
PasswordHash = passwordHash;
|
Email = email.Trim();
|
||||||
RegisterSuccessfulLogin();
|
EmailNormalized = NormalizeEmail(email);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void ChangePasswordHash(string passwordHash) => PasswordHash = passwordHash;
|
||||||
|
|
||||||
public void UpdateProfile(string firstName, string lastName, string? phone, bool emailNotificationsEnabled)
|
public void UpdateProfile(string firstName, string lastName, string? phone, bool emailNotificationsEnabled)
|
||||||
{
|
{
|
||||||
FirstName = firstName.Trim();
|
FirstName = firstName.Trim();
|
||||||
@@ -79,4 +61,14 @@ public sealed class User : IHasCreatedAt
|
|||||||
public void ChangeRole(UserRole role) => Role = role;
|
public void ChangeRole(UserRole role) => Role = role;
|
||||||
|
|
||||||
public void SetActive(bool isActive) => IsActive = isActive;
|
public void SetActive(bool isActive) => IsActive = isActive;
|
||||||
|
|
||||||
|
public void Delete()
|
||||||
|
{
|
||||||
|
UpdateProfile("Smazaný", "uživatel", null, false);
|
||||||
|
ChangeEmail($"deleted:{Id.ToString(System.Globalization.CultureInfo.InvariantCulture)}");
|
||||||
|
ChangePasswordHash("");
|
||||||
|
SetEmailConfirmed(false);
|
||||||
|
SetActive(false);
|
||||||
|
IsDeleted = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
using Helpdesk.Infrastructure.Files;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace Helpdesk.Infrastructure.Background;
|
||||||
|
|
||||||
|
internal sealed partial class AttachmentStorageMonitor(TimeProvider clock, ILogger<AttachmentStorageMonitor> logger) : BackgroundService
|
||||||
|
{
|
||||||
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||||
|
{
|
||||||
|
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(5), clock);
|
||||||
|
do
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var path = Directory.Exists(FileAttachmentStore.UploadDirectory)
|
||||||
|
? FileAttachmentStore.UploadDirectory
|
||||||
|
: AppContext.BaseDirectory;
|
||||||
|
var drive = new DriveInfo(path);
|
||||||
|
var available = drive.AvailableFreeSpace;
|
||||||
|
if (available < drive.TotalSize / 10)
|
||||||
|
LogLowSpace(available / (1024 * 1024));
|
||||||
|
}
|
||||||
|
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
|
||||||
|
{
|
||||||
|
LogCheckFailed(exception);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (await timer.WaitForNextTickAsync(stoppingToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
[LoggerMessage(Level = LogLevel.Warning, Message = "Na úložišti příloh zbývá méně než 10 % volného místa ({FreeMiB} MiB).")]
|
||||||
|
private partial void LogLowSpace(long freeMiB);
|
||||||
|
|
||||||
|
[LoggerMessage(Level = LogLevel.Warning, Message = "Volné místo na úložišti příloh se nepodařilo zjistit.")]
|
||||||
|
private partial void LogCheckFailed(Exception exception);
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
using System.Data;
|
using System.Data;
|
||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
using Helpdesk.Application.Common;
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Application.Notifications;
|
||||||
using Helpdesk.Domain.Notifications;
|
using Helpdesk.Domain.Notifications;
|
||||||
using Helpdesk.Infrastructure.Email;
|
using Helpdesk.Infrastructure.Email;
|
||||||
using Helpdesk.Infrastructure.Notifications;
|
using Helpdesk.Infrastructure.Notifications;
|
||||||
@@ -56,13 +57,13 @@ internal sealed partial class NotificationDispatcher(
|
|||||||
return false;
|
return false;
|
||||||
|
|
||||||
var recipient = await (
|
var recipient = await (
|
||||||
from notification in db.Notifications.AsNoTracking()
|
from notification in NotificationVisibility.VisibleToRecipients(db).AsNoTracking()
|
||||||
join user in db.Users on notification.UserId equals user.Id
|
join user in db.Users on notification.UserId equals user.Id
|
||||||
where notification.Id == delivery.NotificationId
|
where notification.Id == delivery.NotificationId
|
||||||
select new { Notification = notification, user.Id, user.Email, user.IsActive, user.EmailConfirmed, user.EmailNotificationsEnabled }
|
select new { Notification = notification, user.Id, user.Email, user.EmailConfirmed, user.EmailNotificationsEnabled }
|
||||||
).SingleAsync(ct);
|
).SingleOrDefaultAsync(ct);
|
||||||
|
|
||||||
if (!recipient.IsActive)
|
if (recipient is null)
|
||||||
delivery.Skip();
|
delivery.Skip();
|
||||||
else if (delivery.Channel == DeliveryChannel.Email)
|
else if (delivery.Channel == DeliveryChannel.Email)
|
||||||
{
|
{
|
||||||
@@ -73,7 +74,7 @@ internal sealed partial class NotificationDispatcher(
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
await SendPushAsync(db, delivery, recipient.Notification, recipient.Id, ct);
|
await SendPushAsync(db, delivery, recipient.Id, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
@@ -94,8 +95,7 @@ internal sealed partial class NotificationDispatcher(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task SendPushAsync(
|
private async Task SendPushAsync(HelpdeskDbContext db, NotificationDelivery delivery, int userId, CancellationToken ct)
|
||||||
HelpdeskDbContext db, NotificationDelivery delivery, Notification notification, int userId, CancellationToken ct)
|
|
||||||
{
|
{
|
||||||
var devices = db.PushDevices.Where(d => d.UserId == userId);
|
var devices = db.PushDevices.Where(d => d.UserId == userId);
|
||||||
var tokens = await devices.Select(d => d.FcmToken).ToArrayAsync(ct);
|
var tokens = await devices.Select(d => d.FcmToken).ToArrayAsync(ct);
|
||||||
@@ -105,7 +105,7 @@ internal sealed partial class NotificationDispatcher(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var result = await push!.SendAsync(notification, tokens, ct);
|
var result = await push!.SendAsync(tokens, ct);
|
||||||
foreach (var invalidToken in result.InvalidTokens)
|
foreach (var invalidToken in result.InvalidTokens)
|
||||||
await devices.Where(d => d.FcmToken == invalidToken).ExecuteDeleteAsync(ct);
|
await devices.Where(d => d.FcmToken == invalidToken).ExecuteDeleteAsync(ct);
|
||||||
|
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ public static class DependencyInjection
|
|||||||
services.AddHostedService<AdminSeeder>();
|
services.AddHostedService<AdminSeeder>();
|
||||||
services.AddHostedService<AuthTokenCleanupService>();
|
services.AddHostedService<AuthTokenCleanupService>();
|
||||||
services.AddHostedService<NotificationDispatcher>();
|
services.AddHostedService<NotificationDispatcher>();
|
||||||
|
services.AddHostedService<AttachmentStorageMonitor>();
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,16 +8,16 @@ namespace Helpdesk.Infrastructure.Files;
|
|||||||
|
|
||||||
internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) : IAttachmentStore
|
internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) : IAttachmentStore
|
||||||
{
|
{
|
||||||
private readonly string directory = Path.Combine(AppContext.BaseDirectory, "uploads");
|
internal static readonly string UploadDirectory = Path.Combine(AppContext.BaseDirectory, "uploads");
|
||||||
|
|
||||||
public async Task<StoredAttachment> SaveAsync(AttachmentUpload upload, CancellationToken ct)
|
public async Task<StoredAttachment> SaveAsync(AttachmentUpload upload, CancellationToken ct)
|
||||||
{
|
{
|
||||||
if (upload.SizeBytes is <= 0 or > AttachmentLimits.MaxFileBytes)
|
if (upload.SizeBytes is <= 0 or > AttachmentLimits.MaxFileBytes)
|
||||||
throw new BadRequestException("Příloha musí mít velikost od 1 B do 10 MB.");
|
throw new FieldValidationException("files", "Příloha musí mít velikost od 1 B do 10 MB.");
|
||||||
|
|
||||||
var name = Path.GetFileName(upload.FileName.Replace('\\', '/')).Trim();
|
var name = Path.GetFileName(upload.FileName.Replace('\\', '/')).Trim();
|
||||||
if (name.Length is 0 or > 255 || name.Any(char.IsControl))
|
if (name.Length is 0 or > 255 || name.Any(char.IsControl))
|
||||||
throw new BadRequestException("Neplatný název přílohy.");
|
throw new FieldValidationException("files", "Neplatný název přílohy.");
|
||||||
|
|
||||||
var extension = Path.GetExtension(name).ToLowerInvariant();
|
var extension = Path.GetExtension(name).ToLowerInvariant();
|
||||||
var contentType = extension switch
|
var contentType = extension switch
|
||||||
@@ -27,10 +27,10 @@ internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) :
|
|||||||
".heic" => "image/heic",
|
".heic" => "image/heic",
|
||||||
".pdf" => "application/pdf",
|
".pdf" => "application/pdf",
|
||||||
".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||||
_ => throw new BadRequestException("Tento typ přílohy není povolen."),
|
_ => throw new FieldValidationException("files", "Tento typ přílohy není povolen."),
|
||||||
};
|
};
|
||||||
|
|
||||||
Directory.CreateDirectory(directory);
|
Directory.CreateDirectory(UploadDirectory);
|
||||||
var key = Guid.NewGuid().ToString("D");
|
var key = Guid.NewGuid().ToString("D");
|
||||||
var path = FilePath(key);
|
var path = FilePath(key);
|
||||||
|
|
||||||
@@ -49,16 +49,16 @@ internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) :
|
|||||||
{
|
{
|
||||||
written += read;
|
written += read;
|
||||||
if (written > upload.SizeBytes)
|
if (written > upload.SizeBytes)
|
||||||
throw new BadRequestException("Velikost přílohy neodpovídá požadavku.");
|
throw new FieldValidationException("files", "Velikost přílohy neodpovídá požadavku.");
|
||||||
await output.WriteAsync(buffer.AsMemory(0, read), ct);
|
await output.WriteAsync(buffer.AsMemory(0, read), ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (written != upload.SizeBytes)
|
if (written != upload.SizeBytes)
|
||||||
throw new BadRequestException("Velikost přílohy neodpovídá požadavku.");
|
throw new FieldValidationException("files", "Velikost přílohy neodpovídá požadavku.");
|
||||||
|
|
||||||
output.Position = 0;
|
output.Position = 0;
|
||||||
if (!await HasExpectedFormatAsync(output, extension, ct))
|
if (!await HasExpectedFormatAsync(output, extension, ct))
|
||||||
throw new BadRequestException("Obsah přílohy neodpovídá její příponě.");
|
throw new FieldValidationException("files", "Obsah přílohy neodpovídá její příponě.");
|
||||||
|
|
||||||
return new StoredAttachment(name, key, contentType, written);
|
return new StoredAttachment(name, key, contentType, written);
|
||||||
}
|
}
|
||||||
@@ -97,7 +97,7 @@ internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) :
|
|||||||
}
|
}
|
||||||
|
|
||||||
private string FilePath(string key) => Guid.TryParseExact(key, "D", out _)
|
private string FilePath(string key) => Guid.TryParseExact(key, "D", out _)
|
||||||
? Path.Combine(directory, key)
|
? Path.Combine(UploadDirectory, key)
|
||||||
: throw new InvalidOperationException("Neplatný klíč souboru přílohy.");
|
: throw new InvalidOperationException("Neplatný klíč souboru přílohy.");
|
||||||
|
|
||||||
private static async Task<bool> HasExpectedFormatAsync(Stream stream, string extension, CancellationToken ct)
|
private static async Task<bool> HasExpectedFormatAsync(Stream stream, string extension, CancellationToken ct)
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
using System.Globalization;
|
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using FirebaseAdmin;
|
using FirebaseAdmin;
|
||||||
using FirebaseAdmin.Messaging;
|
using FirebaseAdmin.Messaging;
|
||||||
using Google.Apis.Auth.OAuth2;
|
using Google.Apis.Auth.OAuth2;
|
||||||
using Google.Apis.Auth.OAuth2.Responses;
|
using Google.Apis.Auth.OAuth2.Responses;
|
||||||
using Helpdesk.Domain;
|
using Helpdesk.Domain;
|
||||||
using Notification = Helpdesk.Domain.Notifications.Notification;
|
|
||||||
|
|
||||||
namespace Helpdesk.Infrastructure.Notifications;
|
namespace Helpdesk.Infrastructure.Notifications;
|
||||||
|
|
||||||
@@ -37,17 +35,8 @@ internal sealed class FirebasePushSender(FirebaseApp app) : IDisposable
|
|||||||
return new FirebasePushSender(app);
|
return new FirebasePushSender(app);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<PushDeliveryResult> SendAsync(Notification notification, string[] tokens, CancellationToken ct)
|
public async Task<PushDeliveryResult> SendAsync(string[] tokens, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var data = new Dictionary<string, string>
|
|
||||||
{
|
|
||||||
["notificationId"] = notification.Id.ToString(CultureInfo.InvariantCulture),
|
|
||||||
};
|
|
||||||
if (notification.IssueId is int issueId)
|
|
||||||
data["issueId"] = issueId.ToString(CultureInfo.InvariantCulture);
|
|
||||||
if (notification.ProposalId is int proposalId)
|
|
||||||
data["proposalId"] = proposalId.ToString(CultureInfo.InvariantCulture);
|
|
||||||
|
|
||||||
var messaging = FirebaseMessaging.GetMessaging(app);
|
var messaging = FirebaseMessaging.GetMessaging(app);
|
||||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||||
timeout.CancelAfter(TimeSpan.FromSeconds(15));
|
timeout.CancelAfter(TimeSpan.FromSeconds(15));
|
||||||
@@ -65,12 +54,11 @@ internal sealed class FirebasePushSender(FirebaseApp app) : IDisposable
|
|||||||
#pragma warning disable CS0618 // API zařízení podle návrhu přijímá registrační tokeny FCM.
|
#pragma warning disable CS0618 // API zařízení podle návrhu přijímá registrační tokeny FCM.
|
||||||
Tokens = batch,
|
Tokens = batch,
|
||||||
#pragma warning restore CS0618
|
#pragma warning restore CS0618
|
||||||
Notification = new FirebaseAdmin.Messaging.Notification
|
Notification = new Notification
|
||||||
{
|
{
|
||||||
Title = notification.Title,
|
Title = "NTBug",
|
||||||
Body = notification.Message,
|
Body = "V aplikaci máte novou notifikaci.",
|
||||||
},
|
},
|
||||||
Data = data,
|
|
||||||
}, timeout.Token);
|
}, timeout.Token);
|
||||||
|
|
||||||
sent |= result.SuccessCount > 0;
|
sent |= result.SuccessCount > 0;
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ using Microsoft.Extensions.Logging;
|
|||||||
namespace Helpdesk.Infrastructure.Persistence;
|
namespace Helpdesk.Infrastructure.Persistence;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Při startu vytvoří účet administrátora z <c>ADMIN_EMAIL</c> a <c>ADMIN_PASSWORD</c>, pokud ještě neexistuje.
|
/// Při startu vytvoří účet administrátora z <c>ADMIN_EMAIL</c> a <c>ADMIN_PASSWORD</c>, pokud není žádný aktivní administrátor.
|
||||||
/// Admin není v migracích, aby hash hesla vznikl stejným algoritmem jako u ostatních uživatelů.
|
/// Admin není v migracích, aby hash hesla vznikl stejným algoritmem jako u ostatních uživatelů.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal sealed partial class AdminSeeder(
|
internal sealed partial class AdminSeeder(
|
||||||
@@ -29,7 +29,8 @@ internal sealed partial class AdminSeeder(
|
|||||||
var hasher = scope.ServiceProvider.GetRequiredService<IPasswordHasher>();
|
var hasher = scope.ServiceProvider.GetRequiredService<IPasswordHasher>();
|
||||||
|
|
||||||
var normalized = User.NormalizeEmail(email);
|
var normalized = User.NormalizeEmail(email);
|
||||||
if (await db.Users.AnyAsync(u => u.EmailNormalized == normalized, cancellationToken))
|
if (await db.Users.AnyAsync(u => u.EmailNormalized == normalized ||
|
||||||
|
(u.Role == UserRole.Admin && u.IsActive), cancellationToken))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
var admin = User.Create(email, hasher.Hash(password), "Administrátor", "Systému", UserRole.Admin);
|
var admin = User.Create(email, hasher.Hash(password), "Administrátor", "Systému", UserRole.Admin);
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ internal sealed class UserConfiguration(FieldEncryptor encryptor) : IEntityTypeC
|
|||||||
b.Property(u => u.Email).HasMaxLength(254);
|
b.Property(u => u.Email).HasMaxLength(254);
|
||||||
b.Property(u => u.EmailNormalized).HasMaxLength(254);
|
b.Property(u => u.EmailNormalized).HasMaxLength(254);
|
||||||
b.HasIndex(u => u.EmailNormalized).IsUnique();
|
b.HasIndex(u => u.EmailNormalized).IsUnique();
|
||||||
|
b.Property(u => u.RowVersion).IsConcurrencyToken();
|
||||||
b.Property(u => u.Role).HasConversion<EnumCodeConverter<UserRole>>().HasMaxLength(30);
|
b.Property(u => u.Role).HasConversion<EnumCodeConverter<UserRole>>().HasMaxLength(30);
|
||||||
b.Property(u => u.Phone)
|
b.Property(u => u.Phone)
|
||||||
.HasColumnName("phone_encrypted")
|
.HasColumnName("phone_encrypted")
|
||||||
|
|||||||
@@ -42,6 +42,16 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
|||||||
|
|
||||||
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
|
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
|
foreach (var entry in ChangeTracker.Entries<User>())
|
||||||
|
{
|
||||||
|
if (entry.State == EntityState.Modified && entry.Properties.Any(property =>
|
||||||
|
property.IsModified && property.Metadata.Name != nameof(User.RowVersion)))
|
||||||
|
{
|
||||||
|
var version = entry.Property(user => user.RowVersion);
|
||||||
|
version.CurrentValue = checked(version.OriginalValue + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
return await base.SaveChangesAsync(cancellationToken);
|
return await base.SaveChangesAsync(cancellationToken);
|
||||||
@@ -52,11 +62,27 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
|||||||
{
|
{
|
||||||
throw new ConflictException("Kategorie se stejným názvem již existuje.");
|
throw new ConflictException("Kategorie se stejným názvem již existuje.");
|
||||||
}
|
}
|
||||||
|
catch (DbUpdateException exception) when (
|
||||||
|
exception.InnerException is MySqlException { ErrorCode: MySqlErrorCode.DuplicateKeyEntry } &&
|
||||||
|
exception.Entries is [var entry] && entry.Entity is User)
|
||||||
|
{
|
||||||
|
throw new ConflictException("Účet s tímto e-mailem už existuje.");
|
||||||
|
}
|
||||||
|
catch (DbUpdateConcurrencyException exception) when (exception.Entries is [var entry] && entry.Entity is User)
|
||||||
|
{
|
||||||
|
throw new AccountVersionConflictException();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct) =>
|
public Task<IDbContextTransaction> BeginWriteAsync(CancellationToken ct) =>
|
||||||
Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
|
Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
|
||||||
|
|
||||||
|
public async Task<User?> LockUserAsync(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var rows = await Users.FromSql($"SELECT * FROM app_user WHERE id = {id} FOR UPDATE").ToListAsync(ct);
|
||||||
|
return rows.SingleOrDefault();
|
||||||
|
}
|
||||||
|
|
||||||
public async Task<Proposal?> LockProposalAsync(int id, CancellationToken ct)
|
public async Task<Proposal?> LockProposalAsync(int id, CancellationToken ct)
|
||||||
{
|
{
|
||||||
// Všechny zápisy nad návrhem zamykají stejný řádek před čtením stavu a hlasů.
|
// Všechny zápisy nad návrhem zamykají stejný řádek před čtením stavu a hlasů.
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
|
|
||||||
namespace Helpdesk.Infrastructure.Security;
|
namespace Helpdesk.Infrastructure.Security;
|
||||||
@@ -6,8 +7,15 @@ namespace Helpdesk.Infrastructure.Security;
|
|||||||
internal sealed class BCryptPasswordHasher : IPasswordHasher
|
internal sealed class BCryptPasswordHasher : IPasswordHasher
|
||||||
{
|
{
|
||||||
private const int WorkFactor = 12;
|
private const int WorkFactor = 12;
|
||||||
|
private readonly string dummyHash = BCrypt.Net.BCrypt.HashPassword(
|
||||||
|
Convert.ToHexString(RandomNumberGenerator.GetBytes(32)), WorkFactor);
|
||||||
|
|
||||||
public string Hash(string password) => BCrypt.Net.BCrypt.HashPassword(password, WorkFactor);
|
public string Hash(string password) => BCrypt.Net.BCrypt.HashPassword(password, WorkFactor);
|
||||||
|
|
||||||
public bool Verify(string password, string passwordHash) => BCrypt.Net.BCrypt.Verify(password, passwordHash);
|
public bool Verify(string password, string? passwordHash)
|
||||||
|
{
|
||||||
|
var hasPassword = !string.IsNullOrEmpty(passwordHash);
|
||||||
|
var matches = BCrypt.Net.BCrypt.Verify(password, hasPassword ? passwordHash : dummyHash);
|
||||||
|
return hasPassword && matches;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -26,8 +26,9 @@ internal sealed class RevokedTokenStore(TimeProvider clock) : IRevokedTokenStore
|
|||||||
|
|
||||||
public void Add(string jti, DateTime expiresAt)
|
public void Add(string jti, DateTime expiresAt)
|
||||||
{
|
{
|
||||||
if (expiresAt > clock.GetUtcNow().UtcDateTime)
|
var rejectUntil = expiresAt + JwtTokenService.ClockSkew;
|
||||||
_revoked[jti] = expiresAt;
|
if (rejectUntil > clock.GetUtcNow().UtcDateTime)
|
||||||
|
_revoked[jti] = rejectUntil;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void PruneOccasionally()
|
private void PruneOccasionally()
|
||||||
@@ -52,10 +53,10 @@ internal sealed class RevokedTokenStoreLoader(IServiceScopeFactory scopes, IRevo
|
|||||||
{
|
{
|
||||||
using var scope = scopes.CreateScope();
|
using var scope = scopes.CreateScope();
|
||||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
var now = clock.GetUtcNow().UtcDateTime;
|
var earliestExpiry = clock.GetUtcNow().UtcDateTime - JwtTokenService.ClockSkew;
|
||||||
|
|
||||||
var revoked = await db.AuthTokens.AsNoTracking()
|
var revoked = await db.AuthTokens.AsNoTracking()
|
||||||
.Where(t => t.TokenType == TokenType.Access && t.RevokedAt != null && t.ExpiresAt > now)
|
.Where(t => t.TokenType == TokenType.Access && t.RevokedAt != null && t.ExpiresAt > earliestExpiry)
|
||||||
.Select(t => new { t.Jti, t.ExpiresAt })
|
.Select(t => new { t.Jti, t.ExpiresAt })
|
||||||
.ToListAsync(cancellationToken);
|
.ToListAsync(cancellationToken);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,292 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Nodes;
|
||||||
|
using Helpdesk.Application.Abstractions;
|
||||||
|
using Helpdesk.Application.Auth;
|
||||||
|
using Helpdesk.Application.Catalogs;
|
||||||
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Application.Issues;
|
||||||
|
using Helpdesk.Application.Notifications;
|
||||||
|
using Helpdesk.Application.Users;
|
||||||
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.IdentityModel.JsonWebTokens;
|
||||||
|
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||||
|
{
|
||||||
|
private const string Users = "/api/v1/admin/users";
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AdminMustExplicitlySendAccountStateWhenCreatingOrUpdatingAnAccount()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||||
|
var request = new SaveAdminUserRequest("[email protected]", "Test", "Uživatel", null,
|
||||||
|
"STUDENT", true, true, true, Password);
|
||||||
|
var body = JsonSerializer.SerializeToNode(request, JsonSerializerOptions.Web)!.AsObject();
|
||||||
|
string[] fields = ["isActive", "emailConfirmed", "emailNotificationsEnabled"];
|
||||||
|
|
||||||
|
foreach (var field in fields)
|
||||||
|
{
|
||||||
|
var omitted = body.DeepClone().AsObject();
|
||||||
|
omitted.Remove(field);
|
||||||
|
var validation = await ReadAsync<ValidationProblemDetails>(admin.PostAsJsonAsync(Users, omitted, Cancellation),
|
||||||
|
HttpStatusCode.BadRequest);
|
||||||
|
Assert.Equal(field, Assert.Single(validation.Errors.Keys));
|
||||||
|
}
|
||||||
|
|
||||||
|
var created = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
var path = $"{Users}/{created.Id}";
|
||||||
|
var edit = request with { RowVersion = created.RowVersion, Password = null, FirstName = "Upravené jméno" };
|
||||||
|
body = JsonSerializer.SerializeToNode(edit, JsonSerializerOptions.Web)!.AsObject();
|
||||||
|
foreach (var field in fields)
|
||||||
|
{
|
||||||
|
var omitted = body.DeepClone().AsObject();
|
||||||
|
omitted.Remove(field);
|
||||||
|
var validation = await ReadAsync<ValidationProblemDetails>(admin.PutAsJsonAsync(path, omitted, Cancellation),
|
||||||
|
HttpStatusCode.BadRequest);
|
||||||
|
Assert.Equal(field, Assert.Single(validation.Errors.Keys));
|
||||||
|
|
||||||
|
omitted[field] = null;
|
||||||
|
validation = await ReadAsync<ValidationProblemDetails>(admin.PutAsJsonAsync(path, omitted, Cancellation),
|
||||||
|
HttpStatusCode.BadRequest);
|
||||||
|
Assert.Equal(field, Assert.Single(validation.Errors.Keys));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Equal(created, await ReadAsync<AdminUserDetailsDto>(admin.GetAsync(path, Cancellation)));
|
||||||
|
var disabled = edit with { IsActive = false, EmailConfirmed = false, EmailNotificationsEnabled = false };
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync(path, disabled, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
var saved = await ReadAsync<AdminUserDetailsDto>(admin.GetAsync(path, Cancellation));
|
||||||
|
Assert.Equal((edit.FirstName, false, false, false),
|
||||||
|
(saved.FirstName, saved.IsActive, saved.EmailConfirmed, saved.EmailNotificationsEnabled));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AdminCanCreateEditAndAnonymizeAccountsWhileKeepingIssueHistory()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
var administrator = await LoginAsync(anonymous, AdminEmail);
|
||||||
|
using var admin = fixture.CreateClient(administrator.AccessToken);
|
||||||
|
var request = new SaveAdminUserRequest("[email protected]", "Jan", "Novák", "+420 123 456 789",
|
||||||
|
"STUDENT", true, true, false, Password);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
var created = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
var path = $"{Users}/{created.Id}";
|
||||||
|
Assert.Equal(created, await ReadAsync<AdminUserDetailsDto>(admin.GetAsync(path, Cancellation)));
|
||||||
|
Assert.Null(created.VerificationEmailSent);
|
||||||
|
await ExpectAsync(admin.PostAsync(path + "/email-confirmation", null, Cancellation), HttpStatusCode.Conflict);
|
||||||
|
await ExpectAsync(admin.PostAsJsonAsync(Users, request with { Email = "[email protected]" }, Cancellation), HttpStatusCode.Conflict);
|
||||||
|
|
||||||
|
var login = await LoginAsync(anonymous, request.Email);
|
||||||
|
using var student = fixture.CreateClient(login.AccessToken);
|
||||||
|
await ExpectAsync(student.DeleteAsync(path, Cancellation), HttpStatusCode.Forbidden);
|
||||||
|
var category = (await ReadAsync<CategoryDto[]>(student.GetAsync("/api/v1/issue-categories", Cancellation)))[0];
|
||||||
|
var issue = await ReadAsync<IssueDetail>(student.PostAsJsonAsync("/api/v1/issues",
|
||||||
|
new CreateIssueRequest("Rozbitý zámek", "Učebnu nelze otevřít.", category.Id, null, null), Cancellation), HttpStatusCode.Created);
|
||||||
|
|
||||||
|
var edit = request with
|
||||||
|
{
|
||||||
|
Email = "[email protected]", FirstName = "Jana", Role = "TEACHER",
|
||||||
|
Password = "New-password-for-test", RowVersion = created.RowVersion,
|
||||||
|
};
|
||||||
|
var saved = await ReadAsync<AdminUserDetailsDto>(admin.PutAsJsonAsync(path, edit, Cancellation));
|
||||||
|
Assert.False(saved.EmailConfirmed);
|
||||||
|
Assert.True(saved.VerificationEmailSent);
|
||||||
|
await ExpectAsync(student.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(edit.Email, Password), Cancellation),
|
||||||
|
HttpStatusCode.Unauthorized);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(edit.Email, edit.Password!), Cancellation),
|
||||||
|
HttpStatusCode.Unauthorized);
|
||||||
|
await ConfirmEmailAsync(anonymous, await fixture.TakeConfirmationTokenAsync(edit.Email), password: edit.Password!);
|
||||||
|
var edited = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login",
|
||||||
|
new LoginRequest(edit.Email, edit.Password!), Cancellation));
|
||||||
|
Assert.Equal((created.Id, edit.Email, edit.FirstName, edit.Role), (edited.User.Id, edited.User.Email, edited.User.FirstName, edited.User.Role));
|
||||||
|
using var teacher = fixture.CreateClient(edited.AccessToken);
|
||||||
|
await ExpectAsync(teacher.PostAsJsonAsync("/api/v1/devices", new { token = "test-device-token" }, Cancellation),
|
||||||
|
HttpStatusCode.NoContent);
|
||||||
|
|
||||||
|
await ExpectAsync(admin.DeleteAsync(path, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(admin.GetAsync(path, Cancellation), HttpStatusCode.NotFound);
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync(path + "/active", new SetActiveRequest(true), Cancellation), HttpStatusCode.NotFound);
|
||||||
|
await ExpectAsync(teacher.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/refresh", new RefreshTokenRequest(edited.RefreshToken), Cancellation),
|
||||||
|
HttpStatusCode.Unauthorized);
|
||||||
|
var list = await ReadAsync<PagedResult<AdminUserDto>>(admin.GetAsync(Users, Cancellation));
|
||||||
|
Assert.DoesNotContain(list.Items, user => user.Id == created.Id);
|
||||||
|
var issuePath = $"/api/v1/issues/{issue.Id}";
|
||||||
|
Assert.Equal(created.Id, (await ReadAsync<IssueDetail>(admin.GetAsync(issuePath, Cancellation))).ReporterId);
|
||||||
|
var entry = Assert.Single(await ReadAsync<IssueEventDto[]>(admin.GetAsync(issuePath + "/events", Cancellation)));
|
||||||
|
Assert.Equal((created.Id, "Smazaný uživatel"), (entry.ActorId, entry.ActorName));
|
||||||
|
var replacement = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request with { Email = edit.Email }, Cancellation),
|
||||||
|
HttpStatusCode.Created);
|
||||||
|
Assert.NotEqual(created.Id, replacement.Id);
|
||||||
|
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
var retained = await db.Users.AsNoTracking().SingleAsync(user => user.Id == created.Id, Cancellation);
|
||||||
|
Assert.True(retained.IsDeleted);
|
||||||
|
Assert.False(retained.IsActive);
|
||||||
|
Assert.Null(retained.Phone);
|
||||||
|
Assert.Empty(retained.PasswordHash);
|
||||||
|
Assert.NotEqual(edit.Email, retained.Email);
|
||||||
|
Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == created.Id, Cancellation));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AdminCreationSendsAnActivationLinkAndFailedDeliveryCanBeRetried()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||||
|
var request = new SaveAdminUserRequest("[email protected]", "Test", "Uživatel", null,
|
||||||
|
"STUDENT", true, false, false, null);
|
||||||
|
var created = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
Assert.True(created.VerificationEmailSent);
|
||||||
|
Assert.False(created.EmailConfirmed);
|
||||||
|
var originalToken = await fixture.TakeConfirmationTokenAsync(request.Email);
|
||||||
|
|
||||||
|
var moved = request with { Email = "[email protected]", Password = null, RowVersion = created.RowVersion };
|
||||||
|
var updated = await ReadAsync<AdminUserDetailsDto>(admin.PutAsJsonAsync($"{Users}/{created.Id}", moved, Cancellation));
|
||||||
|
Assert.True(updated.VerificationEmailSent);
|
||||||
|
await ConfirmEmailAsync(anonymous, originalToken, HttpStatusCode.BadRequest);
|
||||||
|
await ConfirmEmailAsync(anonymous, await fixture.TakeConfirmationTokenAsync(moved.Email));
|
||||||
|
Assert.Equal(created.Id, (await LoginAsync(anonymous, moved.Email)).User.Id);
|
||||||
|
|
||||||
|
var retry = request with { Email = "[email protected]" };
|
||||||
|
fixture.FailNextEmail(retry.Email, "SMTP_UNAVAILABLE", retryable: true);
|
||||||
|
var saved = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, retry, Cancellation), HttpStatusCode.Created);
|
||||||
|
Assert.False(saved.VerificationEmailSent);
|
||||||
|
Assert.Equal(retry.Email, (await ReadAsync<AdminUserDetailsDto>(admin.GetAsync($"{Users}/{saved.Id}", Cancellation))).Email);
|
||||||
|
await ExpectAsync(admin.PostAsync($"{Users}/{saved.Id}/email-confirmation", null, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ConfirmEmailAsync(anonymous, await fixture.TakeConfirmationTokenAsync(retry.Email));
|
||||||
|
Assert.Equal(saved.Id, (await LoginAsync(anonymous, retry.Email)).User.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task StaleAccountEditCannotRestoreAnOldRoleOrReactivateAnAccount()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||||
|
var request = new SaveAdminUserRequest("[email protected]", "Test", "Uživatel", null,
|
||||||
|
"FACILITY_MANAGER", true, true, false, Password);
|
||||||
|
var created = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
var path = $"{Users}/{created.Id}";
|
||||||
|
var edit = request with { Password = null, Phone = "+420 123 456 789" };
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync(path + "/role", new ChangeRoleRequest("STUDENT"), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
var conflict = await ReadAsync<ProblemDetails>(
|
||||||
|
admin.PutAsJsonAsync(path, edit with { RowVersion = created.RowVersion }, Cancellation), HttpStatusCode.Conflict);
|
||||||
|
Assert.Equal("urn:ntbug:account-version-conflict", conflict.Type);
|
||||||
|
var current = await ReadAsync<AdminUserDetailsDto>(admin.GetAsync(path, Cancellation));
|
||||||
|
Assert.Equal("STUDENT", current.Role);
|
||||||
|
Assert.Null(current.Phone);
|
||||||
|
Assert.True(current.RowVersion > created.RowVersion);
|
||||||
|
|
||||||
|
edit = edit with { Role = current.Role, RowVersion = current.RowVersion };
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
var refreshed = await ReadAsync<AdminUserDetailsDto>(admin.GetAsync(path, Cancellation));
|
||||||
|
Assert.Equal(edit.Phone, refreshed.Phone);
|
||||||
|
|
||||||
|
await ExpectAsync(admin.PostAsJsonAsync(Users + "/bulk",
|
||||||
|
new BulkAdminUsersRequest([created.Id], "deactivate", null), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync(path, edit with
|
||||||
|
{
|
||||||
|
RowVersion = refreshed.RowVersion, Phone = "+420 987 654 321",
|
||||||
|
}, Cancellation), HttpStatusCode.Conflict);
|
||||||
|
var deactivated = await ReadAsync<AdminUserDetailsDto>(admin.GetAsync(path, Cancellation));
|
||||||
|
Assert.False(deactivated.IsActive);
|
||||||
|
Assert.Equal(edit.Phone, deactivated.Phone);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AdminPasswordResetDisconnectsDevicesAndRejectsLateRegistrationsFromTheOldSession()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
var administrator = await LoginAsync(anonymous, AdminEmail);
|
||||||
|
using var admin = fixture.CreateClient(administrator.AccessToken);
|
||||||
|
var request = new SaveAdminUserRequest("[email protected]", "Test", "Účet", null,
|
||||||
|
"STUDENT", true, true, false, Password);
|
||||||
|
var newPassword = new string('č', 36);
|
||||||
|
var tooLong = newPassword + "a";
|
||||||
|
var creationError = await ReadAsync<ValidationProblemDetails>(admin.PostAsJsonAsync(Users,
|
||||||
|
request with { Password = tooLong }, Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
Assert.Contains("72 bajtů", Assert.Single(creationError.Errors["password"]));
|
||||||
|
var created = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
var originalSession = await LoginAsync(anonymous, created.Email);
|
||||||
|
using var member = fixture.CreateClient(originalSession.AccessToken);
|
||||||
|
const string devices = "/api/v1/devices";
|
||||||
|
await ExpectAsync(member.PostAsJsonAsync(devices, new { token = "old-phone" }, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(member.PostAsJsonAsync(devices, new { token = "old-tablet" }, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(admin.PostAsJsonAsync(devices, new { token = "admin-device" }, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
|
||||||
|
var edit = request with { Password = newPassword, RowVersion = created.RowVersion };
|
||||||
|
var editError = await ReadAsync<ValidationProblemDetails>(admin.PutAsJsonAsync($"{Users}/{created.Id}",
|
||||||
|
edit with { Password = tooLong }, Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
Assert.Contains("72 bajtů", Assert.Single(editError.Errors["password"]));
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync($"{Users}/{created.Id}", edit, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(member.PostAsJsonAsync(devices, new { token = "old-phone" }, Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/refresh", new RefreshTokenRequest(originalSession.RefreshToken),
|
||||||
|
Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
var oldSession = new CurrentSession(created.Id, new JsonWebToken(originalSession.AccessToken).Id);
|
||||||
|
await Assert.ThrowsAsync<UnauthorizedException>(() =>
|
||||||
|
new PushDeviceService(db, oldSession).RegisterAsync("late-registration", Cancellation));
|
||||||
|
Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == created.Id, Cancellation));
|
||||||
|
Assert.True(await db.PushDevices.AnyAsync(device => device.UserId == administrator.User.Id && device.FcmToken == "admin-device", Cancellation));
|
||||||
|
|
||||||
|
var newSession = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login",
|
||||||
|
new LoginRequest(created.Email, newPassword), Cancellation));
|
||||||
|
using var signedIn = fixture.CreateClient(newSession.AccessToken);
|
||||||
|
await ExpectAsync(signedIn.PostAsJsonAsync(devices, new { token = "new-phone" }, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task BulkActionsUpdateAllSelectedAccountsAndRejectTheEntireInvalidSelection()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
var administrator = await LoginAsync(anonymous, AdminEmail);
|
||||||
|
using var admin = fixture.CreateClient(administrator.AccessToken);
|
||||||
|
var request = new SaveAdminUserRequest("[email protected]", "První", "Účet", null, "STUDENT", true, true, false, Password);
|
||||||
|
var first = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
var second = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request with { Email = "[email protected]" }, Cancellation),
|
||||||
|
HttpStatusCode.Created);
|
||||||
|
var both = new[] { first.Id, second.Id };
|
||||||
|
|
||||||
|
await ExpectAsync(admin.PostAsJsonAsync(Users + "/bulk",
|
||||||
|
new BulkAdminUsersRequest([first.Id, int.MaxValue], "deactivate", null), Cancellation), HttpStatusCode.NotFound);
|
||||||
|
Assert.True((await ReadAsync<AdminUserDetailsDto>(admin.GetAsync($"{Users}/{first.Id}", Cancellation))).IsActive);
|
||||||
|
await ExpectAsync(admin.PostAsJsonAsync(Users + "/bulk",
|
||||||
|
new BulkAdminUsersRequest([first.Id, administrator.User.Id], "delete", null), Cancellation), HttpStatusCode.Conflict);
|
||||||
|
await ExpectAsync(admin.PostAsJsonAsync(Users + "/bulk",
|
||||||
|
new BulkAdminUsersRequest(both, "role", "TEACHER"), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
foreach (var id in both)
|
||||||
|
Assert.Equal("TEACHER", (await ReadAsync<AdminUserDetailsDto>(admin.GetAsync($"{Users}/{id}", Cancellation))).Role);
|
||||||
|
|
||||||
|
foreach (var (action, active) in new[] { ("deactivate", false), ("activate", true) })
|
||||||
|
{
|
||||||
|
await ExpectAsync(admin.PostAsJsonAsync(Users + "/bulk",
|
||||||
|
new BulkAdminUsersRequest(both, action, null), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
foreach (var id in both)
|
||||||
|
Assert.Equal(active, (await ReadAsync<AdminUserDetailsDto>(admin.GetAsync($"{Users}/{id}", Cancellation))).IsActive);
|
||||||
|
}
|
||||||
|
|
||||||
|
await ExpectAsync(admin.PostAsJsonAsync(Users + "/bulk",
|
||||||
|
new BulkAdminUsersRequest(both, "delete", null), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
foreach (var id in both)
|
||||||
|
await ExpectAsync(admin.GetAsync($"{Users}/{id}", Cancellation), HttpStatusCode.NotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Task ConfirmEmailAsync(HttpClient client, string token, HttpStatusCode expected = HttpStatusCode.NoContent,
|
||||||
|
string password = Password) =>
|
||||||
|
ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/confirm-email", new ConfirmEmailRequest(token, password), Cancellation), expected);
|
||||||
|
|
||||||
|
private sealed record CurrentSession(int Id, string TokenId) : ICurrentUser;
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text;
|
||||||
|
using Helpdesk.Application.Auth;
|
||||||
|
using Helpdesk.Application.Catalogs;
|
||||||
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Application.Users;
|
||||||
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
public sealed class AdministrationTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData("/api/v1/issue-categories")]
|
||||||
|
[InlineData("/api/v1/proposal-categories")]
|
||||||
|
public async Task AdministratorsCanManageCategories(string route)
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||||
|
var user = await fixture.RegisterAsync(anonymous);
|
||||||
|
using var member = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
|
||||||
|
var request = new SaveCategoryRequest("Testovací kategorie", "Popis");
|
||||||
|
await ExpectAsync(member.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Forbidden);
|
||||||
|
var category = await ReadAsync<CategoryDto>(admin.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
await ExpectAsync(admin.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Conflict);
|
||||||
|
var path = $"{route}/{category.Id}";
|
||||||
|
var edited = await ReadAsync<CategoryDto>(admin.PutAsJsonAsync(path, request with { Name = "Upravená kategorie" }, Cancellation));
|
||||||
|
Assert.Equal("Upravená kategorie", edited.Name);
|
||||||
|
await ExpectAsync(admin.DeleteAsync(path, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
|
||||||
|
var active = await ReadAsync<CategoryDto[]>(member.GetAsync(route + "?includeInactive=true", Cancellation));
|
||||||
|
var all = await ReadAsync<CategoryDto[]>(admin.GetAsync(route + "?includeInactive=true", Cancellation));
|
||||||
|
Assert.DoesNotContain(active, item => item.Id == category.Id);
|
||||||
|
Assert.False(Assert.Single(all, item => item.Id == category.Id).IsActive);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task BuildingCodesAreUniqueAndInactiveBuildingsStayAvailableToTheAdministrator()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||||
|
const string route = "/api/v1/buildings";
|
||||||
|
var request = new SaveBuildingRequest("TEST", "Testovací budova", null);
|
||||||
|
var building = await ReadAsync<BuildingDto>(admin.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
await ExpectAsync(admin.PostAsJsonAsync(route, request with { Code = " TEST " }, Cancellation), HttpStatusCode.Conflict);
|
||||||
|
var path = $"{route}/{building.Id}";
|
||||||
|
var edited = await ReadAsync<BuildingDto>(admin.PutAsJsonAsync(path, request with { Address = "Náměstí 1" }, Cancellation));
|
||||||
|
Assert.Equal("Náměstí 1", edited.Address);
|
||||||
|
await ExpectAsync(admin.DeleteAsync(path, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
var active = await ReadAsync<BuildingDto[]>(admin.GetAsync(route, Cancellation));
|
||||||
|
var all = await ReadAsync<BuildingDto[]>(admin.GetAsync(route + "?includeInactive=true", Cancellation));
|
||||||
|
Assert.DoesNotContain(active, item => item.Id == building.Id);
|
||||||
|
Assert.False(Assert.Single(all, item => item.Id == building.Id).IsActive);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ProfileDataRoundTripsAndDeactivationRevokesTheSession()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||||
|
var user = await fixture.RegisterAsync(anonymous);
|
||||||
|
using var member = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
|
||||||
|
const string profile = "/api/v1/users/me";
|
||||||
|
const string phone = "+420 123 456 789";
|
||||||
|
var request = new UpdateProfileRequest("Jana", "Nováková", phone, false);
|
||||||
|
var missingPreference = await ReadAsync<ValidationProblemDetails>(member.PutAsJsonAsync(profile,
|
||||||
|
new { request.FirstName, request.LastName, request.Phone }, Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
Assert.Contains("emailNotificationsEnabled", missingPreference.Errors.Keys);
|
||||||
|
var nullPreference = await ReadAsync<ValidationProblemDetails>(member.PutAsJsonAsync(profile,
|
||||||
|
request with { EmailNotificationsEnabled = null }, Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
Assert.Contains("emailNotificationsEnabled", nullPreference.Errors.Keys);
|
||||||
|
Assert.Equal(user, await ReadAsync<UserDto>(member.GetAsync(profile, Cancellation)));
|
||||||
|
|
||||||
|
var validation = await ReadAsync<ValidationProblemDetails>(member.PutAsJsonAsync(profile,
|
||||||
|
request with { Phone = "invalid" }, Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
Assert.Contains("phone", validation.Errors.Keys);
|
||||||
|
var updated = await ReadAsync<UserDto>(member.PutAsJsonAsync(profile, request, Cancellation));
|
||||||
|
Assert.Equal(updated, await ReadAsync<UserDto>(member.GetAsync(profile, Cancellation)));
|
||||||
|
Assert.Equal((request.FirstName, request.LastName, phone, false),
|
||||||
|
(updated.FirstName, updated.LastName, updated.Phone, updated.EmailNotificationsEnabled));
|
||||||
|
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
var encrypted = await db.Database.SqlQuery<byte[]>($"SELECT phone_encrypted AS Value FROM app_user WHERE id = {user.Id}")
|
||||||
|
.SingleAsync(Cancellation);
|
||||||
|
Assert.NotEmpty(encrypted);
|
||||||
|
Assert.False(Encoding.UTF8.GetBytes(phone).SequenceEqual(encrypted));
|
||||||
|
|
||||||
|
var search = $"/api/v1/admin/users?q={Uri.EscapeDataString(user.Email)}&role=STUDENT&pageSize=1";
|
||||||
|
await ExpectAsync(member.GetAsync(search, Cancellation), HttpStatusCode.Forbidden);
|
||||||
|
var page = await ReadAsync<PagedResult<AdminUserDto>>(admin.GetAsync(search, Cancellation));
|
||||||
|
Assert.Equal(user.Id, Assert.Single(page.Items).Id);
|
||||||
|
var activation = $"/api/v1/admin/users/{user.Id}/active";
|
||||||
|
var missingState = await ReadAsync<ValidationProblemDetails>(admin.PutAsJsonAsync(activation,
|
||||||
|
new { }, Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
Assert.Contains("isActive", missingState.Errors.Keys);
|
||||||
|
var nullState = await ReadAsync<ValidationProblemDetails>(admin.PutAsJsonAsync(activation,
|
||||||
|
new SetActiveRequest(null), Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
Assert.Contains("isActive", nullState.Errors.Keys);
|
||||||
|
Assert.Equal(updated, await ReadAsync<UserDto>(member.GetAsync(profile, Cancellation)));
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync(activation, new SetActiveRequest(false), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(member.GetAsync(profile, Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(user.Email, Password), Cancellation),
|
||||||
|
HttpStatusCode.Unauthorized);
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync(activation, new SetActiveRequest(true), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
Assert.Equal(user.Id, (await LoginAsync(anonymous, user.Email)).User.Id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.IO.Compression;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using Helpdesk.Application.Catalogs;
|
||||||
|
using Helpdesk.Application.Issues;
|
||||||
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
public sealed class AttachmentTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task AttachmentsRespectFormatAndAccessAndFailedBatchesAreNotSaved()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||||
|
var authorUser = await fixture.RegisterAsync(anonymous);
|
||||||
|
var otherUser = await fixture.RegisterAsync(anonymous);
|
||||||
|
using var author = fixture.CreateClient((await LoginAsync(anonymous, authorUser.Email)).AccessToken);
|
||||||
|
using var other = fixture.CreateClient((await LoginAsync(anonymous, otherUser.Email)).AccessToken);
|
||||||
|
var categories = await ReadAsync<CategoryDto[]>(author.GetAsync("/api/v1/issue-categories", Cancellation));
|
||||||
|
var png = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6t1sAAAAASUVORK5CYII=");
|
||||||
|
using var createForm = new MultipartFormDataContent();
|
||||||
|
createForm.Add(new StringContent("Rozbitý zámek"), "title");
|
||||||
|
createForm.Add(new StringContent("Dveře nelze odemknout."), "description");
|
||||||
|
createForm.Add(new StringContent(categories[0].Id.ToString(CultureInfo.InvariantCulture)), "categoryId");
|
||||||
|
AddFile(createForm, "zamek.png", png);
|
||||||
|
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
var store = scope.ServiceProvider.GetRequiredService<IAttachmentStore>();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var issue = await ReadAsync<IssueDetail>(author.PostAsync("/api/v1/issues", createForm, Cancellation), HttpStatusCode.Created);
|
||||||
|
var pngAttachment = Assert.Single(issue.Attachments);
|
||||||
|
var download = $"/api/v1/attachments/{pngAttachment.Id}";
|
||||||
|
using var fetched = await author.GetAsync(download, Cancellation);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, fetched.StatusCode);
|
||||||
|
Assert.Equal("image/png", fetched.Content.Headers.ContentType?.MediaType);
|
||||||
|
Assert.Equal("nosniff", Assert.Single(fetched.Headers.GetValues("X-Content-Type-Options")));
|
||||||
|
Assert.Equal(png, await fetched.Content.ReadAsByteArrayAsync(Cancellation));
|
||||||
|
await ExpectAsync(other.GetAsync(download, Cancellation), HttpStatusCode.Forbidden);
|
||||||
|
|
||||||
|
var path = $"/api/v1/issues/{issue.Id}/attachments";
|
||||||
|
using var mixed = new MultipartFormDataContent();
|
||||||
|
AddFile(mixed, "spravny.pdf", "%PDF-1.7\n%%EOF"u8.ToArray());
|
||||||
|
AddFile(mixed, "podvrzeny.png", "obsah nemá formát PNG"u8.ToArray());
|
||||||
|
var validation = await ReadAsync<ValidationProblemDetails>(author.PostAsync(path, mixed, Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
Assert.Equal("files", Assert.Single(validation.Errors.Keys));
|
||||||
|
|
||||||
|
using var wrongField = new MultipartFormDataContent();
|
||||||
|
wrongField.Add(new ByteArrayContent(png), "image", "zamek.png");
|
||||||
|
await ExpectAsync(author.PostAsync(path, wrongField, Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
var afterFailure = await ReadAsync<IssueDetail>(author.GetAsync($"/api/v1/issues/{issue.Id}", Cancellation));
|
||||||
|
Assert.Equal(issue.RowVersion, afterFailure.RowVersion);
|
||||||
|
Assert.Equal(pngAttachment.Id, Assert.Single(afterFailure.Attachments).Id);
|
||||||
|
|
||||||
|
using var files = new MultipartFormDataContent();
|
||||||
|
AddFile(files, "protokol.pdf", "%PDF-1.7\n%%EOF"u8.ToArray());
|
||||||
|
AddFile(files, "fotka.jpg", [0xff, 0xd8, 0xff, 0xd9]);
|
||||||
|
AddFile(files, "fotka.heic", [0, 0, 0, 20, .. "ftypmif1"u8, 0, 0, 0, 0, .. "heic"u8]);
|
||||||
|
AddFile(files, "protokol.docx", Docx());
|
||||||
|
var added = await ReadAsync<AttachmentDto[]>(admin.PostAsync(path, files, Cancellation));
|
||||||
|
Assert.Equal(["application/pdf", "image/jpeg", "image/heic",
|
||||||
|
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"], added.Select(item => item.ContentType));
|
||||||
|
|
||||||
|
var key = await db.Attachments.Where(item => item.Id == pngAttachment.Id).Select(item => item.StoredFileName).SingleAsync(Cancellation);
|
||||||
|
store.Delete(key);
|
||||||
|
await ExpectAsync(author.GetAsync(download, Cancellation), HttpStatusCode.NotFound);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
foreach (var key in await db.Attachments.Select(item => item.StoredFileName).ToListAsync(CancellationToken.None))
|
||||||
|
store.Delete(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AddFile(MultipartFormDataContent form, string name, byte[] bytes) =>
|
||||||
|
form.Add(new ByteArrayContent(bytes), "files", name);
|
||||||
|
|
||||||
|
private static byte[] Docx()
|
||||||
|
{
|
||||||
|
using var stream = new MemoryStream();
|
||||||
|
using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true))
|
||||||
|
{
|
||||||
|
using (var contentTypes = zip.CreateEntry("[Content_Types].xml").Open())
|
||||||
|
contentTypes.Write("<Types/>"u8);
|
||||||
|
using (var document = zip.CreateEntry("word/document.xml").Open())
|
||||||
|
document.Write("<document/>"u8);
|
||||||
|
}
|
||||||
|
return stream.ToArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using Helpdesk.Api.Controllers;
|
||||||
|
using Helpdesk.Application.Abstractions;
|
||||||
|
using Helpdesk.Application.Auth;
|
||||||
|
using Helpdesk.Domain.Auth;
|
||||||
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.IdentityModel.JsonWebTokens;
|
||||||
|
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task LoginFailuresAreGenericAndLoginLimitAppliesPerClientAndEmail()
|
||||||
|
{
|
||||||
|
using var setup = fixture.CreateClient();
|
||||||
|
var user = await fixture.RegisterAsync(setup);
|
||||||
|
var unrelated = await fixture.RegisterAsync(setup);
|
||||||
|
using var limitedClient = fixture.CreateClient();
|
||||||
|
using var otherClient = fixture.CreateClient();
|
||||||
|
const string login = "/api/v1/auth/login";
|
||||||
|
const string wrongPassword = "Wrong-integration-password";
|
||||||
|
var unknown = await ReadAsync<ProblemDetails>(limitedClient.PostAsJsonAsync(login,
|
||||||
|
new LoginRequest("[email protected]", wrongPassword), Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
|
||||||
|
for (var attempt = 0; attempt < 5; attempt++)
|
||||||
|
{
|
||||||
|
var failure = await ReadAsync<ProblemDetails>(limitedClient.PostAsJsonAsync(login,
|
||||||
|
new LoginRequest($" {user.Email.ToUpperInvariant()} ", wrongPassword), Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
Assert.Equal((unknown.Status, unknown.Title, unknown.Type), (failure.Status, failure.Title, failure.Type));
|
||||||
|
}
|
||||||
|
|
||||||
|
await ExpectAsync(limitedClient.PostAsJsonAsync(login, new LoginRequest(user.Email, Password), Cancellation),
|
||||||
|
HttpStatusCode.TooManyRequests);
|
||||||
|
Assert.Equal(unrelated.Id, (await LoginAsync(limitedClient, unrelated.Email)).User.Id);
|
||||||
|
Assert.Equal(user.Id, (await LoginAsync(otherClient, user.Email)).User.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ResetReplacesALegacyPasswordAndRevokesTheOldSessionAndDevice()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
var user = await fixture.RegisterAsync(anonymous);
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
var hasher = scope.ServiceProvider.GetRequiredService<IPasswordHasher>();
|
||||||
|
var legacyPassword = new string('ž', 37);
|
||||||
|
var account = await db.Users.SingleAsync(u => u.Id == user.Id, Cancellation);
|
||||||
|
account.ChangePasswordHash(hasher.Hash(legacyPassword));
|
||||||
|
await db.SaveChangesAsync(Cancellation);
|
||||||
|
|
||||||
|
var oldLogin = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login",
|
||||||
|
new LoginRequest(user.Email, legacyPassword), Cancellation));
|
||||||
|
using var oldSession = fixture.CreateClient(oldLogin.AccessToken);
|
||||||
|
await ExpectAsync(oldSession.PostAsJsonAsync("/api/v1/devices",
|
||||||
|
new RegisterDeviceRequest("password-reset-device"), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/forgot-password",
|
||||||
|
new ForgotPasswordRequest(user.Email), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
|
||||||
|
var newPassword = new string('č', 36);
|
||||||
|
var reset = new ResetPasswordRequest(await fixture.TakeResetTokenAsync(user.Email), newPassword);
|
||||||
|
var validation = await ReadAsync<ValidationProblemDetails>(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password",
|
||||||
|
reset with { NewPassword = newPassword + "a" }, Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
Assert.Contains("72 bajtů", Assert.Single(validation.Errors["newPassword"]));
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", reset, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", reset, Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
await ExpectAsync(oldSession.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login",
|
||||||
|
new LoginRequest(user.Email, legacyPassword), Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
var session = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login",
|
||||||
|
new LoginRequest(user.Email, newPassword), Cancellation));
|
||||||
|
Assert.Equal(user.Id, session.User.Id);
|
||||||
|
Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == user.Id, Cancellation));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task LogoutRevokesOnlyTheCurrentSession()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
var user = await fixture.RegisterAsync(anonymous);
|
||||||
|
var session = await LoginAsync(anonymous, user.Email);
|
||||||
|
var otherSession = await LoginAsync(anonymous, user.Email);
|
||||||
|
using var client = fixture.CreateClient(session.AccessToken);
|
||||||
|
using var otherClient = fixture.CreateClient(otherSession.AccessToken);
|
||||||
|
var refresh = new RefreshTokenRequest(session.RefreshToken);
|
||||||
|
|
||||||
|
await ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/logout", refresh, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
|
||||||
|
await ExpectAsync(client.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
await ExpectAsync(otherClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.OK);
|
||||||
|
var accessId = new JsonWebToken(session.AccessToken).Id;
|
||||||
|
var refreshId = new JsonWebToken(session.RefreshToken).Id;
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
Assert.Equal(2, await db.AuthTokens.CountAsync(token =>
|
||||||
|
token.UserId == user.Id && (token.Jti == accessId || token.Jti == refreshId) &&
|
||||||
|
token.RevokeReason == RevokeReason.Logout, Cancellation));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task LogoutAllRemovesAllDevicesForTheAccount()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
var user = await fixture.RegisterAsync(anonymous);
|
||||||
|
var otherUser = await fixture.RegisterAsync(anonymous);
|
||||||
|
using var first = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
|
||||||
|
using var second = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
|
||||||
|
using var unrelated = fixture.CreateClient((await LoginAsync(anonymous, otherUser.Email)).AccessToken);
|
||||||
|
const string devices = "/api/v1/devices";
|
||||||
|
await ExpectAsync(first.PostAsJsonAsync(devices, new RegisterDeviceRequest("logout-first"), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(second.PostAsJsonAsync(devices, new RegisterDeviceRequest("logout-second"), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(unrelated.PostAsJsonAsync(devices, new RegisterDeviceRequest("logout-unrelated"), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
|
||||||
|
await ExpectAsync(first.PostAsync("/api/v1/auth/logout-all", null, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(first.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
await ExpectAsync(second.PostAsJsonAsync(devices, new RegisterDeviceRequest("logout-second"), Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == user.Id, Cancellation));
|
||||||
|
Assert.True(await db.PushDevices.AnyAsync(device => device.UserId == otherUser.Id, Cancellation));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ConcurrentRefreshRevokesTheNewPairAndOtherSessions()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
var user = await fixture.RegisterAsync(anonymous);
|
||||||
|
var session = await LoginAsync(anonymous, user.Email);
|
||||||
|
var otherSession = await LoginAsync(anonymous, user.Email);
|
||||||
|
using var otherClient = fixture.CreateClient(otherSession.AccessToken);
|
||||||
|
await ExpectAsync(otherClient.PostAsJsonAsync("/api/v1/devices",
|
||||||
|
new RegisterDeviceRequest("refresh-replay-device"), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
var refresh = new RefreshTokenRequest(session.RefreshToken);
|
||||||
|
|
||||||
|
var pause = fixture.TokenSaves.PauseNextSave();
|
||||||
|
Task<HttpResponseMessage> first;
|
||||||
|
Task<HttpResponseMessage> duplicate;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
first = anonymous.PostAsJsonAsync("/api/v1/auth/refresh", refresh, Cancellation);
|
||||||
|
await pause.Entered.Task.WaitAsync(TimeSpan.FromSeconds(15), Cancellation);
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
Assert.Equal(2, await db.AuthTokens.CountAsync(token =>
|
||||||
|
token.UserId == user.Id && token.TokenType == TokenType.Refresh && token.RevokedAt == null, Cancellation));
|
||||||
|
duplicate = anonymous.PostAsJsonAsync("/api/v1/auth/refresh", refresh, Cancellation);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
pause.Release();
|
||||||
|
}
|
||||||
|
|
||||||
|
var renewed = await ReadAsync<AuthResponse>(first);
|
||||||
|
await ExpectAsync(duplicate, HttpStatusCode.Unauthorized);
|
||||||
|
await using var after = fixture.Services.CreateAsyncScope();
|
||||||
|
var afterDb = after.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
Assert.False(await afterDb.AuthTokens.AnyAsync(token => token.UserId == user.Id && token.RevokedAt == null, Cancellation));
|
||||||
|
Assert.False(await afterDb.PushDevices.AnyAsync(device => device.UserId == user.Id, Cancellation));
|
||||||
|
|
||||||
|
using var renewedClient = fixture.CreateClient(renewed.AccessToken);
|
||||||
|
await ExpectAsync(renewedClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
await ExpectAsync(otherClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using Helpdesk.Application.Abstractions;
|
||||||
|
using Helpdesk.Application.Auth;
|
||||||
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Application.Users;
|
||||||
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
|
using Microsoft.AspNetCore.Hosting;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
|
using Microsoft.AspNetCore.TestHost;
|
||||||
|
using Microsoft.AspNetCore.WebUtilities;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using Testcontainers.MariaDb;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
public sealed class BackendFixture : IAsyncLifetime
|
||||||
|
{
|
||||||
|
internal const string AdminEmail = "[email protected]";
|
||||||
|
internal const string Password = "Integration-test-password";
|
||||||
|
internal static string MigrationsPath => Path.Combine(AppContext.BaseDirectory, "migrations");
|
||||||
|
internal static CancellationToken Cancellation => TestContext.Current.CancellationToken;
|
||||||
|
|
||||||
|
private readonly MariaDbContainer database = new MariaDbBuilder("mariadb:11.4")
|
||||||
|
.WithDatabase("helpdesk")
|
||||||
|
.WithPassword(Convert.ToHexString(RandomNumberGenerator.GetBytes(24)))
|
||||||
|
.WithCommand("--character-set-server=utf8mb4")
|
||||||
|
.Build();
|
||||||
|
private readonly TestEmailSender email = new();
|
||||||
|
private ApiFactory? factory;
|
||||||
|
private int clientNumber;
|
||||||
|
|
||||||
|
internal TokenSaveGate TokenSaves { get; } = new();
|
||||||
|
internal IServiceProvider Services => factory!.Services;
|
||||||
|
|
||||||
|
public async ValueTask InitializeAsync()
|
||||||
|
{
|
||||||
|
await database.StartAsync(Cancellation);
|
||||||
|
await RunMigratorAsync(database.GetConnectionString());
|
||||||
|
factory = new ApiFactory(database.GetConnectionString(), email, TokenSaves);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async ValueTask DisposeAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (factory is not null)
|
||||||
|
await factory.DisposeAsync();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await database.DisposeAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal HttpClient CreateClient(string? accessToken = null)
|
||||||
|
{
|
||||||
|
// Každý klient simuluje vlastní IP adresu a má vlastní limit požadavků na přihlášení.
|
||||||
|
var address = IPAddress.Parse($"2001:db8::{Interlocked.Increment(ref clientNumber):x}");
|
||||||
|
var server = factory!.Server;
|
||||||
|
var client = new HttpClient(server.CreateHandler(context => context.Connection.RemoteIpAddress = address))
|
||||||
|
{
|
||||||
|
BaseAddress = server.BaseAddress,
|
||||||
|
};
|
||||||
|
if (accessToken is not null)
|
||||||
|
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal WebApplicationFactory<Program> CreateApiBehindProxies(string proxyIp, string webIp) =>
|
||||||
|
new ApiFactory(database.GetConnectionString(), email, TokenSaves, proxyIp, webIp);
|
||||||
|
|
||||||
|
internal async Task<UserDto> RegisterAsync(HttpClient client)
|
||||||
|
{
|
||||||
|
var address = $"{Guid.NewGuid():N}@student.example.test";
|
||||||
|
var user = await ReadAsync<UserDto>(client.PostAsJsonAsync("/api/v1/auth/register",
|
||||||
|
new RegisterRequest(address, "Test", "User"), Cancellation), HttpStatusCode.Created);
|
||||||
|
await ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/confirm-email",
|
||||||
|
new ConfirmEmailRequest(await TakeConfirmationTokenAsync(address), Password), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal async Task<AuthResponse> RegisterStaffAsync(HttpClient anonymous, HttpClient admin, string role)
|
||||||
|
{
|
||||||
|
var user = await RegisterAsync(anonymous);
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync($"/api/v1/admin/users/{user.Id}/role",
|
||||||
|
new ChangeRoleRequest(role), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
return await LoginAsync(anonymous, user.Email);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal Task<string> TakeConfirmationTokenAsync(string address) => email.TakeTokenAsync(address, "/confirm-email");
|
||||||
|
|
||||||
|
internal Task<string> TakeResetTokenAsync(string address) => email.TakeTokenAsync(address, "/reset-password");
|
||||||
|
|
||||||
|
internal void FailNextEmail(string address, string reason, bool retryable) =>
|
||||||
|
email.Failures[address] = new EmailDeliveryException(reason, retryable);
|
||||||
|
|
||||||
|
internal static Task<AuthResponse> LoginAsync(HttpClient client, string address) =>
|
||||||
|
ReadAsync<AuthResponse>(client.PostAsJsonAsync("/api/v1/auth/login",
|
||||||
|
new LoginRequest(address, Password), Cancellation));
|
||||||
|
|
||||||
|
internal static async Task<T> ReadAsync<T>(Task<HttpResponseMessage> request, HttpStatusCode expected = HttpStatusCode.OK)
|
||||||
|
where T : class
|
||||||
|
{
|
||||||
|
using var response = await request;
|
||||||
|
Assert.Equal(expected, response.StatusCode);
|
||||||
|
return Assert.IsType<T>(await response.Content.ReadFromJsonAsync<T>(Cancellation));
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static async Task ExpectAsync(Task<HttpResponseMessage> request, HttpStatusCode expected)
|
||||||
|
{
|
||||||
|
using var response = await request;
|
||||||
|
Assert.Equal(expected, response.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task RunMigratorAsync(string connectionString)
|
||||||
|
{
|
||||||
|
var startInfo = new ProcessStartInfo(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet")
|
||||||
|
{
|
||||||
|
RedirectStandardOutput = true,
|
||||||
|
RedirectStandardError = true,
|
||||||
|
};
|
||||||
|
startInfo.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "Helpdesk.Migrator.dll"));
|
||||||
|
startInfo.Environment["ConnectionStrings__Migrator"] = connectionString;
|
||||||
|
startInfo.Environment["MIGRATIONS_PATH"] = MigrationsPath;
|
||||||
|
using var process = Process.Start(startInfo) ?? throw new InvalidOperationException("Could not start the migrator.");
|
||||||
|
var output = process.StandardOutput.ReadToEndAsync(Cancellation);
|
||||||
|
var errors = process.StandardError.ReadToEndAsync(Cancellation);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await process.WaitForExitAsync(Cancellation);
|
||||||
|
Assert.True(process.ExitCode == 0, $"Migrator failed with exit code {process.ExitCode}.\n{await output}\n{await errors}");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (!process.HasExited)
|
||||||
|
{
|
||||||
|
process.Kill();
|
||||||
|
await process.WaitForExitAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class ApiFactory(string connectionString, TestEmailSender email, TokenSaveGate tokenSaves,
|
||||||
|
string proxyIp = "", string webIp = "")
|
||||||
|
: WebApplicationFactory<Program>
|
||||||
|
{
|
||||||
|
private readonly Dictionary<string, string?> settings = new()
|
||||||
|
{
|
||||||
|
["ConnectionStrings:Helpdesk"] = connectionString,
|
||||||
|
["Jwt:SigningKey"] = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)),
|
||||||
|
["Encryption:Key"] = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)),
|
||||||
|
["Registration:StudentEmailDomains:0"] = "student.example.test",
|
||||||
|
["Registration:WebBaseUrl"] = "https://helpdesk.example.test",
|
||||||
|
["ADMIN_EMAIL"] = AdminEmail,
|
||||||
|
["ADMIN_PASSWORD"] = Password,
|
||||||
|
["Firebase:ServiceAccountJson"] = "",
|
||||||
|
["Smtp:Mailbox"] = "",
|
||||||
|
["Smtp:Password"] = "",
|
||||||
|
["ReverseProxy:TrustedIp"] = proxyIp,
|
||||||
|
["ReverseProxy:TrustedWebIp"] = webIp,
|
||||||
|
};
|
||||||
|
|
||||||
|
protected override IHost CreateHost(IHostBuilder builder)
|
||||||
|
{
|
||||||
|
// Program čte konfiguraci před Build(), proto musí hodnoty dostat už při startu.
|
||||||
|
builder.UseEnvironment(Environments.Development)
|
||||||
|
.ConfigureHostConfiguration(config => config.AddInMemoryCollection(settings));
|
||||||
|
return base.CreateHost(builder);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void ConfigureWebHost(IWebHostBuilder builder) =>
|
||||||
|
builder.ConfigureTestServices(services =>
|
||||||
|
{
|
||||||
|
services.RemoveAll<IEmailSender>();
|
||||||
|
services.AddSingleton<IEmailSender>(email);
|
||||||
|
services.AddDbContext<HelpdeskDbContext>((_, options) => options.AddInterceptors(tokenSaves));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class TestEmailSender : IEmailSender
|
||||||
|
{
|
||||||
|
private readonly ConcurrentDictionary<(string Address, string Path), TaskCompletionSource<string>> tokens = new();
|
||||||
|
internal ConcurrentDictionary<string, EmailDeliveryException> Failures { get; } = new();
|
||||||
|
|
||||||
|
public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (Failures.TryRemove(to, out var failure))
|
||||||
|
throw failure;
|
||||||
|
|
||||||
|
if (Uri.TryCreate(body[(body.LastIndexOf('\n') + 1)..], UriKind.Absolute, out var link) &&
|
||||||
|
link.AbsolutePath is "/confirm-email" or "/reset-password")
|
||||||
|
{
|
||||||
|
var token = QueryHelpers.ParseQuery(link.Query)["token"].ToString();
|
||||||
|
GetTokenSlot((to, link.AbsolutePath)).TrySetResult(token);
|
||||||
|
}
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal async Task<string> TakeTokenAsync(string address, string path)
|
||||||
|
{
|
||||||
|
var key = (address, path);
|
||||||
|
var token = await GetTokenSlot(key).Task.WaitAsync(TimeSpan.FromSeconds(10), Cancellation);
|
||||||
|
tokens.TryRemove(key, out _);
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
private TaskCompletionSource<string> GetTokenSlot((string Address, string Path) key) =>
|
||||||
|
tokens.GetOrAdd(key, _ => new(TaskCreationOptions.RunContinuationsAsynchronously));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Helpdesk.Api.Controllers;
|
||||||
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using MySqlConnector;
|
||||||
|
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
public sealed class DatabaseTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task MigratorAppliesEveryScriptAndEfCanReadTheSchema()
|
||||||
|
{
|
||||||
|
using var client = fixture.CreateClient();
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
var expected = Directory.EnumerateFiles(MigrationsPath, "V*__*.sql")
|
||||||
|
.Select(Path.GetFileName).Order(StringComparer.Ordinal).ToArray();
|
||||||
|
var applied = await db.Database
|
||||||
|
.SqlQueryRaw<string>("SELECT scriptname AS Value FROM schema_version ORDER BY schemaversionid")
|
||||||
|
.ToListAsync(Cancellation);
|
||||||
|
Assert.Equal(expected, applied);
|
||||||
|
var health = await ReadAsync<HealthResponse>(client.GetAsync("/health", Cancellation));
|
||||||
|
Assert.Equal(new HealthResponse("Healthy", expected[^1]), health);
|
||||||
|
|
||||||
|
await db.Users.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.AuthTokens.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.Buildings.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.IssueCategories.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.ProposalCategories.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.Issues.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.IssueEvents.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.IssueTimings.ToListAsync(Cancellation);
|
||||||
|
await db.Attachments.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.Proposals.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.ProposalEvents.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.ProposalVotes.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.ProposalScores.ToListAsync(Cancellation);
|
||||||
|
await db.Notifications.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.NotificationDeliveries.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.PushDevices.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task OnlyAdministratorsCanReadTheOpenApiDocument()
|
||||||
|
{
|
||||||
|
using var client = fixture.CreateClient();
|
||||||
|
const string path = "/api/v1/admin/openapi/v1.json";
|
||||||
|
await ExpectAsync(client.GetAsync(path, Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
var student = await fixture.RegisterAsync(client);
|
||||||
|
using var studentClient = fixture.CreateClient((await LoginAsync(client, student.Email)).AccessToken);
|
||||||
|
await ExpectAsync(studentClient.GetAsync(path, Cancellation), HttpStatusCode.Forbidden);
|
||||||
|
using var admin = fixture.CreateClient((await LoginAsync(client, AdminEmail)).AccessToken);
|
||||||
|
await ExpectAsync(admin.GetAsync("/swagger/index.html", Cancellation), HttpStatusCode.NotFound);
|
||||||
|
await ExpectAsync(admin.GetAsync("/swagger/v1/swagger.json", Cancellation), HttpStatusCode.NotFound);
|
||||||
|
using var document = await ReadAsync<JsonDocument>(admin.GetAsync(path, Cancellation));
|
||||||
|
var paths = document.RootElement.GetProperty("paths");
|
||||||
|
var create = paths.GetProperty("/api/v1/issues").GetProperty("post").GetProperty("requestBody").GetProperty("content");
|
||||||
|
Assert.True(create.TryGetProperty("application/json", out _));
|
||||||
|
var createSchema = create.GetProperty("multipart/form-data").GetProperty("schema");
|
||||||
|
Assert.Contains(createSchema.GetProperty("required").EnumerateArray(), field => field.GetString() == "categoryId");
|
||||||
|
var uploadSchema = paths.GetProperty("/api/v1/issues/{id}/attachments").GetProperty("post")
|
||||||
|
.GetProperty("requestBody").GetProperty("content").GetProperty("multipart/form-data").GetProperty("schema");
|
||||||
|
Assert.Equal("files", Assert.Single(uploadSchema.GetProperty("required").EnumerateArray()).GetString());
|
||||||
|
var files = uploadSchema.GetProperty("properties").GetProperty("files");
|
||||||
|
Assert.Equal(5, files.GetProperty("maxItems").GetInt32());
|
||||||
|
Assert.Equal("binary", files.GetProperty("items").GetProperty("format").GetString());
|
||||||
|
|
||||||
|
var schemas = document.RootElement.GetProperty("components").GetProperty("schemas");
|
||||||
|
AssertRequiredBooleans(schemas.GetProperty("UpdateProfileRequest"), "emailNotificationsEnabled");
|
||||||
|
AssertRequiredBooleans(schemas.GetProperty("SetActiveRequest"), "isActive");
|
||||||
|
AssertRequiredBooleans(schemas.GetProperty("SaveAdminUserRequest"), "isActive", "emailConfirmed", "emailNotificationsEnabled");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AssertRequiredBooleans(JsonElement schema, params string[] fields)
|
||||||
|
{
|
||||||
|
var properties = schema.GetProperty("properties");
|
||||||
|
foreach (var field in fields)
|
||||||
|
{
|
||||||
|
Assert.Contains(schema.GetProperty("required").EnumerateArray(), property => property.GetString() == field);
|
||||||
|
Assert.Equal("boolean", properties.GetProperty(field).GetProperty("type").GetString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task DatabaseRejectsAnAssignedIssueWithoutAnAssignee()
|
||||||
|
{
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
var reporterId = await db.Users.Where(user => user.Email == AdminEmail).Select(user => user.Id).SingleAsync(Cancellation);
|
||||||
|
var categoryId = await db.IssueCategories.MinAsync(category => category.Id, Cancellation);
|
||||||
|
|
||||||
|
var error = await Assert.ThrowsAsync<MySqlException>(() => db.Database.ExecuteSqlInterpolatedAsync($"""
|
||||||
|
INSERT INTO issue (title, description, category_id, reporter_id, status)
|
||||||
|
VALUES ('Test', 'Test', {categoryId}, {reporterId}, 'ASSIGNED')
|
||||||
|
""", Cancellation));
|
||||||
|
Assert.Contains("ck_issue_assignee", error.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using Helpdesk.Application.Abstractions;
|
||||||
|
using Helpdesk.Application.Auth;
|
||||||
|
using Helpdesk.Application.Users;
|
||||||
|
using Helpdesk.Domain.Auth;
|
||||||
|
using Helpdesk.Domain.Users;
|
||||||
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
public sealed class EmailConfirmationTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||||
|
{
|
||||||
|
private const string Register = "/api/v1/auth/register";
|
||||||
|
private const string Confirm = "/api/v1/auth/confirm-email";
|
||||||
|
private const string Login = "/api/v1/auth/login";
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task FailedRegistrationEmailCanBeRetriedForTheSameAccount()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
const string address = "[email protected]";
|
||||||
|
var request = new RegisterRequest(address, "Jan", "Novák");
|
||||||
|
fixture.FailNextEmail(address, "SMTP_UNAVAILABLE", retryable: true);
|
||||||
|
|
||||||
|
var failure = await ReadAsync<ProblemDetails>(anonymous.PostAsJsonAsync(Register, request, Cancellation),
|
||||||
|
HttpStatusCode.ServiceUnavailable);
|
||||||
|
Assert.Equal("urn:ntbug:email-delivery-failed", failure.Type);
|
||||||
|
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
var pending = await db.Users.AsNoTracking().SingleAsync(user => user.Email == address, Cancellation);
|
||||||
|
Assert.False(pending.EmailConfirmed);
|
||||||
|
Assert.Empty(pending.PasswordHash);
|
||||||
|
|
||||||
|
var retried = await ReadAsync<UserDto>(anonymous.PostAsJsonAsync(Register, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
Assert.Equal(pending.Id, retried.Id);
|
||||||
|
var token = await fixture.TakeConfirmationTokenAsync(address);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(token, Password), Cancellation),
|
||||||
|
HttpStatusCode.NoContent);
|
||||||
|
Assert.Equal(pending.Id, (await LoginAsync(anonymous, address)).User.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task RegistrationHasNoPasswordUntilTheMailboxOwnerSetsIt()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
const string address = "[email protected]";
|
||||||
|
var user = await ReadAsync<UserDto>(anonymous.PostAsJsonAsync(Register,
|
||||||
|
new RegisterRequest(address, "Jan", "Novák"), Cancellation), HttpStatusCode.Created);
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
var pending = await db.Users.AsNoTracking().SingleAsync(u => u.Id == user.Id, Cancellation);
|
||||||
|
Assert.False(pending.EmailConfirmed);
|
||||||
|
Assert.Empty(pending.PasswordHash);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Login, new LoginRequest(address, Password), Cancellation),
|
||||||
|
HttpStatusCode.Unauthorized);
|
||||||
|
|
||||||
|
var token = await fixture.TakeConfirmationTokenAsync(address);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(token, Password), Cancellation),
|
||||||
|
HttpStatusCode.NoContent);
|
||||||
|
Assert.Equal(user.Id, (await LoginAsync(anonymous, address)).User.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AnExistingConfirmationLinkRequiresANewPasswordAndCanOnlyBeUsedOnce()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
var hasher = scope.ServiceProvider.GetRequiredService<IPasswordHasher>();
|
||||||
|
const string address = "[email protected]";
|
||||||
|
const string oldPassword = "Legacy-unconfirmed-password";
|
||||||
|
var pending = User.Create(address, hasher.Hash(oldPassword), "Eva", "Nováková", UserRole.Student);
|
||||||
|
db.Users.Add(pending);
|
||||||
|
await db.SaveChangesAsync(Cancellation);
|
||||||
|
var original = scope.ServiceProvider.GetRequiredService<ITokenService>().Issue(pending, TokenType.EmailConfirm);
|
||||||
|
db.AuthTokens.Add(original.Record);
|
||||||
|
await db.SaveChangesAsync(Cancellation);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Login, new LoginRequest(address, oldPassword), Cancellation),
|
||||||
|
HttpStatusCode.Unauthorized);
|
||||||
|
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Register, new RegisterRequest(address, "Jiné", "Jméno"), Cancellation),
|
||||||
|
HttpStatusCode.Created);
|
||||||
|
var otherToken = await fixture.TakeConfirmationTokenAsync(address);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new { token = original.Token }, Cancellation),
|
||||||
|
HttpStatusCode.BadRequest);
|
||||||
|
var newPassword = new string('č', 36);
|
||||||
|
var validation = await ReadAsync<ValidationProblemDetails>(anonymous.PostAsJsonAsync(Confirm,
|
||||||
|
new ConfirmEmailRequest(original.Token, newPassword + "a"), Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
Assert.Contains("72 bajtů", Assert.Single(validation.Errors["newPassword"]));
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(original.Token, newPassword), Cancellation),
|
||||||
|
HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(otherToken, oldPassword), Cancellation),
|
||||||
|
HttpStatusCode.BadRequest);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Login, new LoginRequest(address, oldPassword), Cancellation),
|
||||||
|
HttpStatusCode.Unauthorized);
|
||||||
|
var session = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync(Login, new LoginRequest(address, newPassword), Cancellation));
|
||||||
|
Assert.Equal((pending.Id, pending.FirstName, pending.LastName), (session.User.Id, session.User.FirstName, session.User.LastName));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\..\src\Helpdesk.Api\Helpdesk.Api.csproj" />
|
||||||
|
<ProjectReference Include="..\..\src\Helpdesk.Migrator\Helpdesk.Migrator.csproj" />
|
||||||
|
<None Include="..\..\..\db\migrations\V*__*.sql" Link="migrations\%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" />
|
||||||
|
<PackageReference Include="Microsoft.Testing.Extensions.CodeCoverage" PrivateAssets="all" />
|
||||||
|
<PackageReference Include="MySqlConnector" />
|
||||||
|
<PackageReference Include="Testcontainers.MariaDb" />
|
||||||
|
<PackageReference Include="xunit.v3" />
|
||||||
|
<Using Include="Xunit" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using Helpdesk.Application.Catalogs;
|
||||||
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Application.Issues;
|
||||||
|
using Helpdesk.Application.Notifications;
|
||||||
|
using Helpdesk.Application.Statistics;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task IssueValidationReturnsErrorsWithFieldNames()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
var administrator = await LoginAsync(anonymous, AdminEmail);
|
||||||
|
using var admin = fixture.CreateClient(administrator.AccessToken);
|
||||||
|
const string issues = "/api/v1/issues";
|
||||||
|
var invalid = new CreateIssueRequest(new string('t', 201), " ", int.MaxValue, int.MaxValue, new string('l', 256));
|
||||||
|
|
||||||
|
var creationError = await ReadAsync<ValidationProblemDetails>(admin.PostAsJsonAsync(issues, invalid, Cancellation),
|
||||||
|
HttpStatusCode.BadRequest);
|
||||||
|
Assert.Equal(["buildingId", "categoryId", "description", "locationDetail", "title"], creationError.Errors.Keys.Order());
|
||||||
|
|
||||||
|
using var form = new MultipartFormDataContent { { new StringContent("invalid"), "categoryId" } };
|
||||||
|
var uploadError = await ReadAsync<ValidationProblemDetails>(admin.PostAsync(issues, form, Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
Assert.Equal("categoryId", Assert.Single(uploadError.Errors.Keys));
|
||||||
|
|
||||||
|
var categories = await ReadAsync<CategoryDto[]>(admin.GetAsync("/api/v1/issue-categories", Cancellation));
|
||||||
|
var issue = await PostIssueAsync(admin, issues, new CreateIssueRequest("Projektor", "Bliká.", categories[0].Id, null, null),
|
||||||
|
HttpStatusCode.Created);
|
||||||
|
var path = $"{issues}/{issue.Id}";
|
||||||
|
var edit = new EditIssueRequest(issue.Title, issue.Description, int.MaxValue, null, null, issue.RowVersion);
|
||||||
|
var editError = await ReadAsync<ValidationProblemDetails>(admin.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
Assert.Equal("categoryId", Assert.Single(editError.Errors.Keys));
|
||||||
|
|
||||||
|
var assign = new AssignIssueRequest(administrator.User.Id, "UNKNOWN", issue.RowVersion);
|
||||||
|
var priorityError = await ReadAsync<ValidationProblemDetails>(admin.PostAsJsonAsync(path + "/assign", assign, Cancellation),
|
||||||
|
HttpStatusCode.BadRequest);
|
||||||
|
Assert.Equal("priority", Assert.Single(priorityError.Errors.Keys));
|
||||||
|
var saved = await ReadAsync<IssueDetail>(admin.GetAsync(path, Cancellation));
|
||||||
|
Assert.Equal((issue.RowVersion, issue.CategoryId, issue.AssigneeId), (saved.RowVersion, saved.CategoryId, saved.AssigneeId));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ReporterAndAssigneesCanResolveAnIssueAndManagementCanReportOnIt()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
var administrator = await LoginAsync(anonymous, AdminEmail);
|
||||||
|
using var admin = fixture.CreateClient(administrator.AccessToken);
|
||||||
|
var author = await fixture.RegisterAsync(anonymous);
|
||||||
|
using var reporter = fixture.CreateClient((await LoginAsync(anonymous, author.Email)).AccessToken);
|
||||||
|
var management = await fixture.RegisterStaffAsync(anonymous, admin, "MANAGEMENT");
|
||||||
|
var firstAssignee = await fixture.RegisterStaffAsync(anonymous, admin, "FACILITY_MANAGER");
|
||||||
|
var secondAssignee = await fixture.RegisterStaffAsync(anonymous, admin, "FACILITY_MANAGER");
|
||||||
|
using var manager = fixture.CreateClient(management.AccessToken);
|
||||||
|
using var firstSolver = fixture.CreateClient(firstAssignee.AccessToken);
|
||||||
|
using var secondSolver = fixture.CreateClient(secondAssignee.AccessToken);
|
||||||
|
|
||||||
|
var categories = await ReadAsync<CategoryDto[]>(reporter.GetAsync("/api/v1/issue-categories", Cancellation));
|
||||||
|
var buildings = await ReadAsync<BuildingDto[]>(reporter.GetAsync("/api/v1/buildings", Cancellation));
|
||||||
|
var request = new CreateIssueRequest("Nefunkční projektor", "Projektor se nezapne.", categories[0].Id, buildings[0].Id, "A101");
|
||||||
|
var issue = await PostIssueAsync(reporter, "/api/v1/issues", request, HttpStatusCode.Created);
|
||||||
|
var path = $"/api/v1/issues/{issue.Id}";
|
||||||
|
Assert.Equal("RECEIVED", issue.Status);
|
||||||
|
await ExpectAsync(anonymous.GetAsync(path, Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
|
||||||
|
issue = await ReadAsync<IssueDetail>(reporter.PutAsJsonAsync(path,
|
||||||
|
new EditIssueRequest(issue.Title, "Projektor nereaguje ani po restartu.", issue.CategoryId,
|
||||||
|
issue.BuildingId, issue.LocationDetail, issue.RowVersion), Cancellation));
|
||||||
|
Assert.Equal("Projektor nereaguje ani po restartu.", issue.Description);
|
||||||
|
issue = await ReadAsync<IssueDetail>(admin.PutAsJsonAsync(path,
|
||||||
|
new EditIssueRequest(issue.Title, issue.Description, issue.CategoryId,
|
||||||
|
issue.BuildingId, "A102", issue.RowVersion), Cancellation));
|
||||||
|
Assert.Equal(("A102", author.Id), (issue.LocationDetail, issue.ReporterId));
|
||||||
|
var assign = new AssignIssueRequest(firstAssignee.User.Id, null, issue.RowVersion);
|
||||||
|
await ExpectAsync(reporter.PostAsJsonAsync(path + "/assign", assign, Cancellation), HttpStatusCode.Forbidden);
|
||||||
|
issue = await PostIssueAsync(admin, path + "/assign", assign);
|
||||||
|
Assert.Equal(firstAssignee.User.Id, issue.AssigneeId);
|
||||||
|
Assert.Contains("ASSIGN", (await ReadAsync<IssueDetail>(admin.GetAsync(path, Cancellation))).AllowedActions);
|
||||||
|
var adminIssues = await ReadAsync<PagedResult<IssueSummary>>(admin.GetAsync("/api/v1/issues", Cancellation));
|
||||||
|
Assert.Contains(adminIssues.Items, item => item.Id == issue.Id);
|
||||||
|
var assignable = await ReadAsync<AssignableUserDto[]>(admin.GetAsync("/api/v1/users/assignable", Cancellation));
|
||||||
|
Assert.Contains(assignable, user => user.Id == firstAssignee.User.Id);
|
||||||
|
Assert.Contains(assignable, user => user.Id == administrator.User.Id);
|
||||||
|
var conflict = await ReadAsync<ProblemDetails>(firstSolver.PostAsJsonAsync(path + "/start",
|
||||||
|
new IssueVersionRequest(assign.RowVersion), Cancellation), HttpStatusCode.Conflict);
|
||||||
|
Assert.Equal("urn:ntbug:issue-version-conflict", conflict.Type);
|
||||||
|
|
||||||
|
var reporterNotifications = await InboxAsync(reporter, issue.Id);
|
||||||
|
Assert.Equal("ISSUE_STATUS_CHANGED", Assert.Single(reporterNotifications).Type);
|
||||||
|
issue = await PostIssueAsync(manager, path + "/assign", new AssignIssueRequest(secondAssignee.User.Id, null, issue.RowVersion));
|
||||||
|
Assert.Equal("ISSUE_ASSIGNED", Assert.Single(await InboxAsync(secondSolver, issue.Id)).Type);
|
||||||
|
Assert.Equal(reporterNotifications, await InboxAsync(reporter, issue.Id));
|
||||||
|
|
||||||
|
issue = await PostIssueAsync(admin, path + "/start", new IssueVersionRequest(issue.RowVersion));
|
||||||
|
Assert.Equal("IN_PROGRESS", issue.Status);
|
||||||
|
reporterNotifications = await InboxAsync(reporter, issue.Id);
|
||||||
|
issue = await PostIssueAsync(admin, path + "/assign", new AssignIssueRequest(firstAssignee.User.Id, null, issue.RowVersion));
|
||||||
|
Assert.Equal("ASSIGNED", issue.Status);
|
||||||
|
var reassignment = Assert.Single((await InboxAsync(reporter, issue.Id)).Except(reporterNotifications));
|
||||||
|
Assert.Equal("ISSUE_STATUS_CHANGED", reassignment.Type);
|
||||||
|
Assert.Equal(2, (await InboxAsync(firstSolver, issue.Id)).Count(notification => notification.Type == "ISSUE_ASSIGNED"));
|
||||||
|
|
||||||
|
issue = await PostIssueAsync(firstSolver, path + "/start", new IssueVersionRequest(issue.RowVersion));
|
||||||
|
const string commentText = "Porucha stále trvá.";
|
||||||
|
var comment = await ReadAsync<IssueEventDto>(admin.PostAsJsonAsync(path + "/comments",
|
||||||
|
new CommentRequest(commentText), Cancellation));
|
||||||
|
Assert.Equal(administrator.User.Id, comment.ActorId);
|
||||||
|
issue = await ReadAsync<IssueDetail>(firstSolver.GetAsync(path, Cancellation));
|
||||||
|
issue = await PostIssueAsync(firstSolver, path + "/submit-for-verification", new VerifyIssueRequest(issue.RowVersion, null));
|
||||||
|
Assert.Equal("PENDING_VERIFICATION", issue.Status);
|
||||||
|
issue = await PostIssueAsync(admin, path + "/reopen", new IssueReasonRequest(issue.RowVersion, "Porucha se vrátila."));
|
||||||
|
Assert.Equal("IN_PROGRESS", issue.Status);
|
||||||
|
Assert.Contains(await InboxAsync(firstSolver, issue.Id), notification => notification.Type == "ISSUE_REOPENED");
|
||||||
|
issue = await PostIssueAsync(admin, path + "/submit-for-verification", new VerifyIssueRequest(issue.RowVersion, "Ověřeno."));
|
||||||
|
issue = await PostIssueAsync(admin, path + "/confirm", new IssueVersionRequest(issue.RowVersion));
|
||||||
|
Assert.Equal("RESOLVED", issue.Status);
|
||||||
|
var events = await ReadAsync<IssueEventDto[]>(reporter.GetAsync(path + "/events", Cancellation));
|
||||||
|
Assert.Equal(commentText, Assert.Single(events, entry => entry.Id == comment.Id).Note);
|
||||||
|
Assert.Equal("RESOLVED", events[^1].ToStatus);
|
||||||
|
|
||||||
|
var openIssue = await PostIssueAsync(reporter, "/api/v1/issues",
|
||||||
|
request with { Title = "Porucha osvětlení" }, HttpStatusCode.Created);
|
||||||
|
await VerifyReadsAsync(reporter, manager, issue, openIssue);
|
||||||
|
var rejected = await PostIssueAsync(manager, $"/api/v1/issues/{openIssue.Id}/reject",
|
||||||
|
new IssueReasonRequest(openIssue.RowVersion, "Duplicitní hlášení."));
|
||||||
|
Assert.Equal("REJECTED", rejected.Status);
|
||||||
|
|
||||||
|
var officeIssue = await PostIssueAsync(reporter, "/api/v1/issues",
|
||||||
|
request with { Title = "Porucha v kanceláři" }, HttpStatusCode.Created);
|
||||||
|
var officePath = $"/api/v1/issues/{officeIssue.Id}";
|
||||||
|
officeIssue = await PostIssueAsync(manager, officePath + "/assign",
|
||||||
|
new AssignIssueRequest(administrator.User.Id, null, officeIssue.RowVersion));
|
||||||
|
Assert.Equal(administrator.User.Id, officeIssue.AssigneeId);
|
||||||
|
Assert.Equal("ISSUE_ASSIGNED", Assert.Single(await InboxAsync(admin, officeIssue.Id)).Type);
|
||||||
|
var rejectedByAdmin = await PostIssueAsync(admin, officePath + "/reject",
|
||||||
|
new IssueReasonRequest(officeIssue.RowVersion, "Hlášení je duplicitní."));
|
||||||
|
Assert.Equal("REJECTED", rejectedByAdmin.Status);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task VerifyReadsAsync(HttpClient reporter, HttpClient manager, IssueDetail resolved, IssueDetail open)
|
||||||
|
{
|
||||||
|
var query = $"/api/v1/issues?categoryId={resolved.CategoryId}&buildingId={resolved.BuildingId}&pageSize=1";
|
||||||
|
var first = await ReadAsync<PagedResult<IssueSummary>>(manager.GetAsync(query + "&page=1", Cancellation));
|
||||||
|
var second = await ReadAsync<PagedResult<IssueSummary>>(manager.GetAsync(query + "&page=2", Cancellation));
|
||||||
|
var filtered = await ReadAsync<PagedResult<IssueSummary>>(manager.GetAsync(query + "&status=RESOLVED", Cancellation));
|
||||||
|
Assert.Equal(2, first.TotalCount);
|
||||||
|
Assert.Equal(open.Id, Assert.Single(first.Items).Id);
|
||||||
|
Assert.Equal(resolved.Id, Assert.Single(second.Items).Id);
|
||||||
|
Assert.Equal(1, filtered.TotalCount);
|
||||||
|
Assert.Equal(resolved.Id, Assert.Single(filtered.Items).Id);
|
||||||
|
|
||||||
|
const string overview = "/api/v1/statistics/overview";
|
||||||
|
await ExpectAsync(reporter.GetAsync(overview, Cancellation), HttpStatusCode.Forbidden);
|
||||||
|
var from = Uri.EscapeDataString(resolved.CreatedAt.AddMinutes(-1).ToString("O"));
|
||||||
|
var to = Uri.EscapeDataString(open.CreatedAt.AddMinutes(1).ToString("O"));
|
||||||
|
var period = $"?from={from}&to={to}";
|
||||||
|
var statistics = await ReadAsync<StatisticsOverview>(manager.GetAsync(overview + period, Cancellation));
|
||||||
|
Assert.Equal(2, statistics.TotalIssues);
|
||||||
|
Assert.Equal(1, statistics.IssuesByStatus["RESOLVED"]);
|
||||||
|
Assert.Equal(1, statistics.IssuesByStatus["RECEIVED"]);
|
||||||
|
Assert.NotNull(statistics.AverageHoursToAssignment);
|
||||||
|
Assert.NotNull(statistics.AverageHoursToClosure);
|
||||||
|
var byCategory = Assert.Single(await ReadAsync<IssueCategoryStatistics[]>(
|
||||||
|
manager.GetAsync("/api/v1/statistics/issues/by-category" + period, Cancellation)));
|
||||||
|
Assert.Equal((resolved.CategoryId, 2), (byCategory.CategoryId, byCategory.IssueCount));
|
||||||
|
Assert.NotNull(byCategory.AverageHoursToResolution);
|
||||||
|
var byBuilding = Assert.Single(await ReadAsync<IssueBuildingStatistics[]>(
|
||||||
|
manager.GetAsync("/api/v1/statistics/issues/by-building" + period, Cancellation)));
|
||||||
|
Assert.Equal((resolved.BuildingId, 2), (byBuilding.BuildingId, byBuilding.IssueCount));
|
||||||
|
var byAssignee = Assert.Single(await ReadAsync<IssueAssigneeStatistics[]>(
|
||||||
|
manager.GetAsync("/api/v1/statistics/issues/by-assignee" + period, Cancellation)));
|
||||||
|
Assert.Equal((resolved.AssigneeId, 1, 0), ((int?)byAssignee.AssigneeId, byAssignee.ResolvedIssues, byAssignee.OpenIssues));
|
||||||
|
var available = await ReadAsync<AssignableUserDto[]>(manager.GetAsync("/api/v1/users/assignable", Cancellation));
|
||||||
|
Assert.Contains(available, user => user.Id == resolved.AssigneeId && user.OpenIssues == 0);
|
||||||
|
var trend = await ReadAsync<IssueTrendPoint[]>(manager.GetAsync("/api/v1/statistics/issues/trend" + period, Cancellation));
|
||||||
|
Assert.Equal(2, trend.Sum(point => point.CreatedIssues));
|
||||||
|
Assert.Equal(1, trend.Sum(point => point.ClosedIssues));
|
||||||
|
var after = await ReadAsync<StatisticsOverview>(manager.GetAsync(overview + $"?from={to}", Cancellation));
|
||||||
|
Assert.Equal(0, after.TotalIssues);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Task<IssueDetail> PostIssueAsync<T>(
|
||||||
|
HttpClient client, string path, T request, HttpStatusCode expected = HttpStatusCode.OK) =>
|
||||||
|
ReadAsync<IssueDetail>(client.PostAsJsonAsync(path, request, Cancellation), expected);
|
||||||
|
|
||||||
|
private static async Task<NotificationDto[]> InboxAsync(HttpClient client, int issueId)
|
||||||
|
{
|
||||||
|
var notifications = await ReadAsync<PagedResult<NotificationDto>>(client.GetAsync("/api/v1/notifications", Cancellation));
|
||||||
|
return notifications.Items.Where(notification => notification.IssueId == issueId).ToArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using Helpdesk.Api.Controllers;
|
||||||
|
using Helpdesk.Application.Catalogs;
|
||||||
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Application.Issues;
|
||||||
|
using Helpdesk.Application.Notifications;
|
||||||
|
using Helpdesk.Application.Users;
|
||||||
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
public sealed class NotificationTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task FailedEmailCanBeRetriedAndOnlyTheRecipientCanMarkNotificationsRead()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||||
|
var user = await fixture.RegisterAsync(anonymous);
|
||||||
|
using var reporter = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
|
||||||
|
var managerSession = await fixture.RegisterStaffAsync(anonymous, admin, "MANAGEMENT");
|
||||||
|
using var manager = fixture.CreateClient(managerSession.AccessToken);
|
||||||
|
var categories = await ReadAsync<CategoryDto[]>(reporter.GetAsync("/api/v1/issue-categories", Cancellation));
|
||||||
|
var request = new CreateIssueRequest("Porucha v učebně", "Závadu je potřeba prověřit.", categories[0].Id, null, null);
|
||||||
|
const string inbox = "/api/v1/notifications";
|
||||||
|
const string deliveries = "/api/v1/admin/notification-deliveries";
|
||||||
|
|
||||||
|
fixture.FailNextEmail(managerSession.User.Email, "TEST_RECIPIENT_REJECTED", retryable: false);
|
||||||
|
var issue = await ReadAsync<IssueDetail>(reporter.PostAsJsonAsync("/api/v1/issues", request, Cancellation), HttpStatusCode.Created);
|
||||||
|
var notifications = await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation));
|
||||||
|
var notification = Assert.Single(notifications.Items);
|
||||||
|
Assert.Equal((issue.Id, "ISSUE_CREATED"), (notification.IssueId, notification.Type));
|
||||||
|
await ExpectAsync(reporter.PostAsync($"{inbox}/{notification.Id}/read", null, Cancellation), HttpStatusCode.NotFound);
|
||||||
|
await ExpectAsync(reporter.GetAsync(deliveries, Cancellation), HttpStatusCode.Forbidden);
|
||||||
|
await ExpectAsync(admin.GetAsync(deliveries + "?status=invalid", Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
|
||||||
|
var failed = await WaitForDeliveryAsync(admin, notification.Id, "FAILED");
|
||||||
|
Assert.Equal((1, "TEST_RECIPIENT_REJECTED"), (failed.AttemptCount, failed.LastError));
|
||||||
|
Assert.Null(failed.NextAttemptAt);
|
||||||
|
var retry = $"{deliveries}/{failed.Id}/retry";
|
||||||
|
await ExpectAsync(admin.PostAsync(retry, null, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
var sent = await WaitForDeliveryAsync(admin, notification.Id, "SENT");
|
||||||
|
Assert.Equal(1, sent.AttemptCount);
|
||||||
|
Assert.NotNull(sent.SentAt);
|
||||||
|
Assert.Null(sent.LastError);
|
||||||
|
await ExpectAsync(admin.PostAsync(retry, null, Cancellation), HttpStatusCode.Conflict);
|
||||||
|
await ExpectAsync(admin.PostAsync($"{deliveries}/{int.MaxValue}/retry", null, Cancellation), HttpStatusCode.NotFound);
|
||||||
|
|
||||||
|
var read = $"{inbox}/{notification.Id}/read";
|
||||||
|
await ExpectAsync(manager.PostAsync(read, null, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(manager.PostAsync(read, null, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
Assert.Equal(0, (await ReadAsync<UnreadCountDto>(manager.GetAsync(inbox + "/unread-count", Cancellation))).Count);
|
||||||
|
|
||||||
|
fixture.FailNextEmail(managerSession.User.Email, "TEST_TEMPORARY_FAILURE", retryable: true);
|
||||||
|
var secondIssue = await ReadAsync<IssueDetail>(reporter.PostAsJsonAsync("/api/v1/issues", request, Cancellation), HttpStatusCode.Created);
|
||||||
|
notifications = await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation));
|
||||||
|
notification = Assert.Single(notifications.Items);
|
||||||
|
Assert.Equal(secondIssue.Id, notification.IssueId);
|
||||||
|
var pending = await WaitForDeliveryAsync(admin, notification.Id, "PENDING", attempts: 1);
|
||||||
|
Assert.Equal("TEST_TEMPORARY_FAILURE", pending.LastError);
|
||||||
|
Assert.True(pending.NextAttemptAt > DateTime.UtcNow);
|
||||||
|
await ExpectAsync(manager.PostAsync(inbox + "/read-all", null, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
Assert.Empty((await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation))).Items);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task RoleChangeHidesOtherIssuesAndSkipsQueuedEmail()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||||
|
var reporterAccount = await fixture.RegisterAsync(anonymous);
|
||||||
|
using var reporter = fixture.CreateClient((await LoginAsync(anonymous, reporterAccount.Email)).AccessToken);
|
||||||
|
var managerSession = await fixture.RegisterStaffAsync(anonymous, admin, "MANAGEMENT");
|
||||||
|
using var manager = fixture.CreateClient(managerSession.AccessToken);
|
||||||
|
const string issues = "/api/v1/issues";
|
||||||
|
const string inbox = "/api/v1/notifications";
|
||||||
|
var categories = await ReadAsync<CategoryDto[]>(reporter.GetAsync("/api/v1/issue-categories", Cancellation));
|
||||||
|
var request = new CreateIssueRequest("Závada v učebně", "Závadu je potřeba prověřit.", categories[0].Id, null, null);
|
||||||
|
|
||||||
|
fixture.FailNextEmail(managerSession.User.Email, "TEST_RECIPIENT_REJECTED", retryable: false);
|
||||||
|
var issue = await ReadAsync<IssueDetail>(reporter.PostAsJsonAsync(issues, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
var before = await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox, Cancellation));
|
||||||
|
var hidden = Assert.Single(before.Items);
|
||||||
|
Assert.Equal(issue.Id, hidden.IssueId);
|
||||||
|
var failed = await WaitForDeliveryAsync(admin, hidden.Id, "FAILED");
|
||||||
|
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync($"/api/v1/admin/users/{managerSession.User.Id}/role",
|
||||||
|
new ChangeRoleRequest("STUDENT"), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
using var student = fixture.CreateClient((await LoginAsync(anonymous, managerSession.User.Email)).AccessToken);
|
||||||
|
var ownIssue = await ReadAsync<IssueDetail>(student.PostAsJsonAsync(issues, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
await ReadAsync<IssueEventDto>(admin.PostAsJsonAsync($"{issues}/{ownIssue.Id}/comments",
|
||||||
|
new CommentRequest("Komentář k vlastní závadě uživatele."), Cancellation));
|
||||||
|
|
||||||
|
var after = await ReadAsync<PagedResult<NotificationDto>>(student.GetAsync(inbox, Cancellation));
|
||||||
|
Assert.Equal(1, after.TotalCount);
|
||||||
|
Assert.Equal(ownIssue.Id, Assert.Single(after.Items).IssueId);
|
||||||
|
Assert.Equal(1, (await ReadAsync<UnreadCountDto>(student.GetAsync(inbox + "/unread-count", Cancellation))).Count);
|
||||||
|
await ExpectAsync(student.PostAsync($"{inbox}/{hidden.Id}/read", null, Cancellation), HttpStatusCode.NotFound);
|
||||||
|
await ExpectAsync(student.PostAsync(inbox + "/read-all", null, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
Assert.Equal(0, (await ReadAsync<UnreadCountDto>(student.GetAsync(inbox + "/unread-count", Cancellation))).Count);
|
||||||
|
|
||||||
|
await ExpectAsync(admin.PostAsync($"/api/v1/admin/notification-deliveries/{failed.Id}/retry", null, Cancellation),
|
||||||
|
HttpStatusCode.NoContent);
|
||||||
|
await WaitForDeliveryAsync(admin, hidden.Id, "SKIPPED", attempts: 0);
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
Assert.Null(await db.Notifications.Where(n => n.Id == hidden.Id).Select(n => n.ReadAt).SingleAsync(Cancellation));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task DeviceRegistrationPreservesCaseAndTransfersOwnership()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
var firstUser = await fixture.RegisterAsync(anonymous);
|
||||||
|
var secondUser = await fixture.RegisterAsync(anonymous);
|
||||||
|
using var first = fixture.CreateClient((await LoginAsync(anonymous, firstUser.Email)).AccessToken);
|
||||||
|
using var second = fixture.CreateClient((await LoginAsync(anonymous, secondUser.Email)).AccessToken);
|
||||||
|
const string route = "/api/v1/devices";
|
||||||
|
var token = new RegisterDeviceRequest("CaseSensitiveDevice");
|
||||||
|
var otherCase = new RegisterDeviceRequest("casesensitivedevice");
|
||||||
|
await ExpectAsync(first.PostAsJsonAsync(route, new RegisterDeviceRequest("invalid token"), Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
await ExpectAsync(first.PostAsJsonAsync(route, token, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(first.PostAsJsonAsync(route, otherCase, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(second.PostAsJsonAsync(route, token, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(first.DeleteAsync($"{route}/{token.Token}", Cancellation), HttpStatusCode.NoContent);
|
||||||
|
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
var devices = await db.PushDevices.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
Assert.Equal(secondUser.Id, Assert.Single(devices, item => item.FcmToken == token.Token).UserId);
|
||||||
|
Assert.Equal(firstUser.Id, Assert.Single(devices, item => item.FcmToken == otherCase.Token).UserId);
|
||||||
|
await ExpectAsync(second.DeleteAsync($"{route}/{token.Token}", Cancellation), HttpStatusCode.NoContent);
|
||||||
|
Assert.Equal(otherCase.Token, await db.PushDevices.Select(item => item.FcmToken).SingleAsync(Cancellation));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<NotificationDeliveryDto> WaitForDeliveryAsync(HttpClient client, int notificationId, string status, int attempts = 1)
|
||||||
|
{
|
||||||
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(Cancellation);
|
||||||
|
timeout.CancelAfter(TimeSpan.FromSeconds(15));
|
||||||
|
var path = $"/api/v1/admin/notification-deliveries?status={status}";
|
||||||
|
while (!timeout.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
var page = await ReadAsync<PagedResult<NotificationDeliveryDto>>(client.GetAsync(path, timeout.Token));
|
||||||
|
var delivery = page.Items.SingleOrDefault(item =>
|
||||||
|
item.NotificationId == notificationId && item.Channel == "EMAIL" && item.AttemptCount == attempts);
|
||||||
|
if (delivery is not null)
|
||||||
|
return delivery;
|
||||||
|
await Task.Delay(TimeSpan.FromMilliseconds(100), timeout.Token);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new TimeoutException($"Notification {notificationId} did not reach {status}.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using Helpdesk.Application.Catalogs;
|
||||||
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Application.Notifications;
|
||||||
|
using Helpdesk.Application.Proposals;
|
||||||
|
using Helpdesk.Application.Statistics;
|
||||||
|
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
public sealed class ProposalWorkflowTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||||
|
{
|
||||||
|
private const string Proposals = "/api/v1/proposals";
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task VotesAndDecisionsAreReflectedInTheProposalAndItsHistory()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
var administrator = await LoginAsync(anonymous, AdminEmail);
|
||||||
|
using var admin = fixture.CreateClient(administrator.AccessToken);
|
||||||
|
var authorUser = await fixture.RegisterAsync(anonymous);
|
||||||
|
using var author = fixture.CreateClient((await LoginAsync(anonymous, authorUser.Email)).AccessToken);
|
||||||
|
var managerSession = await fixture.RegisterStaffAsync(anonymous, admin, "MANAGEMENT");
|
||||||
|
using var manager = fixture.CreateClient(managerSession.AccessToken);
|
||||||
|
var categories = await ReadAsync<CategoryDto[]>(author.GetAsync("/api/v1/proposal-categories", Cancellation));
|
||||||
|
var request = new SaveProposalRequest("Prodloužení studovny", "Rozšířit večerní otevírací dobu.", categories[0].Id);
|
||||||
|
await ExpectAsync(author.PostAsJsonAsync(Proposals, request with { Title = " " }, Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
await ExpectAsync(author.PostAsJsonAsync(Proposals, request with { CategoryId = int.MaxValue }, Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
|
||||||
|
var proposal = await ReadAsync<ProposalDetail>(author.PostAsJsonAsync(Proposals, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
Assert.Equal("SUBMITTED", proposal.Status);
|
||||||
|
var path = $"{Proposals}/{proposal.Id}";
|
||||||
|
var edit = request with { CategoryId = categories[1].Id, Description = "Otevřít do 22 hodin." };
|
||||||
|
await ExpectAsync(manager.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.Forbidden);
|
||||||
|
proposal = await ReadAsync<ProposalDetail>(author.PutAsJsonAsync(path, edit, Cancellation));
|
||||||
|
Assert.Equal((edit.CategoryId, edit.Description, "UPDATED"), (proposal.CategoryId, proposal.Description, proposal.Events[^1].EventType));
|
||||||
|
var adminEdit = edit with { Description = "Otevřít do 22 hodin ve všední dny." };
|
||||||
|
proposal = await ReadAsync<ProposalDetail>(admin.PutAsJsonAsync(path, adminEdit, Cancellation));
|
||||||
|
Assert.Equal((adminEdit.Description, authorUser.Id, administrator.User.Id),
|
||||||
|
(proposal.Description, proposal.AuthorId, proposal.Events[^1].ActorId));
|
||||||
|
var other = await ReadAsync<ProposalDetail>(author.PostAsJsonAsync(Proposals, edit with
|
||||||
|
{
|
||||||
|
Title = "Vybavení studovny",
|
||||||
|
}, Cancellation), HttpStatusCode.Created);
|
||||||
|
|
||||||
|
await VerifyVotesAsync(author, manager, path);
|
||||||
|
var from = Uri.EscapeDataString(proposal.CreatedAt.AddMinutes(-1).ToString("O"));
|
||||||
|
var to = Uri.EscapeDataString(other.CreatedAt.AddMinutes(1).ToString("O"));
|
||||||
|
var filter = $"{Proposals}?status=SUBMITTED&categoryId={edit.CategoryId}&authorId={authorUser.Id}&q=studovny&from={from}&to={to}";
|
||||||
|
var first = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync(filter + "&sort=score&pageSize=1", Cancellation));
|
||||||
|
var second = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync(filter + "&sort=score&pageSize=1&page=2", Cancellation));
|
||||||
|
Assert.Equal(2, first.TotalCount);
|
||||||
|
Assert.Equal(proposal.Id, Assert.Single(first.Items).Id);
|
||||||
|
Assert.Equal(other.Id, Assert.Single(second.Items).Id);
|
||||||
|
var newest = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync(filter, Cancellation));
|
||||||
|
Assert.Equal(other.Id, newest.Items[0].Id);
|
||||||
|
var outside = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync($"{Proposals}?from={to}", Cancellation));
|
||||||
|
Assert.Empty(outside.Items);
|
||||||
|
|
||||||
|
await ExpectAsync(author.PostAsJsonAsync(path + "/status", new ChangeProposalStatusRequest("ACCEPTED", null), Cancellation),
|
||||||
|
HttpStatusCode.Forbidden);
|
||||||
|
await ExpectAsync(manager.PostAsJsonAsync(path + "/status", new ChangeProposalStatusRequest("REJECTED", " "), Cancellation),
|
||||||
|
HttpStatusCode.BadRequest);
|
||||||
|
await ExpectAsync(admin.PostAsJsonAsync(path + "/status", new ChangeProposalStatusRequest("IMPLEMENTED", null), Cancellation),
|
||||||
|
HttpStatusCode.Conflict);
|
||||||
|
var review = await ReadAsync<ProposalDetail>(admin.PostAsJsonAsync(path + "/status",
|
||||||
|
new ChangeProposalStatusRequest("UNDER_REVIEW", null), Cancellation));
|
||||||
|
Assert.Equal("UNDER_REVIEW", review.Status);
|
||||||
|
var accepted = await ReadAsync<ProposalDetail>(manager.PostAsJsonAsync(path + "/status",
|
||||||
|
new ChangeProposalStatusRequest("ACCEPTED", " Schváleno. "), Cancellation));
|
||||||
|
Assert.Equal(("ACCEPTED", "Schváleno."), (accepted.Status, accepted.Events[^1].Note));
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.Conflict);
|
||||||
|
await ExpectAsync(manager.DeleteAsync(path + "/vote", Cancellation), HttpStatusCode.Conflict);
|
||||||
|
|
||||||
|
var inbox = await ReadAsync<PagedResult<NotificationDto>>(author.GetAsync("/api/v1/notifications", Cancellation));
|
||||||
|
Assert.Equal(2, inbox.Items.Count(item => item.ProposalId == proposal.Id && item.Type == "PROPOSAL_STATUS_CHANGED"));
|
||||||
|
var top = Assert.Single(await ReadAsync<TopProposal[]>(
|
||||||
|
admin.GetAsync($"/api/v1/statistics/proposals/top?limit=1&from={from}&to={to}", Cancellation)));
|
||||||
|
Assert.Equal((proposal.Id, 1L), (top.Id, top.Score));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task VerifyVotesAsync(HttpClient author, HttpClient voter, string path)
|
||||||
|
{
|
||||||
|
var vote = path + "/vote";
|
||||||
|
await ExpectAsync(author.PutAsJsonAsync(vote, new VoteRequest(1), Cancellation), HttpStatusCode.Forbidden);
|
||||||
|
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(0), Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
|
||||||
|
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(1), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
var detail = await ReadAsync<ProposalDetail>(voter.GetAsync(path, Cancellation));
|
||||||
|
Assert.Equal((1L, 0L, 1L, (int?)1), (detail.VotesFor, detail.VotesAgainst, detail.Score, detail.MyVote));
|
||||||
|
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(-1), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
detail = await ReadAsync<ProposalDetail>(voter.GetAsync(path, Cancellation));
|
||||||
|
Assert.Equal((0L, 1L, -1L, (int?)-1), (detail.VotesFor, detail.VotesAgainst, detail.Score, detail.MyVote));
|
||||||
|
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(-1), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(voter.DeleteAsync(vote, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
detail = await ReadAsync<ProposalDetail>(voter.GetAsync(path, Cancellation));
|
||||||
|
Assert.Equal(0L, detail.Score);
|
||||||
|
Assert.Null(detail.MyVote);
|
||||||
|
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(1), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Helpdesk.Application.Auth;
|
||||||
|
using Microsoft.AspNetCore.TestHost;
|
||||||
|
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
public sealed class ProxyRateLimitTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task TrustedProxiesShareTheLimitForEachClientAndSeparateDifferentClients()
|
||||||
|
{
|
||||||
|
const string externalProxy = "192.0.2.10";
|
||||||
|
const string web = "192.0.2.11";
|
||||||
|
const string firstClient = "198.51.100.10";
|
||||||
|
const string secondClient = "198.51.100.11";
|
||||||
|
await using var api = fixture.CreateApiBehindProxies(externalProxy, web);
|
||||||
|
|
||||||
|
for (var attempt = 0; attempt < 20; attempt++)
|
||||||
|
Assert.Equal(401, await LoginAsync(api.Server, web, firstClient, $"absent-{attempt}@example.test"));
|
||||||
|
|
||||||
|
Assert.Equal(429, await LoginAsync(api.Server, externalProxy, firstClient, "[email protected]"));
|
||||||
|
Assert.Equal(401, await LoginAsync(api.Server, web, secondClient, "[email protected]"));
|
||||||
|
Assert.Equal(429, await LoginAsync(api.Server, $"::ffff:{firstClient}", secondClient, "[email protected]"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<int> LoginAsync(TestServer server, string peer, string client, string email)
|
||||||
|
{
|
||||||
|
using var body = new MemoryStream(JsonSerializer.SerializeToUtf8Bytes(new LoginRequest(email, "test-password")));
|
||||||
|
var response = await server.SendAsync(context =>
|
||||||
|
{
|
||||||
|
context.Connection.RemoteIpAddress = IPAddress.Parse(peer);
|
||||||
|
context.Request.Method = "POST";
|
||||||
|
context.Request.Path = "/api/v1/auth/login";
|
||||||
|
context.Request.ContentType = "application/json";
|
||||||
|
context.Request.ContentLength = body.Length;
|
||||||
|
context.Request.Body = body;
|
||||||
|
context.Request.Headers["X-Forwarded-For"] = client;
|
||||||
|
}, Cancellation);
|
||||||
|
return response.Response.StatusCode;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
using Helpdesk.Domain.Auth;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
internal sealed class TokenSaveGate : SaveChangesInterceptor
|
||||||
|
{
|
||||||
|
private Pause? next;
|
||||||
|
|
||||||
|
internal Pause PauseNextSave()
|
||||||
|
{
|
||||||
|
var pause = new Pause();
|
||||||
|
if (Interlocked.CompareExchange(ref next, pause, null) is not null)
|
||||||
|
throw new InvalidOperationException("A save is already scheduled to pause.");
|
||||||
|
return pause;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(
|
||||||
|
DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (Volatile.Read(ref next) is not null &&
|
||||||
|
eventData.Context!.ChangeTracker.Entries<AuthToken>()
|
||||||
|
.Any(entry => entry.State == EntityState.Added && entry.Entity.TokenType == TokenType.Refresh) &&
|
||||||
|
Interlocked.Exchange(ref next, null) is { } pause)
|
||||||
|
{
|
||||||
|
pause.Entered.TrySetResult();
|
||||||
|
await pause.Released.Task.WaitAsync(cancellationToken);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class Pause
|
||||||
|
{
|
||||||
|
internal TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
internal TaskCompletionSource Released { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
|
||||||
|
internal void Release() => Released.TrySetResult();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<Configuration>
|
||||||
|
<CodeCoverage>
|
||||||
|
<EnableStaticManagedInstrumentation>True</EnableStaticManagedInstrumentation>
|
||||||
|
<EnableDynamicManagedInstrumentation>False</EnableDynamicManagedInstrumentation>
|
||||||
|
<CollectFromChildProcesses>True</CollectFromChildProcesses>
|
||||||
|
<ModulePaths>
|
||||||
|
<Include>
|
||||||
|
<ModulePath>(^|[\\/])Helpdesk\.(Api|Application|Domain|Infrastructure|Migrator)\.dll$</ModulePath>
|
||||||
|
</Include>
|
||||||
|
</ModulePaths>
|
||||||
|
<Sources>
|
||||||
|
<Exclude>
|
||||||
|
<Source>[\\/]obj[\\/]</Source>
|
||||||
|
</Exclude>
|
||||||
|
</Sources>
|
||||||
|
</CodeCoverage>
|
||||||
|
</Configuration>
|
||||||
@@ -37,46 +37,11 @@ public class EnumCodeTests
|
|||||||
public void Neznamy_kod_neprojde() => Assert.False(EnumCode.TryParse<UserRole>("SUPERUSER", out _));
|
public void Neznamy_kod_neprojde() => Assert.False(EnumCode.TryParse<UserRole>("SUPERUSER", out _));
|
||||||
}
|
}
|
||||||
|
|
||||||
public class UserLockoutTests
|
public class UserTests
|
||||||
{
|
{
|
||||||
private static readonly DateTime Now = new(2026, 10, 29, 10, 0, 0, DateTimeKind.Utc);
|
|
||||||
|
|
||||||
private static User NewUser() => User.Create("[email protected]", "hash", "Jan", "Novák", UserRole.Student);
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Ctyri_neuspesne_pokusy_ucet_nezamknou()
|
|
||||||
{
|
|
||||||
var user = NewUser();
|
|
||||||
for (var i = 0; i < User.MaxFailedLogins - 1; i++)
|
|
||||||
user.RegisterFailedLogin(Now);
|
|
||||||
|
|
||||||
Assert.False(user.IsLockedOut(Now));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Paty_neuspesny_pokus_zamkne_ucet_na_15_minut()
|
|
||||||
{
|
|
||||||
var user = NewUser();
|
|
||||||
for (var i = 0; i < User.MaxFailedLogins; i++)
|
|
||||||
user.RegisterFailedLogin(Now);
|
|
||||||
|
|
||||||
Assert.True(user.IsLockedOut(Now.AddMinutes(14)));
|
|
||||||
Assert.False(user.IsLockedOut(Now.AddMinutes(15)));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Uspesne_prihlaseni_vynuluje_pocitadlo()
|
|
||||||
{
|
|
||||||
var user = NewUser();
|
|
||||||
user.RegisterFailedLogin(Now);
|
|
||||||
user.RegisterSuccessfulLogin();
|
|
||||||
|
|
||||||
Assert.Equal(0, user.FailedLoginCount);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Email_se_normalizuje_pro_jednoznacne_vyhledani() =>
|
public void Email_se_normalizuje_pro_jednoznacne_vyhledani() =>
|
||||||
Assert.Equal("[email protected]", NewUser().EmailNormalized);
|
Assert.Equal("[email protected]", User.Create("[email protected]", "hash", "Jan", "Novák", UserRole.Student).EmailNormalized);
|
||||||
}
|
}
|
||||||
|
|
||||||
public class RegistrationRoleTests
|
public class RegistrationRoleTests
|
||||||
|
|||||||
@@ -21,15 +21,18 @@ public sealed class IssueTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData(IssueStatus.Received)]
|
[InlineData(IssueStatus.Received, UserRole.Management)]
|
||||||
[InlineData(IssueStatus.Assigned)]
|
[InlineData(IssueStatus.Assigned, UserRole.Management)]
|
||||||
[InlineData(IssueStatus.InProgress)]
|
[InlineData(IssueStatus.InProgress, UserRole.Management)]
|
||||||
public void ManagementCanAssignOrReassign(IssueStatus from)
|
[InlineData(IssueStatus.Received, UserRole.Admin)]
|
||||||
|
[InlineData(IssueStatus.Assigned, UserRole.Admin)]
|
||||||
|
[InlineData(IssueStatus.InProgress, UserRole.Admin)]
|
||||||
|
public void ManagementAndAdminCanAssignOrReassign(IssueStatus from, UserRole role)
|
||||||
{
|
{
|
||||||
var issue = At(from);
|
var issue = At(from);
|
||||||
var version = issue.RowVersion;
|
var version = issue.RowVersion;
|
||||||
Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.Assign, Manager, UserRole.Management));
|
Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.Assign, Manager, role));
|
||||||
issue.Assign(Manager, UserRole.Management, Replacement, UserRole.Management, IssuePriority.High);
|
issue.Assign(Manager, role, Replacement, UserRole.Management, IssuePriority.High);
|
||||||
Assert.Equal(IssueStatus.Assigned, issue.Status);
|
Assert.Equal(IssueStatus.Assigned, issue.Status);
|
||||||
Assert.Equal(Replacement, issue.AssigneeId);
|
Assert.Equal(Replacement, issue.AssigneeId);
|
||||||
Assert.Equal(IssuePriority.High, issue.Priority);
|
Assert.Equal(IssuePriority.High, issue.Priority);
|
||||||
@@ -38,12 +41,17 @@ public sealed class IssueTests
|
|||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData(IssueStatus.Assigned, IssueAction.StartWork, Assignee, UserRole.FacilityManager, IssueStatus.InProgress)]
|
[InlineData(IssueStatus.Assigned, IssueAction.StartWork, Assignee, UserRole.FacilityManager, IssueStatus.InProgress)]
|
||||||
|
[InlineData(IssueStatus.Assigned, IssueAction.StartWork, Replacement, UserRole.Admin, IssueStatus.InProgress)]
|
||||||
[InlineData(IssueStatus.InProgress, IssueAction.SubmitForVerification, Assignee, UserRole.FacilityManager, IssueStatus.PendingVerification)]
|
[InlineData(IssueStatus.InProgress, IssueAction.SubmitForVerification, Assignee, UserRole.FacilityManager, IssueStatus.PendingVerification)]
|
||||||
|
[InlineData(IssueStatus.InProgress, IssueAction.SubmitForVerification, Replacement, UserRole.Admin, IssueStatus.PendingVerification)]
|
||||||
[InlineData(IssueStatus.PendingVerification, IssueAction.Confirm, Reporter, UserRole.Admin, IssueStatus.Resolved)]
|
[InlineData(IssueStatus.PendingVerification, IssueAction.Confirm, Reporter, UserRole.Admin, IssueStatus.Resolved)]
|
||||||
[InlineData(IssueStatus.PendingVerification, IssueAction.Reopen, Reporter, UserRole.Admin, IssueStatus.InProgress)]
|
[InlineData(IssueStatus.PendingVerification, IssueAction.Confirm, Replacement, UserRole.Admin, IssueStatus.Resolved)]
|
||||||
|
[InlineData(IssueStatus.PendingVerification, IssueAction.Reopen, Replacement, UserRole.Admin, IssueStatus.InProgress)]
|
||||||
[InlineData(IssueStatus.Assigned, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueStatus.Rejected)]
|
[InlineData(IssueStatus.Assigned, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueStatus.Rejected)]
|
||||||
[InlineData(IssueStatus.InProgress, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueStatus.Rejected)]
|
[InlineData(IssueStatus.InProgress, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueStatus.Rejected)]
|
||||||
[InlineData(IssueStatus.Received, IssueAction.Reject, Manager, UserRole.Management, IssueStatus.Rejected)]
|
[InlineData(IssueStatus.Received, IssueAction.Reject, Manager, UserRole.Management, IssueStatus.Rejected)]
|
||||||
|
[InlineData(IssueStatus.Received, IssueAction.Reject, Replacement, UserRole.Admin, IssueStatus.Rejected)]
|
||||||
|
[InlineData(IssueStatus.InProgress, IssueAction.Reject, Replacement, UserRole.Admin, IssueStatus.Rejected)]
|
||||||
public void AllowedTransitionsIncrementVersion(
|
public void AllowedTransitionsIncrementVersion(
|
||||||
IssueStatus from, IssueAction action, int actorId, UserRole role, IssueStatus target)
|
IssueStatus from, IssueAction action, int actorId, UserRole role, IssueStatus target)
|
||||||
{
|
{
|
||||||
@@ -63,6 +71,7 @@ public sealed class IssueTests
|
|||||||
[InlineData(IssueStatus.InProgress, IssueAction.StartWork, Assignee, UserRole.FacilityManager, IssueActionAvailability.InvalidState)]
|
[InlineData(IssueStatus.InProgress, IssueAction.StartWork, Assignee, UserRole.FacilityManager, IssueActionAvailability.InvalidState)]
|
||||||
[InlineData(IssueStatus.PendingVerification, IssueAction.Confirm, Assignee, UserRole.FacilityManager, IssueActionAvailability.Forbidden)]
|
[InlineData(IssueStatus.PendingVerification, IssueAction.Confirm, Assignee, UserRole.FacilityManager, IssueActionAvailability.Forbidden)]
|
||||||
[InlineData(IssueStatus.PendingVerification, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueActionAvailability.InvalidState)]
|
[InlineData(IssueStatus.PendingVerification, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueActionAvailability.InvalidState)]
|
||||||
|
[InlineData(IssueStatus.PendingVerification, IssueAction.Reject, Replacement, UserRole.Admin, IssueActionAvailability.InvalidState)]
|
||||||
[InlineData(IssueStatus.Resolved, IssueAction.Reopen, Reporter, UserRole.Admin, IssueActionAvailability.InvalidState)]
|
[InlineData(IssueStatus.Resolved, IssueAction.Reopen, Reporter, UserRole.Admin, IssueActionAvailability.InvalidState)]
|
||||||
[InlineData(IssueStatus.Rejected, IssueAction.Reject, Manager, UserRole.Management, IssueActionAvailability.InvalidState)]
|
[InlineData(IssueStatus.Rejected, IssueAction.Reject, Manager, UserRole.Management, IssueActionAvailability.InvalidState)]
|
||||||
public void DisallowedTransitionsMatchAvailability(
|
public void DisallowedTransitionsMatchAvailability(
|
||||||
@@ -102,10 +111,12 @@ public sealed class IssueTests
|
|||||||
{
|
{
|
||||||
var issue = At(IssueStatus.Assigned);
|
var issue = At(IssueStatus.Assigned);
|
||||||
Assert.True(issue.CanRead(Reporter, UserRole.Admin));
|
Assert.True(issue.CanRead(Reporter, UserRole.Admin));
|
||||||
Assert.False(issue.CanRead(Replacement, UserRole.Admin));
|
Assert.True(issue.CanRead(Replacement, UserRole.Admin));
|
||||||
|
Assert.False(issue.CanRead(Replacement, UserRole.Student));
|
||||||
Assert.True(issue.CanRead(Replacement, UserRole.FacilityManager));
|
Assert.True(issue.CanRead(Replacement, UserRole.FacilityManager));
|
||||||
Assert.Equal(IssueActionAvailability.Forbidden, issue.Availability(IssueAction.Comment, Manager, UserRole.Management));
|
Assert.Equal(IssueActionAvailability.Forbidden, issue.Availability(IssueAction.Comment, Manager, UserRole.Management));
|
||||||
Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.Comment, Reporter, UserRole.Admin));
|
Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.Comment, Reporter, UserRole.Admin));
|
||||||
|
Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.AddAttachments, Replacement, UserRole.Admin));
|
||||||
issue.RecordParticipation(IssueAction.Comment, Reporter, UserRole.Admin);
|
issue.RecordParticipation(IssueAction.Comment, Reporter, UserRole.Admin);
|
||||||
issue.Transition(IssueAction.Reject, Assignee, UserRole.FacilityManager, "Důvod");
|
issue.Transition(IssueAction.Reject, Assignee, UserRole.FacilityManager, "Důvod");
|
||||||
Assert.Equal(IssueActionAvailability.InvalidState, issue.Availability(IssueAction.AddAttachments, Reporter, UserRole.Admin));
|
Assert.Equal(IssueActionAvailability.InvalidState, issue.Availability(IssueAction.AddAttachments, Reporter, UserRole.Admin));
|
||||||
|
|||||||
@@ -35,12 +35,14 @@ public sealed class ProposalTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ReviewRequiresManagementAndRejectionRequiresNote()
|
public void ReviewRequiresManagementOrAdminAndRejectionRequiresNote()
|
||||||
{
|
{
|
||||||
var proposal = At(ProposalStatus.Submitted);
|
var proposal = At(ProposalStatus.Submitted);
|
||||||
Assert.Throws<InvalidOperationException>(() => proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Admin, null));
|
Assert.Throws<InvalidOperationException>(() => proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Student, null));
|
||||||
Assert.Throws<ArgumentException>(() => proposal.ChangeStatus(ProposalStatus.Rejected, UserRole.Management, " "));
|
Assert.Throws<ArgumentException>(() => proposal.ChangeStatus(ProposalStatus.Rejected, UserRole.Admin, " "));
|
||||||
Assert.Equal(ProposalStatus.Submitted, proposal.Status);
|
Assert.Equal(ProposalStatus.Submitted, proposal.Status);
|
||||||
|
proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Admin, null);
|
||||||
|
Assert.Equal(ProposalStatus.Accepted, proposal.Status);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
@@ -49,22 +51,25 @@ public sealed class ProposalTests
|
|||||||
[InlineData(ProposalStatus.Accepted, false, false)]
|
[InlineData(ProposalStatus.Accepted, false, false)]
|
||||||
[InlineData(ProposalStatus.Rejected, false, false)]
|
[InlineData(ProposalStatus.Rejected, false, false)]
|
||||||
[InlineData(ProposalStatus.Implemented, false, false)]
|
[InlineData(ProposalStatus.Implemented, false, false)]
|
||||||
public void AuthorEditsAndOtherUserVotesOnlyInEligibleStates(ProposalStatus state, bool mayEdit, bool mayVote)
|
public void AuthorAndAdminEditAndOtherUsersVoteOnlyInEligibleStates(ProposalStatus state, bool mayEdit, bool mayVote)
|
||||||
{
|
{
|
||||||
var proposal = At(state);
|
var proposal = At(state);
|
||||||
Assert.Equal(mayEdit, proposal.CanEdit(Author));
|
Assert.Equal(mayEdit, proposal.IsEditable);
|
||||||
Assert.False(proposal.CanEdit(Voter));
|
|
||||||
Assert.False(proposal.CanVote(Author));
|
Assert.False(proposal.CanVote(Author));
|
||||||
Assert.Equal(mayVote, proposal.CanVote(Voter));
|
Assert.Equal(mayVote, proposal.CanVote(Voter));
|
||||||
Assert.Throws<InvalidOperationException>(() => proposal.Edit(Voter, "Změna", "Popis", 1));
|
Assert.Throws<InvalidOperationException>(() => proposal.Edit(Voter, UserRole.Student, "Změna", "Popis", 1));
|
||||||
if (mayEdit)
|
if (mayEdit)
|
||||||
{
|
{
|
||||||
proposal.Edit(Author, "Změna", "Popis", 1);
|
proposal.Edit(Author, UserRole.Student, "Změna", "Popis", 1);
|
||||||
Assert.Equal("Změna", proposal.Title);
|
Assert.Equal("Změna", proposal.Title);
|
||||||
|
proposal.Edit(Voter, UserRole.Admin, "Další změna", "Popis", 1);
|
||||||
|
Assert.Equal("Další změna", proposal.Title);
|
||||||
|
Assert.Equal(Author, proposal.AuthorId);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
Assert.Throws<InvalidOperationException>(() => proposal.Edit(Author, "Změna", "Popis", 1));
|
Assert.Throws<InvalidOperationException>(() => proposal.Edit(Author, UserRole.Student, "Změna", "Popis", 1));
|
||||||
|
Assert.Throws<InvalidOperationException>(() => proposal.Edit(Voter, UserRole.Admin, "Změna", "Popis", 1));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE app_user
|
||||||
|
ADD COLUMN is_deleted BOOLEAN NOT NULL DEFAULT FALSE;
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE app_user
|
||||||
|
ADD COLUMN row_version INT NOT NULL DEFAULT 0;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
ALTER TABLE app_user
|
||||||
|
DROP COLUMN IF EXISTS failed_login_count,
|
||||||
|
DROP COLUMN IF EXISTS lockout_until;
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# Vývojové spuštění: docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build
|
# Vývojové spuštění: docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build
|
||||||
# Reverse proxy ukončuje HTTPS a připojuje se k webu a API přes HTTP
|
# Reverse proxy ukončuje HTTPS a připojuje se k webu a API přes HTTP
|
||||||
# (/ → web, /api/* a /swagger → api).
|
# (/ včetně /swagger → web, /api/* → api).
|
||||||
|
|
||||||
name: helpdesk
|
name: helpdesk
|
||||||
|
|
||||||
@@ -53,6 +53,7 @@ services:
|
|||||||
Smtp__Password: ${SMTP_PASSWORD:-}
|
Smtp__Password: ${SMTP_PASSWORD:-}
|
||||||
Firebase__ServiceAccountJson: ${FIREBASE_SERVICE_ACCOUNT_JSON:-}
|
Firebase__ServiceAccountJson: ${FIREBASE_SERVICE_ACCOUNT_JSON:-}
|
||||||
ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-}
|
ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-}
|
||||||
|
ReverseProxy__TrustedWebIp: ${WEB_API_WEB_IP:-172.30.242.6}
|
||||||
ADMIN_EMAIL: ${ADMIN_EMAIL:-}
|
ADMIN_EMAIL: ${ADMIN_EMAIL:-}
|
||||||
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
|
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
|
||||||
volumes:
|
volumes:
|
||||||
@@ -62,7 +63,11 @@ services:
|
|||||||
condition: service_completed_successfully
|
condition: service_completed_successfully
|
||||||
ports:
|
ports:
|
||||||
- "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${API_HTTP_PORT:-8080}:8080"
|
- "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${API_HTTP_PORT:-8080}:8080"
|
||||||
networks: [frontend, backend]
|
networks:
|
||||||
|
frontend:
|
||||||
|
backend:
|
||||||
|
web-api:
|
||||||
|
aliases: [api-web]
|
||||||
|
|
||||||
web:
|
web:
|
||||||
build:
|
build:
|
||||||
@@ -70,8 +75,7 @@ services:
|
|||||||
dockerfile: web/Dockerfile
|
dockerfile: web/Dockerfile
|
||||||
environment:
|
environment:
|
||||||
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Development}
|
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Development}
|
||||||
# Web volá API uvnitř Docker sítě; do databáze přístup nemá (je jen v síti frontend).
|
Api__BaseUrl: http://api-web:8080/
|
||||||
Api__BaseUrl: http://api:8080/
|
|
||||||
ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-}
|
ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-}
|
||||||
volumes:
|
volumes:
|
||||||
# Klíče pro šifrování cookie – bez nich by restart kontejneru odhlásil všechny uživatele.
|
# Klíče pro šifrování cookie – bez nich by restart kontejneru odhlásil všechny uživatele.
|
||||||
@@ -80,12 +84,21 @@ services:
|
|||||||
- api
|
- api
|
||||||
ports:
|
ports:
|
||||||
- "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${WEB_HTTP_PORT:-8081}:8080"
|
- "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${WEB_HTTP_PORT:-8081}:8080"
|
||||||
networks: [frontend]
|
networks:
|
||||||
|
frontend:
|
||||||
|
web-api:
|
||||||
|
ipv4_address: ${WEB_API_WEB_IP:-172.30.242.6}
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
frontend:
|
frontend:
|
||||||
backend:
|
backend:
|
||||||
internal: true
|
internal: true
|
||||||
|
web-api:
|
||||||
|
# Při kolizi s existující sítí lze společně přepsat WEB_API_SUBNET a WEB_API_WEB_IP.
|
||||||
|
internal: true
|
||||||
|
ipam:
|
||||||
|
config:
|
||||||
|
- subnet: ${WEB_API_SUBNET:-172.30.242.0/29}
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
db-data:
|
db-data:
|
||||||
|
|||||||
+101
-94
@@ -72,7 +72,7 @@ Webová i mobilní aplikace jsou **tenké klienty** – nepřistupují do datab
|
|||||||
| `TEACHER` | Vyučující | Samoregistrace | Stejná oprávnění jako student |
|
| `TEACHER` | Vyučující | Samoregistrace | Stejná oprávnění jako student |
|
||||||
| `FACILITY_MANAGER` | Správce budov | Přiděluje administrátor | Řeší přiřazené závady (odpovědná osoba) |
|
| `FACILITY_MANAGER` | Správce budov | Přiděluje administrátor | Řeší přiřazené závady (odpovědná osoba) |
|
||||||
| `MANAGEMENT` | Vedení školy | Přiděluje administrátor | Přiřazuje závady řešitelům, hodnotí návrhy, vidí statistiky |
|
| `MANAGEMENT` | Vedení školy | Přiděluje administrátor | Přiřazuje závady řešitelům, hodnotí návrhy, vidí statistiky |
|
||||||
| `ADMIN` | Administrátor | Přiděluje administrátor / vytvořen při instalaci | Správa uživatelů a jejich rolí, správa číselníků |
|
| `ADMIN` | Administrátor | Přiděluje administrátor / vytvořen při instalaci | Správa systému, všechny akce nad závadami a návrhy, statistiky |
|
||||||
|
|
||||||
- Každý uživatel má **právě jednu roli** (sloupec `app_user.role`). Základní funkce (hlásit závady, podávat návrhy, hlasovat) má každá role, takže kombinace rolí nejsou potřeba – např. vyučující, který je ve vedení, dostane roli `MANAGEMENT`.
|
- Každý uživatel má **právě jednu roli** (sloupec `app_user.role`). Základní funkce (hlásit závady, podávat návrhy, hlasovat) má každá role, takže kombinace rolí nejsou potřeba – např. vyučující, který je ve vedení, dostane roli `MANAGEMENT`.
|
||||||
- Při samoregistraci se role `STUDENT` / `TEACHER` určí automaticky **podle domény e-mailu** (např. `@student.univerzita.cz` → student, `@univerzita.cz` → vyučující). Domény jsou v konfiguraci backendu. Registrace z jiné domény není povolena. Tím se zabrání tomu, aby se student zaregistroval jako vyučující.
|
- Při samoregistraci se role `STUDENT` / `TEACHER` určí automaticky **podle domény e-mailu** (např. `@student.univerzita.cz` → student, `@univerzita.cz` → vyučující). Domény jsou v konfiguraci backendu. Registrace z jiné domény není povolena. Tím se zabrání tomu, aby se student zaregistroval jako vyučující.
|
||||||
@@ -86,23 +86,26 @@ Legenda: ✅ povoleno, 🔸 povoleno s podmínkou, — nepovoleno
|
|||||||
|---|:-:|:-:|:-:|:-:|
|
|---|:-:|:-:|:-:|:-:|
|
||||||
| Nahlásit závadu, přiložit soubory | ✅ | ✅ | ✅ | ✅ |
|
| Nahlásit závadu, přiložit soubory | ✅ | ✅ | ✅ | ✅ |
|
||||||
| Zobrazit vlastní hlášení | ✅ | ✅ | ✅ | ✅ |
|
| Zobrazit vlastní hlášení | ✅ | ✅ | ✅ | ✅ |
|
||||||
| Upravit vlastní hlášení | 🔸 jen ve stavu *Přijata* | 🔸 | 🔸 | 🔸 |
|
| Upravit hlášení | 🔸 vlastní ve stavu *Přijata* | 🔸 vlastní ve stavu *Přijata* | 🔸 vlastní ve stavu *Přijata* | 🔸 libovolné ve stavu *Přijata* |
|
||||||
| Centrální přehled všech závad (filtry) | — | ✅ (jen čtení) | ✅ | — |
|
| Centrální přehled všech závad (filtry) | — | ✅ (jen čtení) | ✅ | ✅ |
|
||||||
| Přiřadit / přeřadit závadu řešiteli, nastavit prioritu | — | — | ✅ | — |
|
| Přiřadit / přeřadit závadu řešiteli, nastavit prioritu | — | — | ✅ | ✅ |
|
||||||
| Zahájit řešení, předat k ověření | — | 🔸 jen přiřazené jemu | 🔸 jen přiřazené jemu | — |
|
| Zahájit řešení, předat k ověření | — | 🔸 jen přiřazené jemu | 🔸 jen přiřazené jemu | 🔸 ve stavu příslušného přechodu |
|
||||||
| Zamítnout závadu (s důvodem) | — | 🔸 jen přiřazené jemu | 🔸 přiřazené jemu nebo nepřiřazené ve stavu *Přijata* | — |
|
| Zamítnout závadu (s důvodem) | — | 🔸 jen přiřazené jemu | 🔸 přiřazené jemu nebo nepřiřazené ve stavu *Přijata* | 🔸 ve stavu příslušného přechodu |
|
||||||
| Potvrdit vyřešení / znovu otevřít | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen hlásič |
|
| Potvrdit vyřešení / znovu otevřít | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 ve stavu *Čeká na ověření* |
|
||||||
| Komentovat závadu | 🔸 hlásič | 🔸 hlásič nebo řešitel | 🔸 hlásič nebo řešitel; ostatní jen čtení | 🔸 hlásič |
|
| Komentovat závadu / přidat přílohu | 🔸 hlásič | 🔸 hlásič nebo řešitel | 🔸 hlásič nebo řešitel; ostatní jen čtení | 🔸 libovolná otevřená závada |
|
||||||
| Podat návrh na zlepšení | ✅ | ✅ | ✅ | ✅ |
|
| Podat návrh na zlepšení | ✅ | ✅ | ✅ | ✅ |
|
||||||
| Zobrazit všechny návrhy | ✅ | ✅ | ✅ | ✅ |
|
| Zobrazit všechny návrhy | ✅ | ✅ | ✅ | ✅ |
|
||||||
| Hlasovat pro návrh | 🔸 ne pro vlastní | 🔸 | 🔸 | 🔸 |
|
| Hlasovat pro návrh | 🔸 ne pro vlastní | 🔸 | 🔸 | 🔸 |
|
||||||
| Hodnotit návrhy (změna stavu, vyjádření) | — | — | ✅ | — |
|
| Upravit návrh ve stavu *Podán* | 🔸 autor | 🔸 autor | 🔸 autor | ✅ |
|
||||||
| Statistiky a výkazy | — | — | ✅ | — |
|
| Hodnotit návrhy (změna stavu, vyjádření) | — | — | ✅ | ✅ |
|
||||||
|
| Statistiky a výkazy | — | — | ✅ | ✅ |
|
||||||
| Správa uživatelů a rolí | — | — | — | ✅ |
|
| Správa uživatelů a rolí | — | — | — | ✅ |
|
||||||
| Správa číselníků (budovy, kategorie) | — | — | — | ✅ |
|
| Správa číselníků (budovy, kategorie) | — | — | — | ✅ |
|
||||||
|
|
||||||
Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkrétním záznamem** (resource-based authorization) a kontroluje je aplikační vrstva backendu (viz kap. 9.3).
|
Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkrétním záznamem** (resource-based authorization) a kontroluje je aplikační vrstva backendu (viz kap. 9.3).
|
||||||
|
|
||||||
|
`ADMIN` může spravovat závady a návrhy ostatních uživatelů. Požadavky na stav záznamu, povinné údaje a `rowVersion` platí pro všechny role. Profil, přihlášení, hlasování, zařízení a osobní notifikace se vztahují k aktuálně přihlášenému účtu.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Funkční požadavky
|
## 3. Funkční požadavky
|
||||||
@@ -110,10 +113,10 @@ Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkr
|
|||||||
### Účty a přístup
|
### Účty a přístup
|
||||||
| ID | Požadavek |
|
| ID | Požadavek |
|
||||||
|---|---|
|
|---|---|
|
||||||
| FR-01 | Registrace e-mailem a heslem; po registraci ověření e-mailu odkazem. |
|
| FR-01 | Registrace univerzitním e-mailem. Příjemce ověří e-mail a nastaví heslo přes jednorázový odkaz. |
|
||||||
| FR-02 | Přihlášení e-mailem a heslem, vydání JWT access tokenu a refresh tokenu; odhlášení zablokuje oba tokeny (podle `jti`); „odhlásit ze všech zařízení“. |
|
| FR-02 | Přihlášení e-mailem a heslem, vydání JWT access tokenu a refresh tokenu; odhlášení zablokuje oba tokeny (podle `jti`); „odhlásit ze všech zařízení“. |
|
||||||
| FR-03 | Obnova zapomenutého hesla přes e-mail. |
|
| FR-03 | Obnova zapomenutého hesla přes e-mail. |
|
||||||
| FR-04 | Administrátor vyhledává uživatele, mění jejich roli, deaktivuje účty. |
|
| FR-04 | Administrátor vyhledává, zakládá a upravuje účty, mění role, aktivuje, deaktivuje a maže účty. Role, stav i smazání může změnit u více účtů najednou. |
|
||||||
| FR-05 | Uživatel upravuje svůj profil (jméno, telefon, zapnutí e-mailových notifikací). |
|
| FR-05 | Uživatel upravuje svůj profil (jméno, telefon, zapnutí e-mailových notifikací). |
|
||||||
|
|
||||||
### Hlášení závad
|
### Hlášení závad
|
||||||
@@ -122,7 +125,7 @@ Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkr
|
|||||||
| FR-10 | Uživatel nahlásí závadu: název, popis, kategorie (typ), budova a upřesnění místa. |
|
| FR-10 | Uživatel nahlásí závadu: název, popis, kategorie (typ), budova a upřesnění místa. |
|
||||||
| FR-11 | K hlášení lze při vytvoření i později v průběhu komunikace přiložit fotografii nebo jiný soubor (JPG, PNG, HEIC, PDF, DOCX; max. 10 MB/soubor, max. 5 souborů najednou). |
|
| FR-11 | K hlášení lze při vytvoření i později v průběhu komunikace přiložit fotografii nebo jiný soubor (JPG, PNG, HEIC, PDF, DOCX; max. 10 MB/soubor, max. 5 souborů najednou). |
|
||||||
| FR-12 | Závada prochází stavy *Přijata → Přiřazena → V řešení → Čeká na ověření → Vyřešena*, případně *Zamítnuta* (kap. 6). Nepovolené přechody server odmítne. |
|
| FR-12 | Závada prochází stavy *Přijata → Přiřazena → V řešení → Čeká na ověření → Vyřešena*, případně *Zamítnuta* (kap. 6). Nepovolené přechody server odmítne. |
|
||||||
| FR-13 | Vedení přiřazuje závadu odpovědné osobě (správci budov); u každého správce vidí počet jeho otevřených závad. |
|
| FR-13 | Vedení a administrátor přiřazují závadu odpovědné osobě; u každého řešitele vidí počet jeho otevřených závad. |
|
||||||
| FR-14 | Řešitel může závadu zamítnout s povinným uvedením důvodu. |
|
| FR-14 | Řešitel může závadu zamítnout s povinným uvedením důvodu. |
|
||||||
| FR-15 | Hlásič potvrdí vyřešení, nebo závadu znovu otevře (s povinným důvodem) → stav *V řešení*. |
|
| FR-15 | Hlásič potvrdí vyřešení, nebo závadu znovu otevře (s povinným důvodem) → stav *V řešení*. |
|
||||||
| FR-16 | Hlásič a řešitel si u závady vyměňují komentáře; protistrana je o novém komentáři informována. |
|
| FR-16 | Hlásič a řešitel si u závady vyměňují komentáře; protistrana je o novém komentáři informována. |
|
||||||
@@ -134,13 +137,13 @@ Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkr
|
|||||||
| FR-20 | Každý uživatel podá návrh: název, popis, oblast (studium, služby, prostředí, ostatní). |
|
| FR-20 | Každý uživatel podá návrh: název, popis, oblast (studium, služby, prostředí, ostatní). |
|
||||||
| FR-21 | Uživatel hlasuje pro/proti návrhu jiného uživatele; jeden hlas na návrh, hlas lze změnit či zrušit; autor pro vlastní návrh hlasovat nemůže. |
|
| FR-21 | Uživatel hlasuje pro/proti návrhu jiného uživatele; jeden hlas na návrh, hlas lze změnit či zrušit; autor pro vlastní návrh hlasovat nemůže. |
|
||||||
| FR-22 | Seznam návrhů lze řadit podle podpory (skóre) a data a filtrovat podle stavu a oblasti. |
|
| FR-22 | Seznam návrhů lze řadit podle podpory (skóre) a data a filtrovat podle stavu a oblasti. |
|
||||||
| FR-23 | Vedení hodnotí návrhy – mění stav (*V posouzení, Přijat, Zamítnut, Realizován*) a připojuje vyjádření. |
|
| FR-23 | Vedení a administrátor hodnotí návrhy, mění jejich stav (*V posouzení, Přijat, Zamítnut, Realizován*) a připojují vyjádření. |
|
||||||
|
|
||||||
### Správa, přehledy, notifikace
|
### Správa, přehledy, notifikace
|
||||||
| ID | Požadavek |
|
| ID | Požadavek |
|
||||||
|---|---|
|
|---|---|
|
||||||
| FR-30 | Centrální přehled závad a návrhů s filtrováním podle typu (kategorie), stavu, lokality (budovy), řešitele a data; stránkování a řazení. |
|
| FR-30 | Centrální přehled závad a návrhů s filtrováním podle typu (kategorie), stavu, lokality (budovy), řešitele a data; stránkování a řazení. |
|
||||||
| FR-31 | Statistiky pro vedení: počet závad podle stavu / kategorie / budovy, průměrná doba do přiřazení a do uzavření, vytížení řešitelů, nejpodporovanější návrhy, vše za zvolené období. |
|
| FR-31 | Statistiky pro vedení a administrátory zahrnují počty závad podle stavu, kategorie či budovy, průměrnou dobu do přiřazení a uzavření, vytížení řešitelů a nejpodporovanější návrhy za zvolené období. |
|
||||||
| FR-32 | Notifikace v aplikaci (seznam, počet nepřečtených), e-mailem a push notifikací v mobilní aplikaci (kap. 8). |
|
| FR-32 | Notifikace v aplikaci (seznam, počet nepřečtených), e-mailem a push notifikací v mobilní aplikaci (kap. 8). |
|
||||||
| FR-33 | Nedoručené e-maily a push notifikace se automaticky opakují; trvale nedoručené vidí administrátor a může je odeslat znovu. |
|
| FR-33 | Nedoručené e-maily a push notifikace se automaticky opakují; trvale nedoručené vidí administrátor a může je odeslat znovu. |
|
||||||
|
|
||||||
@@ -153,7 +156,7 @@ Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkr
|
|||||||
| NFR-01 | Bezpečnost | Komunikace výhradně přes HTTPS; hesla hashovaná; JWT s krátkou platností; citlivé údaje šifrované (kap. 10). |
|
| NFR-01 | Bezpečnost | Komunikace výhradně přes HTTPS; hesla hashovaná; JWT s krátkou platností; citlivé údaje šifrované (kap. 10). |
|
||||||
| NFR-02 | Konzistence | Pravidla životního cyklu a oprávnění jsou pouze na serveru; klienti je jen zobrazují. |
|
| NFR-02 | Konzistence | Pravidla životního cyklu a oprávnění jsou pouze na serveru; klienti je jen zobrazují. |
|
||||||
| NFR-03 | Souběžnost | Změny stavu závady chráněny optimistickým zamykáním (`row_version`) – dvě souběžné změny nevedou k nekonzistentnímu stavu. |
|
| NFR-03 | Souběžnost | Změny stavu závady chráněny optimistickým zamykáním (`row_version`) – dvě souběžné změny nevedou k nekonzistentnímu stavu. |
|
||||||
| NFR-04 | Dokumentace API | Swagger UI (OpenAPI) dostupné na `/swagger`, včetně autorizace tokenem. |
|
| NFR-04 | Dokumentace API | Swagger UI na `/swagger` pro administrátory přihlášené na webu. Volání API ze Swaggeru se autorizují access tokenem. |
|
||||||
| NFR-05 | Výkon | Seznamy stránkované (výchozí 20 záznamů), indexy pro všechny filtry v přehledu. |
|
| NFR-05 | Výkon | Seznamy stránkované (výchozí 20 záznamů), indexy pro všechny filtry v přehledu. |
|
||||||
| NFR-06 | Použitelnost | Responzivní web (desktop i mobil), mobilní aplikace Android 8.0+ (API 26). Rozhraní v češtině. |
|
| NFR-06 | Použitelnost | Responzivní web (desktop i mobil), mobilní aplikace Android 8.0+ (API 26). Rozhraní v češtině. |
|
||||||
| NFR-07 | Nasaditelnost | Celý systém spustitelný příkazem `docker compose up`. |
|
| NFR-07 | Nasaditelnost | Celý systém spustitelný příkazem `docker compose up`. |
|
||||||
@@ -198,7 +201,7 @@ flowchart LR
|
|||||||
S --- UC1 & UC2 & UC3 & UC4 & UC10 & UC11
|
S --- UC1 & UC2 & UC3 & UC4 & UC10 & UC11
|
||||||
F --- UC3 & UC6 & UC7 & UC20
|
F --- UC3 & UC6 & UC7 & UC20
|
||||||
M --- UC5 & UC7 & UC12 & UC20 & UC21
|
M --- UC5 & UC7 & UC12 & UC20 & UC21
|
||||||
A --- UC22 & UC23
|
A --- UC5 & UC6 & UC7 & UC12 & UC20 & UC21 & UC22 & UC23
|
||||||
```
|
```
|
||||||
|
|
||||||
*Správce budov, vedení i administrátor mají navíc všechny případy užití studenta (hlášení závad, návrhy, hlasování).*
|
*Správce budov, vedení i administrátor mají navíc všechny případy užití studenta (hlášení závad, návrhy, hlasování).*
|
||||||
@@ -229,16 +232,16 @@ stateDiagram-v2
|
|||||||
state "Zamítnuta" as REJECTED
|
state "Zamítnuta" as REJECTED
|
||||||
|
|
||||||
[*] --> RECEIVED : hlásič vytvoří
|
[*] --> RECEIVED : hlásič vytvoří
|
||||||
RECEIVED --> ASSIGNED : vedení přiřadí řešitele
|
RECEIVED --> ASSIGNED : vedení nebo admin přiřadí řešitele
|
||||||
ASSIGNED --> ASSIGNED : vedení přeřadí
|
ASSIGNED --> ASSIGNED : vedení nebo admin přeřadí
|
||||||
ASSIGNED --> IN_PROGRESS : řešitel zahájí
|
ASSIGNED --> IN_PROGRESS : řešitel nebo admin zahájí
|
||||||
IN_PROGRESS --> ASSIGNED : vedení přeřadí
|
IN_PROGRESS --> ASSIGNED : vedení nebo admin přeřadí
|
||||||
IN_PROGRESS --> PENDING_VERIFICATION : řešitel předá k ověření
|
IN_PROGRESS --> PENDING_VERIFICATION : řešitel nebo admin předá k ověření
|
||||||
PENDING_VERIFICATION --> RESOLVED : hlásič potvrdí
|
PENDING_VERIFICATION --> RESOLVED : hlásič nebo admin potvrdí
|
||||||
PENDING_VERIFICATION --> IN_PROGRESS : hlásič znovu otevře
|
PENDING_VERIFICATION --> IN_PROGRESS : hlásič nebo admin znovu otevře
|
||||||
RECEIVED --> REJECTED : vedení zamítne
|
RECEIVED --> REJECTED : vedení nebo admin zamítne
|
||||||
ASSIGNED --> REJECTED : řešitel zamítne
|
ASSIGNED --> REJECTED : řešitel nebo admin zamítne
|
||||||
IN_PROGRESS --> REJECTED : řešitel zamítne
|
IN_PROGRESS --> REJECTED : řešitel nebo admin zamítne
|
||||||
RESOLVED --> [*]
|
RESOLVED --> [*]
|
||||||
REJECTED --> [*]
|
REJECTED --> [*]
|
||||||
```
|
```
|
||||||
@@ -248,14 +251,14 @@ stateDiagram-v2
|
|||||||
| # | Z → Do | Kdo smí | Povinné údaje | Vedlejší efekty | Notifikace |
|
| # | Z → Do | Kdo smí | Povinné údaje | Vedlejší efekty | Notifikace |
|
||||||
|---|---|---|---|---|---|
|
|---|---|---|---|---|---|
|
||||||
| T1 | — → **Přijata** | každý přihlášený (stává se hlásičem) | název, popis, kategorie | událost `CREATED` | vedení: `ISSUE_CREATED` |
|
| T1 | — → **Přijata** | každý přihlášený (stává se hlásičem) | název, popis, kategorie | událost `CREATED` | vedení: `ISSUE_CREATED` |
|
||||||
| T2 | Přijata → **Přiřazena** | vedení | řešitel (role správce budov / vedení) | `assignee_id`, událost `ASSIGNED` | řešitel: `ISSUE_ASSIGNED`; hlásič: změna stavu |
|
| T2 | Přijata → **Přiřazena** | vedení / admin | řešitel (správce budov / vedení / admin) | `assignee_id`, událost `ASSIGNED` | řešitel: `ISSUE_ASSIGNED`; hlásič: změna stavu |
|
||||||
| T3 | Přiřazena / V řešení → **Přiřazena** (přeřazení) | vedení | nový řešitel | změna `assignee_id`, událost `ASSIGNED` | nový řešitel: `ISSUE_ASSIGNED` |
|
| T3 | Přiřazena / V řešení → **Přiřazena** (přeřazení) | vedení / admin | nový řešitel | změna `assignee_id`, událost `ASSIGNED` | `ISSUE_ASSIGNED` novému řešiteli, `ISSUE_STATUS_CHANGED` hlásiči při změně stavu, pokud hlásič není novým řešitelem |
|
||||||
| T4 | Přiřazena → **V řešení** | přiřazený řešitel | — | událost `STATUS_CHANGED` | hlásič |
|
| T4 | Přiřazena → **V řešení** | přiřazený řešitel / admin | — | událost `STATUS_CHANGED` | hlásič |
|
||||||
| T5 | V řešení → **Čeká na ověření** | přiřazený řešitel | volitelná poznámka | událost `STATUS_CHANGED` | hlásič |
|
| T5 | V řešení → **Čeká na ověření** | přiřazený řešitel / admin | volitelná poznámka | událost `STATUS_CHANGED` | hlásič |
|
||||||
| T6 | Čeká na ověření → **Vyřešena** | hlásič | — | událost `STATUS_CHANGED` (= čas uzavření) | řešitel |
|
| T6 | Čeká na ověření → **Vyřešena** | hlásič / admin | — | událost `STATUS_CHANGED` (= čas uzavření) | řešitel |
|
||||||
| T7 | Čeká na ověření → **V řešení** | hlásič | důvod znovuotevření | událost s důvodem v `note` | řešitel: `ISSUE_REOPENED` |
|
| T7 | Čeká na ověření → **V řešení** | hlásič / admin | důvod znovuotevření | událost s důvodem v `note` | řešitel: `ISSUE_REOPENED` |
|
||||||
| T8 | Přiřazena / V řešení → **Zamítnuta** | přiřazený řešitel | důvod zamítnutí | událost s důvodem v `note` (= čas uzavření) | hlásič |
|
| T8 | Přiřazena / V řešení → **Zamítnuta** | přiřazený řešitel / admin | důvod zamítnutí | událost s důvodem v `note` (= čas uzavření) | hlásič |
|
||||||
| T9 | Přijata → **Zamítnuta** | vedení | důvod zamítnutí | událost s důvodem v `note` (= čas uzavření) | hlásič |
|
| T9 | Přijata → **Zamítnuta** | vedení / admin | důvod zamítnutí | událost s důvodem v `note` (= čas uzavření) | hlásič |
|
||||||
|
|
||||||
**Obecná pravidla**
|
**Obecná pravidla**
|
||||||
|
|
||||||
@@ -300,19 +303,19 @@ stateDiagram-v2
|
|||||||
state "Realizován" as IMPLEMENTED
|
state "Realizován" as IMPLEMENTED
|
||||||
|
|
||||||
[*] --> SUBMITTED : uživatel podá
|
[*] --> SUBMITTED : uživatel podá
|
||||||
SUBMITTED --> UNDER_REVIEW : vedení
|
SUBMITTED --> UNDER_REVIEW : vedení nebo admin
|
||||||
SUBMITTED --> ACCEPTED : vedení
|
SUBMITTED --> ACCEPTED : vedení nebo admin
|
||||||
SUBMITTED --> REJECTED : vedení (s vyjádřením)
|
SUBMITTED --> REJECTED : vedení nebo admin (s vyjádřením)
|
||||||
UNDER_REVIEW --> ACCEPTED : vedení
|
UNDER_REVIEW --> ACCEPTED : vedení nebo admin
|
||||||
UNDER_REVIEW --> REJECTED : vedení (s vyjádřením)
|
UNDER_REVIEW --> REJECTED : vedení nebo admin (s vyjádřením)
|
||||||
ACCEPTED --> IMPLEMENTED : vedení
|
ACCEPTED --> IMPLEMENTED : vedení nebo admin
|
||||||
REJECTED --> [*]
|
REJECTED --> [*]
|
||||||
IMPLEMENTED --> [*]
|
IMPLEMENTED --> [*]
|
||||||
```
|
```
|
||||||
|
|
||||||
- Stavy mění pouze **vedení školy**; zamítnutí vyžaduje vyjádření, u ostatních je volitelné. Vyjádření se ukládá do `note` příslušné události.
|
- Stavy může měnit vedení školy nebo administrátor. Zamítnutí vyžaduje vyjádření, u ostatních přechodů je volitelné. Vyjádření se ukládá do `note` příslušné události.
|
||||||
- Autor může návrh upravit, dokud je ve stavu *Podán* (událost `UPDATED`).
|
- Autor nebo administrátor může návrh upravit, dokud je ve stavu *Podán* (událost `UPDATED`).
|
||||||
- Každá změna se zapisuje do `proposal_event`, autor dostane notifikaci.
|
- Každá změna se zapisuje do `proposal_event`. Při změně stavu dostane autor notifikaci, pokud stav nezměnil sám.
|
||||||
|
|
||||||
### 7.2 Pravidla hlasování
|
### 7.2 Pravidla hlasování
|
||||||
|
|
||||||
@@ -371,9 +374,10 @@ sequenceDiagram
|
|||||||
end
|
end
|
||||||
```
|
```
|
||||||
|
|
||||||
- **V aplikaci:** tabulka `notification`. Notifikace v aplikaci je doručena vždy, protože vzniká v DB ve stejné transakci jako událost. Klient zobrazuje seznam a počet nepřečtených (`GET /api/v1/notifications/unread-count`, web jej obnovuje periodicky).
|
- **V aplikaci:** notifikace se uloží do tabulky `notification` ve stejné transakci jako událost. Klient zobrazuje seznam a počet nepřečtených (`GET /api/v1/notifications/unread-count`, web jej obnovuje periodicky).
|
||||||
- **E-mail:** SMTP (knihovna MailKit); ve vývoji zachytává e-maily kontejner Mailpit.
|
- **E-mail:** SMTP (knihovna MailKit); ve vývoji zachytává e-maily kontejner Mailpit.
|
||||||
- **Push:** mobilní aplikace po přihlášení zaregistruje FCM token (`POST /api/v1/devices`); backend odesílá přes Firebase Admin SDK.
|
- **Push:** mobilní aplikace po přihlášení zaregistruje FCM token (`POST /api/v1/devices`). Backend přes Firebase Admin SDK posílá obecné upozornění. Podrobnosti klient načte z API po přihlášení.
|
||||||
|
- Při zobrazení notifikace v aplikaci i před doručením e-mailu nebo push backend ověřuje aktuální přístup příjemce k související závadě.
|
||||||
- Pro každou notifikaci se vytvoří řádek `notification_delivery` pro každý externí kanál. Stav kanálu se tak sleduje samostatně: e-mail může selhat, i když push prošel.
|
- Pro každou notifikaci se vytvoří řádek `notification_delivery` pro každý externí kanál. Stav kanálu se tak sleduje samostatně: e-mail může selhat, i když push prošel.
|
||||||
|
|
||||||
### 8.3 Řešení nedoručení
|
### 8.3 Řešení nedoručení
|
||||||
@@ -407,8 +411,8 @@ flowchart TB
|
|||||||
|
|
||||||
subgraph Docker["Docker Compose"]
|
subgraph Docker["Docker Compose"]
|
||||||
PROXY[Reverzní proxy nginx<br/>HTTPS / TLS]
|
PROXY[Reverzní proxy nginx<br/>HTTPS / TLS]
|
||||||
WEB[Webová aplikace<br/>ASP.NET Core MVC]
|
WEB[Webová aplikace<br/>ASP.NET Core MVC<br/>+ Swagger UI]
|
||||||
API[Backend REST API<br/>ASP.NET Core Web API<br/>+ Swagger]
|
API[Backend REST API<br/>ASP.NET Core Web API<br/>+ OpenAPI]
|
||||||
DB[(MariaDB 11)]
|
DB[(MariaDB 11)]
|
||||||
FILES[[Volume: přílohy]]
|
FILES[[Volume: přílohy]]
|
||||||
end
|
end
|
||||||
@@ -419,7 +423,7 @@ flowchart TB
|
|||||||
BROWSER -- HTTPS --> PROXY
|
BROWSER -- HTTPS --> PROXY
|
||||||
MOB -- "HTTPS, JWT" --> PROXY
|
MOB -- "HTTPS, JWT" --> PROXY
|
||||||
PROXY --> WEB
|
PROXY --> WEB
|
||||||
PROXY -- "/api/*, /swagger" --> API
|
PROXY -- "/api/*" --> API
|
||||||
WEB -- "REST, JWT" --> API
|
WEB -- "REST, JWT" --> API
|
||||||
API --> DB
|
API --> DB
|
||||||
API --> FILES
|
API --> FILES
|
||||||
@@ -444,8 +448,8 @@ Fyzické nasazení (sítě, porty, úložiště, tajné klíče) popisuje kapito
|
|||||||
|
|
||||||
### 9.3 Autorizace
|
### 9.3 Autorizace
|
||||||
|
|
||||||
1. **Podle role** – atribut `[Authorize(Roles = "MANAGEMENT")]` / politiky (např. `CanAssignIssues`, `CanEvaluateProposals`, `IsAdmin`). Role je v JWT jako claim `role`.
|
1. **Podle role** – atributy jako `[Authorize(Roles = Roles.ManagementOrAdmin)]` a autorizační politiky. Role je v JWT jako claim `role`.
|
||||||
2. **Nad konkrétním záznamem** – v aplikační vrstvě (`IssueAuthorizationService`): „je aktuální uživatel hlásičem / přiřazeným řešitelem této závady?“, „je autorem návrhu?“. Porušení → 403.
|
2. **Nad konkrétním záznamem** – aplikační a doménová vrstva ověřují oprávnění k akci. U závad a úprav návrhů může administrátor jednat i u cizích záznamů. Porušení → 403.
|
||||||
3. **Podle stavu** – stavový automat v doméně. Porušení → 409.
|
3. **Podle stavu** – stavový automat v doméně. Porušení → 409.
|
||||||
|
|
||||||
Detail závady vrací pole `allowedActions` (např. `["START_WORK", "REJECT", "COMMENT"]`), podle kterého klienti zobrazují ovládací prvky – logika tak není duplikována v klientech.
|
Detail závady vrací pole `allowedActions` (např. `["START_WORK", "REJECT", "COMMENT"]`), podle kterého klienti zobrazují ovládací prvky – logika tak není duplikována v klientech.
|
||||||
@@ -467,7 +471,7 @@ Detail závady vrací pole `allowedActions` (např. `["START_WORK", "REJECT", "C
|
|||||||
| Síť | Retrofit + OkHttp + kotlinx.serialization; `Authenticator` pro obnovu tokenu, `Interceptor` pro Bearer hlavičku |
|
| Síť | Retrofit + OkHttp + kotlinx.serialization; `Authenticator` pro obnovu tokenu, `Interceptor` pro Bearer hlavičku |
|
||||||
| Úložiště tokenů | DataStore, šifrováno klíčem z Android Keystore |
|
| Úložiště tokenů | DataStore, šifrováno klíčem z Android Keystore |
|
||||||
| Fotky | Systémový fotoaparát / výběr z galerie (Activity Result API), náhledy Coil, zmenšení před odesláním |
|
| Fotky | Systémový fotoaparát / výběr z galerie (Activity Result API), náhledy Coil, zmenšení před odesláním |
|
||||||
| Push | Firebase Cloud Messaging (`FirebaseMessagingService`), deep link na detail závady |
|
| Push | Firebase Cloud Messaging (`FirebaseMessagingService`), podrobnosti v přihlášené aplikaci |
|
||||||
| Min. verze | Android 8.0 (API 26) |
|
| Min. verze | Android 8.0 (API 26) |
|
||||||
|
|
||||||
### 9.6 Struktura repozitáře (Git, EngineRevive)
|
### 9.6 Struktura repozitáře (Git, EngineRevive)
|
||||||
@@ -507,11 +511,11 @@ Větvení: `main` (stabilní), `develop`, feature větve `feature/<nazev>`, merg
|
|||||||
|
|
||||||
| Oblast | Řešení |
|
| Oblast | Řešení |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Hesla | Hash BCrypt (knihovna BCrypt.Net-Next, work factor 12; sůl je součástí hashe). Min. délka hesla 8 znaků. |
|
| Hesla | Hash BCrypt (knihovna BCrypt.Net-Next, work factor 12; sůl je součástí hashe). Nové heslo má 8–64 znaků a nejvýše 72 bajtů v UTF-8. |
|
||||||
| Přihlášení | Ochrana proti hádání hesla: po 5 neúspěšných pokusech zámek účtu na 15 minut (`failed_login_count`, `lockout_until`), rate limiting na `/api/v1/auth/*`. |
|
| Přihlášení | Neúspěšné ověření vrací jednotnou odpověď, BCrypt se provádí i pro neznámý účet. Každá instance API omezuje přihlášení na 5 pokusů za minutu pro dvojici klientská IP a normalizovaný e-mail. Pro `/api/v1/auth/*` platí také limit 20 požadavků za minutu na klientskou IP. |
|
||||||
| Tokeny | Všechny tokeny jsou podepsané JWT podle RFC 7519 s unikátním `jti` a typem v hlavičce. V databázi není žádný token ani jeho hash (kap. 10.1). |
|
| Tokeny | Všechny tokeny jsou podepsané JWT podle RFC 7519 s unikátním `jti` a typem v hlavičce. V databázi není žádný token ani jeho hash (kap. 10.1). |
|
||||||
| Šifrování citlivých údajů | Telefonní číslo uživatele šifrováno AES-256-GCM (EF Core value converter), klíč mimo DB – v proměnné prostředí / Docker secret. Přenos výhradně HTTPS (TLS 1.2+), HSTS. |
|
| Šifrování citlivých údajů | Telefonní číslo uživatele šifrováno AES-256-GCM (EF Core value converter), klíč mimo DB – v proměnné prostředí / Docker secret. Přenos výhradně HTTPS (TLS 1.2+), HSTS. |
|
||||||
| Přílohy | Kontrola typu (přípona + signatura souboru) a velikosti, ukládání pod náhodným GUID mimo webový kořen, stahování jen přes API s kontrolou oprávnění k závadě. |
|
| Přílohy | Kontrola typu (přípona + signatura souboru) a velikosti, ukládání pod náhodným GUID mimo webový kořen, stahování jen přes API s kontrolou oprávnění k závadě. Web nabízí PDF ke stažení. API zapisuje varování do logu, pokud na svazku s přílohami zbývá méně než 10 % volného místa. |
|
||||||
| Zápisy závad | Vytvoření závady, přidání komentáře a nahrání příloh mají společný limit 10 požadavků za minutu na účet a instanci API. Překročení vrací 429. |
|
| Zápisy závad | Vytvoření závady, přidání komentáře a nahrání příloh mají společný limit 10 požadavků za minutu na účet a instanci API. Překročení vrací 429. |
|
||||||
| Vstupy | Validace DTO (FluentValidation), parametrizované dotazy (EF Core), HTML výstup kódován Razorem (XSS), anti-forgery tokeny ve webových formulářích (CSRF). |
|
| Vstupy | Validace DTO (FluentValidation), parametrizované dotazy (EF Core), HTML výstup kódován Razorem (XSS), anti-forgery tokeny ve webových formulářích (CSRF). |
|
||||||
| Tajemství | JWT klíč, DB heslo, šifrovací klíč, SMTP a Firebase přístupy pouze v proměnných prostředí / `.env` mimo Git. |
|
| Tajemství | JWT klíč, DB heslo, šifrovací klíč, SMTP a Firebase přístupy pouze v proměnných prostředí / `.env` mimo Git. |
|
||||||
@@ -615,7 +619,7 @@ SET revoked_at = UTC_TIMESTAMP(6), revoke_reason = 'USED'
|
|||||||
WHERE jti = ? AND token_type = 'REFRESH' AND revoked_at IS NULL;
|
WHERE jti = ? AND token_type = 'REFRESH' AND revoked_at IS NULL;
|
||||||
```
|
```
|
||||||
|
|
||||||
- **Změněn 1 řádek** → token se používá poprvé, server vydá nový pár tokenů.
|
- **Změněn 1 řádek** → token se používá poprvé, server uloží nový pár tokenů ve stejné databázové transakci.
|
||||||
- **Změněno 0 řádků** → token už byl použitý nebo zneplatněný. U refresh tokenu to znamená, že ho zneužil někdo jiný. Server zneplatní všechny tokeny uživatele (`REUSE_DETECTED`) a vrátí 401.
|
- **Změněno 0 řádků** → token už byl použitý nebo zneplatněný. U refresh tokenu to znamená, že ho zneužil někdo jiný. Server zneplatní všechny tokeny uživatele (`REUSE_DETECTED`) a vrátí 401.
|
||||||
|
|
||||||
Ze dvou současných požadavků se stejným tokenem vždy uspěje jen jeden. Klienti (mobil i web) proto musí obnovu tokenů provádět vždy jen jednou současně. Jinak by souběžné obnovy vyhodnotil server jako krádež.
|
Ze dvou současných požadavků se stejným tokenem vždy uspěje jen jeden. Klienti (mobil i web) proto musí obnovu tokenů provádět vždy jen jednou současně. Jinak by souběžné obnovy vyhodnotil server jako krádež.
|
||||||
@@ -647,13 +651,13 @@ Aplikační API má základní cestu **`/api/v1`**. Připojte tento prefix před
|
|||||||
|
|
||||||
Číslo v URL je hlavní verze API. Zpětně kompatibilní rozšíření patří do stávající verze. Při nekompatibilní změně vznikne nová cesta (např. `/api/v2`) a samostatný OpenAPI dokument. Během přechodu klientů poběží obě verze souběžně. Před ukončením podpory starší verze se oznámí termín a zdokumentuje přechod.
|
Číslo v URL je hlavní verze API. Zpětně kompatibilní rozšíření patří do stávající verze. Při nekompatibilní změně vznikne nová cesta (např. `/api/v2`) a samostatný OpenAPI dokument. Během přechodu klientů poběží obě verze souběžně. Před ukončením podpory starší verze se oznámí termín a zdokumentuje přechod.
|
||||||
|
|
||||||
Swagger UI je na `/swagger` a OpenAPI dokument pro v1 na `/swagger/v1/swagger.json`. Provozní kontrola API je na `GET /health`.
|
Swagger UI je na webu na `/swagger`. UI i jeho OpenAPI dokument na `/swagger/v1/swagger.json` vyžadují administrátorskou relaci. Web načítá dokument z `GET /api/v1/admin/openapi/v1.json` s access tokenem administrátora. Provozní kontrola API je na `GET /health`.
|
||||||
|
|
||||||
### Autentizace a účet
|
### Autentizace a účet
|
||||||
| Metoda | Endpoint | Role | Popis |
|
| Metoda | Endpoint | Role | Popis |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| POST | `/auth/register` | anonym | Registrace (e-mail, heslo, jméno, příjmení) |
|
| POST | `/auth/register` | anonym | Registrace (e-mail, jméno, příjmení) a odeslání ověřovacího odkazu. Po `503` s typem `urn:ntbug:email-delivery-failed` lze stejným požadavkem zopakovat odeslání pro uložený účet. |
|
||||||
| POST | `/auth/confirm-email` | anonym | Ověření e-mailu tokenem |
|
| POST | `/auth/confirm-email` | anonym | Ověření e-mailu a nastavení hesla v jedné transakci (`{ token, newPassword }`) |
|
||||||
| POST | `/auth/login` | anonym | Vrací `accessToken`, `refreshToken`, údaje uživatele a roli |
|
| POST | `/auth/login` | anonym | Vrací `accessToken`, `refreshToken`, údaje uživatele a roli |
|
||||||
| POST | `/auth/refresh` | anonym | Výměna refresh tokenu za nový pár tokenů (starý `jti` se zablokuje) |
|
| POST | `/auth/refresh` | anonym | Výměna refresh tokenu za nový pár tokenů (starý `jti` se zablokuje) |
|
||||||
| POST | `/auth/logout` | přihlášený | Zablokuje `jti` access i refresh tokenu |
|
| POST | `/auth/logout` | přihlášený | Zablokuje `jti` access i refresh tokenu |
|
||||||
@@ -665,21 +669,21 @@ Swagger UI je na `/swagger` a OpenAPI dokument pro v1 na `/swagger/v1/swagger.js
|
|||||||
### Hlášení závad
|
### Hlášení závad
|
||||||
| Metoda | Endpoint | Role | Popis |
|
| Metoda | Endpoint | Role | Popis |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| GET | `/issues` | přihlášený | Seznam; filtry `status`, `categoryId`, `buildingId`, `assigneeId`, `reporterId`, `from`, `to`, `q`, `mine`; řazení `sort=newest\|oldest`. Student, vyučující a administrátor vidí jen vlastní. |
|
| GET | `/issues` | přihlášený | Seznam; filtry `status`, `categoryId`, `buildingId`, `assigneeId`, `reporterId`, `from`, `to`, `q`, `mine`; řazení `sort=newest\|oldest`. Student a vyučující vidí jen vlastní. |
|
||||||
| POST | `/issues` | přihlášený | Vytvoření hlášení (T1), JSON do 1 MiB nebo multipart s poli hlášení a soubory v poli `files` |
|
| POST | `/issues` | přihlášený | Vytvoření hlášení (T1), JSON do 1 MiB nebo multipart s poli hlášení a soubory v poli `files` |
|
||||||
| GET | `/issues/{id}` | účastník / správce / vedení | Detail vč. `allowedActions` a `rowVersion` |
|
| GET | `/issues/{id}` | účastník / správce / vedení / admin | Detail vč. `allowedActions` a `rowVersion` |
|
||||||
| PUT | `/issues/{id}` | hlásič | Úprava ve stavu Přijata s `rowVersion` |
|
| PUT | `/issues/{id}` | hlásič / admin | Úprava ve stavu Přijata s `rowVersion` |
|
||||||
| POST | `/issues/{id}/assign` | vedení | `{ assigneeId, priority?, rowVersion }` (T2, T3) |
|
| POST | `/issues/{id}/assign` | vedení / admin | `{ assigneeId, priority?, rowVersion }` (T2, T3) |
|
||||||
| POST | `/issues/{id}/start` | řešitel | `{ rowVersion }` (T4) |
|
| POST | `/issues/{id}/start` | řešitel / admin | `{ rowVersion }` (T4) |
|
||||||
| POST | `/issues/{id}/submit-for-verification` | řešitel | `{ rowVersion, note? }` (T5) |
|
| POST | `/issues/{id}/submit-for-verification` | řešitel / admin | `{ rowVersion, note? }` (T5) |
|
||||||
| POST | `/issues/{id}/confirm` | hlásič | `{ rowVersion }` (T6) |
|
| POST | `/issues/{id}/confirm` | hlásič / admin | `{ rowVersion }` (T6) |
|
||||||
| POST | `/issues/{id}/reopen` | hlásič | `{ rowVersion, reason }` (T7) |
|
| POST | `/issues/{id}/reopen` | hlásič / admin | `{ rowVersion, reason }` (T7) |
|
||||||
| POST | `/issues/{id}/reject` | řešitel / vedení | `{ rowVersion, reason }` (T8, T9) |
|
| POST | `/issues/{id}/reject` | řešitel / vedení / admin | `{ rowVersion, reason }` (T8, T9) |
|
||||||
| GET | `/issues/{id}/events` | jako detail | Časová osa – všechny události včetně komentářů (`issue_event`) |
|
| GET | `/issues/{id}/events` | jako detail | Časová osa – všechny události včetně komentářů (`issue_event`) |
|
||||||
| POST | `/issues/{id}/comments` | hlásič, řešitel | `{ text }` – zapíše událost `COMMENTED` |
|
| POST | `/issues/{id}/comments` | hlásič / řešitel / admin | `{ text }` – zapíše událost `COMMENTED` |
|
||||||
| POST | `/issues/{id}/attachments` | hlásič, řešitel | `multipart/form-data`, 1–5 souborů v poli `files` |
|
| POST | `/issues/{id}/attachments` | hlásič / řešitel / admin | `multipart/form-data`, 1–5 souborů v poli `files` |
|
||||||
| GET | `/attachments/{id}` | jako detail závady | Stažení souboru |
|
| GET | `/attachments/{id}` | jako detail závady | Stažení souboru |
|
||||||
| GET | `/users/assignable` | vedení | Možní řešitelé s počtem otevřených závad |
|
| GET | `/users/assignable` | vedení / admin | Možní řešitelé s počtem otevřených závad |
|
||||||
|
|
||||||
Přechody stavů jsou záměrně **samostatné akční endpointy** místo obecného `PATCH status` – každý má vlastní vstupní data, oprávnění a je jednoznačně zdokumentovaný ve Swaggeru.
|
Přechody stavů jsou záměrně **samostatné akční endpointy** místo obecného `PATCH status` – každý má vlastní vstupní data, oprávnění a je jednoznačně zdokumentovaný ve Swaggeru.
|
||||||
Po přidání komentáře nebo příloh klient znovu načte detail, aby získal aktuální `rowVersion`.
|
Po přidání komentáře nebo příloh klient znovu načte detail, aby získal aktuální `rowVersion`.
|
||||||
@@ -690,10 +694,10 @@ Po přidání komentáře nebo příloh klient znovu načte detail, aby získal
|
|||||||
| GET | `/proposals` | přihlášený | Filtry `status`, `categoryId`, `authorId`, `q`; `sort=score\|newest`; obsahuje skóre a můj hlas |
|
| GET | `/proposals` | přihlášený | Filtry `status`, `categoryId`, `authorId`, `q`; `sort=score\|newest`; obsahuje skóre a můj hlas |
|
||||||
| POST | `/proposals` | přihlášený | Podání návrhu |
|
| POST | `/proposals` | přihlášený | Podání návrhu |
|
||||||
| GET | `/proposals/{id}` | přihlášený | Detail vč. událostí a vyjádření vedení |
|
| GET | `/proposals/{id}` | přihlášený | Detail vč. událostí a vyjádření vedení |
|
||||||
| PUT | `/proposals/{id}` | autor | Úprava ve stavu Podán |
|
| PUT | `/proposals/{id}` | autor / admin | Úprava ve stavu Podán |
|
||||||
| PUT | `/proposals/{id}/vote` | přihlášený (ne autor) | `{ value: 1 \| -1 }` – vytvoření nebo změna hlasu |
|
| PUT | `/proposals/{id}/vote` | přihlášený (ne autor) | `{ value: 1 \| -1 }` – vytvoření nebo změna hlasu |
|
||||||
| DELETE | `/proposals/{id}/vote` | přihlášený | Zrušení hlasu |
|
| DELETE | `/proposals/{id}/vote` | přihlášený | Zrušení hlasu |
|
||||||
| POST | `/proposals/{id}/status` | vedení | `{ status, note? }` |
|
| POST | `/proposals/{id}/status` | vedení / admin | `{ status, note? }` |
|
||||||
|
|
||||||
### Notifikace a zařízení
|
### Notifikace a zařízení
|
||||||
| Metoda | Endpoint | Role | Popis |
|
| Metoda | Endpoint | Role | Popis |
|
||||||
@@ -708,12 +712,12 @@ Po přidání komentáře nebo příloh klient znovu načte detail, aby získal
|
|||||||
### Statistiky
|
### Statistiky
|
||||||
| Metoda | Endpoint | Role | Popis |
|
| Metoda | Endpoint | Role | Popis |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| GET | `/statistics/overview?from=&to=` | vedení | Souhrnné KPI: počty podle stavu, průměrná doba do přiřazení a do uzavření |
|
| GET | `/statistics/overview?from=&to=` | vedení / admin | Souhrnné KPI: počty podle stavu, průměrná doba do přiřazení a do uzavření |
|
||||||
| GET | `/statistics/issues/by-category` | vedení | Počty a průměrná doba řešení podle kategorie |
|
| GET | `/statistics/issues/by-category` | vedení / admin | Počty a průměrná doba řešení podle kategorie |
|
||||||
| GET | `/statistics/issues/by-building` | vedení | Podle budovy |
|
| GET | `/statistics/issues/by-building` | vedení / admin | Podle budovy |
|
||||||
| GET | `/statistics/issues/by-assignee` | vedení | Vytížení řešitelů (otevřené / uzavřené) |
|
| GET | `/statistics/issues/by-assignee` | vedení / admin | Vytížení řešitelů (otevřené / uzavřené) |
|
||||||
| GET | `/statistics/issues/trend?granularity=month` | vedení | Nové vs. uzavřené závady v čase |
|
| GET | `/statistics/issues/trend?granularity=month` | vedení / admin | Nové vs. uzavřené závady v čase |
|
||||||
| GET | `/statistics/proposals/top?limit=10` | vedení | Nejpodporovanější návrhy |
|
| GET | `/statistics/proposals/top?limit=10` | vedení / admin | Nejpodporovanější návrhy |
|
||||||
|
|
||||||
### Číselníky a administrace
|
### Číselníky a administrace
|
||||||
| Metoda | Endpoint | Role | Popis |
|
| Metoda | Endpoint | Role | Popis |
|
||||||
@@ -721,6 +725,11 @@ Po přidání komentáře nebo příloh klient znovu načte detail, aby získal
|
|||||||
| GET | `/buildings`, `/issue-categories`, `/proposal-categories` | přihlášený | Číselníky pro formuláře |
|
| GET | `/buildings`, `/issue-categories`, `/proposal-categories` | přihlášený | Číselníky pro formuláře |
|
||||||
| POST / PUT / DELETE | totéž | admin | Správa (DELETE = deaktivace `is_active`) |
|
| POST / PUT / DELETE | totéž | admin | Správa (DELETE = deaktivace `is_active`) |
|
||||||
| GET | `/admin/users?q=&role=` | admin | Vyhledání uživatelů |
|
| GET | `/admin/users?q=&role=` | admin | Vyhledání uživatelů |
|
||||||
|
| POST | `/admin/users` | admin | Založení účtu s ručním ověřením a počátečním heslem, nebo s odkazem pro nastavení hesla příjemcem |
|
||||||
|
| GET / PUT | `/admin/users/{id}` | admin | Detail a úprava účtu s `rowVersion`. Zastaralá verze vrátí 409. Změna adresy aktivního účtu spustí nové ověření. Nové heslo odhlásí relace a odpojí push zařízení. |
|
||||||
|
| POST | `/admin/users/{id}/email-confirmation` | admin | Opětovné odeslání odkazu aktivnímu účtu s neověřeným e-mailem |
|
||||||
|
| DELETE | `/admin/users/{id}` | admin | Znepřístupnění účtu a anonymizace profilu |
|
||||||
|
| POST | `/admin/users/bulk` | admin | Změna role, aktivace, deaktivace nebo smazání vybraných účtů v jedné transakci |
|
||||||
| PUT | `/admin/users/{id}/role` | admin | `{ role: "FACILITY_MANAGER" }` |
|
| PUT | `/admin/users/{id}/role` | admin | `{ role: "FACILITY_MANAGER" }` |
|
||||||
| PUT | `/admin/users/{id}/active` | admin | Aktivace / deaktivace účtu |
|
| PUT | `/admin/users/{id}/active` | admin | Aktivace / deaktivace účtu |
|
||||||
| GET | `/admin/notification-deliveries?status=FAILED` | admin | Nedoručené notifikace s důvodem chyby |
|
| GET | `/admin/notification-deliveries?status=FAILED` | admin | Nedoručené notifikace s důvodem chyby |
|
||||||
@@ -771,8 +780,6 @@ erDiagram
|
|||||||
bool is_active
|
bool is_active
|
||||||
bool email_confirmed
|
bool email_confirmed
|
||||||
bool email_notifications_enabled
|
bool email_notifications_enabled
|
||||||
int failed_login_count
|
|
||||||
datetime lockout_until
|
|
||||||
datetime created_at
|
datetime created_at
|
||||||
}
|
}
|
||||||
auth_token {
|
auth_token {
|
||||||
@@ -942,7 +949,7 @@ V první verzi byla tabulka uživatelů „chobotnice“: vedlo na ni 17 cizích
|
|||||||
- Hlavní tabulky (`issue`, `proposal`, `attachment`, …) obsahují **jen `created_at`**. Je neměnný a potřebný pro řazení a filtrování podle období přes index.
|
- Hlavní tabulky (`issue`, `proposal`, `attachment`, …) obsahují **jen `created_at`**. Je neměnný a potřebný pro řazení a filtrování podle období přes index.
|
||||||
- Všechny ostatní časy životního cyklu (přiřazení, převzetí, uzavření, rozhodnutí vedení, úpravy) jsou v **tabulkách událostí** `issue_event` a `proposal_event`. Jedna řádka = jeden okamžik (`occurred_at`), kdo ho způsobil (`actor_id`) a co se stalo (`event_type`, `from_status` → `to_status`, `note`). Zrušeny byly sloupce `updated_at`, `assigned_at`, `closed_at`, `decided_at`, `rejection_reason`, `decision_note`.
|
- Všechny ostatní časy životního cyklu (přiřazení, převzetí, uzavření, rozhodnutí vedení, úpravy) jsou v **tabulkách událostí** `issue_event` a `proposal_event`. Jedna řádka = jeden okamžik (`occurred_at`), kdo ho způsobil (`actor_id`) a co se stalo (`event_type`, `from_status` → `to_status`, `note`). Zrušeny byly sloupce `updated_at`, `assigned_at`, `closed_at`, `decided_at`, `rejection_reason`, `decision_note`.
|
||||||
- Odvozené časy poskytuje pohled `v_issue_lifecycle` (`first_assigned_at`, `closed_at`, `last_activity_at`). Z něj čerpají statistiky.
|
- Odvozené časy poskytuje pohled `v_issue_lifecycle` (`first_assigned_at`, `closed_at`, `last_activity_at`). Z něj čerpají statistiky.
|
||||||
- Zůstávají jen **funkční časy**, které popisují aktuální stav záznamu a řídí chování systému: `notification.read_at`, `notification_delivery.next_attempt_at` / `sent_at`, `auth_token.issued_at` / `expires_at` / `revoked_at` (odpovídají claimům tokenu), `app_user.lockout_until`.
|
- **Funkční časy** popisují aktuální stav záznamu a řídí chování systému: `notification.read_at`, `notification_delivery.next_attempt_at` / `sent_at`, `auth_token.issued_at` / `expires_at` / `revoked_at` (odpovídají claimům tokenu).
|
||||||
- *Proč ne jedna společná tabulka datumů pro všechny entity:* musela by odkazovat na různé tabulky bez cizího klíče (polymorfní vazba), každý seznam by potřeboval další JOIN a řazení podle data by nevyužilo index. Tabulky událostí pro každou hlavní entitu tyto nevýhody nemají, zachovávají referenční integritu a navíc slouží jako audit.
|
- *Proč ne jedna společná tabulka datumů pro všechny entity:* musela by odkazovat na různé tabulky bez cizího klíče (polymorfní vazba), každý seznam by potřeboval další JOIN a řazení podle data by nevyužilo index. Tabulky událostí pro každou hlavní entitu tyto nevýhody nemají, zachovávají referenční integritu a navíc slouží jako audit.
|
||||||
- `created_at` vyplňuje v EF Core automaticky interceptor `SaveChanges` u entit s rozhraním `IHasCreatedAt`. Výchozí hodnota v DB je `UTC_TIMESTAMP(6)`.
|
- `created_at` vyplňuje v EF Core automaticky interceptor `SaveChanges` u entit s rozhraním `IHasCreatedAt`. Výchozí hodnota v DB je `UTC_TIMESTAMP(6)`.
|
||||||
|
|
||||||
@@ -976,9 +983,9 @@ V první verzi byla tabulka uživatelů „chobotnice“: vedlo na ni 17 cizích
|
|||||||
- **Normalizace (3NF)**: číselníky jsou v samostatných tabulkách. Časy životního cyklu se neukládají redundantně, ale odvozují se z událostí.
|
- **Normalizace (3NF)**: číselníky jsou v samostatných tabulkách. Časy životního cyklu se neukládají redundantně, ale odvozují se z událostí.
|
||||||
- **Stavy jako text + CHECK** místo nativního `ENUM`: hodnoty jsou v DB čitelné, rozšíření je snadné a v EF Core se mapují na C# `enum` přes `HasConversion<string>()`.
|
- **Stavy jako text + CHECK** místo nativního `ENUM`: hodnoty jsou v DB čitelné, rozšíření je snadné a v EF Core se mapují na C# `enum` přes `HasConversion<string>()`.
|
||||||
- **Integritní omezení v DB** jako druhá linie obrany za aplikační logikou. Zamítnutí i znovuotevření musí mít důvod. Závada ve stavu *Přiřazena / V řešení / Čeká na ověření* musí mít řešitele. Událost `CREATED` musí začínat výchozím stavem, komentář (`COMMENTED`) musí mít text a nesmí měnit stav. Hlas je jen `+1`/`-1`, příloha má max. 10 MB a odeslané doručení musí mít `sent_at`. Notifikace typu `ISSUE_*` musí odkazovat na závadu, typu `PROPOSAL_*` na návrh.
|
- **Integritní omezení v DB** jako druhá linie obrany za aplikační logikou. Zamítnutí i znovuotevření musí mít důvod. Závada ve stavu *Přiřazena / V řešení / Čeká na ověření* musí mít řešitele. Událost `CREATED` musí začínat výchozím stavem, komentář (`COMMENTED`) musí mít text a nesmí měnit stav. Hlas je jen `+1`/`-1`, příloha má max. 10 MB a odeslané doručení musí mít `sent_at`. Notifikace typu `ISSUE_*` musí odkazovat na závadu, typu `PROPOSAL_*` na návrh.
|
||||||
- **Pravidla vyžadující více tabulek** (autor nehlasuje pro svůj návrh, řešitel musí mít roli správce budov / vedení) hlídá aplikační vrstva. V DB by vyžadovala triggery a logika by se rozdělila na dvě místa.
|
- **Pravidla vyžadující více tabulek** (autor nehlasuje pro svůj návrh, řešitel musí mít roli správce budov, vedení nebo administrátora) hlídá aplikační vrstva. V DB by vyžadovala triggery a logika by se rozdělila na dvě místa.
|
||||||
- **Optimistické zamykání**: `issue.row_version` (EF Core concurrency token).
|
- **Optimistické zamykání**: `issue.row_version` a `app_user.row_version` (EF Core concurrency token).
|
||||||
- **Mazání**: uživatelé, závady, návrhy a číselníky se nemažou. Uživatelé a číselníky se deaktivují (`is_active`). `ON DELETE CASCADE` je jen u čistě závislých dat.
|
- **Mazání účtů**: smazaný účet se deaktivuje, jeho profil se anonymizuje a účet se skryje ze správy uživatelů (`is_deleted`). Původní e-mail je volný pro nový účet. Vazby závad, návrhů, hlasů a událostí zůstanou v databázi. Číselníky se deaktivují (`is_active`), závady a návrhy zůstávají v historii.
|
||||||
- **Časy v UTC**, `DATETIME(6)`; převod do místního času dělá klient.
|
- **Časy v UTC**, `DATETIME(6)`; převod do místního času dělá klient.
|
||||||
- **Kódování** `utf8mb4`, engine InnoDB (transakce, cizí klíče).
|
- **Kódování** `utf8mb4`, engine InnoDB (transakce, cizí klíče).
|
||||||
- **Indexy** pokrývají filtry centrálního přehledu, frontu nedoručených notifikací (`status, next_attempt_at`), zneplatnění všech tokenů uživatele (`user_id, revoked_at`) a úklid prošlých tokenů (`expires_at`).
|
- **Indexy** pokrývají filtry centrálního přehledu, frontu nedoručených notifikací (`status, next_attempt_at`), zneplatnění všech tokenů uživatele (`user_id, revoked_at`) a úklid prošlých tokenů (`expires_at`).
|
||||||
@@ -1035,13 +1042,13 @@ ORDER BY n.created_at DESC;
|
|||||||
| Nástěnka (moje otevřená hlášení, poslední notifikace, top návrhy) | ✅ | ✅ | všichni |
|
| Nástěnka (moje otevřená hlášení, poslední notifikace, top návrhy) | ✅ | ✅ | všichni |
|
||||||
| Nové hlášení závady (formulář + přílohy / fotoaparát) | ✅ | ✅ | všichni |
|
| Nové hlášení závady (formulář + přílohy / fotoaparát) | ✅ | ✅ | všichni |
|
||||||
| Moje hlášení (seznam se stavem) | ✅ | ✅ | všichni |
|
| Moje hlášení (seznam se stavem) | ✅ | ✅ | všichni |
|
||||||
| Detail závady (stav, časová osa, akce podle `allowedActions`, komentáře, přílohy) | ✅ | ✅ | účastníci, správce, vedení |
|
| Detail závady (stav, časová osa, akce podle `allowedActions`, komentáře, přílohy) | ✅ | ✅ | účastníci, správce, vedení, admin |
|
||||||
| Přiřazené závady (pracovní fronta řešitele) | ✅ | ✅ | správce budov |
|
| Přiřazené závady (pracovní fronta řešitele) | ✅ | ✅ | správce budov |
|
||||||
| Centrální přehled závad (tabulka, filtry, hromadný přehled) | ✅ | — | správce budov, vedení |
|
| Centrální přehled závad (tabulka, filtry, hromadný přehled) | ✅ | — | správce budov, vedení, admin |
|
||||||
| Návrhy – seznam (řazení podle skóre, hlasování přímo v seznamu) | ✅ | ✅ | všichni |
|
| Návrhy – seznam (řazení podle skóre, hlasování přímo v seznamu) | ✅ | ✅ | všichni |
|
||||||
| Detail návrhu / nový návrh | ✅ | ✅ | všichni |
|
| Detail návrhu / nový návrh | ✅ | ✅ | všichni |
|
||||||
| Hodnocení návrhů (fronta podaných návrhů) | ✅ | — | vedení |
|
| Hodnocení návrhů (fronta podaných návrhů) | ✅ | — | vedení, admin |
|
||||||
| Statistiky (KPI dlaždice, grafy, filtr období) | ✅ | — | vedení |
|
| Statistiky (KPI dlaždice, grafy, filtr období) | ✅ | — | vedení, admin |
|
||||||
| Notifikace | ✅ | ✅ | všichni |
|
| Notifikace | ✅ | ✅ | všichni |
|
||||||
| Profil a nastavení notifikací | ✅ | ✅ | všichni |
|
| Profil a nastavení notifikací | ✅ | ✅ | všichni |
|
||||||
| Správa uživatelů a rolí | ✅ | — | admin |
|
| Správa uživatelů a rolí | ✅ | — | admin |
|
||||||
@@ -1129,7 +1136,7 @@ flowchart LR
|
|||||||
BROWSER -- "HTTPS 443" --> PROXY
|
BROWSER -- "HTTPS 443" --> PROXY
|
||||||
MOBILE -- "HTTPS 443 /api/v1/*" --> PROXY
|
MOBILE -- "HTTPS 443 /api/v1/*" --> PROXY
|
||||||
PROXY -- "HTTP 8080 /" --> WEB
|
PROXY -- "HTTP 8080 /" --> WEB
|
||||||
PROXY -- "HTTP 8080 /api/*, /swagger" --> API
|
PROXY -- "HTTP 8080 /api/*" --> API
|
||||||
WEB -- "HTTP 8080 REST + JWT" --> API
|
WEB -- "HTTP 8080 REST + JWT" --> API
|
||||||
API -- "TCP 3306" --> DB
|
API -- "TCP 3306" --> DB
|
||||||
MIG -- "TCP 3306" --> DB
|
MIG -- "TCP 3306" --> DB
|
||||||
@@ -1157,8 +1164,8 @@ flowchart LR
|
|||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
| prohlížeč | proxy | HTTPS 443 (HTTP 80 → přesměrování) | internet | webová aplikace |
|
| prohlížeč | proxy | HTTPS 443 (HTTP 80 → přesměrování) | internet | webová aplikace |
|
||||||
| mobil | proxy | HTTPS 443 | internet | REST API |
|
| mobil | proxy | HTTPS 443 | internet | REST API |
|
||||||
| proxy | web | HTTP 8080 | frontend | stránky (`/`) |
|
| proxy | web | HTTP 8080 | frontend | stránky (`/`), administrátorské Swagger UI (`/swagger`) |
|
||||||
| proxy | api | HTTP 8080 | frontend | `/api/*`, `/swagger` |
|
| proxy | api | HTTP 8080 | frontend | `/api/*` |
|
||||||
| web | api | HTTP 8080 (`http://api:8080/api/v1/`) | frontend | volání API s JWT přihlášeného uživatele |
|
| web | api | HTTP 8080 (`http://api:8080/api/v1/`) | frontend | volání API s JWT přihlášeného uživatele |
|
||||||
| api | db | TCP 3306 | backend | data – DB účet `helpdesk_app` |
|
| api | db | TCP 3306 | backend | data – DB účet `helpdesk_app` |
|
||||||
| migrator | db | TCP 3306 | backend | migrace – DB účet `helpdesk_migrator` |
|
| migrator | db | TCP 3306 | backend | migrace – DB účet `helpdesk_migrator` |
|
||||||
@@ -1171,8 +1178,8 @@ flowchart LR
|
|||||||
| Služba | Image | Sítě | Porty | Úložiště | Poznámka |
|
| Služba | Image | Sítě | Porty | Úložiště | Poznámka |
|
||||||
|---|---|---|---|---|---|
|
|---|---|---|---|---|---|
|
||||||
| `proxy` | `nginx` | frontend | **80, 443 publikované** | certifikáty | TLS (vývoj: `mkcert`, produkce: Let's Encrypt), HSTS, limit velikosti požadavku 51 MiB (5 příloh × 10 MiB a režie multipart) |
|
| `proxy` | `nginx` | frontend | **80, 443 publikované** | certifikáty | TLS (vývoj: `mkcert`, produkce: Let's Encrypt), HSTS, limit velikosti požadavku 51 MiB (5 příloh × 10 MiB a režie multipart) |
|
||||||
| `web` | vlastní (`dotnet/aspnet`) | frontend | interně 8080 | `web-keys` | klíče ASP.NET Core Data Protection pro šifrované cookie (bez persistence by restart odhlásil všechny uživatele) |
|
| `web` | vlastní (`dotnet/aspnet`) | frontend | interně 8080 | `web-keys` | administrátorské Swagger UI na `/swagger`, klíče Data Protection pro šifrované cookie |
|
||||||
| `api` | vlastní (`dotnet/aspnet`) | frontend, backend | interně 8080 | `uploads` | Swagger na `/swagger`, `GET /health`, vytvoření admin účtu z env |
|
| `api` | vlastní (`dotnet/aspnet`) | frontend, backend | interně 8080 | `uploads` | OpenAPI pro administrátory, `GET /health`, vytvoření admin účtu z env |
|
||||||
| `migrator` | vlastní (`dotnet/runtime`) | backend | — | — | aplikuje nové migrace z `db/migrations` a skončí |
|
| `migrator` | vlastní (`dotnet/runtime`) | backend | — | — | aplikuje nové migrace z `db/migrations` a skončí |
|
||||||
| `db` | `mariadb:11.4` | backend | interně 3306 | `db-data` | při prvním startu vytvoří DB účty skriptem z `deploy/db-init/` |
|
| `db` | `mariadb:11.4` | backend | interně 3306 | `db-data` | při prvním startu vytvoří DB účty skriptem z `deploy/db-init/` |
|
||||||
| `mailpit` | `axllent/mailpit` | frontend | 8025 (jen vývoj) | — | zachytává e-maily, v produkci se nespouští |
|
| `mailpit` | `axllent/mailpit` | frontend | 8025 (jen vývoj) | — | zachytává e-maily, v produkci se nespouští |
|
||||||
|
|||||||
@@ -3,7 +3,9 @@
|
|||||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<!-- Webová aplikace vystačí se sdíleným frameworkem ASP.NET Core; balíčky jsou jen pro testy. -->
|
<PackageVersion Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.3.1" />
|
||||||
|
<!-- Testy -->
|
||||||
|
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.14" />
|
||||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
|
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
|
||||||
<PackageVersion Include="xunit.v3" Version="4.0.2" />
|
<PackageVersion Include="xunit.v3" Version="4.0.2" />
|
||||||
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
|
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
|
||||||
|
|||||||
@@ -0,0 +1,328 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Text;
|
||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Helpdesk.Web.Auth;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
|
using Microsoft.AspNetCore.TestHost;
|
||||||
|
using Microsoft.AspNetCore.WebUtilities;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using static Helpdesk.Web.Tests.WebTestSession;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Tests;
|
||||||
|
|
||||||
|
public sealed class AdminUsersTests
|
||||||
|
{
|
||||||
|
private const string UsersPath = "/admin/users";
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(null, "/login")]
|
||||||
|
[InlineData(UserRoles.Student, "/error/403")]
|
||||||
|
[InlineData(UserRoles.Management, "/error/403")]
|
||||||
|
public async Task OnlyAnAdministratorCanListOrChangeUsers(string? role, string redirect)
|
||||||
|
{
|
||||||
|
var backend = new AdminUsersBackend();
|
||||||
|
await using var application = CreateApplication(backend);
|
||||||
|
using var client = CreateClient(application);
|
||||||
|
if (role is not null)
|
||||||
|
SignIn(application.Services, client, role);
|
||||||
|
var ct = TestContext.Current.CancellationToken;
|
||||||
|
|
||||||
|
foreach (var path in new[] { UsersPath, UsersPath + "/new", UsersPath + "/7/edit" })
|
||||||
|
{
|
||||||
|
using var page = await client.GetAsync(path, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, page.StatusCode);
|
||||||
|
Assert.Equal(redirect, page.Headers.Location?.AbsolutePath);
|
||||||
|
}
|
||||||
|
foreach (var action in new[] { "7/role", "7/active", "new", "7/edit", "7/delete", "7/email-confirmation", "bulk" })
|
||||||
|
{
|
||||||
|
using var update = await client.PostAsync($"{UsersPath}/{action}", null, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, update.StatusCode);
|
||||||
|
Assert.Equal(redirect, update.Headers.Location?.AbsolutePath);
|
||||||
|
}
|
||||||
|
Assert.Empty(backend.Requests);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AdministratorCanSearchAndChangeRoleAndActivation()
|
||||||
|
{
|
||||||
|
var backend = new AdminUsersBackend();
|
||||||
|
await using var application = CreateApplication(backend);
|
||||||
|
using var client = CreateClient(application);
|
||||||
|
SignIn(application.Services, client, UserRoles.Admin);
|
||||||
|
var ct = TestContext.Current.CancellationToken;
|
||||||
|
const string query = "?q=Nov%C3%A1k&role=STUDENT&page=2";
|
||||||
|
|
||||||
|
using var list = await client.GetAsync(UsersPath + query, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, list.StatusCode);
|
||||||
|
Assert.True(list.Headers.CacheControl?.NoStore == true);
|
||||||
|
var html = WebUtility.HtmlDecode(await list.Content.ReadAsStringAsync(ct));
|
||||||
|
Assert.Contains("Správa uživatelů", html);
|
||||||
|
Assert.Contains("Strana 2 z 3", html);
|
||||||
|
Assert.Contains("[email protected]", html);
|
||||||
|
Assert.Contains("E-mail neověřený", html);
|
||||||
|
Assert.Contains("Váš účet", html);
|
||||||
|
Assert.DoesNotContain($"{UsersPath}/1/role", html);
|
||||||
|
Assert.DoesNotContain($"{UsersPath}/1/active", html);
|
||||||
|
Assert.Contains($"{UsersPath}/7/role{query}", html);
|
||||||
|
Assert.Contains($"{UsersPath}/7/active{query}", html);
|
||||||
|
var token = AntiforgeryToken(html);
|
||||||
|
|
||||||
|
var search = Assert.Single(backend.Requests);
|
||||||
|
Assert.Equal(HttpMethod.Get, search.Method);
|
||||||
|
var filters = QueryHelpers.ParseQuery(search.Uri.Query);
|
||||||
|
Assert.Equal("Novák", filters["q"].ToString());
|
||||||
|
Assert.Equal("STUDENT", filters["role"].ToString());
|
||||||
|
Assert.Equal("2", filters["page"].ToString());
|
||||||
|
|
||||||
|
var updates = new[]
|
||||||
|
{
|
||||||
|
(Endpoint: "role", Field: "newRole", Value: UserRoles.Teacher, Body: """{"role":"TEACHER"}"""),
|
||||||
|
(Endpoint: "active", Field: "isActive", Value: "false", Body: """{"isActive":false}"""),
|
||||||
|
(Endpoint: "active", Field: "isActive", Value: "true", Body: """{"isActive":true}"""),
|
||||||
|
};
|
||||||
|
foreach (var update in updates)
|
||||||
|
{
|
||||||
|
using var form = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["__RequestVerificationToken"] = token,
|
||||||
|
[update.Field] = update.Value,
|
||||||
|
});
|
||||||
|
using var response = await client.PostAsync($"{UsersPath}/7/{update.Endpoint}{query}", form, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||||
|
Assert.Equal(UsersPath + query, response.Headers.Location?.OriginalString);
|
||||||
|
var request = backend.Requests[^1];
|
||||||
|
Assert.Equal(HttpMethod.Put, request.Method);
|
||||||
|
Assert.Equal($"/api/v1{UsersPath}/7/{update.Endpoint}", request.Uri.AbsolutePath);
|
||||||
|
Assert.Equal(update.Body, request.Body);
|
||||||
|
}
|
||||||
|
Assert.Equal(4, backend.Requests.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("role")]
|
||||||
|
[InlineData("active")]
|
||||||
|
public async Task AdministratorUpdatesRequireAntiforgeryToken(string action)
|
||||||
|
{
|
||||||
|
var backend = new AdminUsersBackend();
|
||||||
|
await using var application = CreateApplication(backend);
|
||||||
|
using var client = CreateClient(application);
|
||||||
|
SignIn(application.Services, client, UserRoles.Admin);
|
||||||
|
using var response = await client.PostAsync($"{UsersPath}/7/{action}", null, TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||||
|
Assert.Empty(backend.Requests);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AdminCanSubmitAccountFormsAndConfirmedBulkDeletion()
|
||||||
|
{
|
||||||
|
var backend = new AdminUsersBackend();
|
||||||
|
await using var application = CreateApplication(backend);
|
||||||
|
using var client = CreateClient(application);
|
||||||
|
SignIn(application.Services, client, UserRoles.Admin);
|
||||||
|
var ct = TestContext.Current.CancellationToken;
|
||||||
|
|
||||||
|
using var createPage = await client.GetAsync(UsersPath + "/new", ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, createPage.StatusCode);
|
||||||
|
var page = WebUtility.HtmlDecode(await createPage.Content.ReadAsStringAsync(ct));
|
||||||
|
Assert.Contains("Počáteční heslo", page);
|
||||||
|
Assert.Contains("Ověřit e-mail ručně", page);
|
||||||
|
Assert.Matches("""<input\b(?=[^>]*id="verification-email")(?=[^>]*checked="checked")[^>]*>""", page);
|
||||||
|
Assert.True(page.IndexOf("Správa uživatelů", StringComparison.Ordinal) < page.IndexOf("Swagger API", StringComparison.Ordinal));
|
||||||
|
var fields = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["__RequestVerificationToken"] = AntiforgeryToken(page),
|
||||||
|
["FirstName"] = "Jan",
|
||||||
|
["LastName"] = "Test",
|
||||||
|
["Email"] = "[email protected]",
|
||||||
|
["Role"] = UserRoles.Student,
|
||||||
|
["Password"] = "Initial-password",
|
||||||
|
["IsActive"] = "true",
|
||||||
|
["EmailConfirmed"] = "true",
|
||||||
|
};
|
||||||
|
using var createForm = new FormUrlEncodedContent(fields);
|
||||||
|
using var created = await client.PostAsync(UsersPath + "/new", createForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, created.StatusCode);
|
||||||
|
var createdRequest = Assert.Single(backend.Requests);
|
||||||
|
Assert.Equal(HttpMethod.Post, createdRequest.Method);
|
||||||
|
Assert.Equal("/api/v1/admin/users", createdRequest.Uri.AbsolutePath);
|
||||||
|
Assert.Contains("\"email\":\"[email protected]\"", createdRequest.Body);
|
||||||
|
Assert.Contains("\"emailConfirmed\":true", createdRequest.Body);
|
||||||
|
|
||||||
|
using var editPage = await client.GetAsync(UsersPath + "/7/edit", ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, editPage.StatusCode);
|
||||||
|
var editHtml = await editPage.Content.ReadAsStringAsync(ct);
|
||||||
|
Assert.Contains("[email protected]", editHtml);
|
||||||
|
Assert.Matches("""<input\b(?=[^>]*name="RowVersion")(?=[^>]*value="3")[^>]*>""", editHtml);
|
||||||
|
fields.Remove("Password");
|
||||||
|
fields["RowVersion"] = "3";
|
||||||
|
using var editForm = new FormUrlEncodedContent(fields);
|
||||||
|
using var edited = await client.PostAsync(UsersPath + "/7/edit", editForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, edited.StatusCode);
|
||||||
|
Assert.Equal(HttpMethod.Put, backend.Requests[^1].Method);
|
||||||
|
Assert.Contains("\"password\":null", backend.Requests[^1].Body);
|
||||||
|
Assert.Contains("\"rowVersion\":3", backend.Requests[^1].Body);
|
||||||
|
|
||||||
|
var bulk = new List<KeyValuePair<string, string>>
|
||||||
|
{
|
||||||
|
new("__RequestVerificationToken", fields["__RequestVerificationToken"]),
|
||||||
|
new("action", "delete"),
|
||||||
|
new("userIds", "7"),
|
||||||
|
new("userIds", "8"),
|
||||||
|
};
|
||||||
|
var count = backend.Requests.Count;
|
||||||
|
using var unconfirmedForm = new FormUrlEncodedContent(bulk);
|
||||||
|
using var unconfirmed = await client.PostAsync(UsersPath + "/bulk", unconfirmedForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, unconfirmed.StatusCode);
|
||||||
|
Assert.Equal(count, backend.Requests.Count);
|
||||||
|
|
||||||
|
bulk.Add(new("confirmDelete", "true"));
|
||||||
|
using var confirmedForm = new FormUrlEncodedContent(bulk);
|
||||||
|
using var confirmed = await client.PostAsync(UsersPath + "/bulk", confirmedForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, confirmed.StatusCode);
|
||||||
|
Assert.Equal("/api/v1/admin/users/bulk", backend.Requests[^1].Uri.AbsolutePath);
|
||||||
|
Assert.Contains("\"userIds\":[7,8]", backend.Requests[^1].Body);
|
||||||
|
Assert.Contains("\"action\":\"delete\"", backend.Requests[^1].Body);
|
||||||
|
|
||||||
|
using var singleForm = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["__RequestVerificationToken"] = fields["__RequestVerificationToken"],
|
||||||
|
["confirmDelete"] = "true",
|
||||||
|
});
|
||||||
|
using var deleted = await client.PostAsync(UsersPath + "/7/delete", singleForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, deleted.StatusCode);
|
||||||
|
Assert.Equal(HttpMethod.Delete, backend.Requests[^1].Method);
|
||||||
|
Assert.Equal("/api/v1/admin/users/7", backend.Requests[^1].Uri.AbsolutePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AdminCanResendVerificationAfterCreationSavedAnAccountButDeliveryFailed()
|
||||||
|
{
|
||||||
|
var backend = new AdminUsersBackend(failVerification: true);
|
||||||
|
await using var application = CreateApplication(backend);
|
||||||
|
using var client = CreateClient(application);
|
||||||
|
SignIn(application.Services, client, UserRoles.Admin);
|
||||||
|
var ct = TestContext.Current.CancellationToken;
|
||||||
|
|
||||||
|
using var createPage = await client.GetAsync(UsersPath + "/new", ct);
|
||||||
|
var page = WebUtility.HtmlDecode(await createPage.Content.ReadAsStringAsync(ct));
|
||||||
|
using var createForm = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["__RequestVerificationToken"] = AntiforgeryToken(page),
|
||||||
|
["FirstName"] = "Jan",
|
||||||
|
["LastName"] = "Novák",
|
||||||
|
["Email"] = "[email protected]",
|
||||||
|
["Role"] = UserRoles.Student,
|
||||||
|
["IsActive"] = "true",
|
||||||
|
["EmailConfirmed"] = "false",
|
||||||
|
});
|
||||||
|
using var created = await client.PostAsync(UsersPath + "/new", createForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, created.StatusCode);
|
||||||
|
Assert.StartsWith(UsersPath + "/7/edit", created.Headers.Location?.OriginalString);
|
||||||
|
|
||||||
|
using var editPage = await client.GetAsync(created.Headers.Location, ct);
|
||||||
|
var edit = WebUtility.HtmlDecode(await editPage.Content.ReadAsStringAsync(ct));
|
||||||
|
Assert.Contains("Účet byl založen.", edit);
|
||||||
|
Assert.Contains("Ověřovací e-mail se nepodařilo odeslat.", edit);
|
||||||
|
Assert.Contains("Poslat ověřovací e-mail", edit);
|
||||||
|
|
||||||
|
using var resendForm = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["__RequestVerificationToken"] = AntiforgeryToken(edit),
|
||||||
|
});
|
||||||
|
using var resent = await client.PostAsync(UsersPath + "/7/email-confirmation", resendForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, resent.StatusCode);
|
||||||
|
Assert.Equal((HttpMethod.Post, "/api/v1/admin/users/7/email-confirmation"),
|
||||||
|
(backend.Requests[^1].Method, backend.Requests[^1].Uri.AbsolutePath));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task StaleEditReloadsTheCurrentAccountAndShowsTheConflict()
|
||||||
|
{
|
||||||
|
var backend = new AdminUsersBackend(staleEdit: true);
|
||||||
|
await using var application = CreateApplication(backend);
|
||||||
|
using var client = CreateClient(application);
|
||||||
|
SignIn(application.Services, client, UserRoles.Admin);
|
||||||
|
var ct = TestContext.Current.CancellationToken;
|
||||||
|
using var editPage = await client.GetAsync(UsersPath + "/7/edit", ct);
|
||||||
|
using var form = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["__RequestVerificationToken"] = AntiforgeryToken(await editPage.Content.ReadAsStringAsync(ct)),
|
||||||
|
["FirstName"] = "Jan",
|
||||||
|
["LastName"] = "Novák",
|
||||||
|
["Email"] = "[email protected]",
|
||||||
|
["Role"] = UserRoles.Admin,
|
||||||
|
["RowVersion"] = "2",
|
||||||
|
});
|
||||||
|
|
||||||
|
using var response = await client.PostAsync(UsersPath + "/7/edit?q=Jan", form, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||||
|
Assert.StartsWith(UsersPath + "/7/edit?q=Jan", response.Headers.Location?.OriginalString);
|
||||||
|
Assert.Contains("\"rowVersion\":2", backend.Requests[^1].Body);
|
||||||
|
|
||||||
|
using var fresh = await client.GetAsync(response.Headers.Location, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, fresh.StatusCode);
|
||||||
|
var html = WebUtility.HtmlDecode(await fresh.Content.ReadAsStringAsync(ct));
|
||||||
|
Assert.Contains("Účet se mezitím změnil.", html);
|
||||||
|
Assert.Matches("""<input\b(?=[^>]*name="RowVersion")(?=[^>]*value="3")[^>]*>""", html);
|
||||||
|
Assert.Contains("value=\"STUDENT\" selected=\"selected\"", html);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static WebApplicationFactory<Program> CreateApplication(AdminUsersBackend backend) =>
|
||||||
|
new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||||
|
builder.ConfigureTestServices(services => services.AddHttpClient(nameof(HelpdeskApiClient))
|
||||||
|
.ConfigurePrimaryHttpMessageHandler(() => backend)));
|
||||||
|
|
||||||
|
private static HttpClient CreateClient(WebApplicationFactory<Program> application) =>
|
||||||
|
application.CreateClient(new WebApplicationFactoryClientOptions
|
||||||
|
{
|
||||||
|
AllowAutoRedirect = false,
|
||||||
|
BaseAddress = new Uri("https://localhost"),
|
||||||
|
});
|
||||||
|
|
||||||
|
private sealed class AdminUsersBackend(bool failVerification = false, bool staleEdit = false) : HttpMessageHandler
|
||||||
|
{
|
||||||
|
public List<(HttpMethod Method, Uri Uri, string? Body)> Requests { get; } = [];
|
||||||
|
|
||||||
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
Assert.Equal("test-access", request.Headers.Authorization?.Parameter);
|
||||||
|
var uri = Assert.IsType<Uri>(request.RequestUri);
|
||||||
|
Requests.Add((request.Method, uri, request.Content is null ? null : await request.Content.ReadAsStringAsync(ct)));
|
||||||
|
if (request.Method == HttpMethod.Post && uri.AbsolutePath == "/api/v1/admin/users" && failVerification)
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.Created)
|
||||||
|
{
|
||||||
|
Content = new StringContent("""
|
||||||
|
{"id":7,"email":"[email protected]","firstName":"Jan","lastName":"Novák","role":"STUDENT","isActive":true,"emailConfirmed":false,"emailNotificationsEnabled":true,"verificationEmailSent":false}
|
||||||
|
""", Encoding.UTF8, "application/json"),
|
||||||
|
};
|
||||||
|
if (request.Method == HttpMethod.Put && uri.AbsolutePath == "/api/v1/admin/users/7" && staleEdit)
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.Conflict)
|
||||||
|
{
|
||||||
|
Content = new StringContent("""
|
||||||
|
{"type":"urn:ntbug:account-version-conflict","title":"Účet se mezitím změnil.","status":409}
|
||||||
|
""", Encoding.UTF8, "application/problem+json"),
|
||||||
|
};
|
||||||
|
if (request.Method != HttpMethod.Get)
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.NoContent);
|
||||||
|
|
||||||
|
if (uri.AbsolutePath == "/api/v1/admin/users/7")
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||||
|
{
|
||||||
|
Content = new StringContent("""
|
||||||
|
{"id":7,"email":"[email protected]","firstName":"Jan","lastName":"Novák","role":"STUDENT","isActive":true,"emailConfirmed":false,"emailNotificationsEnabled":true,"rowVersion":3}
|
||||||
|
""", Encoding.UTF8, "application/json"),
|
||||||
|
};
|
||||||
|
|
||||||
|
Assert.Equal("/api/v1" + UsersPath, uri.AbsolutePath);
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||||
|
{
|
||||||
|
Content = new StringContent("""
|
||||||
|
{"items":[
|
||||||
|
{"id":1,"email":"[email protected]","firstName":"Test","lastName":"Admin","role":"ADMIN","isActive":true,"emailConfirmed":true,"createdAt":"2026-10-03T08:00:00Z"},
|
||||||
|
{"id":7,"email":"[email protected]","firstName":"Jan","lastName":"Novák","role":"STUDENT","isActive":false,"emailConfirmed":false,"createdAt":"2026-10-05T08:00:00Z"}
|
||||||
|
],"totalCount":45,"page":2,"pageSize":20}
|
||||||
|
""", Encoding.UTF8, "application/json"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -100,9 +100,9 @@ public class ModelStateExtensionsTests
|
|||||||
var error = new ApiException(HttpStatusCode.BadRequest, "Neplatná vstupní data.",
|
var error = new ApiException(HttpStatusCode.BadRequest, "Neplatná vstupní data.",
|
||||||
new Dictionary<string, string[]> { ["newPassword"] = ["Heslo musí mít alespoň 8 znaků."] });
|
new Dictionary<string, string[]> { ["newPassword"] = ["Heslo musí mít alespoň 8 znaků."] });
|
||||||
|
|
||||||
modelState.AddApiErrors(error, typeof(ResetPasswordViewModel));
|
modelState.AddApiErrors(error, typeof(EmailPasswordViewModel));
|
||||||
|
|
||||||
Assert.Equal("Heslo musí mít alespoň 8 znaků.", modelState[nameof(ResetPasswordViewModel.NewPassword)]!.Errors.Single().ErrorMessage);
|
Assert.Equal("Heslo musí mít alespoň 8 znaků.", modelState[nameof(EmailPasswordViewModel.NewPassword)]!.Errors.Single().ErrorMessage);
|
||||||
Assert.False(modelState.ContainsKey(string.Empty));
|
Assert.False(modelState.ContainsKey(string.Empty));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
using System.Net;
|
||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Tests;
|
||||||
|
|
||||||
|
public sealed class ForwardedClientIpHandlerTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task UsesTheCurrentConnectionAddressInsteadOfTheIncomingHeader()
|
||||||
|
{
|
||||||
|
const string header = "X-Forwarded-For";
|
||||||
|
var context = new DefaultHttpContext();
|
||||||
|
context.Connection.RemoteIpAddress = IPAddress.Parse("198.51.100.10");
|
||||||
|
context.Request.Headers[header] = "203.0.113.11";
|
||||||
|
var accessor = new HttpContextAccessor { HttpContext = context };
|
||||||
|
using var client = new HttpMessageInvoker(new ForwardedClientIpHandler(accessor) { InnerHandler = new Responder() });
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Post, "http://api-web:8080/api/v1/auth/login");
|
||||||
|
using var response = await client.SendAsync(request, TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal("198.51.100.10", Assert.Single(request.Headers.GetValues(header)));
|
||||||
|
|
||||||
|
accessor.HttpContext = null;
|
||||||
|
using var next = new HttpRequestMessage(HttpMethod.Post, request.RequestUri);
|
||||||
|
using var nextResponse = await client.SendAsync(next, TestContext.Current.CancellationToken);
|
||||||
|
Assert.False(next.Headers.Contains(header));
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class Responder : HttpMessageHandler
|
||||||
|
{
|
||||||
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
|
||||||
|
Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" />
|
||||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||||
<PackageReference Include="xunit.v3" />
|
<PackageReference Include="xunit.v3" />
|
||||||
<PackageReference Include="xunit.runner.visualstudio" />
|
<PackageReference Include="xunit.runner.visualstudio" />
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Helpdesk.Web.Auth;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
|
using Microsoft.AspNetCore.TestHost;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using static Helpdesk.Web.Tests.WebTestSession;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Tests;
|
||||||
|
|
||||||
|
public sealed class IssueActionFormTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData("assign", "/assign")]
|
||||||
|
[InlineData("transition", "/reject")]
|
||||||
|
[InlineData("edit", "")]
|
||||||
|
public async Task IssueActionsRequireAnExplicitValidVersionAndAcceptZero(string action, string apiAction)
|
||||||
|
{
|
||||||
|
var backend = new IssueBackend();
|
||||||
|
await using var application = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||||
|
builder.ConfigureTestServices(services => services.AddHttpClient(nameof(HelpdeskApiClient))
|
||||||
|
.ConfigurePrimaryHttpMessageHandler(() => backend)));
|
||||||
|
using var client = application.CreateClient(new WebApplicationFactoryClientOptions
|
||||||
|
{
|
||||||
|
AllowAutoRedirect = false,
|
||||||
|
BaseAddress = new Uri("https://localhost"),
|
||||||
|
});
|
||||||
|
SignIn(application.Services, client, UserRoles.Admin);
|
||||||
|
var ct = TestContext.Current.CancellationToken;
|
||||||
|
const string detail = "/issues/42";
|
||||||
|
using var page = await client.GetAsync(detail, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, page.StatusCode);
|
||||||
|
var fields = action switch
|
||||||
|
{
|
||||||
|
"assign" => new Dictionary<string, string> { ["AssigneeId"] = "7", ["Priority"] = "HIGH" },
|
||||||
|
"transition" => new Dictionary<string, string> { ["Action"] = IssueActions.Reject, ["Text"] = "Duplicitní hlášení." },
|
||||||
|
_ => new Dictionary<string, string> { ["Title"] = "Projektor", ["Description"] = "Bliká.", ["CategoryId"] = "2" },
|
||||||
|
};
|
||||||
|
fields["__RequestVerificationToken"] = AntiforgeryToken(await page.Content.ReadAsStringAsync(ct));
|
||||||
|
var route = $"{detail}/{action}";
|
||||||
|
|
||||||
|
using (var missing = new FormUrlEncodedContent(fields))
|
||||||
|
using (var response = await client.PostAsync(route + "?RowVersion=0", missing, ct))
|
||||||
|
{
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||||
|
Assert.Equal(detail, response.Headers.Location?.OriginalString);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var invalidVersion in new[] { "", "abc", "-1", "2147483648" })
|
||||||
|
{
|
||||||
|
fields["RowVersion"] = invalidVersion;
|
||||||
|
using var form = new FormUrlEncodedContent(fields);
|
||||||
|
using var response = await client.PostAsync(route, form, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||||
|
Assert.Equal(detail, response.Headers.Location?.OriginalString);
|
||||||
|
}
|
||||||
|
|
||||||
|
fields["RowVersion"] = "0";
|
||||||
|
if (action == "assign")
|
||||||
|
{
|
||||||
|
fields["Priority"] = "UNKNOWN";
|
||||||
|
using var invalid = new FormUrlEncodedContent(fields);
|
||||||
|
using var response = await client.PostAsync(route, invalid, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||||
|
using var next = await client.GetAsync(detail, ct);
|
||||||
|
Assert.Contains("Vyberte platnou prioritu.", WebUtility.HtmlDecode(await next.Content.ReadAsStringAsync(ct)));
|
||||||
|
fields["Priority"] = "HIGH";
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Empty(backend.Writes);
|
||||||
|
using var valid = new FormUrlEncodedContent(fields);
|
||||||
|
using var accepted = await client.PostAsync(route, valid, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, accepted.StatusCode);
|
||||||
|
var saved = Assert.Single(backend.Writes);
|
||||||
|
Assert.Equal("/api/v1/issues/42" + apiAction, saved.Path);
|
||||||
|
Assert.Equal(0, saved.Body.GetProperty("rowVersion").GetInt32());
|
||||||
|
if (action == "assign")
|
||||||
|
Assert.Equal("HIGH", saved.Body.GetProperty("priority").GetString());
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class IssueBackend : HttpMessageHandler
|
||||||
|
{
|
||||||
|
private const string Detail = """
|
||||||
|
{"id":42,"title":"Projektor","description":"Bliká.","categoryId":2,"status":"RECEIVED","priority":"NORMAL",
|
||||||
|
"reporterId":1,"createdAt":"2026-10-03T08:00:00Z","rowVersion":0,"allowedActions":["ASSIGN","REJECT","EDIT"],"attachments":[]}
|
||||||
|
""";
|
||||||
|
|
||||||
|
public List<(string Path, JsonElement Body)> Writes { get; } = [];
|
||||||
|
|
||||||
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var path = request.RequestUri!.AbsolutePath;
|
||||||
|
var detail = path == "/api/v1/issues/42";
|
||||||
|
if (request.Method != HttpMethod.Get)
|
||||||
|
{
|
||||||
|
Writes.Add((path, await request.Content!.ReadFromJsonAsync<JsonElement>(ct)));
|
||||||
|
detail = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||||
|
{
|
||||||
|
Content = new StringContent(detail ? Detail : "[]", Encoding.UTF8, "application/json"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json.Nodes;
|
||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Helpdesk.Web.Controllers;
|
||||||
|
using Helpdesk.Web.Models;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Tests;
|
||||||
|
|
||||||
|
public class IssueDetailViewModelTests
|
||||||
|
{
|
||||||
|
private static readonly DateTimeOffset T = DateTimeOffset.UnixEpoch;
|
||||||
|
|
||||||
|
private static IssueEventDto Event(string type, string? from, string to, string actor, string? note = null) =>
|
||||||
|
new(1, type, from, to, 1, actor, note, T);
|
||||||
|
|
||||||
|
private static IssueDetailViewModel Model(int? assigneeId, params IssueEventDto[] events) => new()
|
||||||
|
{
|
||||||
|
Issue = new IssueDetail(42, "Projektor", "Bliká.", 2, null, null, "IN_PROGRESS", "HIGH", 5, assigneeId, T, 3,
|
||||||
|
[IssueActions.SubmitForVerification, IssueActions.Reject, IssueActions.Comment], []),
|
||||||
|
Events = events,
|
||||||
|
CategoryName = "Technické vybavení",
|
||||||
|
};
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Jmena_hlasice_a_resitele_vezme_z_casove_osy()
|
||||||
|
{
|
||||||
|
var model = Model(7,
|
||||||
|
Event("CREATED", null, "RECEIVED", "Jan Novák"),
|
||||||
|
Event("ASSIGNED", "RECEIVED", "ASSIGNED", "Vedení Školy", "Petr Svoboda"),
|
||||||
|
Event("ASSIGNED", "ASSIGNED", "ASSIGNED", "Vedení Školy", "Eva Malá"));
|
||||||
|
|
||||||
|
Assert.Equal("Jan Novák", model.ReporterName);
|
||||||
|
Assert.Equal("Eva Malá", model.AssigneeName); // po přeřazení platí poslední přiřazení
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Nepriprazena_zavada_nema_resitele() => Assert.Null(Model(null, Event("CREATED", null, "RECEIVED", "Jan")).AssigneeName);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Akce_zmeny_stavu_jsou_jen_povolene_a_v_poradi_zivotniho_cyklu() =>
|
||||||
|
Assert.Equal([IssueActions.SubmitForVerification, IssueActions.Reject], Model(7).Transitions);
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("CREATED", null, "RECEIVED", null, "nahlásil/a závadu", null)]
|
||||||
|
[InlineData("ASSIGNED", "RECEIVED", "ASSIGNED", "Petr Svoboda", "přiřadil/a závadu řešiteli Petr Svoboda", null)]
|
||||||
|
[InlineData("ASSIGNED", "IN_PROGRESS", "ASSIGNED", "Eva Malá", "přeřadil/a závadu na Eva Malá", null)]
|
||||||
|
[InlineData("STATUS_CHANGED", "ASSIGNED", "IN_PROGRESS", null, "zahájil/a řešení", null)]
|
||||||
|
[InlineData("STATUS_CHANGED", "PENDING_VERIFICATION", "IN_PROGRESS", "Pořád bliká", "znovu otevřel/a závadu", "Důvod")]
|
||||||
|
[InlineData("STATUS_CHANGED", "IN_PROGRESS", "PENDING_VERIFICATION", "Vyměněna lampa", "předal/a závadu k ověření", "Poznámka")]
|
||||||
|
[InlineData("STATUS_CHANGED", "IN_PROGRESS", "REJECTED", "Duplicitní hlášení", "zamítl/a závadu", "Důvod")]
|
||||||
|
[InlineData("COMMENTED", null, "IN_PROGRESS", "Funguje HDMI?", "napsal/a komentář", null)]
|
||||||
|
public void Udalost_casove_osy_ma_srozumitelny_popis(string type, string? from, string to, string? note, string text, string? noteLabel)
|
||||||
|
{
|
||||||
|
var entry = TimelineEntry.From(Event(type, from, to, "Někdo", note));
|
||||||
|
|
||||||
|
Assert.Equal(text, entry.Text);
|
||||||
|
Assert.Equal(noteLabel, entry.NoteLabel);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Komentar_nema_stitek_stavu()
|
||||||
|
{
|
||||||
|
var entry = TimelineEntry.From(Event("COMMENTED", null, "IN_PROGRESS", "Jan", "Funguje HDMI?"));
|
||||||
|
|
||||||
|
Assert.True(entry.IsComment);
|
||||||
|
Assert.Null(entry.Status);
|
||||||
|
Assert.Equal("Funguje HDMI?", entry.Note);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(900, "900 B")]
|
||||||
|
[InlineData(300_000, "293 kB")]
|
||||||
|
[InlineData(2_500_000, "2,4 MB")]
|
||||||
|
public void Velikost_prilohy_je_citelna(long bytes, string expected) =>
|
||||||
|
Assert.Equal(expected, IssueDetailViewModel.FileSize(bytes).Replace('.', ','));
|
||||||
|
}
|
||||||
|
|
||||||
|
public class IssueActionsApiTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData(IssueActions.StartWork, null, "/api/v1/issues/42/start", """{"rowVersion":3}""")]
|
||||||
|
[InlineData(IssueActions.SubmitForVerification, "Hotovo", "/api/v1/issues/42/submit-for-verification", """{"rowVersion":3,"note":"Hotovo"}""")]
|
||||||
|
[InlineData(IssueActions.Confirm, null, "/api/v1/issues/42/confirm", """{"rowVersion":3}""")]
|
||||||
|
[InlineData(IssueActions.Reopen, "Bliká dál", "/api/v1/issues/42/reopen", """{"rowVersion":3,"reason":"Bliká dál"}""")]
|
||||||
|
[InlineData(IssueActions.Reject, "Duplicita", "/api/v1/issues/42/reject", """{"rowVersion":3,"reason":"Duplicita"}""")]
|
||||||
|
public async Task Zmena_stavu_jde_na_akcni_endpoint_s_rowVersion(string action, string? text, string path, string body)
|
||||||
|
{
|
||||||
|
var handler = new RecordingHandler(DetailJson);
|
||||||
|
await Client(handler).TransitionIssueAsync(42, action, 3, text, CancellationToken.None);
|
||||||
|
|
||||||
|
Assert.Equal(HttpMethod.Post, handler.Method);
|
||||||
|
Assert.Equal(path, handler.Path);
|
||||||
|
Assert.True(JsonNode.DeepEquals(JsonNode.Parse(body), JsonNode.Parse(handler.Body!)), handler.Body);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Neznama_akce_se_do_API_neposle() =>
|
||||||
|
await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||||
|
Client(new RecordingHandler(DetailJson)).TransitionIssueAsync(42, "DELETE", 3, null, CancellationToken.None));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Prirazeni_posle_resitele_prioritu_a_verzi()
|
||||||
|
{
|
||||||
|
var handler = new RecordingHandler(DetailJson);
|
||||||
|
await Client(handler).AssignIssueAsync(42, new AssignIssueRequest(7, "HIGH", 3), CancellationToken.None);
|
||||||
|
|
||||||
|
Assert.Equal("/api/v1/issues/42/assign", handler.Path);
|
||||||
|
Assert.Equal("""{"assigneeId":7,"priority":"HIGH","rowVersion":3}""", handler.Body);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Detail_nacte_akce_i_prilohy()
|
||||||
|
{
|
||||||
|
var issue = await Client(new RecordingHandler(DetailJson)).GetIssueAsync(42, CancellationToken.None);
|
||||||
|
|
||||||
|
Assert.True(issue.Can(IssueActions.Comment));
|
||||||
|
Assert.False(issue.Can(IssueActions.Assign));
|
||||||
|
Assert.Equal("foto.jpg", Assert.Single(issue.Attachments).FileName);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Priloha_si_zachova_cesky_nazev_souboru()
|
||||||
|
{
|
||||||
|
var handler = new RecordingHandler("", response =>
|
||||||
|
{
|
||||||
|
response.Content = new ByteArrayContent([0xFF, 0xD8, 0xFF]);
|
||||||
|
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
|
||||||
|
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileNameStar = "učebna B-205.jpg" };
|
||||||
|
});
|
||||||
|
|
||||||
|
using var file = await Client(handler).DownloadAttachmentAsync(9, CancellationToken.None);
|
||||||
|
|
||||||
|
Assert.Equal("/api/v1/attachments/9", handler.Path);
|
||||||
|
Assert.Equal("učebna B-205.jpg", file.FileName);
|
||||||
|
Assert.Equal("image/jpeg", file.ContentType);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("application/pdf", "attachment")]
|
||||||
|
[InlineData("image/png", "inline")]
|
||||||
|
public async Task Web_pdf_stahuje_a_png_zobrazuje_v_prohlizeci(string contentType, string expectedDisposition)
|
||||||
|
{
|
||||||
|
using var handler = new RecordingHandler("", response =>
|
||||||
|
{
|
||||||
|
response.Content = new ByteArrayContent([1]);
|
||||||
|
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
|
||||||
|
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileNameStar = "příloha" };
|
||||||
|
});
|
||||||
|
var context = new DefaultHttpContext();
|
||||||
|
var controller = new IssuesController(Client(handler)) { ControllerContext = new ControllerContext { HttpContext = context } };
|
||||||
|
|
||||||
|
var result = Assert.IsType<FileStreamResult>(await controller.Attachment(9, CancellationToken.None));
|
||||||
|
using var stream = result.FileStream;
|
||||||
|
var disposition = ContentDispositionHeaderValue.Parse(context.Response.Headers.ContentDisposition.ToString());
|
||||||
|
Assert.Equal(expectedDisposition, disposition.DispositionType);
|
||||||
|
Assert.Equal("příloha", disposition.FileNameStar);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Chyby_poli_z_API_se_spoji_do_jedne_zpravy()
|
||||||
|
{
|
||||||
|
var ex = new ApiException(HttpStatusCode.BadRequest, "One or more validation errors occurred.",
|
||||||
|
new Dictionary<string, string[]> { ["reason"] = ["Důvod je povinný."], ["rowVersion"] = ["Chybí verze."] });
|
||||||
|
|
||||||
|
Assert.Equal("Důvod je povinný. Chybí verze.", ex.AllMessages);
|
||||||
|
}
|
||||||
|
|
||||||
|
private const string DetailJson = """
|
||||||
|
{"id":42,"title":"Projektor","description":"Bliká.","categoryId":2,"buildingId":null,"locationDetail":null,
|
||||||
|
"status":"IN_PROGRESS","priority":"NORMAL","reporterId":5,"assigneeId":7,"createdAt":"2026-10-03T08:00:00Z",
|
||||||
|
"rowVersion":4,"allowedActions":["COMMENT","ADD_ATTACHMENTS"],
|
||||||
|
"attachments":[{"id":9,"fileName":"foto.jpg","contentType":"image/jpeg","sizeBytes":3,"createdAt":"2026-10-03T08:00:00Z"}]}
|
||||||
|
""";
|
||||||
|
|
||||||
|
private static HelpdeskApiClient Client(HttpMessageHandler handler) =>
|
||||||
|
new(new HttpClient(handler) { BaseAddress = new ApiOptions { BaseUrl = "http://api/" }.VersionedBaseAddress() });
|
||||||
|
|
||||||
|
private sealed class RecordingHandler(string json, Action<HttpResponseMessage>? customize = null) : HttpMessageHandler
|
||||||
|
{
|
||||||
|
public HttpMethod? Method { get; private set; }
|
||||||
|
public string? Path { get; private set; }
|
||||||
|
public string? Body { get; private set; }
|
||||||
|
|
||||||
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
Method = request.Method;
|
||||||
|
Path = request.RequestUri!.AbsolutePath;
|
||||||
|
Body = request.Content is null ? null : await request.Content.ReadAsStringAsync(ct);
|
||||||
|
var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
|
||||||
|
customize?.Invoke(response);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Text;
|
||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Helpdesk.Web.Models;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Tests;
|
||||||
|
|
||||||
|
public class AttachmentRulesTests
|
||||||
|
{
|
||||||
|
private static IFormFile File(string name, long length) =>
|
||||||
|
new FormFile(new MemoryStream(new byte[Math.Min(length, 16)]), 0, length, "Files", name);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Povolene_soubory_projdou() =>
|
||||||
|
Assert.Empty(AttachmentRules.Validate([File("projektor.JPG", 2_000_000), File("protokol.pdf", 300_000)]));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Vic_nez_pet_souboru_neprojde() =>
|
||||||
|
Assert.Contains(AttachmentRules.Validate(Enumerable.Range(1, 6).Select(i => File($"foto{i}.png", 1000)).ToList()),
|
||||||
|
e => e.Contains("nejvýše 5"));
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("virus.exe", "povolený typ")]
|
||||||
|
[InlineData("velka.jpg", "10 MB")]
|
||||||
|
[InlineData("prazdny.png", "prázdný")]
|
||||||
|
public void Nepovoleny_soubor_ma_srozumitelnou_chybu(string name, string expected)
|
||||||
|
{
|
||||||
|
var length = name switch { "velka.jpg" => AttachmentRules.MaxFileBytes + 1, "prazdny.png" => 0, _ => 100 };
|
||||||
|
Assert.Contains(AttachmentRules.Validate([File(name, length)]), e => e.Contains(expected));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class IssueListViewModelTests
|
||||||
|
{
|
||||||
|
private static readonly IssueListViewModel Model = new()
|
||||||
|
{
|
||||||
|
Issues = new PagedResult<IssueSummary>([], 0, 1, 20),
|
||||||
|
CategoryNames = new Dictionary<int, string> { [2] = "Technické vybavení" },
|
||||||
|
BuildingNames = new Dictionary<int, string> { [2] = "Budova B" },
|
||||||
|
};
|
||||||
|
|
||||||
|
private static IssueSummary Issue(int? buildingId, string? detail) =>
|
||||||
|
new(1, "Projektor", 2, buildingId, detail, "RECEIVED", "NORMAL", 1, null, DateTimeOffset.UnixEpoch);
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(2, "učebna B-205", "Budova B – učebna B-205")]
|
||||||
|
[InlineData(2, null, "Budova B")]
|
||||||
|
[InlineData(null, "venku u vchodu", "venku u vchodu")]
|
||||||
|
[InlineData(null, null, null)]
|
||||||
|
public void Misto_spoji_budovu_a_upresneni(int? buildingId, string? detail, string? expected) =>
|
||||||
|
Assert.Equal(expected, Model.Location(Issue(buildingId, detail)));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Neznama_kategorie_neshodi_stranku() => Assert.Equal("Neznámá kategorie", Model.CategoryName(99));
|
||||||
|
}
|
||||||
|
|
||||||
|
public class CreateIssueRequestTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task Hlaseni_s_prilohou_jde_do_API_jako_multipart()
|
||||||
|
{
|
||||||
|
var handler = new RecordingHandler();
|
||||||
|
var api = new HelpdeskApiClient(new HttpClient(handler) { BaseAddress = new ApiOptions { BaseUrl = "http://api/" }.VersionedBaseAddress() });
|
||||||
|
|
||||||
|
var issue = await api.CreateIssueAsync(
|
||||||
|
new CreateIssueRequest("Projektor", "Bliká.", 2, BuildingId: null, LocationDetail: "B-205"),
|
||||||
|
[new UploadFile("foto.jpg", "image/jpeg", () => new MemoryStream([0xFF, 0xD8, 0xFF]))],
|
||||||
|
CancellationToken.None);
|
||||||
|
|
||||||
|
Assert.Equal(7, issue.Id);
|
||||||
|
Assert.Equal("/api/v1/issues", handler.Path);
|
||||||
|
Assert.StartsWith("multipart/form-data", handler.ContentType);
|
||||||
|
Assert.Contains("name=title", handler.Body);
|
||||||
|
Assert.Contains("name=categoryId", handler.Body);
|
||||||
|
Assert.Contains("name=files; filename=foto.jpg", handler.Body);
|
||||||
|
Assert.DoesNotContain("name=buildingId", handler.Body); // nepovinná pole bez hodnoty se neposílají
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class RecordingHandler : HttpMessageHandler
|
||||||
|
{
|
||||||
|
public string? Path { get; private set; }
|
||||||
|
public string? ContentType { get; private set; }
|
||||||
|
public string Body { get; private set; } = "";
|
||||||
|
|
||||||
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
Path = request.RequestUri!.AbsolutePath;
|
||||||
|
ContentType = request.Content!.Headers.ContentType!.ToString();
|
||||||
|
Body = await request.Content.ReadAsStringAsync(ct);
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.Created)
|
||||||
|
{
|
||||||
|
Content = new StringContent("""{"id":7,"title":"Projektor","status":"RECEIVED","rowVersion":0,"allowedActions":["EDIT"]}""",
|
||||||
|
Encoding.UTF8, "application/json"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
|
using Microsoft.AspNetCore.TestHost;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using static Helpdesk.Web.Tests.WebTestSession;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Tests;
|
||||||
|
|
||||||
|
public sealed class RegistrationTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task RegistrationOffersToResendAfterTheBackendReportsEmailDeliveryFailure()
|
||||||
|
{
|
||||||
|
var backend = new RegistrationBackend(failFirstDelivery: true);
|
||||||
|
await using var application = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||||
|
builder.ConfigureTestServices(services => services.AddHttpClient(nameof(AuthApiClient))
|
||||||
|
.ConfigurePrimaryHttpMessageHandler(() => backend)));
|
||||||
|
using var client = application.CreateClient(new WebApplicationFactoryClientOptions
|
||||||
|
{
|
||||||
|
AllowAutoRedirect = false,
|
||||||
|
BaseAddress = new Uri("https://localhost"),
|
||||||
|
});
|
||||||
|
var ct = TestContext.Current.CancellationToken;
|
||||||
|
using var registration = await client.GetAsync("/register", ct);
|
||||||
|
var fields = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["__RequestVerificationToken"] = AntiforgeryToken(await registration.Content.ReadAsStringAsync(ct)),
|
||||||
|
["Email"] = "[email protected]",
|
||||||
|
["FirstName"] = "Jan",
|
||||||
|
["LastName"] = "Novák",
|
||||||
|
};
|
||||||
|
using var initial = new FormUrlEncodedContent(fields);
|
||||||
|
using var failed = await client.PostAsync("/register", initial, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, failed.StatusCode);
|
||||||
|
var retryPage = WebUtility.HtmlDecode(await failed.Content.ReadAsStringAsync(ct));
|
||||||
|
Assert.Contains("Účet je uložený.", retryPage);
|
||||||
|
Assert.Contains("Poslat ověřovací e-mail znovu", retryPage);
|
||||||
|
Assert.Contains("value=\"[email protected]\"", retryPage);
|
||||||
|
|
||||||
|
fields["__RequestVerificationToken"] = AntiforgeryToken(retryPage);
|
||||||
|
using var retry = new FormUrlEncodedContent(fields);
|
||||||
|
using var sent = await client.PostAsync("/register", retry, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, sent.StatusCode);
|
||||||
|
Assert.Contains("Ověřte svůj e-mail", WebUtility.HtmlDecode(await sent.Content.ReadAsStringAsync(ct)));
|
||||||
|
Assert.Equal(2, backend.Requests.Count);
|
||||||
|
Assert.Equal(backend.Requests[0].Body.GetRawText(), backend.Requests[1].Body.GetRawText());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task RegistrationRequestsAnEmailAndConfirmationSetsThePassword()
|
||||||
|
{
|
||||||
|
var backend = new RegistrationBackend();
|
||||||
|
await using var application = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||||
|
builder.ConfigureTestServices(services => services.AddHttpClient(nameof(AuthApiClient))
|
||||||
|
.ConfigurePrimaryHttpMessageHandler(() => backend)));
|
||||||
|
using var client = application.CreateClient(new WebApplicationFactoryClientOptions
|
||||||
|
{
|
||||||
|
AllowAutoRedirect = false,
|
||||||
|
BaseAddress = new Uri("https://localhost"),
|
||||||
|
});
|
||||||
|
var ct = TestContext.Current.CancellationToken;
|
||||||
|
|
||||||
|
using var registration = await client.GetAsync("/register", ct);
|
||||||
|
var registerHtml = await registration.Content.ReadAsStringAsync(ct);
|
||||||
|
Assert.DoesNotContain("type=\"password\"", registerHtml);
|
||||||
|
using var registerForm = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["__RequestVerificationToken"] = AntiforgeryToken(registerHtml),
|
||||||
|
["Email"] = "[email protected]",
|
||||||
|
["FirstName"] = "Jan",
|
||||||
|
["LastName"] = "Novák",
|
||||||
|
});
|
||||||
|
using var registered = await client.PostAsync("/register", registerForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, registered.StatusCode);
|
||||||
|
var start = Assert.Single(backend.Requests);
|
||||||
|
Assert.Equal("/api/v1/auth/register", start.Path);
|
||||||
|
Assert.False(start.Body.TryGetProperty("password", out _));
|
||||||
|
|
||||||
|
using var link = await client.GetAsync("/confirm-email?token=email-token", ct);
|
||||||
|
var confirmHtml = await link.Content.ReadAsStringAsync(ct);
|
||||||
|
Assert.Contains("name=\"NewPassword\"", confirmHtml);
|
||||||
|
Assert.Contains("name=\"ConfirmPassword\"", confirmHtml);
|
||||||
|
Assert.Single(backend.Requests);
|
||||||
|
var form = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["__RequestVerificationToken"] = AntiforgeryToken(confirmHtml),
|
||||||
|
["Token"] = "email-token",
|
||||||
|
["NewPassword"] = "Mailbox-owner-password",
|
||||||
|
["ConfirmPassword"] = "Different-password",
|
||||||
|
};
|
||||||
|
using var invalidForm = new FormUrlEncodedContent(form);
|
||||||
|
using var invalid = await client.PostAsync("/confirm-email", invalidForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, invalid.StatusCode);
|
||||||
|
Assert.Contains("Hesla se neshodují.", WebUtility.HtmlDecode(await invalid.Content.ReadAsStringAsync(ct)));
|
||||||
|
Assert.Single(backend.Requests);
|
||||||
|
|
||||||
|
form["ConfirmPassword"] = form["NewPassword"];
|
||||||
|
using var confirmForm = new FormUrlEncodedContent(form);
|
||||||
|
using var confirmed = await client.PostAsync("/confirm-email", confirmForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, confirmed.StatusCode);
|
||||||
|
Assert.Equal("/login", confirmed.Headers.Location?.OriginalString);
|
||||||
|
var confirmation = backend.Requests[1];
|
||||||
|
Assert.Equal("/api/v1/auth/confirm-email", confirmation.Path);
|
||||||
|
Assert.Equal("email-token", confirmation.Body.GetProperty("token").GetString());
|
||||||
|
Assert.Equal(form["NewPassword"], confirmation.Body.GetProperty("newPassword").GetString());
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class RegistrationBackend(bool failFirstDelivery = false) : HttpMessageHandler
|
||||||
|
{
|
||||||
|
public List<(string Path, JsonElement Body)> Requests { get; } = [];
|
||||||
|
|
||||||
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
Assert.Equal(HttpMethod.Post, request.Method);
|
||||||
|
var path = request.RequestUri!.AbsolutePath;
|
||||||
|
using var json = JsonDocument.Parse(await request.Content!.ReadAsStringAsync(ct));
|
||||||
|
Requests.Add((path, json.RootElement.Clone()));
|
||||||
|
if (path == "/api/v1/auth/confirm-email")
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.NoContent);
|
||||||
|
|
||||||
|
Assert.Equal("/api/v1/auth/register", path);
|
||||||
|
if (failFirstDelivery && Requests.Count == 1)
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
|
||||||
|
{
|
||||||
|
Content = new StringContent("""
|
||||||
|
{"type":"urn:ntbug:email-delivery-failed","title":"E-mail se nepodařilo odeslat.","status":503}
|
||||||
|
""", Encoding.UTF8, "application/problem+json"),
|
||||||
|
};
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.Created)
|
||||||
|
{
|
||||||
|
Content = new StringContent("""
|
||||||
|
{"id":7,"email":"[email protected]","firstName":"Jan","lastName":"Novák","role":"STUDENT","emailNotificationsEnabled":true}
|
||||||
|
""", Encoding.UTF8, "application/json"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Text;
|
||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Helpdesk.Web.Auth;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
|
using Microsoft.AspNetCore.TestHost;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using static Helpdesk.Web.Tests.WebTestSession;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Tests;
|
||||||
|
|
||||||
|
public sealed class SwaggerAccessTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task SwaggerAndItsAssetsRequireAnAdministratorSession()
|
||||||
|
{
|
||||||
|
await using var application = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||||
|
builder.ConfigureTestServices(services => services.AddHttpClient(nameof(HelpdeskApiClient))
|
||||||
|
.ConfigurePrimaryHttpMessageHandler(() => new OpenApiBackend())));
|
||||||
|
using var client = application.CreateClient(new WebApplicationFactoryClientOptions
|
||||||
|
{
|
||||||
|
AllowAutoRedirect = false,
|
||||||
|
BaseAddress = new Uri("https://localhost"),
|
||||||
|
});
|
||||||
|
var ct = TestContext.Current.CancellationToken;
|
||||||
|
string[] paths = ["/swagger", "/swagger/index.html", "/swagger/index.js", "/swagger/swagger-ui.css", "/swagger/v1/swagger.json"];
|
||||||
|
foreach (var path in paths)
|
||||||
|
{
|
||||||
|
using var response = await client.GetAsync(path, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||||
|
Assert.Equal("/login", response.Headers.Location?.AbsolutePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
SignIn(application.Services, client, UserRoles.Student);
|
||||||
|
foreach (var path in paths)
|
||||||
|
{
|
||||||
|
using var response = await client.GetAsync(path, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||||
|
Assert.Equal("/error/403", response.Headers.Location?.AbsolutePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
SignIn(application.Services, client, UserRoles.Admin);
|
||||||
|
using var entry = await client.GetAsync("/swagger", ct);
|
||||||
|
Assert.Equal(HttpStatusCode.MovedPermanently, entry.StatusCode);
|
||||||
|
using var index = await client.GetAsync("/swagger/index.html", ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, index.StatusCode);
|
||||||
|
Assert.Contains("Helpdesk API", await index.Content.ReadAsStringAsync(ct));
|
||||||
|
Assert.True(index.Headers.CacheControl?.NoStore == true);
|
||||||
|
using var script = await client.GetAsync("/swagger/index.js", ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, script.StatusCode);
|
||||||
|
Assert.Contains("v1/swagger.json", await script.Content.ReadAsStringAsync(ct));
|
||||||
|
using var css = await client.GetAsync("/swagger/swagger-ui.css", ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, css.StatusCode);
|
||||||
|
using var document = await client.GetAsync("/swagger/v1/swagger.json", ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, document.StatusCode);
|
||||||
|
Assert.Contains("\"openapi\"", await document.Content.ReadAsStringAsync(ct));
|
||||||
|
Assert.True(document.Headers.CacheControl?.NoStore == true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class OpenApiBackend : HttpMessageHandler
|
||||||
|
{
|
||||||
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
Assert.Equal("/api/v1/admin/openapi/v1.json", request.RequestUri?.AbsolutePath);
|
||||||
|
Assert.Equal("Bearer", request.Headers.Authorization?.Scheme);
|
||||||
|
Assert.Equal("test-access", request.Headers.Authorization?.Parameter);
|
||||||
|
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
|
||||||
|
{
|
||||||
|
Content = new StringContent("""{"openapi":"3.0.4"}""", Encoding.UTF8, "application/json"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Helpdesk.Web.Infrastructure;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Tests;
|
||||||
|
|
||||||
|
public class ApiVersioningTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData("http://api:8080/")]
|
||||||
|
[InlineData("http://api:8080")]
|
||||||
|
public void Zaklad_adresy_obsahuje_verzi_API(string baseUrl) =>
|
||||||
|
Assert.Equal("http://api:8080/api/v1/", new ApiOptions { BaseUrl = baseUrl }.VersionedBaseAddress().ToString());
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Relativni_cesta_se_slozi_pod_verzi()
|
||||||
|
{
|
||||||
|
var baseAddress = new ApiOptions { BaseUrl = "http://api:8080/" }.VersionedBaseAddress();
|
||||||
|
|
||||||
|
Assert.Equal("/api/v1/auth/login", new Uri(baseAddress, "auth/login").AbsolutePath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class AppVersionTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData("0.2.0+6e742b4029cca8896173c0d64783b7fb7540f214", "0.2.0 (6e742b4)")]
|
||||||
|
[InlineData("0.2.0", "0.2.0")]
|
||||||
|
[InlineData(null, "neznámá")]
|
||||||
|
public void Verze_se_zobrazi_s_kratkym_hashem_commitu(string? informational, string expected) =>
|
||||||
|
Assert.Equal(expected, AppVersion.Format(informational));
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Helpdesk.Web.Auth;
|
||||||
|
using Microsoft.AspNetCore.Authentication;
|
||||||
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Tests;
|
||||||
|
|
||||||
|
internal static class WebTestSession
|
||||||
|
{
|
||||||
|
public static string AntiforgeryToken(string html)
|
||||||
|
{
|
||||||
|
var token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value;
|
||||||
|
Assert.NotEmpty(token);
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void SignIn(IServiceProvider services, HttpClient client, string role)
|
||||||
|
{
|
||||||
|
var scheme = CookieAuthenticationDefaults.AuthenticationScheme;
|
||||||
|
var options = services.GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>().Get(scheme);
|
||||||
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
var properties = new AuthenticationProperties { IssuedUtc = now, ExpiresUtc = now.AddHours(1) };
|
||||||
|
AuthCookie.StoreTokens(properties, new TokenSet("test-access", now.AddMinutes(15), "test-refresh", now.AddDays(1)));
|
||||||
|
var user = new UserDto(1, "[email protected]", "Test", "User", null, role, true);
|
||||||
|
var ticket = new AuthenticationTicket(AuthCookie.CreatePrincipal(user), properties, scheme);
|
||||||
|
|
||||||
|
client.DefaultRequestHeaders.Remove("Cookie");
|
||||||
|
client.DefaultRequestHeaders.Add("Cookie", $"{AuthCookie.Name}={options.TicketDataFormat.Protect(ticket)}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,11 +8,12 @@ namespace Helpdesk.Web.Api;
|
|||||||
/// Neúspěšná odpověď API ve formátu ProblemDetails (RFC 9457). Nese stav, titulek
|
/// 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).
|
/// a u validačních chyb seznam chyb podle polí (klíče jsou názvy vlastností v camelCase).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class ApiException(HttpStatusCode statusCode, string? title, IReadOnlyDictionary<string, string[]> errors)
|
public sealed class ApiException(HttpStatusCode statusCode, string? title, IReadOnlyDictionary<string, string[]> errors, string? problemType = null)
|
||||||
: Exception(title ?? $"API vrátilo stav {(int)statusCode}.")
|
: Exception(title ?? $"API vrátilo stav {(int)statusCode}.")
|
||||||
{
|
{
|
||||||
public HttpStatusCode StatusCode { get; } = statusCode;
|
public HttpStatusCode StatusCode { get; } = statusCode;
|
||||||
public string? Title { get; } = title;
|
public string? Title { get; } = title;
|
||||||
|
public string? ProblemType { get; } = problemType;
|
||||||
public IReadOnlyDictionary<string, string[]> Errors { get; } = errors;
|
public IReadOnlyDictionary<string, string[]> Errors { get; } = errors;
|
||||||
|
|
||||||
/// <summary>Text pro uživatele. API píše titulky chyb česky, kromě odpovědí bez těla (např. 429).</summary>
|
/// <summary>Text pro uživatele. API píše titulky chyb česky, kromě odpovědí bez těla (např. 429).</summary>
|
||||||
@@ -25,9 +26,15 @@ public sealed class ApiException(HttpStatusCode statusCode, string? title, IRead
|
|||||||
_ => "Požadavek se nepodařilo zpracovat. Zkuste to prosím znovu.",
|
_ => "Požadavek se nepodařilo zpracovat. Zkuste to prosím znovu.",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// <summary>Chyby polí, pokud je API poslalo, jinak <see cref="UserMessage"/> – pro zprávu mimo formulář.</summary>
|
||||||
|
public string AllMessages => Errors.Count == 0
|
||||||
|
? UserMessage
|
||||||
|
: string.Join(" ", Errors.Values.SelectMany(messages => messages).Distinct());
|
||||||
|
|
||||||
public static async Task<ApiException> FromResponseAsync(HttpResponseMessage response, CancellationToken ct)
|
public static async Task<ApiException> FromResponseAsync(HttpResponseMessage response, CancellationToken ct)
|
||||||
{
|
{
|
||||||
string? title = null;
|
string? title = null;
|
||||||
|
string? type = null;
|
||||||
Dictionary<string, string[]> errors = new(StringComparer.OrdinalIgnoreCase);
|
Dictionary<string, string[]> errors = new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
if (response.Content.Headers.ContentType?.MediaType is { } mediaType && mediaType.Contains("json", StringComparison.OrdinalIgnoreCase))
|
if (response.Content.Headers.ContentType?.MediaType is { } mediaType && mediaType.Contains("json", StringComparison.OrdinalIgnoreCase))
|
||||||
@@ -36,6 +43,7 @@ public sealed class ApiException(HttpStatusCode statusCode, string? title, IRead
|
|||||||
{
|
{
|
||||||
var problem = await response.Content.ReadFromJsonAsync<ProblemBody>(ct);
|
var problem = await response.Content.ReadFromJsonAsync<ProblemBody>(ct);
|
||||||
title = problem?.Title;
|
title = problem?.Title;
|
||||||
|
type = problem?.Type;
|
||||||
if (problem?.Errors is { } fieldErrors)
|
if (problem?.Errors is { } fieldErrors)
|
||||||
{
|
{
|
||||||
foreach (var (field, messages) in fieldErrors)
|
foreach (var (field, messages) in fieldErrors)
|
||||||
@@ -48,10 +56,10 @@ public sealed class ApiException(HttpStatusCode statusCode, string? title, IRead
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return new ApiException(response.StatusCode, title, errors);
|
return new ApiException(response.StatusCode, title, errors, type);
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed record ProblemBody(string? Title, Dictionary<string, string[]>? Errors);
|
private sealed record ProblemBody(string? Title, Dictionary<string, string[]>? Errors, string? Type);
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static class ApiResponse
|
internal static class ApiResponse
|
||||||
|
|||||||
@@ -34,14 +34,151 @@ public sealed record TokenSet(
|
|||||||
|
|
||||||
public sealed record LoginRequest(string Email, string Password);
|
public sealed record LoginRequest(string Email, string Password);
|
||||||
|
|
||||||
public sealed record RegisterRequest(string Email, string Password, string FirstName, string LastName);
|
public sealed record RegisterRequest(string Email, string FirstName, string LastName);
|
||||||
|
|
||||||
public sealed record RefreshTokenRequest(string RefreshToken);
|
public sealed record RefreshTokenRequest(string RefreshToken);
|
||||||
|
|
||||||
public sealed record EmailTokenRequest(string Token);
|
public sealed record ConfirmEmailRequest(string Token, string NewPassword);
|
||||||
|
|
||||||
public sealed record ForgotPasswordRequest(string Email);
|
public sealed record ForgotPasswordRequest(string Email);
|
||||||
|
|
||||||
public sealed record ResetPasswordRequest(string Token, string NewPassword);
|
public sealed record ResetPasswordRequest(string Token, string NewPassword);
|
||||||
|
|
||||||
public sealed record UpdateProfileRequest(string FirstName, string LastName, string? Phone, bool EmailNotificationsEnabled);
|
public sealed record UpdateProfileRequest(string FirstName, string LastName, string? Phone, bool EmailNotificationsEnabled);
|
||||||
|
|
||||||
|
public sealed record AdminUserDto(
|
||||||
|
int Id, string Email, string FirstName, string LastName, string Role, bool IsActive, bool EmailConfirmed, DateTimeOffset CreatedAt)
|
||||||
|
{
|
||||||
|
public string FullName => $"{FirstName} {LastName}";
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record AdminUserDetailsDto(int Id, string Email, string FirstName, string LastName, string? Phone,
|
||||||
|
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, int RowVersion,
|
||||||
|
bool? VerificationEmailSent = null);
|
||||||
|
|
||||||
|
public sealed record SaveAdminUserRequest(string Email, string FirstName, string LastName, string? Phone,
|
||||||
|
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, string? Password, int? RowVersion);
|
||||||
|
|
||||||
|
/// <summary>Stránkovaný seznam z API: <c>{ items, totalCount, page, pageSize }</c>.</summary>
|
||||||
|
public sealed record PagedResult<T>(IReadOnlyList<T> Items, int TotalCount, int Page, int PageSize)
|
||||||
|
{
|
||||||
|
public int PageCount => PageSize <= 0 ? 0 : (int)Math.Ceiling(TotalCount / (double)PageSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record CategoryDto(int Id, string Name, string? Description, bool IsActive);
|
||||||
|
|
||||||
|
public sealed record BuildingDto(int Id, string Code, string Name, string? Address, bool IsActive);
|
||||||
|
|
||||||
|
/// <summary>Závada v seznamu. Kategorie a budova jsou jen ID – názvy doplňuje web z číselníků.</summary>
|
||||||
|
public sealed record IssueSummary(
|
||||||
|
int Id, string Title, int CategoryId, int? BuildingId, string? LocationDetail, string Status,
|
||||||
|
string Priority, int ReporterId, int? AssigneeId, DateTimeOffset CreatedAt);
|
||||||
|
|
||||||
|
/// <summary>Nové hlášení. Přílohy jdou ve stejném požadavku (multipart, pole <c>files</c>).</summary>
|
||||||
|
public sealed record CreateIssueRequest(string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail);
|
||||||
|
|
||||||
|
/// <summary>Soubor přeposílaný z formuláře webu do API.</summary>
|
||||||
|
public sealed record UploadFile(string FileName, string ContentType, Func<Stream> OpenRead);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Detail závady. <c>AllowedActions</c> říká, co smí aktuální uživatel udělat (kódy z <see cref="IssueActions"/>),
|
||||||
|
/// <c>RowVersion</c> se posílá zpět s každou úpravou a změnou stavu (optimistické zamykání, jinak 409).
|
||||||
|
/// </summary>
|
||||||
|
public sealed record IssueDetail(
|
||||||
|
int Id, string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail, string Status,
|
||||||
|
string Priority, int ReporterId, int? AssigneeId, DateTimeOffset CreatedAt, int RowVersion,
|
||||||
|
IReadOnlyList<string> AllowedActions, IReadOnlyList<AttachmentDto> Attachments)
|
||||||
|
{
|
||||||
|
public bool Can(string action) => AllowedActions?.Contains(action) == true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record AttachmentDto(int Id, string FileName, string ContentType, long SizeBytes, DateTimeOffset CreatedAt);
|
||||||
|
|
||||||
|
/// <summary>Událost na časové ose závady – vytvoření, přiřazení, změna stavu i komentář (FR-17).</summary>
|
||||||
|
public sealed record IssueEventDto(
|
||||||
|
int Id, string EventType, string? FromStatus, string ToStatus, int ActorId, string ActorName, string? Note,
|
||||||
|
DateTimeOffset OccurredAt);
|
||||||
|
|
||||||
|
/// <summary>Možný řešitel (jen pro vedení) s počtem jeho otevřených závad (FR-13).</summary>
|
||||||
|
public sealed record AssignableUserDto(int Id, string FirstName, string LastName, string Role, int OpenIssues)
|
||||||
|
{
|
||||||
|
public string FullName => $"{FirstName} {LastName}";
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record EditIssueRequest(
|
||||||
|
string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail, int RowVersion);
|
||||||
|
|
||||||
|
public sealed record AssignIssueRequest(int AssigneeId, string? Priority, int RowVersion);
|
||||||
|
|
||||||
|
public sealed record CommentRequest(string Text);
|
||||||
|
|
||||||
|
/// <summary>Stažená příloha. Proud čte přímo odpověď API a uvolní se spolu s ní.</summary>
|
||||||
|
public sealed class ApiFile(Stream content, string contentType, string fileName, IDisposable response) : IDisposable
|
||||||
|
{
|
||||||
|
public Stream Content { get; } = content;
|
||||||
|
public string ContentType { get; } = contentType;
|
||||||
|
public string FileName { get; } = fileName;
|
||||||
|
|
||||||
|
public void Dispose() => response.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Kódy akcí z <c>allowedActions</c> v detailu závady.</summary>
|
||||||
|
public static class IssueActions
|
||||||
|
{
|
||||||
|
public const string Edit = "EDIT";
|
||||||
|
public const string Assign = "ASSIGN";
|
||||||
|
public const string StartWork = "START_WORK";
|
||||||
|
public const string SubmitForVerification = "SUBMIT_FOR_VERIFICATION";
|
||||||
|
public const string Confirm = "CONFIRM";
|
||||||
|
public const string Reopen = "REOPEN";
|
||||||
|
public const string Reject = "REJECT";
|
||||||
|
public const string Comment = "COMMENT";
|
||||||
|
public const string AddAttachments = "ADD_ATTACHMENTS";
|
||||||
|
|
||||||
|
/// <summary>Změny stavu v pořadí, v jakém je web nabízí (T4 – T9).</summary>
|
||||||
|
public static readonly IReadOnlyList<string> Transitions = [StartWork, SubmitForVerification, Confirm, Reopen, Reject];
|
||||||
|
|
||||||
|
/// <summary>Akční endpoint <c>POST /issues/{id}/…</c> pro změnu stavu.</summary>
|
||||||
|
public static string? TransitionPath(string? action) => action switch
|
||||||
|
{
|
||||||
|
StartWork => "start",
|
||||||
|
SubmitForVerification => "submit-for-verification",
|
||||||
|
Confirm => "confirm",
|
||||||
|
Reopen => "reopen",
|
||||||
|
Reject => "reject",
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>Zamítnutí a znovuotevření vyžadují důvod (T7 – T9).</summary>
|
||||||
|
public static bool RequiresReason(string action) => action is Reopen or Reject;
|
||||||
|
|
||||||
|
/// <summary>Předání k ověření má nepovinnou poznámku (T5).</summary>
|
||||||
|
public static bool AcceptsText(string action) => action is SubmitForVerification || RequiresReason(action);
|
||||||
|
|
||||||
|
/// <summary>Texty tlačítek – stejné jako v mobilní aplikaci.</summary>
|
||||||
|
public static string Label(string action) => action switch
|
||||||
|
{
|
||||||
|
StartWork => "Zahájit řešení",
|
||||||
|
SubmitForVerification => "Předat k ověření",
|
||||||
|
Confirm => "Potvrdit vyřešení",
|
||||||
|
Reopen => "Znovu otevřít závadu",
|
||||||
|
Reject => "Zamítnout závadu",
|
||||||
|
_ => action,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Priorita závady; názvy jako v mobilní aplikaci.</summary>
|
||||||
|
public static class IssuePriorities
|
||||||
|
{
|
||||||
|
public static readonly IReadOnlyList<string> All = ["LOW", "NORMAL", "HIGH"];
|
||||||
|
|
||||||
|
public static string Label(string? priority) => priority switch
|
||||||
|
{
|
||||||
|
"LOW" => "Nízká",
|
||||||
|
"HIGH" => "Vysoká",
|
||||||
|
_ => "Běžná",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Filtry <c>GET /api/v1/issues</c>; prázdné hodnoty se do dotazu neposílají.</summary>
|
||||||
|
public sealed record IssueListQuery(string? Status = null, bool Mine = false, string Sort = "newest", int Page = 1, int PageSize = 20);
|
||||||
@@ -5,7 +5,21 @@ public sealed class ApiOptions
|
|||||||
{
|
{
|
||||||
public const string Section = "Api";
|
public const string Section = "Api";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Hlavní verze REST API, proti které je web napsaný (kap. 11 návrhu). Je jen tady:
|
||||||
|
/// klienti API používají relativní cesty (<c>issues</c>, <c>auth/login</c>) a verze je
|
||||||
|
/// součástí <see cref="HttpClient.BaseAddress"/>. Přechod na <c>v2</c> = změna této
|
||||||
|
/// konstanty a DTO, která se ve v2 změnila. Záměrně to není konfigurace – web je
|
||||||
|
/// napsaný proti konkrétní verzi a s jinou by nefungoval.
|
||||||
|
/// </summary>
|
||||||
|
public const string ApiVersion = "v1";
|
||||||
|
|
||||||
|
/// <summary>Adresa backendu bez cesty API, např. <c>http://api:8080/</c>.</summary>
|
||||||
public string BaseUrl { get; set; } = "";
|
public string BaseUrl { get; set; } = "";
|
||||||
|
|
||||||
public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(15);
|
/// <summary>Delší kvůli nahrávání příloh (až 5 × 10 MB) na pomalejším připojení.</summary>
|
||||||
|
public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(100);
|
||||||
|
|
||||||
|
/// <summary>Základ pro všechna volání: <c>{BaseUrl}/api/v1/</c> (koncové lomítko je nutné pro relativní cesty).</summary>
|
||||||
|
public Uri VersionedBaseAddress() => new(new Uri(BaseUrl.EndsWith('/') ? BaseUrl : BaseUrl + "/"), $"api/{ApiVersion}/");
|
||||||
}
|
}
|
||||||
@@ -4,47 +4,47 @@ using System.Net.Http.Json;
|
|||||||
namespace Helpdesk.Web.Api;
|
namespace Helpdesk.Web.Api;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Anonymní endpointy <c>/api/v1/auth</c>. Záměrně bez <see cref="BearerTokenHandler"/>:
|
/// Anonymní endpointy <c>auth/*</c>. Záměrně bez <see cref="BearerTokenHandler"/>:
|
||||||
/// obnova tokenu běží uvnitř ověřování cookie a čtení tokenu z cookie by se zacyklilo.
|
/// obnova tokenu běží uvnitř ověřování cookie a čtení tokenu z cookie by se zacyklilo.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class AuthApiClient(HttpClient http)
|
public sealed class AuthApiClient(HttpClient http)
|
||||||
{
|
{
|
||||||
public async Task<AuthResponse> LoginAsync(LoginRequest request, CancellationToken ct)
|
public async Task<AuthResponse> LoginAsync(LoginRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
using var response = await http.PostAsJsonAsync("api/v1/auth/login", request, ct);
|
using var response = await http.PostAsJsonAsync("auth/login", request, ct);
|
||||||
return await ApiResponse.ReadAsync<AuthResponse>(response, ct);
|
return await ApiResponse.ReadAsync<AuthResponse>(response, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Registrace. Roli (student / vyučující) určí API podle domény e-mailu.</summary>
|
/// <summary>Registrace. Roli (student / vyučující) určí API podle domény e-mailu.</summary>
|
||||||
public async Task<UserDto> RegisterAsync(RegisterRequest request, CancellationToken ct)
|
public async Task<UserDto> RegisterAsync(RegisterRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
using var response = await http.PostAsJsonAsync("api/v1/auth/register", request, ct);
|
using var response = await http.PostAsJsonAsync("auth/register", request, ct);
|
||||||
return await ApiResponse.ReadAsync<UserDto>(response, ct);
|
return await ApiResponse.ReadAsync<UserDto>(response, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task ConfirmEmailAsync(string token, CancellationToken ct)
|
public async Task ConfirmEmailAsync(ConfirmEmailRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
using var response = await http.PostAsJsonAsync("api/v1/auth/confirm-email", new EmailTokenRequest(token), ct);
|
using var response = await http.PostAsJsonAsync("auth/confirm-email", request, ct);
|
||||||
await ApiResponse.EnsureSuccessAsync(response, ct);
|
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>API odpoví stejně, ať účet existuje, nebo ne – stránka tak neprozradí registrované e-maily.</summary>
|
/// <summary>API odpoví stejně, ať účet existuje, nebo ne – stránka tak neprozradí registrované e-maily.</summary>
|
||||||
public async Task ForgotPasswordAsync(string email, CancellationToken ct)
|
public async Task ForgotPasswordAsync(string email, CancellationToken ct)
|
||||||
{
|
{
|
||||||
using var response = await http.PostAsJsonAsync("api/v1/auth/forgot-password", new ForgotPasswordRequest(email), ct);
|
using var response = await http.PostAsJsonAsync("auth/forgot-password", new ForgotPasswordRequest(email), ct);
|
||||||
await ApiResponse.EnsureSuccessAsync(response, ct);
|
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task ResetPasswordAsync(ResetPasswordRequest request, CancellationToken ct)
|
public async Task ResetPasswordAsync(ResetPasswordRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
using var response = await http.PostAsJsonAsync("api/v1/auth/reset-password", request, ct);
|
using var response = await http.PostAsJsonAsync("auth/reset-password", request, ct);
|
||||||
await ApiResponse.EnsureSuccessAsync(response, ct);
|
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Obnoví pár tokenů. Neplatný nebo už použitý refresh token → <c>null</c>.</summary>
|
/// <summary>Obnoví pár tokenů. Neplatný nebo už použitý refresh token → <c>null</c>.</summary>
|
||||||
public async Task<TokenSet?> RefreshAsync(string refreshToken, CancellationToken ct)
|
public async Task<TokenSet?> RefreshAsync(string refreshToken, CancellationToken ct)
|
||||||
{
|
{
|
||||||
using var response = await http.PostAsJsonAsync("api/v1/auth/refresh", new RefreshTokenRequest(refreshToken), ct);
|
using var response = await http.PostAsJsonAsync("auth/refresh", new RefreshTokenRequest(refreshToken), ct);
|
||||||
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
||||||
return null;
|
return null;
|
||||||
return (await ApiResponse.ReadAsync<AuthResponse>(response, ct)).Tokens;
|
return (await ApiResponse.ReadAsync<AuthResponse>(response, ct)).Tokens;
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
using Microsoft.AspNetCore.HttpOverrides;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Api;
|
||||||
|
|
||||||
|
internal sealed class ForwardedClientIpHandler(IHttpContextAccessor accessor) : DelegatingHandler
|
||||||
|
{
|
||||||
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var header = ForwardedHeadersDefaults.XForwardedForHeaderName;
|
||||||
|
request.Headers.Remove(header);
|
||||||
|
if (accessor.HttpContext?.Connection.RemoteIpAddress is { } address)
|
||||||
|
request.Headers.Add(header, address.ToString());
|
||||||
|
return base.SendAsync(request, cancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,33 +1,263 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
using System.Net.Http.Json;
|
using System.Net.Http.Json;
|
||||||
|
using Microsoft.AspNetCore.WebUtilities;
|
||||||
|
|
||||||
namespace Helpdesk.Web.Api;
|
namespace Helpdesk.Web.Api;
|
||||||
|
|
||||||
/// <summary>Endpointy API pro přihlášeného uživatele; access token přidává <see cref="BearerTokenHandler"/>.</summary>
|
/// <summary>Endpointy API pro přihlášeného uživatele; access token přidává <see cref="BearerTokenHandler"/>.</summary>
|
||||||
public sealed class HelpdeskApiClient(HttpClient http)
|
public sealed class HelpdeskApiClient(HttpClient http)
|
||||||
{
|
{
|
||||||
|
/// <summary>OpenAPI dokument pro Swagger UI (jen admin). Cesta je relativní – verzi API přidává základní adresa.</summary>
|
||||||
|
public async Task<string> GetOpenApiAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.GetAsync("admin/openapi/v1.json", ct);
|
||||||
|
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||||
|
return await response.Content.ReadAsStringAsync(ct);
|
||||||
|
}
|
||||||
|
|
||||||
public async Task<UserDto> GetMeAsync(CancellationToken ct)
|
public async Task<UserDto> GetMeAsync(CancellationToken ct)
|
||||||
{
|
{
|
||||||
using var response = await http.GetAsync("api/v1/users/me", ct);
|
using var response = await http.GetAsync("users/me", ct);
|
||||||
return await ApiResponse.ReadAsync<UserDto>(response, ct);
|
return await ApiResponse.ReadAsync<UserDto>(response, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<UserDto> UpdateMeAsync(UpdateProfileRequest request, CancellationToken ct)
|
public async Task<UserDto> UpdateMeAsync(UpdateProfileRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
using var response = await http.PutAsJsonAsync("api/v1/users/me", request, ct);
|
using var response = await http.PutAsJsonAsync("users/me", request, ct);
|
||||||
return await ApiResponse.ReadAsync<UserDto>(response, ct);
|
return await ApiResponse.ReadAsync<UserDto>(response, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<PagedResult<AdminUserDto>> GetAdminUsersAsync(string? q, string? role, int page, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var parameters = new Dictionary<string, string?>
|
||||||
|
{
|
||||||
|
["q"] = q,
|
||||||
|
["role"] = role,
|
||||||
|
["page"] = page.ToString(CultureInfo.InvariantCulture),
|
||||||
|
};
|
||||||
|
using var response = await http.GetAsync(QueryHelpers.AddQueryString("admin/users", parameters), ct);
|
||||||
|
return await ApiResponse.ReadAsync<PagedResult<AdminUserDto>>(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task ChangeUserRoleAsync(int id, string role, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.PutAsJsonAsync(AdminUserPath(id) + "/role", new { role }, ct);
|
||||||
|
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task SetUserActiveAsync(int id, bool isActive, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.PutAsJsonAsync(AdminUserPath(id) + "/active", new { isActive }, ct);
|
||||||
|
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<AdminUserDetailsDto> GetAdminUserAsync(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.GetAsync(AdminUserPath(id), ct);
|
||||||
|
return await ApiResponse.ReadAsync<AdminUserDetailsDto>(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<AdminUserDetailsDto?> SaveAdminUserAsync(int? id, SaveAdminUserRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = id is int userId
|
||||||
|
? await http.PutAsJsonAsync(AdminUserPath(userId), request, ct)
|
||||||
|
: await http.PostAsJsonAsync("admin/users", request, ct);
|
||||||
|
return response.StatusCode == HttpStatusCode.NoContent
|
||||||
|
? null
|
||||||
|
: await ApiResponse.ReadAsync<AdminUserDetailsDto>(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task SendAdminUserEmailConfirmationAsync(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.PostAsync(AdminUserPath(id) + "/email-confirmation", null, ct);
|
||||||
|
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task DeleteAdminUserAsync(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.DeleteAsync(AdminUserPath(id), ct);
|
||||||
|
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task UpdateAdminUsersAsync(int[] userIds, string action, string? role, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.PostAsJsonAsync("admin/users/bulk", new { userIds, action, role }, ct);
|
||||||
|
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string AdminUserPath(int id) => $"admin/users/{id.ToString(CultureInfo.InvariantCulture)}";
|
||||||
|
|
||||||
|
public async Task<PagedResult<IssueSummary>> GetIssuesAsync(IssueListQuery query, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var parameters = new Dictionary<string, string?>
|
||||||
|
{
|
||||||
|
["status"] = query.Status,
|
||||||
|
["mine"] = query.Mine ? "true" : null,
|
||||||
|
["sort"] = query.Sort,
|
||||||
|
["page"] = query.Page.ToString(CultureInfo.InvariantCulture),
|
||||||
|
["pageSize"] = query.PageSize.ToString(CultureInfo.InvariantCulture),
|
||||||
|
};
|
||||||
|
using var response = await http.GetAsync(QueryHelpers.AddQueryString("issues", parameters.Where(p => !string.IsNullOrEmpty(p.Value))), ct);
|
||||||
|
return await ApiResponse.ReadAsync<PagedResult<IssueSummary>>(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Nahlásí závadu i s přílohami jedním požadavkem (multipart). Soubory se z formuláře
|
||||||
|
/// posílají rovnou dál jako proud, web je celé nenačítá do paměti.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<IssueDetail> CreateIssueAsync(CreateIssueRequest request, IReadOnlyCollection<UploadFile> files, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var content = new MultipartFormDataContent
|
||||||
|
{
|
||||||
|
{ new StringContent(request.Title), "title" },
|
||||||
|
{ new StringContent(request.Description), "description" },
|
||||||
|
{ new StringContent(request.CategoryId.ToString(CultureInfo.InvariantCulture)), "categoryId" },
|
||||||
|
};
|
||||||
|
if (request.BuildingId is { } buildingId)
|
||||||
|
content.Add(new StringContent(buildingId.ToString(CultureInfo.InvariantCulture)), "buildingId");
|
||||||
|
if (!string.IsNullOrWhiteSpace(request.LocationDetail))
|
||||||
|
content.Add(new StringContent(request.LocationDetail), "locationDetail");
|
||||||
|
|
||||||
|
AddFiles(content, files);
|
||||||
|
|
||||||
|
using var response = await http.PostAsync("issues", content, ct);
|
||||||
|
return await ApiResponse.ReadAsync<IssueDetail>(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Detail včetně <c>allowedActions</c> a aktuální <c>rowVersion</c>.</summary>
|
||||||
|
public async Task<IssueDetail> GetIssueAsync(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.GetAsync(IssuePath(id), ct);
|
||||||
|
return await ApiResponse.ReadAsync<IssueDetail>(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Časová osa – změny stavu i komentáře od nejstarších.</summary>
|
||||||
|
public async Task<IReadOnlyList<IssueEventDto>> GetIssueEventsAsync(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.GetAsync(IssuePath(id, "events"), ct);
|
||||||
|
return await ApiResponse.ReadAsync<List<IssueEventDto>>(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Úprava hlášení hlásičem, dokud je ve stavu Přijata.</summary>
|
||||||
|
public async Task<IssueDetail> EditIssueAsync(int id, EditIssueRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.PutAsJsonAsync(IssuePath(id), request, ct);
|
||||||
|
return await ApiResponse.ReadAsync<IssueDetail>(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Přiřazení nebo přeřazení řešiteli (T2, T3), jen vedení.</summary>
|
||||||
|
public async Task<IssueDetail> AssignIssueAsync(int id, AssignIssueRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.PostAsJsonAsync(IssuePath(id, "assign"), request, ct);
|
||||||
|
return await ApiResponse.ReadAsync<IssueDetail>(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Změna stavu přes akční endpoint (T4 – T9). <paramref name="text"/> je důvod u zamítnutí
|
||||||
|
/// a znovuotevření, nebo nepovinná poznámka u předání k ověření.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<IssueDetail> TransitionIssueAsync(int id, string action, int rowVersion, string? text, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var path = IssueActions.TransitionPath(action) ?? throw new ArgumentException($"Neznámá akce {action}.", nameof(action));
|
||||||
|
object body = action switch
|
||||||
|
{
|
||||||
|
IssueActions.SubmitForVerification => new { rowVersion, note = text },
|
||||||
|
IssueActions.Reopen or IssueActions.Reject => new { rowVersion, reason = text },
|
||||||
|
_ => new { rowVersion },
|
||||||
|
};
|
||||||
|
using var response = await http.PostAsJsonAsync(IssuePath(id, path), body, ct);
|
||||||
|
return await ApiResponse.ReadAsync<IssueDetail>(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IssueEventDto> AddCommentAsync(int id, string text, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.PostAsJsonAsync(IssuePath(id, "comments"), new CommentRequest(text), ct);
|
||||||
|
return await ApiResponse.ReadAsync<IssueEventDto>(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Doplnění příloh k existující závadě (FR-11), 1–5 souborů.</summary>
|
||||||
|
public async Task<IReadOnlyList<AttachmentDto>> AddAttachmentsAsync(int id, IReadOnlyCollection<UploadFile> files, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var content = new MultipartFormDataContent();
|
||||||
|
AddFiles(content, files);
|
||||||
|
using var response = await http.PostAsync(IssuePath(id, "attachments"), content, ct);
|
||||||
|
return await ApiResponse.ReadAsync<List<AttachmentDto>>(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Stažení přílohy. Odpověď se nečte do paměti – web ji jako proud předá prohlížeči
|
||||||
|
/// a po odeslání ji uvolní (<see cref="ApiFile.Dispose"/>).
|
||||||
|
/// </summary>
|
||||||
|
public async Task<ApiFile> DownloadAttachmentAsync(int attachmentId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var response = await http.GetAsync($"attachments/{attachmentId.ToString(CultureInfo.InvariantCulture)}",
|
||||||
|
HttpCompletionOption.ResponseHeadersRead, ct);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||||
|
var disposition = response.Content.Headers.ContentDisposition;
|
||||||
|
var fileName = (disposition?.FileNameStar ?? disposition?.FileName)?.Trim('"');
|
||||||
|
return new ApiFile(
|
||||||
|
await response.Content.ReadAsStreamAsync(ct),
|
||||||
|
response.Content.Headers.ContentType?.MediaType ?? "application/octet-stream",
|
||||||
|
string.IsNullOrWhiteSpace(fileName) ? $"priloha-{attachmentId}" : fileName,
|
||||||
|
response);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
response.Dispose();
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Řešitelé s počtem otevřených závad – jen pro vedení.</summary>
|
||||||
|
public async Task<IReadOnlyList<AssignableUserDto>> GetAssignableUsersAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.GetAsync("users/assignable", ct);
|
||||||
|
return await ApiResponse.ReadAsync<List<AssignableUserDto>>(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string IssuePath(int id, string? action = null) =>
|
||||||
|
action is null ? $"issues/{id.ToString(CultureInfo.InvariantCulture)}" : $"issues/{id.ToString(CultureInfo.InvariantCulture)}/{action}";
|
||||||
|
|
||||||
|
/// <summary>Soubory z formuláře jdou do API jako proud v poli <c>files</c>, web je nenačítá do paměti.</summary>
|
||||||
|
private static void AddFiles(MultipartFormDataContent content, IEnumerable<UploadFile> files)
|
||||||
|
{
|
||||||
|
foreach (var file in files)
|
||||||
|
{
|
||||||
|
var part = new StreamContent(file.OpenRead());
|
||||||
|
part.Headers.ContentType = MediaTypeHeaderValue.TryParse(file.ContentType, out var type)
|
||||||
|
? type
|
||||||
|
: new MediaTypeHeaderValue("application/octet-stream");
|
||||||
|
content.Add(part, "files", file.FileName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<CategoryDto>> GetIssueCategoriesAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.GetAsync("issue-categories", ct);
|
||||||
|
return await ApiResponse.ReadAsync<List<CategoryDto>>(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<BuildingDto>> GetBuildingsAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.GetAsync("buildings", ct);
|
||||||
|
return await ApiResponse.ReadAsync<List<BuildingDto>>(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Odhlásí ze všech zařízení – API zneplatní všechny tokeny uživatele.</summary>
|
/// <summary>Odhlásí ze všech zařízení – API zneplatní všechny tokeny uživatele.</summary>
|
||||||
public async Task LogoutAllAsync(CancellationToken ct)
|
public async Task LogoutAllAsync(CancellationToken ct)
|
||||||
{
|
{
|
||||||
using var response = await http.PostAsync("api/v1/auth/logout-all", content: null, ct);
|
using var response = await http.PostAsync("auth/logout-all", content: null, ct);
|
||||||
await ApiResponse.EnsureSuccessAsync(response, ct);
|
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Odhlásí toto zařízení – API zneplatní aktuální access token i předaný refresh token.</summary>
|
/// <summary>Odhlásí toto zařízení – API zneplatní aktuální access token i předaný refresh token.</summary>
|
||||||
public async Task LogoutAsync(string refreshToken, CancellationToken ct)
|
public async Task LogoutAsync(string refreshToken, CancellationToken ct)
|
||||||
{
|
{
|
||||||
using var response = await http.PostAsJsonAsync("api/v1/auth/logout", new RefreshTokenRequest(refreshToken), ct);
|
using var response = await http.PostAsJsonAsync("auth/logout", new RefreshTokenRequest(refreshToken), ct);
|
||||||
await ApiResponse.EnsureSuccessAsync(response, ct);
|
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -9,6 +9,8 @@ public static class UserRoles
|
|||||||
public const string Management = "MANAGEMENT";
|
public const string Management = "MANAGEMENT";
|
||||||
public const string Admin = "ADMIN";
|
public const string Admin = "ADMIN";
|
||||||
|
|
||||||
|
public static IReadOnlyList<string> All { get; } = [Student, Teacher, FacilityManager, Management, Admin];
|
||||||
|
|
||||||
public static string DisplayName(string? role) => role switch
|
public static string DisplayName(string? role) => role switch
|
||||||
{
|
{
|
||||||
Student => "Student",
|
Student => "Student",
|
||||||
|
|||||||
@@ -44,7 +44,6 @@ public sealed class AccountController(AuthApiClient authApi, HelpdeskApiClient a
|
|||||||
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Unauthorized
|
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Unauthorized
|
||||||
or HttpStatusCode.Forbidden or HttpStatusCode.TooManyRequests)
|
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));
|
ModelState.AddApiErrors(ex, typeof(LoginViewModel));
|
||||||
model.Password = "";
|
model.Password = "";
|
||||||
return View(model);
|
return View(model);
|
||||||
@@ -66,39 +65,48 @@ public sealed class AccountController(AuthApiClient authApi, HelpdeskApiClient a
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
var user = await authApi.RegisterAsync(
|
var user = await authApi.RegisterAsync(
|
||||||
new RegisterRequest(model.Email.Trim(), model.Password, model.FirstName.Trim(), model.LastName.Trim()), ct);
|
new RegisterRequest(model.Email.Trim(), model.FirstName.Trim(), model.LastName.Trim()), ct);
|
||||||
return View("RegisterDone", user.Email);
|
return View("RegisterDone", user.Email);
|
||||||
}
|
}
|
||||||
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict or HttpStatusCode.TooManyRequests)
|
catch (ApiException ex) when (ex is { StatusCode: HttpStatusCode.ServiceUnavailable, ProblemType: "urn:ntbug:email-delivery-failed" })
|
||||||
|
{
|
||||||
|
ViewData["VerificationEmailFailed"] = true;
|
||||||
|
ModelState.AddModelError(string.Empty, "Účet je uložený. Ověřovací e-mail se nepodařilo odeslat, zkuste ho prosím poslat znovu.");
|
||||||
|
return View(model);
|
||||||
|
}
|
||||||
|
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict
|
||||||
|
or HttpStatusCode.TooManyRequests or HttpStatusCode.ServiceUnavailable)
|
||||||
{
|
{
|
||||||
// 400 cizí doména nebo validace, 409 účet už existuje.
|
|
||||||
ModelState.AddApiErrors(ex, typeof(RegisterViewModel));
|
ModelState.AddApiErrors(ex, typeof(RegisterViewModel));
|
||||||
model.Password = model.ConfirmPassword = "";
|
|
||||||
return View(model);
|
return View(model);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Odkaz z registračního e-mailu. Token se spotřebuje až tlačítkem, ne samotným otevřením odkazu.</summary>
|
/// <summary>Odkaz z ověřovacího e-mailu. Token se spotřebuje při uložení hesla.</summary>
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
[HttpGet("confirm-email")]
|
[HttpGet("confirm-email")]
|
||||||
public IActionResult ConfirmEmail(string? token) => View(new EmailTokenViewModel { Token = token ?? "" });
|
public IActionResult ConfirmEmail(string? token) => View(new EmailPasswordViewModel { Token = token ?? "" });
|
||||||
|
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
[HttpPost("confirm-email")]
|
[HttpPost("confirm-email")]
|
||||||
public async Task<IActionResult> ConfirmEmail(EmailTokenViewModel model, CancellationToken ct)
|
public async Task<IActionResult> ConfirmEmail(EmailPasswordViewModel model, CancellationToken ct)
|
||||||
{
|
{
|
||||||
if (!ModelState.IsValid)
|
if (!ModelState.IsValid)
|
||||||
|
{
|
||||||
|
model.NewPassword = model.ConfirmPassword = "";
|
||||||
return View(model);
|
return View(model);
|
||||||
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await authApi.ConfirmEmailAsync(model.Token, ct);
|
await authApi.ConfirmEmailAsync(new ConfirmEmailRequest(model.Token, model.NewPassword), ct);
|
||||||
TempData.SetSuccess("E-mail je ověřený. Teď se můžete přihlásit.");
|
TempData.SetSuccess("E-mail je ověřený. Teď se můžete přihlásit nastaveným heslem.");
|
||||||
return RedirectToAction(nameof(Login));
|
return RedirectToAction(nameof(Login));
|
||||||
}
|
}
|
||||||
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.TooManyRequests)
|
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.TooManyRequests)
|
||||||
{
|
{
|
||||||
ModelState.AddModelError(string.Empty, ex.UserMessage);
|
ModelState.AddApiErrors(ex, typeof(EmailPasswordViewModel));
|
||||||
|
model.NewPassword = model.ConfirmPassword = "";
|
||||||
return View(model);
|
return View(model);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -128,11 +136,11 @@ public sealed class AccountController(AuthApiClient authApi, HelpdeskApiClient a
|
|||||||
|
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
[HttpGet("reset-password")]
|
[HttpGet("reset-password")]
|
||||||
public IActionResult ResetPassword(string? token) => View(new ResetPasswordViewModel { Token = token ?? "" });
|
public IActionResult ResetPassword(string? token) => View(new EmailPasswordViewModel { Token = token ?? "" });
|
||||||
|
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
[HttpPost("reset-password")]
|
[HttpPost("reset-password")]
|
||||||
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model, CancellationToken ct)
|
public async Task<IActionResult> ResetPassword(EmailPasswordViewModel model, CancellationToken ct)
|
||||||
{
|
{
|
||||||
if (!ModelState.IsValid)
|
if (!ModelState.IsValid)
|
||||||
{
|
{
|
||||||
@@ -146,7 +154,7 @@ public sealed class AccountController(AuthApiClient authApi, HelpdeskApiClient a
|
|||||||
}
|
}
|
||||||
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.TooManyRequests)
|
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.TooManyRequests)
|
||||||
{
|
{
|
||||||
ModelState.AddApiErrors(ex, typeof(ResetPasswordViewModel));
|
ModelState.AddApiErrors(ex, typeof(EmailPasswordViewModel));
|
||||||
model.NewPassword = model.ConfirmPassword = "";
|
model.NewPassword = model.ConfirmPassword = "";
|
||||||
return View(model);
|
return View(model);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,213 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Net;
|
||||||
|
using System.Security.Claims;
|
||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Helpdesk.Web.Auth;
|
||||||
|
using Helpdesk.Web.Infrastructure;
|
||||||
|
using Helpdesk.Web.Models;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Controllers;
|
||||||
|
|
||||||
|
[Authorize(Roles = UserRoles.Admin)]
|
||||||
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||||
|
[Route("admin/users")]
|
||||||
|
public sealed class AdminUsersController(HelpdeskApiClient api) : Controller
|
||||||
|
{
|
||||||
|
[HttpGet("")]
|
||||||
|
public async Task<IActionResult> Index([FromQuery] AdminUsersQuery query, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var q = string.IsNullOrWhiteSpace(query.Q) ? null : query.Q.Trim();
|
||||||
|
var role = query.Role is { } filter && UserRoles.All.Contains(filter) ? filter : null;
|
||||||
|
var users = await api.GetAdminUsersAsync(q, role, Math.Max(1, query.Page), ct);
|
||||||
|
if (users.Items.Count == 0 && users.Page > 1)
|
||||||
|
return BackToList(new AdminUsersQuery(q, role, Math.Max(1, users.PageCount)));
|
||||||
|
|
||||||
|
return View(new AdminUsersViewModel(users, new AdminUsersQuery(q, role, users.Page), CurrentUserId));
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("new")]
|
||||||
|
public IActionResult New([FromQuery] AdminUsersQuery query) => View("Form", new AdminUserForm { Query = query });
|
||||||
|
|
||||||
|
[HttpPost("new")]
|
||||||
|
public Task<IActionResult> New([FromForm] AdminUserForm model, [FromQuery] AdminUsersQuery query, CancellationToken ct) =>
|
||||||
|
SaveAsync(null, model, query, ct);
|
||||||
|
|
||||||
|
[HttpGet("{id:int}/edit")]
|
||||||
|
public async Task<IActionResult> Edit([FromRoute] int id, [FromQuery] AdminUsersQuery query, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (id == CurrentUserId)
|
||||||
|
return RedirectToAction("Index", "Profile");
|
||||||
|
|
||||||
|
var user = await api.GetAdminUserAsync(id, ct);
|
||||||
|
return View("Form", new AdminUserForm
|
||||||
|
{
|
||||||
|
Id = user.Id,
|
||||||
|
Query = query,
|
||||||
|
RowVersion = user.RowVersion,
|
||||||
|
Email = user.Email,
|
||||||
|
FirstName = user.FirstName,
|
||||||
|
LastName = user.LastName,
|
||||||
|
Phone = user.Phone,
|
||||||
|
Role = user.Role,
|
||||||
|
IsActive = user.IsActive,
|
||||||
|
EmailConfirmed = user.EmailConfirmed,
|
||||||
|
EmailNotificationsEnabled = user.EmailNotificationsEnabled,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/edit")]
|
||||||
|
public Task<IActionResult> Edit([FromRoute] int id, [FromForm] AdminUserForm model, [FromQuery] AdminUsersQuery query,
|
||||||
|
CancellationToken ct) => SaveAsync(id, model, query, ct);
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/email-confirmation")]
|
||||||
|
public async Task<IActionResult> SendEmailConfirmation([FromRoute] int id, [FromQuery] AdminUsersQuery query, CancellationToken ct)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await api.SendAdminUserEmailConfirmationAsync(id, ct);
|
||||||
|
TempData.SetSuccess("Ověřovací e-mail byl odeslán.");
|
||||||
|
}
|
||||||
|
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.Conflict or HttpStatusCode.ServiceUnavailable)
|
||||||
|
{
|
||||||
|
TempData.SetError(ex.AllMessages);
|
||||||
|
}
|
||||||
|
|
||||||
|
return BackToEdit(id, query);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/delete")]
|
||||||
|
public async Task<IActionResult> Delete([FromRoute] int id, [FromForm] bool confirmDelete, [FromQuery] AdminUsersQuery query,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (!confirmDelete)
|
||||||
|
{
|
||||||
|
TempData.SetError("Potvrďte smazání účtu.");
|
||||||
|
return BackToEdit(id, query);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await UpdateAsync(query, () => api.DeleteAdminUserAsync(id, ct), "Účet byl smazán a jeho profil anonymizován.");
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("bulk")]
|
||||||
|
public async Task<IActionResult> Bulk([FromForm] int[] userIds, [FromForm] string? action, [FromForm] string? newRole,
|
||||||
|
[FromForm] bool confirmDelete, [FromQuery] AdminUsersQuery query, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (!ModelState.IsValid || userIds is not { Length: >= 1 } ||
|
||||||
|
action is not ("activate" or "deactivate" or "role" or "delete"))
|
||||||
|
{
|
||||||
|
TempData.SetError("Označte účty a vyberte hromadnou akci.");
|
||||||
|
return BackToList(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (action == "delete" && !confirmDelete)
|
||||||
|
{
|
||||||
|
TempData.SetError("Potvrďte smazání vybraných účtů.");
|
||||||
|
return BackToList(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (action == "role" && (newRole is null || !UserRoles.All.Contains(newRole)))
|
||||||
|
{
|
||||||
|
TempData.SetError("Vyberte roli pro označené účty.");
|
||||||
|
return BackToList(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await UpdateAsync(query, () => api.UpdateAdminUsersAsync(userIds, action, newRole, ct), "Hromadná akce byla provedena.");
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/role")]
|
||||||
|
public async Task<IActionResult> ChangeRole([FromRoute] int id, [FromForm] string? newRole, [FromQuery] AdminUsersQuery query,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (newRole is null || !UserRoles.All.Contains(newRole))
|
||||||
|
{
|
||||||
|
TempData.SetError("Vyberte platnou roli.");
|
||||||
|
return BackToList(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await UpdateAsync(query, () => api.ChangeUserRoleAsync(id, newRole, ct), "Role uživatele byla uložena.");
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/active")]
|
||||||
|
public async Task<IActionResult> SetActive([FromRoute] int id, [FromForm] bool? isActive, [FromQuery] AdminUsersQuery query,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (isActive is not bool active)
|
||||||
|
{
|
||||||
|
TempData.SetError("Vyberte stav účtu.");
|
||||||
|
return BackToList(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await UpdateAsync(query, () => api.SetUserActiveAsync(id, active, ct),
|
||||||
|
active ? "Účet byl aktivován." : "Účet byl deaktivován.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<IActionResult> UpdateAsync(AdminUsersQuery query, Func<Task> update, string success)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await update();
|
||||||
|
TempData.SetSuccess(success);
|
||||||
|
}
|
||||||
|
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict or HttpStatusCode.NotFound)
|
||||||
|
{
|
||||||
|
TempData.SetError(ex.AllMessages);
|
||||||
|
}
|
||||||
|
|
||||||
|
return BackToList(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<IActionResult> SaveAsync(int? id, AdminUserForm model, AdminUsersQuery query, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (id is not null && id == CurrentUserId)
|
||||||
|
return RedirectToAction("Index", "Profile");
|
||||||
|
|
||||||
|
if (id is int userId && model.RowVersion is null or < 0)
|
||||||
|
{
|
||||||
|
TempData.SetError("Formulář nemá platnou verzi účtu. Změny zadejte znovu.");
|
||||||
|
return BackToEdit(userId, query);
|
||||||
|
}
|
||||||
|
|
||||||
|
model.Id = id;
|
||||||
|
model.Query = query;
|
||||||
|
if (id is null && model.EmailConfirmed && string.IsNullOrWhiteSpace(model.Password))
|
||||||
|
ModelState.AddModelError(nameof(model.Password), "Při ručním ověření e-mailu zadejte počáteční heslo.");
|
||||||
|
if (ModelState.IsValid)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await api.SaveAdminUserAsync(id, model.ToRequest(), ct);
|
||||||
|
var message = id is null ? "Účet byl založen." : "Změny účtu byly uloženy.";
|
||||||
|
TempData.SetSuccess(result?.VerificationEmailSent == true ? message + " Ověřovací e-mail byl odeslán." : message);
|
||||||
|
if (result is { VerificationEmailSent: false })
|
||||||
|
{
|
||||||
|
TempData.SetError("Ověřovací e-mail se nepodařilo odeslat. Můžete ho poslat znovu.");
|
||||||
|
return BackToEdit(result.Id, query);
|
||||||
|
}
|
||||||
|
return BackToList(query);
|
||||||
|
}
|
||||||
|
catch (ApiException ex) when (id is int editedUserId && ex is
|
||||||
|
{ StatusCode: HttpStatusCode.Conflict, ProblemType: "urn:ntbug:account-version-conflict" })
|
||||||
|
{
|
||||||
|
TempData.SetError(ex.UserMessage);
|
||||||
|
return BackToEdit(editedUserId, query);
|
||||||
|
}
|
||||||
|
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict)
|
||||||
|
{
|
||||||
|
ModelState.AddApiErrors(ex, typeof(AdminUserForm));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return View("Form", model);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int? CurrentUserId =>
|
||||||
|
int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier), CultureInfo.InvariantCulture, out var id) ? id : null;
|
||||||
|
|
||||||
|
private RedirectToActionResult BackToList(AdminUsersQuery query) =>
|
||||||
|
RedirectToAction(nameof(Index), new { q = query.Q, role = query.Role, page = query.Page });
|
||||||
|
|
||||||
|
private RedirectToActionResult BackToEdit(int id, AdminUsersQuery query) =>
|
||||||
|
RedirectToAction(nameof(Edit), new { id, q = query.Q, role = query.Role, page = query.Page });
|
||||||
|
}
|
||||||
@@ -0,0 +1,258 @@
|
|||||||
|
using System.Net;
|
||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Helpdesk.Web.Infrastructure;
|
||||||
|
using Helpdesk.Web.Models;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.Net.Http.Headers;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Controllers;
|
||||||
|
|
||||||
|
/// <summary>Hlášení závad (FR-10 – FR-17).</summary>
|
||||||
|
[Route("issues")]
|
||||||
|
public sealed class IssuesController(HelpdeskApiClient api) : Controller
|
||||||
|
{
|
||||||
|
/// <summary>Moje hlášení – závady, které uživatel nahlásil, od nejnovějších.</summary>
|
||||||
|
[HttpGet("")]
|
||||||
|
public async Task<IActionResult> Index(string? status, int page = 1, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
if (status is not null && !IssueListViewModel.Statuses.Contains(status))
|
||||||
|
status = null;
|
||||||
|
|
||||||
|
var issues = await api.GetIssuesAsync(new IssueListQuery(status, Mine: true, Page: Math.Max(page, 1)), ct);
|
||||||
|
// API vrací u závady jen ID kategorie a budovy – názvy doplníme z číselníků.
|
||||||
|
var categories = await api.GetIssueCategoriesAsync(ct);
|
||||||
|
var buildings = await api.GetBuildingsAsync(ct);
|
||||||
|
|
||||||
|
return View(new IssueListViewModel
|
||||||
|
{
|
||||||
|
Issues = issues,
|
||||||
|
CategoryNames = categories.ToDictionary(c => c.Id, c => c.Name),
|
||||||
|
BuildingNames = buildings.ToDictionary(b => b.Id, b => b.Name),
|
||||||
|
Status = status,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Formulář nového hlášení (T1 – závada vznikne ve stavu Přijata).</summary>
|
||||||
|
[HttpGet("new")]
|
||||||
|
public async Task<IActionResult> New(CancellationToken ct) => View(await WithCatalogsAsync(new NewIssueViewModel(), ct));
|
||||||
|
|
||||||
|
[HttpPost("new")]
|
||||||
|
[RequestSizeLimit(AttachmentRules.MaxRequestBytes)]
|
||||||
|
[RequestFormLimits(MultipartBodyLengthLimit = AttachmentRules.MaxRequestBytes)]
|
||||||
|
public async Task<IActionResult> New(NewIssueViewModel model, CancellationToken ct)
|
||||||
|
{
|
||||||
|
foreach (var error in AttachmentRules.Validate(model.Files))
|
||||||
|
ModelState.AddModelError(nameof(NewIssueViewModel.Files), error);
|
||||||
|
if (!ModelState.IsValid)
|
||||||
|
return View(await WithCatalogsAsync(model, ct));
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var issue = await api.CreateIssueAsync(
|
||||||
|
new CreateIssueRequest(model.Title.Trim(), model.Description.Trim(), model.CategoryId!.Value, model.BuildingId, model.LocationDetail?.Trim()),
|
||||||
|
ToUploads(model.Files),
|
||||||
|
ct);
|
||||||
|
TempData.SetSuccess($"Závada #{issue.Id} je nahlášená. Vedení školy ji přiřadí řešiteli.");
|
||||||
|
return RedirectToAction(nameof(Detail), new { id = issue.Id });
|
||||||
|
}
|
||||||
|
catch (ApiException ex) when (IsUserError(ex))
|
||||||
|
{
|
||||||
|
ModelState.AddApiErrors(ex, typeof(NewIssueViewModel));
|
||||||
|
return View(await WithCatalogsAsync(model, ct));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Detail závady s časovou osou, přílohami a akcemi podle <c>allowedActions</c>.</summary>
|
||||||
|
[HttpGet("{id:int}")]
|
||||||
|
public async Task<IActionResult> Detail(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
// Postupně, ne paralelně: všechna volání sdílejí HttpContext (token v cookie, jeho obnova).
|
||||||
|
var issue = await api.GetIssueAsync(id, ct);
|
||||||
|
var events = await api.GetIssueEventsAsync(id, ct);
|
||||||
|
var categories = await api.GetIssueCategoriesAsync(ct);
|
||||||
|
var buildings = await api.GetBuildingsAsync(ct);
|
||||||
|
IReadOnlyList<AssignableUserDto> assignees = issue.Can(IssueActions.Assign) ? await api.GetAssignableUsersAsync(ct) : [];
|
||||||
|
|
||||||
|
return View(new IssueDetailViewModel
|
||||||
|
{
|
||||||
|
Issue = issue,
|
||||||
|
Events = events,
|
||||||
|
CategoryName = categories.FirstOrDefault(c => c.Id == issue.CategoryId)?.Name ?? "Neznámá kategorie",
|
||||||
|
Location = IssueListViewModel.FormatLocation(buildings.FirstOrDefault(b => b.Id == issue.BuildingId)?.Name, issue.LocationDetail),
|
||||||
|
Assignees = assignees,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Změna stavu: zahájit, předat k ověření, potvrdit, znovu otevřít, zamítnout (T4 – T9).</summary>
|
||||||
|
[HttpPost("{id:int}/transition")]
|
||||||
|
public async Task<IActionResult> Transition(int id, [FromForm] IssueActionForm form, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var action = form.Action ?? "";
|
||||||
|
if (IssueActions.TransitionPath(action) is null)
|
||||||
|
return BadRequest();
|
||||||
|
if (!ModelState.IsValid || form.RowVersion is not int rowVersion || rowVersion < 0)
|
||||||
|
return BackToDetail(id, error: InvalidActionFormMessage);
|
||||||
|
|
||||||
|
var text = string.IsNullOrWhiteSpace(form.Text) || !IssueActions.AcceptsText(action) ? null : form.Text.Trim();
|
||||||
|
if (IssueActions.RequiresReason(action) && text is null)
|
||||||
|
return BackToDetail(id, error: "Napište prosím důvod.");
|
||||||
|
if (text?.Length > IssueActionForm.MaxTextLength)
|
||||||
|
return BackToDetail(id, error: $"Text může mít nejvýše {IssueActionForm.MaxTextLength} znaků.");
|
||||||
|
|
||||||
|
return await RunAsync(id, () => api.TransitionIssueAsync(id, action, rowVersion, text, ct), action switch
|
||||||
|
{
|
||||||
|
IssueActions.StartWork => "Řešení závady je zahájené.",
|
||||||
|
IssueActions.SubmitForVerification => "Závada je předaná k ověření. Hlásič potvrdí, jestli je vyřešená.",
|
||||||
|
IssueActions.Confirm => "Děkujeme, závada je vyřešená.",
|
||||||
|
IssueActions.Reopen => "Závada je znovu otevřená a vrací se řešiteli.",
|
||||||
|
_ => "Závada je zamítnutá.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Přiřazení nebo přeřazení řešiteli (T2, T3) – jen vedení.</summary>
|
||||||
|
[HttpPost("{id:int}/assign")]
|
||||||
|
public async Task<IActionResult> Assign(int id, [FromForm] IssueActionForm form, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (!ModelState.IsValid || form.RowVersion is not int rowVersion || rowVersion < 0)
|
||||||
|
return BackToDetail(id, error: InvalidActionFormMessage);
|
||||||
|
if (form.AssigneeId is not { } assigneeId)
|
||||||
|
return BackToDetail(id, error: "Vyberte řešitele.");
|
||||||
|
if (form.Priority is not null && !IssuePriorities.All.Contains(form.Priority))
|
||||||
|
return BackToDetail(id, error: "Vyberte platnou prioritu.");
|
||||||
|
|
||||||
|
return await RunAsync(id, () => api.AssignIssueAsync(id, new AssignIssueRequest(assigneeId, form.Priority, rowVersion), ct),
|
||||||
|
"Závada je přiřazená řešiteli.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Komentář hlásiče nebo řešitele (FR-16).</summary>
|
||||||
|
[HttpPost("{id:int}/comments")]
|
||||||
|
public async Task<IActionResult> Comment(int id, IssueActionForm form, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var text = form.Text?.Trim();
|
||||||
|
if (string.IsNullOrEmpty(text))
|
||||||
|
return BackToDetail(id, error: "Napište text komentáře.", fragment: "komentar");
|
||||||
|
if (text.Length > IssueActionForm.MaxTextLength)
|
||||||
|
return BackToDetail(id, error: $"Komentář může mít nejvýše {IssueActionForm.MaxTextLength} znaků.", fragment: "komentar");
|
||||||
|
|
||||||
|
return await RunAsync(id, () => api.AddCommentAsync(id, text, ct), "Komentář je odeslaný.", fragment: "komentar");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Doplnění příloh k závadě v průběhu řešení (FR-11).</summary>
|
||||||
|
[HttpPost("{id:int}/attachments")]
|
||||||
|
[RequestSizeLimit(AttachmentRules.MaxRequestBytes)]
|
||||||
|
[RequestFormLimits(MultipartBodyLengthLimit = AttachmentRules.MaxRequestBytes)]
|
||||||
|
public async Task<IActionResult> Attachments(int id, IssueActionForm form, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var error = form.Files.Count == 0 ? "Vyberte alespoň jeden soubor." : AttachmentRules.Validate(form.Files).FirstOrDefault();
|
||||||
|
if (error is not null)
|
||||||
|
return BackToDetail(id, error: error, fragment: "prilohy");
|
||||||
|
|
||||||
|
return await RunAsync(id, () => api.AddAttachmentsAsync(id, ToUploads(form.Files), ct),
|
||||||
|
form.Files.Count == 1 ? "Příloha je nahraná." : "Přílohy jsou nahrané.", fragment: "prilohy");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Příloha přes web: prohlížeč nemá access token, proto ji web stáhne z API a pošle dál jako proud.
|
||||||
|
/// Oprávnění kontroluje API (jen ten, kdo vidí závadu).
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("attachments/{attachmentId:int}")]
|
||||||
|
public async Task<IActionResult> Attachment(int attachmentId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var file = await api.DownloadAttachmentAsync(attachmentId, ct);
|
||||||
|
HttpContext.Response.RegisterForDispose(file);
|
||||||
|
// filename i filename* (RFC 6266), aby prohlížeč zachoval diakritiku v názvu souboru.
|
||||||
|
var disposition = new ContentDispositionHeaderValue(IssueDetailViewModel.OpensInBrowser(file.ContentType) ? "inline" : "attachment");
|
||||||
|
disposition.SetHttpFileName(file.FileName);
|
||||||
|
Response.Headers.ContentDisposition = disposition.ToString();
|
||||||
|
return File(file.Content, file.ContentType);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Úprava hlášení, dokud je ve stavu Přijata (jen hlásič).</summary>
|
||||||
|
[HttpGet("{id:int}/edit")]
|
||||||
|
public async Task<IActionResult> Edit(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var issue = await api.GetIssueAsync(id, ct);
|
||||||
|
if (!issue.Can(IssueActions.Edit))
|
||||||
|
return BackToDetail(id, error: "Hlášení už nejde upravit – vedení ho mezitím převzalo. Doplňující informace napište do komentáře.");
|
||||||
|
|
||||||
|
return View(await WithCatalogsAsync(EditIssueViewModel.From(issue), ct));
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/edit")]
|
||||||
|
public async Task<IActionResult> Edit(int id, [FromForm] EditIssueViewModel model, CancellationToken ct)
|
||||||
|
{
|
||||||
|
model.Id = id;
|
||||||
|
if (model.RowVersion is not int rowVersion || rowVersion < 0)
|
||||||
|
return BackToDetail(id, error: InvalidActionFormMessage);
|
||||||
|
if (!ModelState.IsValid)
|
||||||
|
return View(await WithCatalogsAsync(model, ct));
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await api.EditIssueAsync(id, new EditIssueRequest(model.Title.Trim(), model.Description.Trim(), model.CategoryId!.Value,
|
||||||
|
model.BuildingId, model.LocationDetail?.Trim(), rowVersion), ct);
|
||||||
|
return BackToDetail(id, success: "Změny hlášení jsou uložené.");
|
||||||
|
}
|
||||||
|
catch (ApiException ex) when (ex.StatusCode == HttpStatusCode.Conflict)
|
||||||
|
{
|
||||||
|
return BackToDetail(id, error: ConflictError(ex));
|
||||||
|
}
|
||||||
|
catch (ApiException ex) when (IsUserError(ex))
|
||||||
|
{
|
||||||
|
ModelState.AddApiErrors(ex, typeof(EditIssueViewModel));
|
||||||
|
return View(await WithCatalogsAsync(model, ct));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private const string InvalidActionFormMessage =
|
||||||
|
"Formulář obsahuje chybějící nebo neplatné údaje. Zkontrolujte aktuální detail závady a akci zopakujte.";
|
||||||
|
|
||||||
|
private const string ConflictMessage =
|
||||||
|
"Závadu mezitím někdo změnil. Níže je její aktuální stav – zkontrolujte ho a akci případně zopakujte.";
|
||||||
|
|
||||||
|
private static string ConflictError(ApiException ex) =>
|
||||||
|
ex.ProblemType == "urn:ntbug:issue-version-conflict" ? ConflictMessage : ex.UserMessage;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Provede akci a vrátí uživatele na detail se zprávou (Post/Redirect/Get). Chyby, které může
|
||||||
|
/// uživatel napravit, ukáže nad detailem; 401/403/404 zpracuje <see cref="ApiExceptionFilter"/>.
|
||||||
|
/// </summary>
|
||||||
|
private async Task<IActionResult> RunAsync(int id, Func<Task> action, string success, string? fragment = null)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await action();
|
||||||
|
return BackToDetail(id, success: success, fragment: fragment);
|
||||||
|
}
|
||||||
|
catch (ApiException ex) when (ex.StatusCode == HttpStatusCode.Conflict)
|
||||||
|
{
|
||||||
|
return BackToDetail(id, error: ConflictError(ex));
|
||||||
|
}
|
||||||
|
catch (ApiException ex) when (IsUserError(ex))
|
||||||
|
{
|
||||||
|
return BackToDetail(id, error: ex.AllMessages, fragment: fragment);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private RedirectToActionResult BackToDetail(int id, string? success = null, string? error = null, string? fragment = null)
|
||||||
|
{
|
||||||
|
if (success is not null)
|
||||||
|
TempData.SetSuccess(success);
|
||||||
|
if (error is not null)
|
||||||
|
TempData.SetError(error);
|
||||||
|
return RedirectToAction(nameof(Detail), null, new { id }, fragment);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>400 validace nebo nepovolený obsah souboru, 413 příliš velké přílohy, 415, 429 limit zápisů (10/min).</summary>
|
||||||
|
private static bool IsUserError(ApiException ex) => ex.StatusCode is HttpStatusCode.BadRequest
|
||||||
|
or HttpStatusCode.RequestEntityTooLarge or HttpStatusCode.UnsupportedMediaType or HttpStatusCode.TooManyRequests;
|
||||||
|
|
||||||
|
private static List<UploadFile> ToUploads(IEnumerable<IFormFile> files) =>
|
||||||
|
files.Select(f => new UploadFile(f.FileName, f.ContentType, f.OpenReadStream)).ToList();
|
||||||
|
|
||||||
|
private async Task<T> WithCatalogsAsync<T>(T model, CancellationToken ct) where T : IssueFormViewModel
|
||||||
|
{
|
||||||
|
model.SetCatalogs(await api.GetIssueCategoriesAsync(ct), await api.GetBuildingsAsync(ct));
|
||||||
|
return model;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Helpdesk.Web.Auth;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Controllers;
|
||||||
|
|
||||||
|
[Authorize(Roles = UserRoles.Admin)]
|
||||||
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||||
|
public sealed class SwaggerController(HelpdeskApiClient api) : Controller
|
||||||
|
{
|
||||||
|
[HttpGet("/swagger/v1/swagger.json")]
|
||||||
|
public async Task<IActionResult> Document(CancellationToken ct) =>
|
||||||
|
Content(await api.GetOpenApiAsync(ct), "application/json");
|
||||||
|
}
|
||||||
@@ -1,7 +1,17 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<!--
|
||||||
|
Verze webové aplikace (semver, před vydáním 1.0 jako 0.x):
|
||||||
|
MINOR = nová část aplikace (závady, návrhy, …), PATCH = opravy.
|
||||||
|
Zobrazuje se v patičce; při sestavení z Gitu se k ní přidá krátký hash commitu.
|
||||||
|
-->
|
||||||
|
<Version>0.3.0</Version>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<InternalsVisibleTo Include="Helpdesk.Web.Tests" />
|
<InternalsVisibleTo Include="Helpdesk.Web.Tests" />
|
||||||
|
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
using System.Reflection;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Infrastructure;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verze běžící webové aplikace z <c><Version></c> v projektu. SDK k ní při sestavení
|
||||||
|
/// v Gitu přidá hash commitu (<c>0.2.0+6e742b4…</c>); zobrazujeme jeho prvních 7 znaků,
|
||||||
|
/// aby při ladění bylo jasné, který commit běží.
|
||||||
|
/// </summary>
|
||||||
|
public static class AppVersion
|
||||||
|
{
|
||||||
|
public static string Display { get; } = Format(
|
||||||
|
typeof(AppVersion).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion);
|
||||||
|
|
||||||
|
internal static string Format(string? informationalVersion)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(informationalVersion))
|
||||||
|
return "neznámá";
|
||||||
|
|
||||||
|
var parts = informationalVersion.Split('+', 2);
|
||||||
|
var commit = parts.Length == 2 ? parts[1].Split('.')[0] : null;
|
||||||
|
return string.IsNullOrEmpty(commit) ? parts[0] : $"{parts[0]} ({commit[..Math.Min(7, commit.Length)]})";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Infrastructure;
|
||||||
|
|
||||||
|
/// <summary>API vrací časy v UTC; uživatelům je zobrazujeme v českém čase (kap. 12.6 návrhu).</summary>
|
||||||
|
public static class DisplayTime
|
||||||
|
{
|
||||||
|
private static readonly TimeZoneInfo Prague = TimeZoneInfo.FindSystemTimeZoneById("Europe/Prague");
|
||||||
|
private static readonly CultureInfo Czech = CultureInfo.GetCultureInfo("cs-CZ");
|
||||||
|
|
||||||
|
public static DateTimeOffset ToLocal(DateTimeOffset utc) => TimeZoneInfo.ConvertTime(utc, Prague);
|
||||||
|
|
||||||
|
/// <summary>Např. „3. 10. 2026 14:05“.</summary>
|
||||||
|
public static string Format(DateTimeOffset utc) => ToLocal(utc).ToString("d. M. yyyy H:mm", Czech);
|
||||||
|
}
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using Helpdesk.Web.Auth;
|
|
||||||
|
|
||||||
namespace Helpdesk.Web.Infrastructure;
|
namespace Helpdesk.Web.Infrastructure;
|
||||||
|
|
||||||
@@ -19,6 +18,8 @@ public static class Navigation
|
|||||||
public static readonly IReadOnlyList<NavItem> Items =
|
public static readonly IReadOnlyList<NavItem> Items =
|
||||||
[
|
[
|
||||||
new("Nástěnka", "Home", "Index"),
|
new("Nástěnka", "Home", "Index"),
|
||||||
|
new("Nahlásit závadu", "Issues", "New"),
|
||||||
|
new("Moje hlášení", "Issues", "Index"),
|
||||||
];
|
];
|
||||||
|
|
||||||
public static IEnumerable<NavItem> For(ClaimsPrincipal user) => Items.Where(i => i.IsVisibleTo(user));
|
public static IEnumerable<NavItem> For(ClaimsPrincipal user) => Items.Where(i => i.IsVisibleTo(user));
|
||||||
|
|||||||
@@ -43,25 +43,6 @@ public sealed class RegisterViewModel
|
|||||||
[StringLength(100, ErrorMessage = "Příjmení může mít nejvýše 100 znaků.")]
|
[StringLength(100, ErrorMessage = "Příjmení může mít nejvýše 100 znaků.")]
|
||||||
[Display(Name = "Příjmení")]
|
[Display(Name = "Příjmení")]
|
||||||
public string LastName { get; set; } = "";
|
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; } = "";
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Stránka z odkazu v e-mailu – token se odešle až tlačítkem.</summary>
|
|
||||||
public sealed class EmailTokenViewModel
|
|
||||||
{
|
|
||||||
[Required]
|
|
||||||
public string Token { get; set; } = "";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class ForgotPasswordViewModel
|
public sealed class ForgotPasswordViewModel
|
||||||
@@ -72,7 +53,7 @@ public sealed class ForgotPasswordViewModel
|
|||||||
public string Email { get; set; } = "";
|
public string Email { get; set; } = "";
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class ResetPasswordViewModel
|
public sealed class EmailPasswordViewModel
|
||||||
{
|
{
|
||||||
[Required]
|
[Required]
|
||||||
public string Token { get; set; } = "";
|
public string Token { get; set; } = "";
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Helpdesk.Web.Auth;
|
||||||
|
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Models;
|
||||||
|
|
||||||
|
public sealed record AdminUsersViewModel(PagedResult<AdminUserDto> Users, AdminUsersQuery Query, int? CurrentUserId);
|
||||||
|
|
||||||
|
public sealed record AdminUsersQuery(string? Q = null, string? Role = null, int Page = 1);
|
||||||
|
|
||||||
|
public sealed class AdminUserForm
|
||||||
|
{
|
||||||
|
[BindNever]
|
||||||
|
public int? Id { get; set; }
|
||||||
|
|
||||||
|
[BindNever]
|
||||||
|
public AdminUsersQuery Query { get; set; } = new();
|
||||||
|
|
||||||
|
public int? RowVersion { get; set; }
|
||||||
|
|
||||||
|
[Display(Name = "Jméno"), Required(ErrorMessage = "Zadejte jméno."), StringLength(100)]
|
||||||
|
public string FirstName { get; set; } = "";
|
||||||
|
|
||||||
|
[Display(Name = "Příjmení"), Required(ErrorMessage = "Zadejte příjmení."), StringLength(100)]
|
||||||
|
public string LastName { get; set; } = "";
|
||||||
|
|
||||||
|
[Display(Name = "E-mail"), Required(ErrorMessage = "Zadejte e-mail."), EmailAddress(ErrorMessage = "Zadejte platný e-mail."), StringLength(254)]
|
||||||
|
public string Email { get; set; } = "";
|
||||||
|
|
||||||
|
[Display(Name = "Telefon"), StringLength(30)]
|
||||||
|
public string? Phone { get; set; }
|
||||||
|
|
||||||
|
[Display(Name = "Role"), Required(ErrorMessage = "Vyberte roli.")]
|
||||||
|
public string Role { get; set; } = UserRoles.Student;
|
||||||
|
|
||||||
|
[Display(Name = "Heslo"), DataType(DataType.Password)]
|
||||||
|
[StringLength(PasswordRules.MaxLength, MinimumLength = PasswordRules.MinLength, ErrorMessage = PasswordRules.LengthMessage)]
|
||||||
|
public string? Password { get; set; }
|
||||||
|
|
||||||
|
[Display(Name = "Aktivní účet")]
|
||||||
|
public bool IsActive { get; set; } = true;
|
||||||
|
|
||||||
|
[Display(Name = "E-mail je ověřený")]
|
||||||
|
public bool EmailConfirmed { get; set; }
|
||||||
|
|
||||||
|
[Display(Name = "E-mailové notifikace")]
|
||||||
|
public bool EmailNotificationsEnabled { get; set; } = true;
|
||||||
|
|
||||||
|
public SaveAdminUserRequest ToRequest() => new(Email.Trim(), FirstName.Trim(), LastName.Trim(), Phone,
|
||||||
|
Role, IsActive, EmailConfirmed, EmailNotificationsEnabled, Password, RowVersion);
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
using Helpdesk.Web.Api;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Models;
|
||||||
|
|
||||||
|
/// <summary>Detail závady: údaje, akce podle <c>allowedActions</c>, přílohy a časová osa (kap. 13.2 návrhu).</summary>
|
||||||
|
public sealed class IssueDetailViewModel
|
||||||
|
{
|
||||||
|
public required IssueDetail Issue { get; init; }
|
||||||
|
public required IReadOnlyList<IssueEventDto> Events { get; init; }
|
||||||
|
public required string CategoryName { get; init; }
|
||||||
|
public string? Location { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Možní řešitelé – načítají se jen pro vedení, když smí závadu přiřadit.</summary>
|
||||||
|
public IReadOnlyList<AssignableUserDto> Assignees { get; init; } = [];
|
||||||
|
|
||||||
|
public bool Can(string action) => Issue.Can(action);
|
||||||
|
|
||||||
|
public IEnumerable<string> Transitions => IssueActions.Transitions.Where(Can);
|
||||||
|
|
||||||
|
/// <summary>API vrací u závady jen ID lidí; jméno hlásiče je u události vytvoření.</summary>
|
||||||
|
public string ReporterName =>
|
||||||
|
Events.FirstOrDefault(e => e.EventType == IssueEventTypes.Created)?.ActorName ?? $"Uživatel #{Issue.ReporterId}";
|
||||||
|
|
||||||
|
/// <summary>Jméno řešitele zapisuje API do poznámky poslední události přiřazení.</summary>
|
||||||
|
public string? AssigneeName => Issue.AssigneeId is not { } assigneeId
|
||||||
|
? null
|
||||||
|
: Events.LastOrDefault(e => e.EventType == IssueEventTypes.Assigned)?.Note ?? $"Uživatel #{assigneeId}";
|
||||||
|
|
||||||
|
/// <summary>Řešitelé kromě současného – přeřadit na stejného API nedovolí.</summary>
|
||||||
|
public IEnumerable<AssignableUserDto> OtherAssignees => Assignees.Where(a => a.Id != Issue.AssigneeId);
|
||||||
|
|
||||||
|
public IEnumerable<TimelineEntry> Timeline => Events.Select(TimelineEntry.From);
|
||||||
|
|
||||||
|
public bool IsClosed => Issue.Status is "RESOLVED" or "REJECTED";
|
||||||
|
|
||||||
|
/// <summary>Co se se závadou děje, když uživatel sám nemá žádnou akci.</summary>
|
||||||
|
public string NextStepText => Issue.Status switch
|
||||||
|
{
|
||||||
|
"RECEIVED" => "Závada čeká, až ji vedení školy přiřadí řešiteli.",
|
||||||
|
"ASSIGNED" => "Závada je přiřazená řešiteli, ten ji zatím nezačal řešit.",
|
||||||
|
"IN_PROGRESS" => "Řešitel na závadě pracuje.",
|
||||||
|
"PENDING_VERIFICATION" => "Řešitel závadu opravil a čeká, až hlásič potvrdí, že je vyřešená.",
|
||||||
|
"RESOLVED" => "Závada je vyřešená a uzavřená.",
|
||||||
|
"REJECTED" => "Závada je zamítnutá a uzavřená. Důvod najdete v průběhu řešení.",
|
||||||
|
_ => "Stav závady se nepodařilo určit.",
|
||||||
|
};
|
||||||
|
|
||||||
|
public static string FileSize(long bytes) => bytes switch
|
||||||
|
{
|
||||||
|
< 1024 => $"{bytes} B",
|
||||||
|
< 1024 * 1024 => $"{Math.Round(bytes / 1024d)} kB",
|
||||||
|
_ => $"{bytes / (1024d * 1024):0.#} MB",
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>Fotky a PDF otevře prohlížeč rovnou, ostatní (DOCX, HEIC) se stáhnou.</summary>
|
||||||
|
public static bool OpensInBrowser(string contentType) => contentType is "image/jpeg" or "image/png";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class IssueEventTypes
|
||||||
|
{
|
||||||
|
public const string Created = "CREATED";
|
||||||
|
public const string Updated = "UPDATED";
|
||||||
|
public const string Assigned = "ASSIGNED";
|
||||||
|
public const string StatusChanged = "STATUS_CHANGED";
|
||||||
|
public const string Commented = "COMMENTED";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Jedna položka časové osy pro zobrazení: co se stalo („zahájil/a řešení“), případně poznámka
|
||||||
|
/// s popiskem („Důvod“) a stav, do kterého závada přešla.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record TimelineEntry(IssueEventDto Event, string Text, string? NoteLabel, string? Note, string? Status)
|
||||||
|
{
|
||||||
|
public bool IsComment => Event.EventType == IssueEventTypes.Commented;
|
||||||
|
|
||||||
|
public static TimelineEntry From(IssueEventDto e) => e.EventType switch
|
||||||
|
{
|
||||||
|
IssueEventTypes.Created => new(e, "nahlásil/a závadu", null, null, e.ToStatus),
|
||||||
|
IssueEventTypes.Updated => new(e, "upravil/a údaje hlášení", null, null, null),
|
||||||
|
IssueEventTypes.Assigned => new(e,
|
||||||
|
e.FromStatus is "ASSIGNED" or "IN_PROGRESS" ? $"přeřadil/a závadu na {e.Note}" : $"přiřadil/a závadu řešiteli {e.Note}",
|
||||||
|
null, null, e.ToStatus),
|
||||||
|
IssueEventTypes.Commented => new(e, "napsal/a komentář", null, e.Note, null),
|
||||||
|
IssueEventTypes.StatusChanged => e.ToStatus switch
|
||||||
|
{
|
||||||
|
"IN_PROGRESS" when e.FromStatus == "PENDING_VERIFICATION" => new(e, "znovu otevřel/a závadu", "Důvod", e.Note, e.ToStatus),
|
||||||
|
"IN_PROGRESS" => new(e, "zahájil/a řešení", null, e.Note, e.ToStatus),
|
||||||
|
"PENDING_VERIFICATION" => new(e, "předal/a závadu k ověření", "Poznámka", e.Note, e.ToStatus),
|
||||||
|
"RESOLVED" => new(e, "potvrdil/a vyřešení", null, e.Note, e.ToStatus),
|
||||||
|
"REJECTED" => new(e, "zamítl/a závadu", "Důvod", e.Note, e.ToStatus),
|
||||||
|
_ => new(e, "změnil/a stav", null, e.Note, e.ToStatus),
|
||||||
|
},
|
||||||
|
_ => new(e, "provedl/a změnu", null, e.Note, null),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Formuláře akcí na detailu závady. Každý POST použije jen svá pole.</summary>
|
||||||
|
public sealed class IssueActionForm
|
||||||
|
{
|
||||||
|
public int? RowVersion { get; set; }
|
||||||
|
public string? Action { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Důvod (zamítnutí, znovuotevření) nebo poznámka (předání k ověření).</summary>
|
||||||
|
public string? Text { get; set; }
|
||||||
|
|
||||||
|
public int? AssigneeId { get; set; }
|
||||||
|
public string? Priority { get; set; }
|
||||||
|
|
||||||
|
public List<IFormFile> Files { get; set; } = [];
|
||||||
|
|
||||||
|
public const int MaxTextLength = 5000;
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
using Helpdesk.Web.Api;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Models;
|
||||||
|
|
||||||
|
public sealed class IssueListViewModel
|
||||||
|
{
|
||||||
|
/// <summary>Stavy závady v pořadí životního cyklu (kap. 6 návrhu) pro filtr.</summary>
|
||||||
|
public static readonly IReadOnlyList<string> Statuses =
|
||||||
|
["RECEIVED", "ASSIGNED", "IN_PROGRESS", "PENDING_VERIFICATION", "RESOLVED", "REJECTED"];
|
||||||
|
|
||||||
|
public required PagedResult<IssueSummary> Issues { get; init; }
|
||||||
|
public required IReadOnlyDictionary<int, string> CategoryNames { get; init; }
|
||||||
|
public required IReadOnlyDictionary<int, string> BuildingNames { get; init; }
|
||||||
|
public string? Status { get; init; }
|
||||||
|
|
||||||
|
public string CategoryName(int id) => CategoryNames.GetValueOrDefault(id, "Neznámá kategorie");
|
||||||
|
|
||||||
|
/// <summary>Budova a upřesnění místa, např. „Budova B – učebna B-205“.</summary>
|
||||||
|
public string? Location(IssueSummary issue) =>
|
||||||
|
FormatLocation(issue.BuildingId is { } id ? BuildingNames.GetValueOrDefault(id) : null, issue.LocationDetail);
|
||||||
|
|
||||||
|
public static string? FormatLocation(string? building, string? locationDetail)
|
||||||
|
{
|
||||||
|
return (building, locationDetail) switch
|
||||||
|
{
|
||||||
|
(null, null or "") => null,
|
||||||
|
(null, var detail) => detail,
|
||||||
|
(var b, null or "") => b,
|
||||||
|
var (b, detail) => $"{b} – {detail}",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Rendering;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Models;
|
||||||
|
|
||||||
|
/// <summary>Limity příloh – stejné jako v API (FR-11).</summary>
|
||||||
|
public static class AttachmentRules
|
||||||
|
{
|
||||||
|
public const int MaxFiles = 5;
|
||||||
|
public const long MaxFileBytes = 10 * 1024 * 1024;
|
||||||
|
/// <summary>Celý požadavek: všechny soubory plus pole formuláře.</summary>
|
||||||
|
public const long MaxRequestBytes = MaxFiles * MaxFileBytes + 1024 * 1024;
|
||||||
|
|
||||||
|
public static readonly IReadOnlyList<string> Extensions = [".jpg", ".jpeg", ".png", ".heic", ".pdf", ".docx"];
|
||||||
|
|
||||||
|
/// <summary>Atribut <c>accept</c> pro výběr souborů.</summary>
|
||||||
|
public static string Accept => string.Join(",", Extensions);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Rychlá kontrola na webu, aby uživatel nečekal na nahrání 50 MB jen kvůli špatnému typu.
|
||||||
|
/// Skutečný obsah souboru (signaturu) ověřuje API.
|
||||||
|
/// </summary>
|
||||||
|
public static IEnumerable<string> Validate(IReadOnlyCollection<IFormFile> files)
|
||||||
|
{
|
||||||
|
if (files.Count > MaxFiles)
|
||||||
|
yield return $"Najednou můžete přiložit nejvýše {MaxFiles} souborů.";
|
||||||
|
|
||||||
|
foreach (var file in files)
|
||||||
|
{
|
||||||
|
if (!Extensions.Contains(Path.GetExtension(file.FileName).ToLowerInvariant()))
|
||||||
|
yield return $"Soubor {file.FileName} nemá povolený typ. Povolené jsou JPG, PNG, HEIC, PDF a DOCX.";
|
||||||
|
else if (file.Length > MaxFileBytes)
|
||||||
|
yield return $"Soubor {file.FileName} je větší než 10 MB.";
|
||||||
|
else if (file.Length == 0)
|
||||||
|
yield return $"Soubor {file.FileName} je prázdný.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Údaje hlášení společné pro nové hlášení i jeho úpravu (partial <c>_IssueFields</c>).</summary>
|
||||||
|
public abstract class IssueFormViewModel
|
||||||
|
{
|
||||||
|
[Required(ErrorMessage = "Zadejte název.")]
|
||||||
|
[StringLength(200, ErrorMessage = "Název může mít nejvýše 200 znaků.")]
|
||||||
|
[Display(Name = "Co se stalo")]
|
||||||
|
public string Title { get; set; } = "";
|
||||||
|
|
||||||
|
[Required(ErrorMessage = "Popište závadu.")]
|
||||||
|
[StringLength(10_000, ErrorMessage = "Popis může mít nejvýše 10 000 znaků.")] // stejně jako v mobilu
|
||||||
|
[Display(Name = "Popis")]
|
||||||
|
public string Description { get; set; } = "";
|
||||||
|
|
||||||
|
[Required(ErrorMessage = "Vyberte kategorii.")]
|
||||||
|
[Display(Name = "Kategorie")]
|
||||||
|
public int? CategoryId { get; set; }
|
||||||
|
|
||||||
|
[Display(Name = "Budova")]
|
||||||
|
public int? BuildingId { get; set; }
|
||||||
|
|
||||||
|
[StringLength(255, ErrorMessage = "Upřesnění místa může mít nejvýše 255 znaků.")]
|
||||||
|
[Display(Name = "Upřesnění místa")]
|
||||||
|
public string? LocationDetail { get; set; }
|
||||||
|
|
||||||
|
// Nabídky pro výběr – plní je kontroler z číselníků API.
|
||||||
|
public IReadOnlyList<SelectListItem> Categories { get; set; } = [];
|
||||||
|
public IReadOnlyList<SelectListItem> Buildings { get; set; } = [];
|
||||||
|
|
||||||
|
public void SetCatalogs(IEnumerable<CategoryDto> categories, IEnumerable<BuildingDto> buildings)
|
||||||
|
{
|
||||||
|
Categories = categories.Select(c => new SelectListItem(c.Name, c.Id.ToString())).ToList();
|
||||||
|
Buildings = buildings.Select(b => new SelectListItem(b.Name, b.Id.ToString())).ToList();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class NewIssueViewModel : IssueFormViewModel
|
||||||
|
{
|
||||||
|
[Display(Name = "Fotografie nebo soubory")]
|
||||||
|
public List<IFormFile> Files { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Úprava hlášení hlásičem, dokud ho vedení nepřiřadí (stav Přijata).</summary>
|
||||||
|
public sealed class EditIssueViewModel : IssueFormViewModel
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Verze, kterou uživatel upravuje; když se závada mezitím změní, API vrátí 409.</summary>
|
||||||
|
public int? RowVersion { get; set; }
|
||||||
|
|
||||||
|
public static EditIssueViewModel From(IssueDetail issue) => new()
|
||||||
|
{
|
||||||
|
Id = issue.Id,
|
||||||
|
RowVersion = issue.RowVersion,
|
||||||
|
Title = issue.Title,
|
||||||
|
Description = issue.Description,
|
||||||
|
CategoryId = issue.CategoryId,
|
||||||
|
BuildingId = issue.BuildingId,
|
||||||
|
LocationDetail = issue.LocationDetail,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -31,14 +31,18 @@ builder.Services.AddOptions<ApiOptions>()
|
|||||||
static void ConfigureApiClient(IServiceProvider services, HttpClient http)
|
static void ConfigureApiClient(IServiceProvider services, HttpClient http)
|
||||||
{
|
{
|
||||||
var options = services.GetRequiredService<IOptions<ApiOptions>>().Value;
|
var options = services.GetRequiredService<IOptions<ApiOptions>>().Value;
|
||||||
http.BaseAddress = new Uri(options.BaseUrl.EndsWith('/') ? options.BaseUrl : options.BaseUrl + "/");
|
http.BaseAddress = options.VersionedBaseAddress();
|
||||||
http.Timeout = options.Timeout;
|
http.Timeout = options.Timeout;
|
||||||
}
|
}
|
||||||
|
|
||||||
builder.Services.AddHttpContextAccessor();
|
builder.Services.AddHttpContextAccessor();
|
||||||
builder.Services.AddTransient<BearerTokenHandler>();
|
builder.Services.AddTransient<BearerTokenHandler>();
|
||||||
builder.Services.AddHttpClient<AuthApiClient>(ConfigureApiClient);
|
builder.Services.AddTransient<ForwardedClientIpHandler>();
|
||||||
builder.Services.AddHttpClient<HelpdeskApiClient>(ConfigureApiClient).AddHttpMessageHandler<BearerTokenHandler>();
|
builder.Services.AddHttpClient<AuthApiClient>(ConfigureApiClient)
|
||||||
|
.AddHttpMessageHandler<ForwardedClientIpHandler>();
|
||||||
|
builder.Services.AddHttpClient<HelpdeskApiClient>(ConfigureApiClient)
|
||||||
|
.AddHttpMessageHandler<ForwardedClientIpHandler>()
|
||||||
|
.AddHttpMessageHandler<BearerTokenHandler>();
|
||||||
|
|
||||||
// Přihlášení: tokeny API v šifrované HttpOnly cookie, obnova access tokenu při ověření cookie.
|
// 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(TimeProvider.System);
|
||||||
@@ -111,6 +115,13 @@ app.UseRouting();
|
|||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
|
|
||||||
|
app.MapSwaggerUI("swagger", options =>
|
||||||
|
{
|
||||||
|
options.SwaggerEndpoint("v1/swagger.json", "Helpdesk API v1");
|
||||||
|
options.DocumentTitle = "Helpdesk API";
|
||||||
|
options.CacheLifetime = null;
|
||||||
|
}).RequireAuthorization(policy => policy.RequireRole(UserRoles.Admin));
|
||||||
|
|
||||||
app.MapStaticAssets();
|
app.MapStaticAssets();
|
||||||
app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}").WithStaticAssets();
|
app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}").WithStaticAssets();
|
||||||
|
|
||||||
|
|||||||
@@ -1,27 +1,28 @@
|
|||||||
@model EmailTokenViewModel
|
@model EmailPasswordViewModel
|
||||||
@{
|
@{
|
||||||
ViewData["Title"] = "Ověření e-mailu";
|
ViewData["Title"] = "Ověření e-mailu";
|
||||||
var failed = !ViewData.ModelState.IsValid || string.IsNullOrEmpty(Model.Token);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
<section class="app-auth">
|
<section class="app-auth">
|
||||||
<h1>Ověření e-mailu</h1>
|
<h1>Ověření e-mailu</h1>
|
||||||
<div class="app-card">
|
<div class="app-card">
|
||||||
@if (failed)
|
@if (string.IsNullOrEmpty(Model.Token))
|
||||||
{
|
{
|
||||||
<partial name="_FormErrors" />
|
<p class="mb-0">Odkaz je neúplný. Otevřete ho prosím znovu z e-mailu.</p>
|
||||||
<p class="mb-0">Odkaz je neplatný, už byl použit, nebo vypršel. Pokud jste e-mail už ověřili, stačí se přihlásit.</p>
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
<p>Dokončete registraci potvrzením svého e-mailu.</p>
|
<p>Nastavením hesla ověříte svůj e-mail.</p>
|
||||||
<form method="post" asp-action="ConfirmEmail">
|
<partial name="_FormErrors" />
|
||||||
|
<form method="post" asp-action="ConfirmEmail" novalidate>
|
||||||
<input type="hidden" asp-for="Token" />
|
<input type="hidden" asp-for="Token" />
|
||||||
<button type="submit" class="btn btn-primary w-100">Ověřit e-mail</button>
|
<partial name="_NewPasswordFields" />
|
||||||
|
<button type="submit" class="btn btn-primary w-100">Ověřit e-mail a nastavit heslo</button>
|
||||||
</form>
|
</form>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
<div class="app-auth-links">
|
<div class="app-auth-links">
|
||||||
|
<a asp-action="Register">Poslat nový ověřovací odkaz</a>
|
||||||
<a asp-action="Login">Přejít na přihlášení</a>
|
<a asp-action="Login">Přejít na přihlášení</a>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
@model RegisterViewModel
|
@model RegisterViewModel
|
||||||
@{
|
@{
|
||||||
ViewData["Title"] = "Registrace";
|
ViewData["Title"] = "Registrace";
|
||||||
|
var resend = ViewData["VerificationEmailFailed"] is true;
|
||||||
}
|
}
|
||||||
|
|
||||||
<section class="app-auth">
|
<section class="app-auth">
|
||||||
@@ -27,18 +28,7 @@
|
|||||||
<span asp-validation-for="LastName" class="invalid-feedback d-block"></span>
|
<span asp-validation-for="LastName" class="invalid-feedback d-block"></span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="mb-3">
|
<button type="submit" class="btn btn-primary w-100">@(resend ? "Poslat ověřovací e-mail znovu" : "Poslat ověřovací e-mail")</button>
|
||||||
<label asp-for="Password" class="form-label"></label>
|
|
||||||
<input asp-for="Password" class="form-control" autocomplete="new-password" aria-describedby="passwordHelp" />
|
|
||||||
<div id="passwordHelp" class="form-text">8 až 64 znaků.</div>
|
|
||||||
<span asp-validation-for="Password" class="invalid-feedback d-block"></span>
|
|
||||||
</div>
|
|
||||||
<div class="mb-4">
|
|
||||||
<label asp-for="ConfirmPassword" class="form-label"></label>
|
|
||||||
<input asp-for="ConfirmPassword" class="form-control" autocomplete="new-password" />
|
|
||||||
<span asp-validation-for="ConfirmPassword" class="invalid-feedback d-block"></span>
|
|
||||||
</div>
|
|
||||||
<button type="submit" class="btn btn-primary w-100">Zaregistrovat se</button>
|
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user