Compare commits
2
Commits
main
..
a65516b810
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a65516b810 | ||
|
|
d056b54f50 |
No files matched your search
@@ -3,13 +3,8 @@
|
|||||||
!backend/Directory.Packages.props
|
!backend/Directory.Packages.props
|
||||||
!backend/src/
|
!backend/src/
|
||||||
!db/migrations/
|
!db/migrations/
|
||||||
!web/Directory.Build.props
|
|
||||||
!web/Directory.Packages.props
|
|
||||||
!web/Helpdesk.Web/
|
|
||||||
backend/**/bin
|
backend/**/bin
|
||||||
backend/**/obj
|
backend/**/obj
|
||||||
web/**/bin
|
|
||||||
web/**/obj
|
|
||||||
**/.env
|
**/.env
|
||||||
**/*.env
|
**/*.env
|
||||||
**/*.pem
|
**/*.pem
|
||||||
|
|||||||
@@ -2,3 +2,5 @@
|
|||||||
* text=auto
|
* text=auto
|
||||||
*.sh text eol=lf
|
*.sh text eol=lf
|
||||||
*.sql text eol=lf
|
*.sql text eol=lf
|
||||||
|
gradlew text eol=lf
|
||||||
|
*.bat text eol=crlf
|
||||||
@@ -55,6 +55,7 @@ replay_pid*
|
|||||||
|
|
||||||
# Gradle wrapper se do repozitáře commituje (jinak by šablona výše vyřadila *.jar)
|
# Gradle wrapper se do repozitáře commituje (jinak by šablona výše vyřadila *.jar)
|
||||||
!gradle/wrapper/gradle-wrapper.jar
|
!gradle/wrapper/gradle-wrapper.jar
|
||||||
|
!**/gradle/wrapper/gradle-wrapper.jar
|
||||||
|
|
||||||
# ---> Android / Gradle
|
# ---> Android / Gradle
|
||||||
.gradle/
|
.gradle/
|
||||||
|
|||||||
@@ -9,12 +9,12 @@ Univerzitní helpdesk a portál návrhů na zlepšení – semestrální práce
|
|||||||
| Složka / soubor | Obsah |
|
| Složka / soubor | Obsah |
|
||||||
|---|---|
|
|---|---|
|
||||||
| [docs/navrh-aplikace.md](docs/navrh-aplikace.md) | Návrhový dokument (v1.1 – včetně zapracovaných připomínek z obhajoby) |
|
| [docs/navrh-aplikace.md](docs/navrh-aplikace.md) | Návrhový dokument (v1.1 – včetně zapracovaných připomínek z obhajoby) |
|
||||||
| [db/migrations/](db/migrations/) | Verzované SQL migrace (MariaDB 11) – schéma, číselníky a porovnávání FCM tokenů |
|
| [db/migrations/](db/migrations/) | Verzované SQL migrace (MariaDB 11) – `V001` schéma, `V002` číselníky |
|
||||||
| [backend/](backend/) | ASP.NET Core Web API, DbUp migrator, unit testy (.NET 10) |
|
| [backend/](backend/) | ASP.NET Core Web API, DbUp migrator, unit testy (.NET 10) |
|
||||||
| [web/](web/) | Webová aplikace ASP.NET Core MVC – tenký klient REST API |
|
| [mobile/](mobile/) | Android klient v Kotlinu a Jetpack Compose (Android 8+), připojení k API a ukázkový režim |
|
||||||
| [deploy/](deploy/) | Docker Compose, inicializace DB účtů, šablona `.env` |
|
| [deploy/](deploy/) | Docker Compose, inicializace DB účtů, šablona `.env` |
|
||||||
|
|
||||||
## Spuštění (Docker)
|
## Spuštění backendu (Docker)
|
||||||
|
|
||||||
Potřeba je jen Docker Desktop.
|
Potřeba je jen Docker Desktop.
|
||||||
|
|
||||||
@@ -24,25 +24,19 @@ Potřeba je jen Docker Desktop.
|
|||||||
cp deploy/.env.example deploy/.env
|
cp deploy/.env.example deploy/.env
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Spusťte databázi, migrace, API a web:
|
Výchozí port API je `8080`. Pokud jej používá jiná aplikace, přidejte do `deploy/.env` například `API_PORT=8081`.
|
||||||
|
|
||||||
|
2. Spusťte databázi, migrace a API:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
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 po přihlášení administrátora: <http://localhost:8081/swagger> · stav a verze schématu: <http://localhost:8080/health>
|
3. Swagger UI: <http://localhost:8080/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.
|
Při `API_PORT=8081` použijte <http://localhost:8081/swagger> a <http://localhost:8081/health>.
|
||||||
|
|
||||||
Při prvním startu se vytvoří účet administrátora, pokud vyplníte `ADMIN_EMAIL` a `ADMIN_PASSWORD`. V režimu `Development` s prázdnými hodnotami `SMTP_MAILBOX` a `SMTP_PASSWORD` najdete ověřovací odkazy a odkazy pro obnovu hesla v logu služby `api`.
|
Při prvním startu se vytvoří účet administrátora z `ADMIN_EMAIL` / `ADMIN_PASSWORD`. Odesílání e-mailů je zatím jen do logu – odkaz pro ověření e-mailu po registraci najdete v `docker compose -f deploy/docker-compose.yml logs api`.
|
||||||
|
|
||||||
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/*` 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.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
### Vývoj bez Dockeru
|
### Vývoj bez Dockeru
|
||||||
|
|
||||||
@@ -52,43 +46,18 @@ Vyžaduje .NET SDK 10. Unit testy:
|
|||||||
dotnet run --project backend/tests/Helpdesk.UnitTests/Helpdesk.UnitTests.csproj
|
dotnet run --project backend/tests/Helpdesk.UnitTests/Helpdesk.UnitTests.csproj
|
||||||
```
|
```
|
||||||
|
|
||||||
Webová aplikace proti API běžícímu v Dockeru (otevře se na <http://localhost:5080>):
|
## Mobilní aplikace
|
||||||
|
|
||||||
```bash
|
Otevřete složku `mobile` v Android Studiu, nechte dokončit synchronizaci Gradle a spusťte aplikaci na Androidu 8.0 nebo novějším. Na úvodní obrazovce lze zvolit **Prohlédnout ukázku** bez běžícího serveru. Vlastní backend se nastavuje přes **Nastavení serveru**; výchozí adresa pro emulátor je `http://10.0.2.2:8080/`.
|
||||||
dotnet run --project web/Helpdesk.Web
|
|
||||||
```
|
|
||||||
|
|
||||||
Testy webové aplikace:
|
Pokud jste v `deploy/.env` nastavili `API_PORT=8081`, zadejte v aplikaci `http://10.0.2.2:8081/`.
|
||||||
|
|
||||||
```bash
|
Podrobný postup sestavení, rozsah funkcí a stav napojení na API: [mobile/README.md](mobile/README.md).
|
||||||
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,17 +15,12 @@
|
|||||||
<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.SwaggerGen" Version="10.3.1" />
|
<PackageVersion Include="Swashbuckle.AspNetCore" 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="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,8 +15,6 @@ 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
|
||||||
@@ -99,18 +97,6 @@ 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
|
||||||
|
|||||||
@@ -1,32 +0,0 @@
|
|||||||
using Helpdesk.Api.Infrastructure;
|
|
||||||
using Helpdesk.Application.Common;
|
|
||||||
using Helpdesk.Application.Notifications;
|
|
||||||
using Microsoft.AspNetCore.Authorization;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
|
|
||||||
namespace Helpdesk.Api.Controllers;
|
|
||||||
|
|
||||||
[ApiController]
|
|
||||||
[Authorize(Roles = Roles.Admin)]
|
|
||||||
[Route(ApiRoutes.V1 + "/admin/notification-deliveries")]
|
|
||||||
public sealed class AdminNotificationDeliveriesController(NotificationDeliveryService deliveries) : ControllerBase
|
|
||||||
{
|
|
||||||
/// <summary>Přehled doručení podle stavu, výchozí stav je FAILED.</summary>
|
|
||||||
[HttpGet]
|
|
||||||
[ProducesResponseType<PagedResult<NotificationDeliveryDto>>(StatusCodes.Status200OK)]
|
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
|
||||||
public Task<PagedResult<NotificationDeliveryDto>> List(
|
|
||||||
CancellationToken ct, [FromQuery] string status = "FAILED", [FromQuery] int page = 1, [FromQuery] int pageSize = 20) =>
|
|
||||||
deliveries.ListAsync(status, page, pageSize, ct);
|
|
||||||
|
|
||||||
/// <summary>Vrátí neúspěšné doručení do fronty s novým počtem pokusů.</summary>
|
|
||||||
[HttpPost("{id:int}/retry")]
|
|
||||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
|
||||||
public async Task<IActionResult> Retry(int id, CancellationToken ct)
|
|
||||||
{
|
|
||||||
await deliveries.RetryAsync(id, ct);
|
|
||||||
return NoContent();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -10,7 +10,7 @@ namespace Helpdesk.Api.Controllers;
|
|||||||
/// <summary>Správa uživatelů a rolí (jen administrátor).</summary>
|
/// <summary>Správa uživatelů a rolí (jen administrátor).</summary>
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Authorize(Roles = Roles.Admin)]
|
[Authorize(Roles = Roles.Admin)]
|
||||||
[Route(ApiRoutes.V1 + "/admin/users")]
|
[Route("api/admin/users")]
|
||||||
[Produces("application/json")]
|
[Produces("application/json")]
|
||||||
public sealed class AdminUsersController(UserService users, ICurrentUser currentUser) : ControllerBase
|
public sealed class AdminUsersController(UserService users, ICurrentUser currentUser) : ControllerBase
|
||||||
{
|
{
|
||||||
@@ -22,53 +22,6 @@ 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)]
|
||||||
@@ -83,7 +36,6 @@ 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)
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
using Helpdesk.Api.Infrastructure;
|
|
||||||
using Helpdesk.Application.Issues;
|
using Helpdesk.Application.Issues;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
@@ -8,7 +7,7 @@ namespace Helpdesk.Api.Controllers;
|
|||||||
[ApiController]
|
[ApiController]
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||||
[Route(ApiRoutes.V1 + "/attachments")]
|
[Route("api/attachments")]
|
||||||
public sealed class AttachmentsController(IssueService issues) : ControllerBase
|
public sealed class AttachmentsController(IssueService issues) : ControllerBase
|
||||||
{
|
{
|
||||||
[HttpGet("{id:int}")]
|
[HttpGet("{id:int}")]
|
||||||
|
|||||||
@@ -10,29 +10,28 @@ namespace Helpdesk.Api.Controllers;
|
|||||||
|
|
||||||
/// <summary>Registrace, přihlášení a správa tokenů.</summary>
|
/// <summary>Registrace, přihlášení a správa tokenů.</summary>
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Route(ApiRoutes.V1 + "/auth")]
|
[Route("api/auth")]
|
||||||
[EnableRateLimiting(RateLimitPolicies.Auth)]
|
[EnableRateLimiting(RateLimitPolicies.Auth)]
|
||||||
[Produces("application/json")]
|
[Produces("application/json")]
|
||||||
public sealed class AuthController(AuthService auth) : ControllerBase
|
public sealed class AuthController(AuthService auth) : ControllerBase
|
||||||
{
|
{
|
||||||
/// <summary>Registrace e-mailem. Role (student / vyučující) se určí podle domény e-mailu.</summary>
|
/// <summary>Registrace e-mailem a heslem. Role (student / vyučující) se určí podle domény e-mailu.</summary>
|
||||||
/// <remarks>Heslo se nastavuje až po otevření ověřovacího odkazu z e-mailu.</remarks>
|
/// <remarks>Po registraci přijde e-mail s odkazem pro ověření; bez ověření se nelze přihlásit.</remarks>
|
||||||
[HttpPost("register")]
|
[HttpPost("register")]
|
||||||
[ProducesResponseType<UserDto>(StatusCodes.Status201Created)]
|
[ProducesResponseType<UserDto>(StatusCodes.Status201Created)]
|
||||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status503ServiceUnavailable)]
|
|
||||||
public async Task<ActionResult<UserDto>> Register(RegisterRequest request, CancellationToken ct)
|
public async Task<ActionResult<UserDto>> Register(RegisterRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var user = await auth.RegisterAsync(request, ct);
|
var user = await auth.RegisterAsync(request, ct);
|
||||||
return Created($"/{ApiRoutes.V1}/users/me", user);
|
return Created("/api/users/me", user);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Ověří e-mail jednorázovým tokenem a nastaví heslo k účtu.</summary>
|
/// <summary>Ověření e-mailu tokenem z registračního e-mailu (jednorázový).</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(ConfirmEmailRequest request, CancellationToken ct)
|
public async Task<IActionResult> ConfirmEmail(EmailTokenRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
await auth.ConfirmEmailAsync(request, ct);
|
await auth.ConfirmEmailAsync(request, ct);
|
||||||
return NoContent();
|
return NoContent();
|
||||||
@@ -42,15 +41,8 @@ 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.Status429TooManyRequests)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
||||||
public async Task<ActionResult<AuthResponse>> Login(LoginRequest request, [FromServices] LoginRateLimiter limiter, CancellationToken ct)
|
public Task<AuthResponse> Login(LoginRequest request, CancellationToken ct) => auth.LoginAsync(request, 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>
|
||||||
@@ -69,7 +61,7 @@ public sealed class AuthController(AuthService auth) : ControllerBase
|
|||||||
return NoContent();
|
return NoContent();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Odhlášení ze všech zařízení. Zneplatní tokeny a odstraní registrace pro push.</summary>
|
/// <summary>Odhlášení ze všech zařízení – zneplatní všechny tokeny uživatele.</summary>
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[HttpPost("logout-all")]
|
[HttpPost("logout-all")]
|
||||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
@@ -82,10 +74,9 @@ public sealed class AuthController(AuthService auth) : ControllerBase
|
|||||||
/// <summary>Odešle e-mail s odkazem pro nastavení nového hesla. Odpověď je stejná, ať účet existuje, nebo ne.</summary>
|
/// <summary>Odešle e-mail s odkazem pro nastavení nového hesla. Odpověď je stejná, ať účet existuje, nebo ne.</summary>
|
||||||
[HttpPost("forgot-password")]
|
[HttpPost("forgot-password")]
|
||||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
public IActionResult ForgotPassword(ForgotPasswordRequest request, [FromServices] IHostApplicationLifetime lifetime)
|
public async Task<IActionResult> ForgotPassword(ForgotPasswordRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
// Doba vyhledání účtu a doručení přes SMTP se nesmí projevit v době odpovědi.
|
await auth.ForgotPasswordAsync(request, ct);
|
||||||
Response.OnCompleted(() => auth.ForgotPasswordAsync(request, lifetime.ApplicationStopping));
|
|
||||||
return NoContent();
|
return NoContent();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ namespace Helpdesk.Api.Controllers;
|
|||||||
/// <summary>Číselníky pro formuláře (budovy, kategorie závad a návrhů) a jejich správa.</summary>
|
/// <summary>Číselníky pro formuláře (budovy, kategorie závad a návrhů) a jejich správa.</summary>
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[Route(ApiRoutes.V1)]
|
[Route("api")]
|
||||||
[Produces("application/json")]
|
[Produces("application/json")]
|
||||||
public sealed class CatalogsController(CatalogService catalogs) : ControllerBase
|
public sealed class CatalogsController(CatalogService catalogs) : ControllerBase
|
||||||
{
|
{
|
||||||
@@ -17,6 +17,12 @@ public sealed class CatalogsController(CatalogService catalogs) : ControllerBase
|
|||||||
public Task<IReadOnlyList<BuildingDto>> GetBuildings([FromQuery] bool includeInactive = false, CancellationToken ct = default) =>
|
public Task<IReadOnlyList<BuildingDto>> GetBuildings([FromQuery] bool includeInactive = false, CancellationToken ct = default) =>
|
||||||
catalogs.GetBuildingsAsync(includeInactive && User.IsInRole(Roles.Admin), ct);
|
catalogs.GetBuildingsAsync(includeInactive && User.IsInRole(Roles.Admin), ct);
|
||||||
|
|
||||||
|
[HttpGet("issue-categories")]
|
||||||
|
public Task<IReadOnlyList<CategoryDto>> GetIssueCategories(CancellationToken ct) => catalogs.GetIssueCategoriesAsync(ct);
|
||||||
|
|
||||||
|
[HttpGet("proposal-categories")]
|
||||||
|
public Task<IReadOnlyList<CategoryDto>> GetProposalCategories(CancellationToken ct) => catalogs.GetProposalCategoriesAsync(ct);
|
||||||
|
|
||||||
[Authorize(Roles = Roles.Admin)]
|
[Authorize(Roles = Roles.Admin)]
|
||||||
[HttpPost("buildings")]
|
[HttpPost("buildings")]
|
||||||
[ProducesResponseType<BuildingDto>(StatusCodes.Status201Created)]
|
[ProducesResponseType<BuildingDto>(StatusCodes.Status201Created)]
|
||||||
@@ -24,7 +30,7 @@ public sealed class CatalogsController(CatalogService catalogs) : ControllerBase
|
|||||||
public async Task<ActionResult<BuildingDto>> CreateBuilding(SaveBuildingRequest request, CancellationToken ct)
|
public async Task<ActionResult<BuildingDto>> CreateBuilding(SaveBuildingRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var building = await catalogs.CreateBuildingAsync(request, ct);
|
var building = await catalogs.CreateBuildingAsync(request, ct);
|
||||||
return Created($"/{ApiRoutes.V1}/buildings/{building.Id}", building);
|
return Created($"/api/buildings/{building.Id}", building);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Authorize(Roles = Roles.Admin)]
|
[Authorize(Roles = Roles.Admin)]
|
||||||
@@ -45,76 +51,4 @@ public sealed class CatalogsController(CatalogService catalogs) : ControllerBase
|
|||||||
await catalogs.DeactivateBuildingAsync(id, ct);
|
await catalogs.DeactivateBuildingAsync(id, ct);
|
||||||
return NoContent();
|
return NoContent();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Kategorie závad. Administrátor může zobrazit i deaktivované pomocí <c>includeInactive=true</c>.</summary>
|
|
||||||
[HttpGet("issue-categories")]
|
|
||||||
public Task<IReadOnlyList<CategoryDto>> GetIssueCategories([FromQuery] bool includeInactive = false, CancellationToken ct = default) =>
|
|
||||||
catalogs.GetIssueCategoriesAsync(includeInactive && User.IsInRole(Roles.Admin), ct);
|
|
||||||
|
|
||||||
[Authorize(Roles = Roles.Admin)]
|
|
||||||
[HttpPost("issue-categories")]
|
|
||||||
[ProducesResponseType<CategoryDto>(StatusCodes.Status201Created)]
|
|
||||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
|
||||||
public async Task<ActionResult<CategoryDto>> CreateIssueCategory(SaveCategoryRequest request, CancellationToken ct)
|
|
||||||
{
|
|
||||||
var category = await catalogs.CreateIssueCategoryAsync(request, ct);
|
|
||||||
return Created($"/{ApiRoutes.V1}/issue-categories/{category.Id}", category);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Authorize(Roles = Roles.Admin)]
|
|
||||||
[HttpPut("issue-categories/{id:int}")]
|
|
||||||
[ProducesResponseType<CategoryDto>(StatusCodes.Status200OK)]
|
|
||||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
|
||||||
public Task<CategoryDto> UpdateIssueCategory(int id, SaveCategoryRequest request, CancellationToken ct) =>
|
|
||||||
catalogs.UpdateIssueCategoryAsync(id, request, ct);
|
|
||||||
|
|
||||||
/// <summary>Deaktivuje kategorii závad.</summary>
|
|
||||||
[Authorize(Roles = Roles.Admin)]
|
|
||||||
[HttpDelete("issue-categories/{id:int}")]
|
|
||||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
|
||||||
public async Task<IActionResult> DeactivateIssueCategory(int id, CancellationToken ct)
|
|
||||||
{
|
|
||||||
await catalogs.DeactivateIssueCategoryAsync(id, ct);
|
|
||||||
return NoContent();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Kategorie návrhů. Administrátor může zobrazit i deaktivované pomocí <c>includeInactive=true</c>.</summary>
|
|
||||||
[HttpGet("proposal-categories")]
|
|
||||||
public Task<IReadOnlyList<CategoryDto>> GetProposalCategories([FromQuery] bool includeInactive = false, CancellationToken ct = default) =>
|
|
||||||
catalogs.GetProposalCategoriesAsync(includeInactive && User.IsInRole(Roles.Admin), ct);
|
|
||||||
|
|
||||||
[Authorize(Roles = Roles.Admin)]
|
|
||||||
[HttpPost("proposal-categories")]
|
|
||||||
[ProducesResponseType<CategoryDto>(StatusCodes.Status201Created)]
|
|
||||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
|
||||||
public async Task<ActionResult<CategoryDto>> CreateProposalCategory(SaveCategoryRequest request, CancellationToken ct)
|
|
||||||
{
|
|
||||||
var category = await catalogs.CreateProposalCategoryAsync(request, ct);
|
|
||||||
return Created($"/{ApiRoutes.V1}/proposal-categories/{category.Id}", category);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Authorize(Roles = Roles.Admin)]
|
|
||||||
[HttpPut("proposal-categories/{id:int}")]
|
|
||||||
[ProducesResponseType<CategoryDto>(StatusCodes.Status200OK)]
|
|
||||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
|
||||||
public Task<CategoryDto> UpdateProposalCategory(int id, SaveCategoryRequest request, CancellationToken ct) =>
|
|
||||||
catalogs.UpdateProposalCategoryAsync(id, request, ct);
|
|
||||||
|
|
||||||
/// <summary>Deaktivuje kategorii návrhů.</summary>
|
|
||||||
[Authorize(Roles = Roles.Admin)]
|
|
||||||
[HttpDelete("proposal-categories/{id:int}")]
|
|
||||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
|
||||||
public async Task<IActionResult> DeactivateProposalCategory(int id, CancellationToken ct)
|
|
||||||
{
|
|
||||||
await catalogs.DeactivateProposalCategoryAsync(id, ct);
|
|
||||||
return NoContent();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
using Helpdesk.Api.Infrastructure;
|
|
||||||
using Helpdesk.Application.Notifications;
|
|
||||||
using Microsoft.AspNetCore.Authorization;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
|
|
||||||
namespace Helpdesk.Api.Controllers;
|
|
||||||
|
|
||||||
public sealed record RegisterDeviceRequest(string Token);
|
|
||||||
|
|
||||||
[ApiController]
|
|
||||||
[Authorize]
|
|
||||||
[Route(ApiRoutes.V1 + "/devices")]
|
|
||||||
public sealed class DevicesController(PushDeviceService devices) : ControllerBase
|
|
||||||
{
|
|
||||||
/// <summary>Zaregistruje FCM token pro právě přihlášeného uživatele.</summary>
|
|
||||||
[HttpPost]
|
|
||||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
|
||||||
public async Task<IActionResult> Register(RegisterDeviceRequest request, CancellationToken ct)
|
|
||||||
{
|
|
||||||
await devices.RegisterAsync(request.Token, ct);
|
|
||||||
return NoContent();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Odregistruje token právě přihlášeného uživatele.</summary>
|
|
||||||
[HttpDelete("{token}")]
|
|
||||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
|
||||||
public async Task<IActionResult> Unregister(string token, CancellationToken ct)
|
|
||||||
{
|
|
||||||
await devices.UnregisterAsync(token, ct);
|
|
||||||
return NoContent();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -16,7 +16,7 @@ namespace Helpdesk.Api.Controllers;
|
|||||||
[ApiController]
|
[ApiController]
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||||
[Route(ApiRoutes.V1 + "/issues")]
|
[Route("api/issues")]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
||||||
@@ -41,7 +41,6 @@ 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)]
|
||||||
@@ -56,7 +55,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") ?? 0,
|
ReadId(form, "categoryId") ?? throw new BadRequestException("Kategorie je povinná."),
|
||||||
ReadId(form, "buildingId"), form["locationDetail"].ToString());
|
ReadId(form, "buildingId"), form["locationDetail"].ToString());
|
||||||
uploads = ReadUploads(form.Files);
|
uploads = ReadUploads(form.Files);
|
||||||
}
|
}
|
||||||
@@ -88,7 +87,6 @@ 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);
|
||||||
|
|
||||||
@@ -162,16 +160,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 FieldValidationException(key, "Zadejte platné ID.");
|
throw new BadRequestException($"Neplatná hodnota {key}.");
|
||||||
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 FieldValidationException("files", "Najednou lze přiložit nejvýše pět souborů.");
|
throw new BadRequestException("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 FieldValidationException("files", "Přílohy patří do pole files.");
|
throw new BadRequestException("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();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
using Helpdesk.Application.Common;
|
using Helpdesk.Application.Common;
|
||||||
using Helpdesk.Api.Infrastructure;
|
|
||||||
using Helpdesk.Application.Notifications;
|
using Helpdesk.Application.Notifications;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
@@ -8,7 +7,7 @@ namespace Helpdesk.Api.Controllers;
|
|||||||
|
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[Route(ApiRoutes.V1 + "/notifications")]
|
[Route("api/notifications")]
|
||||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
||||||
public sealed class NotificationsController(NotificationService notifications) : ControllerBase
|
public sealed class NotificationsController(NotificationService notifications) : ControllerBase
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ namespace Helpdesk.Api.Controllers;
|
|||||||
[ApiController]
|
[ApiController]
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||||
[Route(ApiRoutes.V1 + "/proposals")]
|
[Route("api/proposals")]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
||||||
@@ -17,15 +17,9 @@ namespace Helpdesk.Api.Controllers;
|
|||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||||
public sealed class ProposalsController(ProposalService proposals) : ControllerBase
|
public sealed class ProposalsController(ProposalService proposals) : ControllerBase
|
||||||
{
|
{
|
||||||
/// <summary>Seznam návrhů s volitelným filtrem podle data podání.</summary>
|
|
||||||
/// <param name="query">Filtry, řazení a stránkování.</param>
|
|
||||||
/// <param name="from">Dolní hranice data podání včetně.</param>
|
|
||||||
/// <param name="to">Horní hranice data podání bez uvedeného okamžiku.</param>
|
|
||||||
/// <param name="ct">Token pro zrušení požadavku.</param>
|
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
public Task<PagedResult<ProposalSummary>> List([FromQuery] ProposalQuery query,
|
public Task<PagedResult<ProposalSummary>> List([FromQuery] ProposalQuery query, CancellationToken ct) =>
|
||||||
[FromQuery] DateTimeOffset? from, [FromQuery] DateTimeOffset? to, CancellationToken ct) =>
|
proposals.ListAsync(query, ct);
|
||||||
proposals.ListAsync(query, from, to, ct);
|
|
||||||
|
|
||||||
[HttpGet("{id:int}")]
|
[HttpGet("{id:int}")]
|
||||||
public Task<ProposalDetail> Get(int id, CancellationToken ct) => proposals.GetAsync(id, ct);
|
public Task<ProposalDetail> Get(int id, CancellationToken ct) => proposals.GetAsync(id, ct);
|
||||||
@@ -62,7 +56,7 @@ public sealed class ProposalsController(ProposalService proposals) : ControllerB
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("{id:int}/status")]
|
[HttpPost("{id:int}/status")]
|
||||||
[Authorize(Roles = Roles.ManagementOrAdmin)]
|
[Authorize(Roles = Roles.Management)]
|
||||||
[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);
|
||||||
|
|||||||
@@ -1,61 +0,0 @@
|
|||||||
using System.ComponentModel.DataAnnotations;
|
|
||||||
using Helpdesk.Api.Infrastructure;
|
|
||||||
using Helpdesk.Application.Statistics;
|
|
||||||
using Microsoft.AspNetCore.Authorization;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
|
|
||||||
namespace Helpdesk.Api.Controllers;
|
|
||||||
|
|
||||||
/// <summary>Statistiky pro vedení školy a administrátory. Období v UTC zahrnuje začátek a vylučuje konec.</summary>
|
|
||||||
[ApiController]
|
|
||||||
[Authorize(Roles = Roles.ManagementOrAdmin)]
|
|
||||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
|
||||||
[Route(ApiRoutes.V1 + "/statistics")]
|
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
|
||||||
public sealed class StatisticsController(StatisticsService statistics) : ControllerBase
|
|
||||||
{
|
|
||||||
/// <summary>Počty podle aktuálního stavu a průměrné časy pro závady nahlášené v období.</summary>
|
|
||||||
[HttpGet("overview")]
|
|
||||||
public Task<StatisticsOverview> GetOverview([FromQuery] StatisticsQuery query, CancellationToken ct) =>
|
|
||||||
statistics.GetOverviewAsync(query.ToPeriod(), ct);
|
|
||||||
|
|
||||||
/// <summary>Počty nahlášených závad a průměrná doba vyřešení podle kategorie.</summary>
|
|
||||||
[HttpGet("issues/by-category")]
|
|
||||||
public Task<IReadOnlyList<IssueCategoryStatistics>> GetByCategory([FromQuery] StatisticsQuery query, CancellationToken ct) =>
|
|
||||||
statistics.GetByCategoryAsync(query.ToPeriod(), ct);
|
|
||||||
|
|
||||||
/// <summary>Počty nahlášených závad podle budovy včetně závad bez budovy.</summary>
|
|
||||||
[HttpGet("issues/by-building")]
|
|
||||||
public Task<IReadOnlyList<IssueBuildingStatistics>> GetByBuilding([FromQuery] StatisticsQuery query, CancellationToken ct) =>
|
|
||||||
statistics.GetByBuildingAsync(query.ToPeriod(), ct);
|
|
||||||
|
|
||||||
/// <summary>Otevřené, vyřešené a zamítnuté závady podle aktuálního řešitele.</summary>
|
|
||||||
[HttpGet("issues/by-assignee")]
|
|
||||||
public Task<IReadOnlyList<IssueAssigneeStatistics>> GetByAssignee([FromQuery] StatisticsQuery query, CancellationToken ct) =>
|
|
||||||
statistics.GetByAssigneeAsync(query.ToPeriod(), ct);
|
|
||||||
|
|
||||||
/// <summary>Počty vytvoření a uzavření závad po měsících podle data události.</summary>
|
|
||||||
[HttpGet("issues/trend")]
|
|
||||||
public Task<IReadOnlyList<IssueTrendPoint>> GetTrend([FromQuery] StatisticsQuery query, CancellationToken ct,
|
|
||||||
[FromQuery, AllowedValues("month")] string granularity = "month") =>
|
|
||||||
statistics.GetTrendAsync(query.ToPeriod(), ct);
|
|
||||||
|
|
||||||
/// <summary>Návrhy podané v období podle aktuálního skóre, počtu hlasů pro a data podání.</summary>
|
|
||||||
[HttpGet("proposals/top")]
|
|
||||||
public Task<IReadOnlyList<TopProposal>> GetTopProposals([FromQuery] StatisticsQuery query, CancellationToken ct,
|
|
||||||
[FromQuery, Range(1, 100)] int limit = 10) =>
|
|
||||||
statistics.GetTopProposalsAsync(query.ToPeriod(), limit, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed class StatisticsQuery
|
|
||||||
{
|
|
||||||
[FromQuery(Name = "from")]
|
|
||||||
public DateTimeOffset? From { get; init; }
|
|
||||||
|
|
||||||
[FromQuery(Name = "to")]
|
|
||||||
public DateTimeOffset? To { get; init; }
|
|
||||||
|
|
||||||
internal StatisticsPeriod ToPeriod() => new(From, To);
|
|
||||||
}
|
|
||||||
@@ -10,7 +10,7 @@ namespace Helpdesk.Api.Controllers;
|
|||||||
/// <summary>Profil přihlášeného uživatele.</summary>
|
/// <summary>Profil přihlášeného uživatele.</summary>
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[Route(ApiRoutes.V1 + "/users")]
|
[Route("api/users")]
|
||||||
[Produces("application/json")]
|
[Produces("application/json")]
|
||||||
public sealed class UsersController(UserService users, ICurrentUser currentUser, IssueService issues) : ControllerBase
|
public sealed class UsersController(UserService users, ICurrentUser currentUser, IssueService issues) : ControllerBase
|
||||||
{
|
{
|
||||||
@@ -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.ManagementOrAdmin)]
|
[Authorize(Roles = Roles.Management)]
|
||||||
[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.SwaggerGen" />
|
<PackageReference Include="Swashbuckle.AspNetCore" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
namespace Helpdesk.Api.Infrastructure;
|
|
||||||
|
|
||||||
internal static class ApiRoutes
|
|
||||||
{
|
|
||||||
public const string V1 = "api/v1";
|
|
||||||
}
|
|
||||||
@@ -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, Type = app.ProblemType },
|
AppException app => new ProblemDetails { Status = app.StatusCode, Title = app.Message },
|
||||||
BadHttpRequestException request => new ProblemDetails { Status = request.StatusCode },
|
BadHttpRequestException request => new ProblemDetails { Status = request.StatusCode },
|
||||||
_ => null,
|
_ => null,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -43,10 +43,4 @@ 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";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
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,5 +8,4 @@ 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,7 +2,6 @@ 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;
|
||||||
|
|
||||||
@@ -10,7 +9,7 @@ public static class SwaggerSetup
|
|||||||
{
|
{
|
||||||
private const string SchemeId = "Bearer";
|
private const string SchemeId = "Bearer";
|
||||||
|
|
||||||
/// <summary>Generování OpenAPI dokumentu pro administrátorské Swagger UI (NFR-04).</summary>
|
/// <summary>Swagger UI na <c>/swagger</c> včetně přihlášení access tokenem (NFR-04).</summary>
|
||||||
public static IServiceCollection AddHelpdeskSwagger(this IServiceCollection services)
|
public static IServiceCollection AddHelpdeskSwagger(this IServiceCollection services)
|
||||||
{
|
{
|
||||||
services.AddEndpointsApiExplorer();
|
services.AddEndpointsApiExplorer();
|
||||||
@@ -20,7 +19,7 @@ public static class SwaggerSetup
|
|||||||
{
|
{
|
||||||
Title = "Univerzitní helpdesk – API",
|
Title = "Univerzitní helpdesk – API",
|
||||||
Version = "v1",
|
Version = "v1",
|
||||||
Description = $"REST API pro webovou a mobilní aplikaci. Access token získáte přes POST /{ApiRoutes.V1}/auth/login.",
|
Description = "REST API pro webovou a mobilní aplikaci. Access token získáte přes POST /api/auth/login.",
|
||||||
});
|
});
|
||||||
|
|
||||||
options.AddSecurityDefinition(SchemeId, new OpenApiSecurityScheme
|
options.AddSecurityDefinition(SchemeId, new OpenApiSecurityScheme
|
||||||
@@ -35,7 +34,6 @@ 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))
|
||||||
@@ -45,30 +43,6 @@ 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)
|
||||||
|
|||||||
@@ -1,23 +1,14 @@
|
|||||||
using System.Net;
|
|
||||||
using System.Threading.RateLimiting;
|
using System.Threading.RateLimiting;
|
||||||
using Helpdesk.Api.Infrastructure;
|
using Helpdesk.Api.Infrastructure;
|
||||||
using Helpdesk.Application;
|
using Helpdesk.Application;
|
||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
using Helpdesk.Application.Auth;
|
|
||||||
using Helpdesk.Infrastructure;
|
using Helpdesk.Infrastructure;
|
||||||
using Microsoft.AspNetCore.HttpOverrides;
|
|
||||||
using Microsoft.IdentityModel.JsonWebTokens;
|
using Microsoft.IdentityModel.JsonWebTokens;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
builder.Services.AddApplication(builder.Configuration);
|
builder.Services.AddApplication(builder.Configuration);
|
||||||
builder.Services.AddInfrastructure(builder.Configuration, builder.Environment);
|
builder.Services.AddInfrastructure(builder.Configuration);
|
||||||
builder.Services.AddOptions<RegistrationOptions>()
|
|
||||||
.Validate(options => Uri.TryCreate(options.WebBaseUrl, UriKind.Absolute, out var url) &&
|
|
||||||
(url.Scheme == Uri.UriSchemeHttps || (builder.Environment.IsDevelopment() && url.Scheme == Uri.UriSchemeHttp)) &&
|
|
||||||
string.IsNullOrEmpty(url.UserInfo) && string.IsNullOrEmpty(url.Query) && string.IsNullOrEmpty(url.Fragment),
|
|
||||||
"Nastavte Registration:WebBaseUrl na veřejnou HTTPS adresu webové aplikace bez parametrů.")
|
|
||||||
.ValidateOnStart();
|
|
||||||
|
|
||||||
builder.Services.AddHttpContextAccessor();
|
builder.Services.AddHttpContextAccessor();
|
||||||
builder.Services.AddScoped<ICurrentUser, HttpCurrentUser>();
|
builder.Services.AddScoped<ICurrentUser, HttpCurrentUser>();
|
||||||
@@ -30,31 +21,12 @@ builder.Services.AddProblemDetails();
|
|||||||
builder.Services.AddExceptionHandler<AppExceptionHandler>();
|
builder.Services.AddExceptionHandler<AppExceptionHandler>();
|
||||||
builder.Services.AddHelpdeskSwagger();
|
builder.Services.AddHelpdeskSwagger();
|
||||||
|
|
||||||
var trustedProxies = new[] { "ReverseProxy:TrustedIp", "ReverseProxy:TrustedWebIp" }
|
|
||||||
.Where(key => !string.IsNullOrWhiteSpace(builder.Configuration[key]))
|
|
||||||
.Select(key => IPAddress.TryParse(builder.Configuration[key], out var address) ? address
|
|
||||||
: throw new InvalidOperationException($"Nastavte platnou IP adresu v {key}."))
|
|
||||||
.ToArray();
|
|
||||||
|
|
||||||
if (trustedProxies.Length > 0)
|
|
||||||
{
|
|
||||||
builder.Services.Configure<ForwardedHeadersOptions>(options =>
|
|
||||||
{
|
|
||||||
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
|
|
||||||
options.KnownIPNetworks.Clear();
|
|
||||||
options.KnownProxies.Clear();
|
|
||||||
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(
|
||||||
RateLimitPolicies.ClientIp(http),
|
http.Connection.RemoteIpAddress?.ToString() ?? "unknown",
|
||||||
_ => 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",
|
||||||
@@ -68,18 +40,20 @@ builder.Services.AddRateLimiter(options =>
|
|||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
|
|
||||||
if (trustedProxies.Length > 0)
|
|
||||||
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();
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
using Helpdesk.Application.Statistics;
|
|
||||||
using Helpdesk.Domain.Auth;
|
using Helpdesk.Domain.Auth;
|
||||||
using Helpdesk.Domain.Catalogs;
|
using Helpdesk.Domain.Catalogs;
|
||||||
using Helpdesk.Domain.Issues;
|
using Helpdesk.Domain.Issues;
|
||||||
@@ -19,7 +18,6 @@ public interface IAppDbContext
|
|||||||
DbSet<ProposalCategory> ProposalCategories { get; }
|
DbSet<ProposalCategory> ProposalCategories { get; }
|
||||||
DbSet<Issue> Issues { get; }
|
DbSet<Issue> Issues { get; }
|
||||||
DbSet<IssueEvent> IssueEvents { get; }
|
DbSet<IssueEvent> IssueEvents { get; }
|
||||||
IQueryable<IssueTiming> IssueTimings { get; }
|
|
||||||
DbSet<Attachment> Attachments { get; }
|
DbSet<Attachment> Attachments { get; }
|
||||||
DbSet<Proposal> Proposals { get; }
|
DbSet<Proposal> Proposals { get; }
|
||||||
DbSet<ProposalEvent> ProposalEvents { get; }
|
DbSet<ProposalEvent> ProposalEvents { get; }
|
||||||
@@ -30,16 +28,14 @@ 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> BeginWriteAsync(CancellationToken ct);
|
Task<IDbContextTransaction> BeginProposalWriteAsync(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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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 FirstName, string LastName);
|
public sealed record RegisterRequest(string Email, string Password, 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);
|
||||||
|
|
||||||
public sealed record ConfirmEmailRequest(string Token, string NewPassword);
|
/// <summary>Token z odkazu v e-mailu (ověření e-mailu).</summary>
|
||||||
|
public sealed record EmailTokenRequest(string Token);
|
||||||
|
|
||||||
public sealed record ForgotPasswordRequest(string Email);
|
public sealed record ForgotPasswordRequest(string Email);
|
||||||
|
|
||||||
@@ -26,15 +26,11 @@ public sealed record AuthResponse(
|
|||||||
|
|
||||||
internal static class PasswordRules
|
internal static class PasswordRules
|
||||||
{
|
{
|
||||||
private const int MinLength = 8;
|
public const int MinLength = 8;
|
||||||
private const int MaxLength = 64;
|
public const int MaxLength = 64; // BCrypt zpracuje nejvýše 72 bajtů
|
||||||
private const int MaxUtf8Bytes = 72;
|
|
||||||
|
|
||||||
public static IRuleBuilderOptions<T, string?> ValidPassword<T>(this IRuleBuilderInitial<T, string?> rule) =>
|
public static IRuleBuilderOptions<T, string> ValidPassword<T>(this IRuleBuilder<T, string> rule) =>
|
||||||
rule.Cascade(CascadeMode.Stop)
|
rule.NotEmpty().MinimumLength(MinLength).MaximumLength(MaxLength);
|
||||||
.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>
|
||||||
@@ -42,20 +38,12 @@ 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,65 +29,56 @@ 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 FieldValidationException(nameof(request.Email), "Registrace je možná jen s univerzitním e-mailem.");
|
?? throw new BadRequestException("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);
|
if (await db.Users.AnyAsync(u => u.EmailNormalized == normalized, ct))
|
||||||
if (user is null)
|
|
||||||
{
|
|
||||||
user = User.Create(request.Email, "", request.FirstName, request.LastName, role);
|
|
||||||
db.Users.Add(user);
|
|
||||||
await db.SaveChangesAsync(ct);
|
|
||||||
}
|
|
||||||
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 SendEmailConfirmationAsync(user, ct);
|
var user = User.Create(request.Email, passwordHasher.Hash(request.Password), request.FirstName, request.LastName, role);
|
||||||
|
db.Users.Add(user);
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
|
||||||
|
await SendEmailTokenAsync(user, TokenType.EmailConfirm, ct);
|
||||||
return UserDto.From(user);
|
return UserDto.From(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
internal Task<bool> SendEmailConfirmationAsync(User user, CancellationToken ct) =>
|
public async Task ConfirmEmailAsync(EmailTokenRequest request, 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 account = await db.Users.Where(u => u.EmailNormalized == normalized && u.IsActive && !u.IsDeleted && u.EmailConfirmed)
|
var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized, ct);
|
||||||
.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.";
|
||||||
var passwordHash = account?.EmailNormalized == normalized ? account.PasswordHash : null;
|
if (user is 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.");
|
||||||
|
|
||||||
// Po ověření hesla ověříme pod zámkem, že se účet mezitím nezměnil.
|
if (!passwordHasher.Verify(request.Password, user.PasswordHash))
|
||||||
await using var transaction = await db.BeginWriteAsync(ct);
|
{
|
||||||
var user = await db.LockUserAsync(account.Id, ct);
|
user.RegisterFailedLogin(now);
|
||||||
if (user is not { IsActive: true, IsDeleted: false, EmailConfirmed: true } ||
|
await db.SaveChangesAsync(ct);
|
||||||
user.EmailNormalized != normalized || user.PasswordHash != passwordHash)
|
|
||||||
throw new UnauthorizedException(invalidCredentials);
|
throw new UnauthorizedException(invalidCredentials);
|
||||||
|
}
|
||||||
|
|
||||||
var response = await IssueTokenPairAsync(user, ct);
|
if (!user.IsActive)
|
||||||
await transaction.CommitAsync(ct);
|
throw new ForbiddenException("Účet je deaktivován.");
|
||||||
return response;
|
if (!user.EmailConfirmed)
|
||||||
|
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>
|
||||||
@@ -99,23 +90,17 @@ 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.");
|
||||||
|
|
||||||
// Stejný zámek účtu používá jeho správa, takže během zneplatnění nevznikne nová relace.
|
if (!await revocation.TryConsumeAsync(token.Jti, TokenType.Refresh, ct))
|
||||||
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))
|
|
||||||
{
|
{
|
||||||
var response = await IssueTokenPairAsync(user, ct);
|
await revocation.RevokeAllAsync(token.UserId, RevokeReason.ReuseDetected, ct);
|
||||||
await transaction.CommitAsync(ct);
|
throw new UnauthorizedException("Refresh token už byl použit. Přihlaste se znovu.");
|
||||||
return response;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var revoked = await StageDisconnectAsync(user.Id, RevokeReason.ReuseDetected, ct);
|
var user = await db.Users.SingleOrDefaultAsync(u => u.Id == token.UserId, ct);
|
||||||
await transaction.CommitAsync(ct);
|
if (user is null || !user.IsActive)
|
||||||
revocation.Publish(revoked);
|
throw new UnauthorizedException("Účet neexistuje nebo je deaktivován.");
|
||||||
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>
|
||||||
@@ -130,54 +115,28 @@ public sealed class AuthService(
|
|||||||
await revocation.RevokeAsync(currentUser.Id, jtis, RevokeReason.Logout, ct);
|
await revocation.RevokeAsync(currentUser.Id, jtis, RevokeReason.Logout, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task LogoutAllAsync(ICurrentUser currentUser, CancellationToken ct)
|
public 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)
|
||||||
{
|
{
|
||||||
var normalized = User.NormalizeEmail(request.Email ?? "");
|
var normalized = User.NormalizeEmail(request.Email ?? "");
|
||||||
var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized && u.IsActive, ct);
|
var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized && u.IsActive, ct);
|
||||||
if (user is null)
|
if (user is not null)
|
||||||
return;
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await SendEmailTokenAsync(user, TokenType.PasswordReset, ct);
|
await SendEmailTokenAsync(user, TokenType.PasswordReset, ct);
|
||||||
}
|
|
||||||
catch (EmailDeliveryException)
|
|
||||||
{
|
|
||||||
// SMTP zapisuje typ chyby. Odpověď na obnovu hesla zůstává pro všechny adresy stejná.
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task ResetPasswordAsync(ResetPasswordRequest request, CancellationToken ct)
|
public async Task ResetPasswordAsync(ResetPasswordRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
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)
|
||||||
@@ -193,33 +152,21 @@ public sealed class AuthService(
|
|||||||
UserDto.From(user));
|
UserDto.From(user));
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<bool> SendEmailTokenAsync(User user, TokenType type, CancellationToken ct)
|
private async Task SendEmailTokenAsync(User user, TokenType type, CancellationToken ct)
|
||||||
{
|
{
|
||||||
IssuedToken issued;
|
var issued = tokens.Issue(user, type);
|
||||||
await using (var transaction = await db.BeginWriteAsync(ct))
|
db.AuthTokens.Add(issued.Record);
|
||||||
{
|
await db.SaveChangesAsync(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);
|
|
||||||
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", "Ověřte svůj e-mail a nastavte heslo k účtu"),
|
TokenType.EmailConfirm => ("Ověření e-mailu", "confirm-email", "Pro dokončení registrace ověřte svůj e-mail"),
|
||||||
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)
|
||||||
@@ -227,11 +174,10 @@ 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);
|
||||||
var user = await db.LockUserAsync(validated.UserId, ct);
|
if (!await revocation.TryConsumeAsync(validated.Jti, type, 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 user;
|
return await db.Users.SingleOrDefaultAsync(u => u.Id == validated.UserId && u.IsActive, ct)
|
||||||
|
?? throw new BadRequestException(invalid);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -31,37 +31,35 @@ 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);
|
||||||
Publish(await LoadRevokedAccessTokensAsync([userId], now, ct));
|
await AddRevokedAccessTokensToStoreAsync(userId, now, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
internal async Task<List<RevokedAccessToken>> StageRevokeAllAsync(int[] userIds, RevokeReason reason, CancellationToken ct)
|
/// <summary>Zneplatní všechny platné tokeny uživatele – jeden UPDATE (kap. 10.1).</summary>
|
||||||
|
public async Task RevokeAllAsync(int userId, RevokeReason reason, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var now = Now();
|
var now = Now();
|
||||||
await db.AuthTokens
|
await db.AuthTokens
|
||||||
.Where(t => userIds.Contains(t.UserId) && t.RevokedAt == null)
|
.Where(t => t.UserId == 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);
|
||||||
return await LoadRevokedAccessTokensAsync(userIds, now, ct);
|
await AddRevokedAccessTokensToStoreAsync(userId, 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 Task<List<RevokedAccessToken>> LoadRevokedAccessTokensAsync(int[] userIds, DateTime revokedAt, CancellationToken ct) =>
|
private async Task AddRevokedAccessTokensToStoreAsync(int userId, DateTime revokedAt, CancellationToken ct)
|
||||||
db.AuthTokens
|
{
|
||||||
|
var revoked = await db.AuthTokens
|
||||||
.AsNoTracking()
|
.AsNoTracking()
|
||||||
.Where(t => userIds.Contains(t.UserId) && t.TokenType == TokenType.Access && t.RevokedAt == revokedAt)
|
.Where(t => t.UserId == userId && t.TokenType == TokenType.Access && t.RevokedAt == revokedAt)
|
||||||
.Select(t => new RevokedAccessToken(t.Jti, t.ExpiresAt))
|
.Select(t => new { 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()
|
||||||
|
|||||||
@@ -12,8 +12,6 @@ public sealed record CategoryDto(int Id, string Name, string? Description, bool
|
|||||||
|
|
||||||
public sealed record SaveBuildingRequest(string Code, string Name, string? Address);
|
public sealed record SaveBuildingRequest(string Code, string Name, string? Address);
|
||||||
|
|
||||||
public sealed record SaveCategoryRequest(string Name, string? Description);
|
|
||||||
|
|
||||||
public sealed class SaveBuildingRequestValidator : AbstractValidator<SaveBuildingRequest>
|
public sealed class SaveBuildingRequestValidator : AbstractValidator<SaveBuildingRequest>
|
||||||
{
|
{
|
||||||
public SaveBuildingRequestValidator()
|
public SaveBuildingRequestValidator()
|
||||||
@@ -24,18 +22,8 @@ public sealed class SaveBuildingRequestValidator : AbstractValidator<SaveBuildin
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class SaveCategoryRequestValidator : AbstractValidator<SaveCategoryRequest>
|
|
||||||
{
|
|
||||||
public SaveCategoryRequestValidator()
|
|
||||||
{
|
|
||||||
RuleFor(x => x.Name).NotEmpty().MaximumLength(100);
|
|
||||||
RuleFor(x => x.Description).MaximumLength(500);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Číselníky pro formuláře a jejich správa administrátorem. Mazání = deaktivace.</summary>
|
/// <summary>Číselníky pro formuláře a jejich správa administrátorem. Mazání = deaktivace.</summary>
|
||||||
public sealed class CatalogService(
|
public sealed class CatalogService(IAppDbContext db, IValidator<SaveBuildingRequest> buildingValidator)
|
||||||
IAppDbContext db, IValidator<SaveBuildingRequest> buildingValidator, IValidator<SaveCategoryRequest> categoryValidator)
|
|
||||||
{
|
{
|
||||||
public async Task<IReadOnlyList<BuildingDto>> GetBuildingsAsync(bool includeInactive, CancellationToken ct) =>
|
public async Task<IReadOnlyList<BuildingDto>> GetBuildingsAsync(bool includeInactive, CancellationToken ct) =>
|
||||||
await db.Buildings.AsNoTracking()
|
await db.Buildings.AsNoTracking()
|
||||||
@@ -44,16 +32,16 @@ public sealed class CatalogService(
|
|||||||
.Select(b => new BuildingDto(b.Id, b.Code, b.Name, b.Address, b.IsActive))
|
.Select(b => new BuildingDto(b.Id, b.Code, b.Name, b.Address, b.IsActive))
|
||||||
.ToListAsync(ct);
|
.ToListAsync(ct);
|
||||||
|
|
||||||
public async Task<IReadOnlyList<CategoryDto>> GetIssueCategoriesAsync(bool includeInactive, CancellationToken ct) =>
|
public async Task<IReadOnlyList<CategoryDto>> GetIssueCategoriesAsync(CancellationToken ct) =>
|
||||||
await db.IssueCategories.AsNoTracking()
|
await db.IssueCategories.AsNoTracking()
|
||||||
.Where(c => includeInactive || c.IsActive)
|
.Where(c => c.IsActive)
|
||||||
.OrderBy(c => c.Id)
|
.OrderBy(c => c.Id)
|
||||||
.Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive))
|
.Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive))
|
||||||
.ToListAsync(ct);
|
.ToListAsync(ct);
|
||||||
|
|
||||||
public async Task<IReadOnlyList<CategoryDto>> GetProposalCategoriesAsync(bool includeInactive, CancellationToken ct) =>
|
public async Task<IReadOnlyList<CategoryDto>> GetProposalCategoriesAsync(CancellationToken ct) =>
|
||||||
await db.ProposalCategories.AsNoTracking()
|
await db.ProposalCategories.AsNoTracking()
|
||||||
.Where(c => includeInactive || c.IsActive)
|
.Where(c => c.IsActive)
|
||||||
.OrderBy(c => c.Id)
|
.OrderBy(c => c.Id)
|
||||||
.Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive))
|
.Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive))
|
||||||
.ToListAsync(ct);
|
.ToListAsync(ct);
|
||||||
@@ -87,68 +75,10 @@ public sealed class CatalogService(
|
|||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<CategoryDto> CreateIssueCategoryAsync(SaveCategoryRequest request, CancellationToken ct)
|
|
||||||
{
|
|
||||||
await categoryValidator.ValidateAndThrowAsync(request, ct);
|
|
||||||
var category = new IssueCategory(request.Name, request.Description);
|
|
||||||
db.IssueCategories.Add(category);
|
|
||||||
await db.SaveChangesAsync(ct);
|
|
||||||
return ToDto(category);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<CategoryDto> UpdateIssueCategoryAsync(int id, SaveCategoryRequest request, CancellationToken ct)
|
|
||||||
{
|
|
||||||
await categoryValidator.ValidateAndThrowAsync(request, ct);
|
|
||||||
var category = await GetIssueCategoryAsync(id, ct);
|
|
||||||
category.Update(request.Name, request.Description);
|
|
||||||
await db.SaveChangesAsync(ct);
|
|
||||||
return ToDto(category);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task DeactivateIssueCategoryAsync(int id, CancellationToken ct)
|
|
||||||
{
|
|
||||||
var category = await GetIssueCategoryAsync(id, ct);
|
|
||||||
category.Deactivate();
|
|
||||||
await db.SaveChangesAsync(ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<CategoryDto> CreateProposalCategoryAsync(SaveCategoryRequest request, CancellationToken ct)
|
|
||||||
{
|
|
||||||
await categoryValidator.ValidateAndThrowAsync(request, ct);
|
|
||||||
var category = new ProposalCategory(request.Name, request.Description);
|
|
||||||
db.ProposalCategories.Add(category);
|
|
||||||
await db.SaveChangesAsync(ct);
|
|
||||||
return ToDto(category);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<CategoryDto> UpdateProposalCategoryAsync(int id, SaveCategoryRequest request, CancellationToken ct)
|
|
||||||
{
|
|
||||||
await categoryValidator.ValidateAndThrowAsync(request, ct);
|
|
||||||
var category = await GetProposalCategoryAsync(id, ct);
|
|
||||||
category.Update(request.Name, request.Description);
|
|
||||||
await db.SaveChangesAsync(ct);
|
|
||||||
return ToDto(category);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task DeactivateProposalCategoryAsync(int id, CancellationToken ct)
|
|
||||||
{
|
|
||||||
var category = await GetProposalCategoryAsync(id, ct);
|
|
||||||
category.Deactivate();
|
|
||||||
await db.SaveChangesAsync(ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task<Building> GetBuildingAsync(int id, CancellationToken ct) =>
|
private async Task<Building> GetBuildingAsync(int id, CancellationToken ct) =>
|
||||||
await db.Buildings.SingleOrDefaultAsync(b => b.Id == id, ct)
|
await db.Buildings.SingleOrDefaultAsync(b => b.Id == id, ct)
|
||||||
?? throw new NotFoundException($"Budova {id} neexistuje.");
|
?? throw new NotFoundException($"Budova {id} neexistuje.");
|
||||||
|
|
||||||
private async Task<IssueCategory> GetIssueCategoryAsync(int id, CancellationToken ct) =>
|
|
||||||
await db.IssueCategories.SingleOrDefaultAsync(c => c.Id == id, ct)
|
|
||||||
?? throw new NotFoundException($"Kategorie závad {id} neexistuje.");
|
|
||||||
|
|
||||||
private async Task<ProposalCategory> GetProposalCategoryAsync(int id, CancellationToken ct) =>
|
|
||||||
await db.ProposalCategories.SingleOrDefaultAsync(c => c.Id == id, ct)
|
|
||||||
?? throw new NotFoundException($"Kategorie návrhů {id} neexistuje.");
|
|
||||||
|
|
||||||
private async Task EnsureUniqueCodeAsync(string code, int? exceptId, CancellationToken ct)
|
private async Task EnsureUniqueCodeAsync(string code, int? exceptId, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var trimmed = code.Trim();
|
var trimmed = code.Trim();
|
||||||
@@ -157,6 +87,4 @@ public sealed class CatalogService(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static BuildingDto ToDto(Building b) => new(b.Id, b.Code, b.Name, b.Address, b.IsActive);
|
private static BuildingDto ToDto(Building b) => new(b.Id, b.Code, b.Name, b.Address, b.IsActive);
|
||||||
private static CategoryDto ToDto(IssueCategory c) => new(c.Id, c.Name, c.Description, c.IsActive);
|
|
||||||
private static CategoryDto ToDto(ProposalCategory c) => new(c.Id, c.Name, c.Description, c.IsActive);
|
|
||||||
}
|
}
|
||||||
@@ -1,13 +1,9 @@
|
|||||||
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, string? problemType = null) : Exception(message)
|
public abstract class AppException(string message) : 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)
|
||||||
@@ -15,13 +11,7 @@ public sealed class NotFoundException(string message) : AppException(message)
|
|||||||
public override int StatusCode => 404;
|
public override int StatusCode => 404;
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class ConflictException(string message, string? problemType = null) : AppException(message, problemType)
|
public sealed class ConflictException(string message) : AppException(message)
|
||||||
{
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
@@ -41,17 +31,4 @@ 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)
|
|
||||||
: AppException("E-mail se nepodařilo odeslat. Zkuste požadavek později.", "urn:ntbug:email-delivery-failed")
|
|
||||||
{
|
|
||||||
public string Reason { get; } = reason;
|
|
||||||
public bool Retryable { get; } = retryable;
|
|
||||||
public override int StatusCode => 503;
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed record PagedResult<T>(IReadOnlyList<T> Items, int TotalCount, int Page, int PageSize);
|
public sealed record PagedResult<T>(IReadOnlyList<T> Items, int TotalCount, int Page, int PageSize);
|
||||||
@@ -4,7 +4,6 @@ using Helpdesk.Application.Catalogs;
|
|||||||
using Helpdesk.Application.Issues;
|
using Helpdesk.Application.Issues;
|
||||||
using Helpdesk.Application.Notifications;
|
using Helpdesk.Application.Notifications;
|
||||||
using Helpdesk.Application.Proposals;
|
using Helpdesk.Application.Proposals;
|
||||||
using Helpdesk.Application.Statistics;
|
|
||||||
using Helpdesk.Application.Users;
|
using Helpdesk.Application.Users;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
@@ -24,11 +23,8 @@ public static class DependencyInjection
|
|||||||
services.AddScoped<CatalogService>();
|
services.AddScoped<CatalogService>();
|
||||||
services.AddScoped<IssueService>();
|
services.AddScoped<IssueService>();
|
||||||
services.AddScoped<NotificationService>();
|
services.AddScoped<NotificationService>();
|
||||||
services.AddScoped<NotificationDeliveryService>();
|
|
||||||
services.AddScoped<NotificationWriter>();
|
services.AddScoped<NotificationWriter>();
|
||||||
services.AddScoped<PushDeviceService>();
|
|
||||||
services.AddScoped<ProposalService>();
|
services.AddScoped<ProposalService>();
|
||||||
services.AddScoped<StatisticsService>();
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -80,11 +80,10 @@ 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 (!Issue.CanAssign(actor.Role))
|
if (actor.Role != UserRole.Management)
|
||||||
throw new ForbiddenException("Přehled řešitelů je určen vedení a administrátorům.");
|
throw new ForbiddenException("Přehled řešitelů je určen vedení.");
|
||||||
|
|
||||||
var users = await db.Users.Where(u => u.IsActive &&
|
var users = await db.Users.Where(u => u.IsActive && (u.Role == UserRole.Management || u.Role == UserRole.FacilityManager))
|
||||||
(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,6 +1,4 @@
|
|||||||
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;
|
||||||
@@ -46,22 +44,16 @@ 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 FieldValidationException(nameof(request.AssigneeId), "Vyberte aktivního správce budov, člena vedení nebo administrátora.");
|
throw new BadRequestException("Vyberte aktivního správce budov nebo člena vedení.");
|
||||||
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 = null;
|
IssuePriority? priority = request.Priority is null ? null : ParseCode<IssuePriority>(request.Priority);
|
||||||
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 != issue.Status && issue.ReporterId != assignee.Id)
|
if (from == IssueStatus.Received && 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);
|
||||||
@@ -73,8 +65,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, nameof(IssueReasonRequest.Reason), "Důvod")
|
? RequiredText(note, "Důvod", MaxTextBytes)
|
||||||
: OptionalText(note, nameof(VerifyIssueRequest.Note), "Poznámka");
|
: OptionalText(note, "Poznámka", MaxTextBytes);
|
||||||
|
|
||||||
var from = issue.Status;
|
var from = issue.Status;
|
||||||
issue.Transition(action, actor.Id, actor.Role, note);
|
issue.Transition(action, actor.Id, actor.Role, note);
|
||||||
@@ -95,7 +87,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, nameof(request.Text), "Komentář");
|
var text = RequiredText(request.Text, "Komentář", MaxTextBytes);
|
||||||
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];
|
||||||
@@ -110,7 +102,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 FieldValidationException("files", "Vyberte alespoň jeden soubor.");
|
throw new BadRequestException("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);
|
||||||
@@ -121,7 +113,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 FieldValidationException("files", "Najednou lze přiložit nejvýše pět souborů.");
|
throw new BadRequestException("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;
|
||||||
@@ -180,31 +172,18 @@ 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 errors = new List<ValidationFailure>();
|
var title = RequiredText(request.Title, "Název", MaxTextBytes);
|
||||||
var title = request.Title?.Trim();
|
RequiredText(request.Description, "Popis", MaxTextBytes);
|
||||||
if (string.IsNullOrEmpty(title))
|
if (title.Length > 200 || request.LocationDetail?.Trim().Length > 255)
|
||||||
errors.Add(new(nameof(request.Title), "Zadejte název."));
|
throw new BadRequestException("Název smí mít nejvýše 200 znaků a upřesnění místa 255 znaků.");
|
||||||
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))
|
||||||
errors.Add(new(nameof(request.CategoryId), "Vyberte aktivní kategorii závady."));
|
throw new BadRequestException("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))
|
||||||
errors.Add(new(nameof(request.BuildingId), "Vyberte aktivní budovu."));
|
throw new BadRequestException("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)
|
||||||
@@ -222,33 +201,30 @@ public sealed partial class IssueService(
|
|||||||
}
|
}
|
||||||
catch (DbUpdateConcurrencyException)
|
catch (DbUpdateConcurrencyException)
|
||||||
{
|
{
|
||||||
throw IssueVersionConflict();
|
throw new ConflictException("Závada se mezitím změnila. Načtěte aktuální stav.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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 FieldValidationException(nameof(IssueVersionRequest.RowVersion), "Zadejte platnou verzi závady.");
|
throw new BadRequestException("Zadejte platnou hodnotu rowVersion.");
|
||||||
if (issue.RowVersion != supplied)
|
if (issue.RowVersion != supplied)
|
||||||
throw IssueVersionConflict();
|
throw new ConflictException("Závada se mezitím změnila. Načtěte aktuální stav.");
|
||||||
}
|
}
|
||||||
|
|
||||||
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 field, string label) =>
|
private static string RequiredText(string? input, string name, int maxBytes) =>
|
||||||
OptionalText(input, field, label) ?? throw new FieldValidationException(field, $"{label}: hodnota je povinná.");
|
OptionalText(input, name, maxBytes) ?? throw new BadRequestException($"{name}: hodnota je povinná.");
|
||||||
|
|
||||||
private static string? OptionalText(string? input, string field, string label)
|
private static string? OptionalText(string? input, string name, int maxBytes)
|
||||||
{
|
{
|
||||||
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) > MaxTextBytes)
|
if (Encoding.UTF8.GetByteCount(text) > maxBytes)
|
||||||
throw new FieldValidationException(field, $"{label}: hodnota je příliš dlouhá.");
|
throw new BadRequestException($"{name}: hodnota je příliš dlouhá.");
|
||||||
return text;
|
return text;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,53 +0,0 @@
|
|||||||
using Helpdesk.Application.Abstractions;
|
|
||||||
using Helpdesk.Application.Common;
|
|
||||||
using Helpdesk.Domain;
|
|
||||||
using Helpdesk.Domain.Notifications;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
|
|
||||||
namespace Helpdesk.Application.Notifications;
|
|
||||||
|
|
||||||
public sealed record NotificationDeliveryDto(
|
|
||||||
int Id, int NotificationId, string Channel, string Status, int AttemptCount,
|
|
||||||
string? LastError, DateTime? NextAttemptAt, DateTime? SentAt);
|
|
||||||
|
|
||||||
public sealed class NotificationDeliveryService(IAppDbContext db, TimeProvider clock)
|
|
||||||
{
|
|
||||||
public async Task<PagedResult<NotificationDeliveryDto>> ListAsync(string status, int page, int pageSize, CancellationToken ct)
|
|
||||||
{
|
|
||||||
if (!EnumCode.TryParse<DeliveryStatus>(status, out var deliveryStatus))
|
|
||||||
throw new BadRequestException("Neplatný stav doručení.");
|
|
||||||
|
|
||||||
page = Math.Max(1, page);
|
|
||||||
pageSize = Math.Clamp(pageSize, 1, 100);
|
|
||||||
var query = db.NotificationDeliveries.AsNoTracking().Where(d => d.Status == deliveryStatus);
|
|
||||||
var count = await query.CountAsync(ct);
|
|
||||||
var offset = (long)(page - 1) * pageSize;
|
|
||||||
if (offset >= count)
|
|
||||||
return new PagedResult<NotificationDeliveryDto>([], count, page, pageSize);
|
|
||||||
|
|
||||||
var rows = await query.OrderByDescending(d => d.Id).Skip((int)offset).Take(pageSize).ToListAsync(ct);
|
|
||||||
var items = rows.Select(d => new NotificationDeliveryDto(d.Id, d.NotificationId, d.Channel.ToCode(),
|
|
||||||
d.Status.ToCode(), d.AttemptCount, d.LastError, d.NextAttemptAt, d.SentAt)).ToArray();
|
|
||||||
return new PagedResult<NotificationDeliveryDto>(items, count, page, pageSize);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task RetryAsync(int id, CancellationToken ct)
|
|
||||||
{
|
|
||||||
var now = clock.GetUtcNow().UtcDateTime;
|
|
||||||
var delivery = db.NotificationDeliveries.Where(d => d.Id == id);
|
|
||||||
var updated = await delivery.Where(d => d.Status == DeliveryStatus.Failed)
|
|
||||||
.ExecuteUpdateAsync(setters => setters
|
|
||||||
.SetProperty(d => d.Status, DeliveryStatus.Pending)
|
|
||||||
.SetProperty(d => d.AttemptCount, 0)
|
|
||||||
.SetProperty(d => d.NextAttemptAt, now)
|
|
||||||
.SetProperty(d => d.LastError, (string?)null)
|
|
||||||
.SetProperty(d => d.SentAt, (DateTime?)null), ct);
|
|
||||||
if (updated == 1)
|
|
||||||
return;
|
|
||||||
|
|
||||||
if (!await delivery.AnyAsync(ct))
|
|
||||||
throw new NotFoundException("Doručení neexistuje.");
|
|
||||||
|
|
||||||
throw new ConflictException("Zopakovat lze pouze neúspěšné doručení.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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 NotificationVisibility.VisibleToRecipients(db).Where(n => n.UserId == userId);
|
return db.Notifications.Where(n => n.UserId == userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Task<int> MarkUnreadRowsAsync(IQueryable<Notification> query, CancellationToken ct)
|
private Task<int> MarkUnreadRowsAsync(IQueryable<Notification> query, CancellationToken ct)
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
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,7 +14,8 @@ 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 => u.Id == reporterId || NotificationVisibility.ReadAllIssueRoles.Contains(u.Role));
|
var eligibleUsers = db.Users.Where(u =>
|
||||||
|
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,39 +0,0 @@
|
|||||||
using Helpdesk.Application.Abstractions;
|
|
||||||
using Helpdesk.Application.Common;
|
|
||||||
using Helpdesk.Domain.Auth;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
|
|
||||||
namespace Helpdesk.Application.Notifications;
|
|
||||||
|
|
||||||
public sealed class PushDeviceService(IAppDbContext db, ICurrentUser currentUser)
|
|
||||||
{
|
|
||||||
public async Task RegisterAsync(string token, CancellationToken ct)
|
|
||||||
{
|
|
||||||
ValidateToken(token);
|
|
||||||
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)
|
|
||||||
{
|
|
||||||
ValidateToken(token);
|
|
||||||
var userId = currentUser.Id;
|
|
||||||
await db.PushDevices.Where(d => d.UserId == userId && d.FcmToken == token).ExecuteDeleteAsync(ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void ValidateToken(string? token)
|
|
||||||
{
|
|
||||||
if (string.IsNullOrEmpty(token) || token.Length > 512 || token.Any(c => char.IsWhiteSpace(c) || char.IsControl(c)))
|
|
||||||
throw new BadRequestException("Neplatný registrační token zařízení.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -7,8 +7,7 @@ namespace Helpdesk.Application.Proposals;
|
|||||||
|
|
||||||
public sealed partial class ProposalService
|
public sealed partial class ProposalService
|
||||||
{
|
{
|
||||||
public async Task<PagedResult<ProposalSummary>> ListAsync(
|
public async Task<PagedResult<ProposalSummary>> ListAsync(ProposalQuery filters, CancellationToken ct)
|
||||||
ProposalQuery filters, DateTimeOffset? from, DateTimeOffset? to, CancellationToken ct)
|
|
||||||
{
|
{
|
||||||
await GetActorRoleAsync(ct);
|
await GetActorRoleAsync(ct);
|
||||||
var proposals = db.Proposals.AsNoTracking();
|
var proposals = db.Proposals.AsNoTracking();
|
||||||
@@ -21,12 +20,6 @@ public sealed partial class ProposalService
|
|||||||
proposals = proposals.Where(p => p.CategoryId == categoryId);
|
proposals = proposals.Where(p => p.CategoryId == categoryId);
|
||||||
if (filters.AuthorId is int authorId)
|
if (filters.AuthorId is int authorId)
|
||||||
proposals = proposals.Where(p => p.AuthorId == authorId);
|
proposals = proposals.Where(p => p.AuthorId == authorId);
|
||||||
if (from >= to)
|
|
||||||
throw new BadRequestException("Začátek období musí předcházet jeho konci.");
|
|
||||||
if (from?.UtcDateTime is DateTime fromUtc)
|
|
||||||
proposals = proposals.Where(p => p.CreatedAt >= fromUtc);
|
|
||||||
if (to?.UtcDateTime is DateTime toUtc)
|
|
||||||
proposals = proposals.Where(p => p.CreatedAt < toUtc);
|
|
||||||
if (!string.IsNullOrWhiteSpace(filters.Q))
|
if (!string.IsNullOrWhiteSpace(filters.Q))
|
||||||
{
|
{
|
||||||
var term = filters.Q.Trim();
|
var term = filters.Q.Trim();
|
||||||
|
|||||||
@@ -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)
|
||||||
{
|
{
|
||||||
var role = await GetActorRoleAsync(ct);
|
await GetActorRoleAsync(ct);
|
||||||
var (title, description) = ValidateDetails(request);
|
var (title, description) = ValidateDetails(request);
|
||||||
await using (var transaction = await db.BeginWriteAsync(ct))
|
await using (var transaction = await db.BeginProposalWriteAsync(ct))
|
||||||
{
|
{
|
||||||
var proposal = await LockProposalAsync(id, ct);
|
var proposal = await LockProposalAsync(id, ct);
|
||||||
if (!proposal.CanEditAs(currentUser.Id, role))
|
if (!proposal.IsAuthor(currentUser.Id))
|
||||||
throw new ForbiddenException("Návrh může upravit jeho autor nebo administrátor.");
|
throw new ForbiddenException("Návrh může upravit jen jeho autor.");
|
||||||
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, role, title, description, request.CategoryId);
|
proposal.Edit(currentUser.Id, 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 (!Proposal.CanReview(role))
|
if (role != UserRole.Management)
|
||||||
throw new ForbiddenException("Stav návrhu může změnit vedení školy nebo administrátor.");
|
throw new ForbiddenException("Stav návrhu může změnit jen vedení školy.");
|
||||||
|
|
||||||
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.BeginWriteAsync(ct))
|
await using (var transaction = await db.BeginProposalWriteAsync(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.BeginWriteAsync(ct);
|
await using var transaction = await db.BeginProposalWriteAsync(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,26 +0,0 @@
|
|||||||
using Helpdesk.Application.Common;
|
|
||||||
|
|
||||||
namespace Helpdesk.Application.Statistics;
|
|
||||||
|
|
||||||
public sealed record StatisticsPeriod(DateTimeOffset? From, DateTimeOffset? To)
|
|
||||||
{
|
|
||||||
internal (DateTime? From, DateTime? To) UtcBounds()
|
|
||||||
{
|
|
||||||
if (From >= To)
|
|
||||||
throw new BadRequestException("Začátek období musí předcházet jeho konci.");
|
|
||||||
|
|
||||||
return (From?.UtcDateTime, To?.UtcDateTime);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed record IssueTiming(int IssueId, long? MicrosecondsToAssignment, long? MicrosecondsToClosure);
|
|
||||||
|
|
||||||
public sealed record StatisticsOverview(
|
|
||||||
int TotalIssues, IReadOnlyDictionary<string, int> IssuesByStatus,
|
|
||||||
decimal? AverageHoursToAssignment, decimal? AverageHoursToClosure);
|
|
||||||
|
|
||||||
public sealed record IssueCategoryStatistics(int CategoryId, string Name, int IssueCount, decimal? AverageHoursToResolution);
|
|
||||||
public sealed record IssueBuildingStatistics(int? BuildingId, string? Name, int IssueCount);
|
|
||||||
public sealed record IssueAssigneeStatistics(int AssigneeId, string Name, int OpenIssues, int ResolvedIssues, int RejectedIssues);
|
|
||||||
public sealed record IssueTrendPoint(DateOnly Month, int CreatedIssues, int ClosedIssues);
|
|
||||||
public sealed record TopProposal(int Id, string Title, string Status, long VotesFor, long VotesAgainst, long Score);
|
|
||||||
@@ -1,141 +0,0 @@
|
|||||||
using Helpdesk.Application.Abstractions;
|
|
||||||
using Helpdesk.Application.Common;
|
|
||||||
using Helpdesk.Domain;
|
|
||||||
using Helpdesk.Domain.Issues;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
|
|
||||||
namespace Helpdesk.Application.Statistics;
|
|
||||||
|
|
||||||
public sealed class StatisticsService(IAppDbContext db)
|
|
||||||
{
|
|
||||||
private const decimal MicrosecondsPerHour = 3_600_000_000m;
|
|
||||||
|
|
||||||
public async Task<StatisticsOverview> GetOverviewAsync(StatisticsPeriod period, CancellationToken ct)
|
|
||||||
{
|
|
||||||
var byStatus = await (
|
|
||||||
from issue in IssuesInPeriod(period)
|
|
||||||
join timing in db.IssueTimings on issue.Id equals timing.IssueId into timings
|
|
||||||
from timing in timings.DefaultIfEmpty()
|
|
||||||
group timing by issue.Status into rows
|
|
||||||
select new
|
|
||||||
{
|
|
||||||
Status = rows.Key,
|
|
||||||
Count = rows.Count(),
|
|
||||||
AssignedCount = rows.Count(t => t.MicrosecondsToAssignment != null),
|
|
||||||
ClosedCount = rows.Count(t => t.MicrosecondsToClosure != null),
|
|
||||||
AssignmentTime = rows.Sum(t => (decimal?)t.MicrosecondsToAssignment),
|
|
||||||
ClosureTime = rows.Sum(t => (decimal?)t.MicrosecondsToClosure),
|
|
||||||
}).ToDictionaryAsync(row => row.Status, ct);
|
|
||||||
|
|
||||||
var counts = Enum.GetValues<IssueStatus>()
|
|
||||||
.ToDictionary(status => status.ToCode(), status => byStatus.GetValueOrDefault(status)?.Count ?? 0);
|
|
||||||
return new StatisticsOverview(
|
|
||||||
counts.Values.Sum(),
|
|
||||||
counts,
|
|
||||||
AverageHours(byStatus.Values.Sum(row => row.AssignmentTime), byStatus.Values.Sum(row => row.AssignedCount)),
|
|
||||||
AverageHours(byStatus.Values.Sum(row => row.ClosureTime), byStatus.Values.Sum(row => row.ClosedCount)));
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<IReadOnlyList<IssueCategoryStatistics>> GetByCategoryAsync(StatisticsPeriod period, CancellationToken ct)
|
|
||||||
{
|
|
||||||
var groups = await (
|
|
||||||
from issue in IssuesInPeriod(period)
|
|
||||||
join category in db.IssueCategories on issue.CategoryId equals category.Id
|
|
||||||
join timing in db.IssueTimings on issue.Id equals timing.IssueId into timings
|
|
||||||
from timing in timings.DefaultIfEmpty()
|
|
||||||
group new { issue.Status, timing.MicrosecondsToClosure } by new { category.Id, category.Name } into rows
|
|
||||||
orderby rows.Key.Id
|
|
||||||
select new
|
|
||||||
{
|
|
||||||
rows.Key.Id,
|
|
||||||
rows.Key.Name,
|
|
||||||
Count = rows.Count(),
|
|
||||||
ResolutionTime = rows.Average(row => row.Status == IssueStatus.Resolved
|
|
||||||
? (decimal?)row.MicrosecondsToClosure : null),
|
|
||||||
}).ToListAsync(ct);
|
|
||||||
|
|
||||||
return groups.Select(row => new IssueCategoryStatistics(
|
|
||||||
row.Id, row.Name, row.Count, row.ResolutionTime / MicrosecondsPerHour)).ToArray();
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<IReadOnlyList<IssueBuildingStatistics>> GetByBuildingAsync(StatisticsPeriod period, CancellationToken ct) =>
|
|
||||||
await (
|
|
||||||
from issue in IssuesInPeriod(period)
|
|
||||||
join building in db.Buildings on issue.BuildingId equals building.Id into buildings
|
|
||||||
from building in buildings.DefaultIfEmpty()
|
|
||||||
group issue by new { issue.BuildingId, building.Name } into rows
|
|
||||||
orderby rows.Key.BuildingId
|
|
||||||
select new IssueBuildingStatistics(rows.Key.BuildingId, rows.Key.Name, rows.Count())).ToListAsync(ct);
|
|
||||||
|
|
||||||
public async Task<IReadOnlyList<IssueAssigneeStatistics>> GetByAssigneeAsync(StatisticsPeriod period, CancellationToken ct) =>
|
|
||||||
await (
|
|
||||||
from issue in IssuesInPeriod(period)
|
|
||||||
join assignee in db.Users on issue.AssigneeId equals assignee.Id
|
|
||||||
group issue by new { assignee.Id, assignee.FirstName, assignee.LastName } into rows
|
|
||||||
orderby rows.Key.LastName, rows.Key.FirstName, rows.Key.Id
|
|
||||||
select new IssueAssigneeStatistics(
|
|
||||||
rows.Key.Id,
|
|
||||||
rows.Key.FirstName + " " + rows.Key.LastName,
|
|
||||||
rows.Count(i => i.Status == IssueStatus.Assigned || i.Status == IssueStatus.InProgress ||
|
|
||||||
i.Status == IssueStatus.PendingVerification),
|
|
||||||
rows.Count(i => i.Status == IssueStatus.Resolved),
|
|
||||||
rows.Count(i => i.Status == IssueStatus.Rejected))).ToListAsync(ct);
|
|
||||||
|
|
||||||
public async Task<IReadOnlyList<IssueTrendPoint>> GetTrendAsync(StatisticsPeriod period, CancellationToken ct)
|
|
||||||
{
|
|
||||||
var (from, to) = period.UtcBounds();
|
|
||||||
var created = await CountByMonthAsync(db.Issues.Select(i => i.CreatedAt), from, to, ct);
|
|
||||||
var closed = await CountByMonthAsync(
|
|
||||||
db.IssueEvents.Where(e => e.EventType == IssueEventType.StatusChanged &&
|
|
||||||
(e.ToStatus == IssueStatus.Resolved || e.ToStatus == IssueStatus.Rejected)).Select(e => e.OccurredAt),
|
|
||||||
from, to, ct);
|
|
||||||
|
|
||||||
var observed = created.Keys.Concat(closed.Keys).ToArray();
|
|
||||||
if (observed.Length == 0 && (from is null || to is null))
|
|
||||||
return [];
|
|
||||||
|
|
||||||
var first = from is DateTime start ? MonthIndex(start) : observed.Min();
|
|
||||||
var last = to is DateTime end ? MonthIndex(end.AddTicks(-1)) : observed.Max();
|
|
||||||
var result = new List<IssueTrendPoint>();
|
|
||||||
for (var month = first; month <= last; month++)
|
|
||||||
{
|
|
||||||
var date = new DateOnly(month / 12 + 1, month % 12 + 1, 1);
|
|
||||||
result.Add(new IssueTrendPoint(date, created.GetValueOrDefault(month), closed.GetValueOrDefault(month)));
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<IReadOnlyList<TopProposal>> GetTopProposalsAsync(StatisticsPeriod period, int limit, CancellationToken ct)
|
|
||||||
{
|
|
||||||
var (start, end) = period.UtcBounds();
|
|
||||||
var top = await (
|
|
||||||
from proposal in db.Proposals
|
|
||||||
where (start == null || proposal.CreatedAt >= start) && (end == null || proposal.CreatedAt < end)
|
|
||||||
join score in db.ProposalScores on proposal.Id equals score.ProposalId
|
|
||||||
orderby score.Score descending, score.VotesFor descending, proposal.CreatedAt, proposal.Id
|
|
||||||
select new { proposal.Id, proposal.Title, proposal.Status, score.VotesFor, score.VotesAgainst, score.Score })
|
|
||||||
.Take(limit).ToListAsync(ct);
|
|
||||||
|
|
||||||
return top.Select(row => new TopProposal(row.Id, row.Title, row.Status.ToCode(),
|
|
||||||
(long)row.VotesFor, (long)row.VotesAgainst, (long)row.Score)).ToArray();
|
|
||||||
}
|
|
||||||
|
|
||||||
private IQueryable<Issue> IssuesInPeriod(StatisticsPeriod period)
|
|
||||||
{
|
|
||||||
var (from, to) = period.UtcBounds();
|
|
||||||
return db.Issues.Where(i => (from == null || i.CreatedAt >= from) && (to == null || i.CreatedAt < to));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Task<Dictionary<int, int>> CountByMonthAsync(
|
|
||||||
IQueryable<DateTime> dates, DateTime? from, DateTime? to, CancellationToken ct) =>
|
|
||||||
dates.Where(date => (from == null || date >= from) && (to == null || date < to))
|
|
||||||
.GroupBy(date => (date.Year - 1) * 12 + date.Month - 1)
|
|
||||||
.Select(rows => new { Month = rows.Key, Count = rows.Count() })
|
|
||||||
.ToDictionaryAsync(row => row.Month, row => row.Count, ct);
|
|
||||||
|
|
||||||
private static int MonthIndex(DateTime date) => (date.Year - 1) * 12 + date.Month - 1;
|
|
||||||
|
|
||||||
private static decimal? AverageHours(decimal? microseconds, int count) =>
|
|
||||||
count == 0 ? null : microseconds / count / MicrosecondsPerHour;
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
using FluentValidation;
|
using FluentValidation;
|
||||||
using Helpdesk.Application.Auth;
|
|
||||||
using Helpdesk.Domain;
|
using Helpdesk.Domain;
|
||||||
using Helpdesk.Domain.Users;
|
using Helpdesk.Domain.Users;
|
||||||
|
|
||||||
@@ -19,7 +18,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>
|
||||||
{
|
{
|
||||||
@@ -29,7 +28,6 @@ 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é.");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,38 +44,4 @@ 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,11 +13,7 @@ namespace Helpdesk.Application.Users;
|
|||||||
public sealed class UserService(
|
public sealed class UserService(
|
||||||
IAppDbContext db,
|
IAppDbContext db,
|
||||||
TokenRevocationService revocation,
|
TokenRevocationService revocation,
|
||||||
AuthService auth,
|
IValidator<UpdateProfileRequest> profileValidator)
|
||||||
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));
|
||||||
@@ -26,13 +22,9 @@ public sealed class UserService(
|
|||||||
{
|
{
|
||||||
await profileValidator.ValidateAndThrowAsync(request, ct);
|
await profileValidator.ValidateAndThrowAsync(request, ct);
|
||||||
|
|
||||||
await using var transaction = await db.BeginWriteAsync(ct);
|
var user = await GetAsync(currentUser.Id, ct);
|
||||||
var user = RequireAccount(await db.LockUserAsync(currentUser.Id, ct), currentUser.Id);
|
user.UpdateProfile(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled);
|
||||||
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,7 +33,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().Where(u => !u.IsDeleted);
|
var query = db.Users.AsNoTracking();
|
||||||
if (!string.IsNullOrWhiteSpace(q))
|
if (!string.IsNullOrWhiteSpace(q))
|
||||||
{
|
{
|
||||||
var term = q.Trim();
|
var term = q.Trim();
|
||||||
@@ -54,13 +46,9 @@ 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((int)offset).Take(pageSize)
|
.Skip((page - 1) * pageSize).Take(pageSize)
|
||||||
.ToListAsync(ct);
|
.ToListAsync(ct);
|
||||||
|
|
||||||
var items = users
|
var items = users
|
||||||
@@ -70,214 +58,39 @@ 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 Task ChangeRoleAsync(ICurrentUser admin, int userId, ChangeRoleRequest request, CancellationToken ct)
|
public async Task ChangeRoleAsync(ICurrentUser admin, int userId, ChangeRoleRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var role = ParseRole(request.Role);
|
var role = ParseRole(request.Role);
|
||||||
return UpdateAccountsAsync(admin, [userId], user => ChangeRole(user, role), ct);
|
if (userId == admin.Id)
|
||||||
|
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)
|
||||||
{
|
{
|
||||||
await activeValidator.ValidateAndThrowAsync(request, ct);
|
if (userId == admin.Id && !request.IsActive)
|
||||||
var isActive = request.IsActive!.Value;
|
throw new ConflictException("Administrátor nemůže deaktivovat sám sebe.");
|
||||||
if (userId == admin.Id && isActive)
|
|
||||||
return;
|
|
||||||
await UpdateAccountsAsync(admin, [userId], user => SetActive(user, isActive), ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<AdminUserDetailsDto> GetAdminAsync(int id, CancellationToken ct) =>
|
|
||||||
AdminUserDetailsDto.From(await GetAsync(id, ct));
|
|
||||||
|
|
||||||
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 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);
|
var user = await GetAsync(userId, ct);
|
||||||
if (!user.IsActive || user.EmailConfirmed)
|
if (user.IsActive == request.IsActive)
|
||||||
throw new ConflictException("Ověřovací odkaz lze poslat pouze aktivnímu účtu s neověřeným e-mailem.");
|
return;
|
||||||
|
|
||||||
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);
|
|
||||||
|
|
||||||
|
if (!request.IsActive)
|
||||||
|
await revocation.RevokeAllAsync(user.Id, RevokeReason.AccountDeactivated, ct);
|
||||||
|
user.SetActive(request.IsActive);
|
||||||
await db.SaveChangesAsync(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) =>
|
||||||
RequireAccount(await db.Users.SingleOrDefaultAsync(u => u.Id == id, ct), id);
|
await db.Users.SingleOrDefaultAsync(u => u.Id == id, ct)
|
||||||
|
?? 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,20 +31,10 @@ public sealed class IssueCategory
|
|||||||
{
|
{
|
||||||
private IssueCategory() { } // EF Core
|
private IssueCategory() { } // EF Core
|
||||||
|
|
||||||
public IssueCategory(string name, string? description) => Update(name, description);
|
|
||||||
|
|
||||||
public int Id { get; private set; }
|
public int Id { get; private set; }
|
||||||
public string Name { get; private set; } = null!;
|
public string Name { get; private set; } = null!;
|
||||||
public string? Description { get; private set; }
|
public string? Description { get; private set; }
|
||||||
public bool IsActive { get; private set; } = true;
|
public bool IsActive { get; private set; } = true;
|
||||||
|
|
||||||
public void Update(string name, string? description)
|
|
||||||
{
|
|
||||||
Name = name.Trim();
|
|
||||||
Description = string.IsNullOrWhiteSpace(description) ? null : description.Trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Deactivate() => IsActive = false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Oblast návrhu na zlepšení (tabulka <c>proposal_category</c>).</summary>
|
/// <summary>Oblast návrhu na zlepšení (tabulka <c>proposal_category</c>).</summary>
|
||||||
@@ -52,18 +42,8 @@ public sealed class ProposalCategory
|
|||||||
{
|
{
|
||||||
private ProposalCategory() { } // EF Core
|
private ProposalCategory() { } // EF Core
|
||||||
|
|
||||||
public ProposalCategory(string name, string? description) => Update(name, description);
|
|
||||||
|
|
||||||
public int Id { get; private set; }
|
public int Id { get; private set; }
|
||||||
public string Name { get; private set; } = null!;
|
public string Name { get; private set; } = null!;
|
||||||
public string? Description { get; private set; }
|
public string? Description { get; private set; }
|
||||||
public bool IsActive { get; private set; } = true;
|
public bool IsActive { get; private set; } = true;
|
||||||
|
|
||||||
public void Update(string name, string? description)
|
|
||||||
{
|
|
||||||
Name = name.Trim();
|
|
||||||
Description = string.IsNullOrWhiteSpace(description) ? null : description.Trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Deactivate() => IsActive = false;
|
|
||||||
}
|
}
|
||||||
@@ -31,11 +31,9 @@ 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 == UserRole.FacilityManager || CanAssign(role);
|
public static bool CanReadAll(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;
|
||||||
|
|
||||||
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;
|
||||||
|
|
||||||
@@ -44,15 +42,14 @@ 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 => admin || reporter,
|
IssueAction.Edit or IssueAction.Confirm or IssueAction.Reopen => reporter,
|
||||||
IssueAction.Assign => CanAssign(role),
|
IssueAction.Assign => management,
|
||||||
IssueAction.StartWork or IssueAction.SubmitForVerification => admin || assignee,
|
IssueAction.StartWork or IssueAction.SubmitForVerification => assignee,
|
||||||
IssueAction.Reject => admin || assignee || (management && AssigneeId is null),
|
IssueAction.Reject => assignee || (management && AssigneeId is null),
|
||||||
IssueAction.Comment or IssueAction.AddAttachments => admin || reporter || assignee,
|
IssueAction.Comment or IssueAction.AddAttachments => reporter || assignee,
|
||||||
_ => false,
|
_ => false,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -67,8 +64,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
|
||||||
? admin || management
|
? management
|
||||||
: (admin || assignee) && Status is (IssueStatus.Assigned or IssueStatus.InProgress),
|
: 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,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ namespace Helpdesk.Domain.Notifications;
|
|||||||
|
|
||||||
public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened, ProposalStatusChanged }
|
public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened, ProposalStatusChanged }
|
||||||
public enum DeliveryChannel { Email, Push }
|
public enum DeliveryChannel { Email, Push }
|
||||||
public enum DeliveryStatus { Pending, Sent, Failed, Skipped }
|
public enum DeliveryStatus { Pending, Skipped }
|
||||||
|
|
||||||
public sealed class Notification : IHasCreatedAt
|
public sealed class Notification : IHasCreatedAt
|
||||||
{
|
{
|
||||||
@@ -46,9 +46,6 @@ public sealed class Notification : IHasCreatedAt
|
|||||||
public sealed class NotificationDelivery(
|
public sealed class NotificationDelivery(
|
||||||
Notification notification, DeliveryChannel channel, bool enabled, DateTime now)
|
Notification notification, DeliveryChannel channel, bool enabled, DateTime now)
|
||||||
{
|
{
|
||||||
private static readonly TimeSpan[] RetryDelays =
|
|
||||||
[TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(30), TimeSpan.FromHours(2)];
|
|
||||||
|
|
||||||
private NotificationDelivery() : this(null!, default, false, default) { }
|
private NotificationDelivery() : this(null!, default, false, default) { }
|
||||||
|
|
||||||
public int Id { get; private set; }
|
public int Id { get; private set; }
|
||||||
@@ -56,45 +53,11 @@ public sealed class NotificationDelivery(
|
|||||||
public Notification Notification { get; private set; } = notification;
|
public Notification Notification { get; private set; } = notification;
|
||||||
public DeliveryChannel Channel { get; private set; } = channel;
|
public DeliveryChannel Channel { get; private set; } = channel;
|
||||||
public DeliveryStatus Status { get; private set; } = enabled ? DeliveryStatus.Pending : DeliveryStatus.Skipped;
|
public DeliveryStatus Status { get; private set; } = enabled ? DeliveryStatus.Pending : DeliveryStatus.Skipped;
|
||||||
public int AttemptCount { get; private set; }
|
|
||||||
public DateTime? NextAttemptAt { get; private set; } = enabled ? now : null;
|
public DateTime? NextAttemptAt { get; private set; } = enabled ? now : null;
|
||||||
public string? LastError { get; private set; }
|
|
||||||
public DateTime? SentAt { get; private set; }
|
|
||||||
|
|
||||||
public void RecordSent(DateTime now)
|
|
||||||
{
|
|
||||||
AttemptCount++;
|
|
||||||
Status = DeliveryStatus.Sent;
|
|
||||||
SentAt = now;
|
|
||||||
NextAttemptAt = null;
|
|
||||||
LastError = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void RecordFailure(DateTime now, string reason, bool retryable)
|
|
||||||
{
|
|
||||||
AttemptCount++;
|
|
||||||
LastError = reason;
|
|
||||||
if (retryable && AttemptCount <= RetryDelays.Length)
|
|
||||||
{
|
|
||||||
NextAttemptAt = now + RetryDelays[AttemptCount - 1];
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Status = DeliveryStatus.Failed;
|
|
||||||
NextAttemptAt = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Skip()
|
|
||||||
{
|
|
||||||
Status = DeliveryStatus.Skipped;
|
|
||||||
NextAttemptAt = null;
|
|
||||||
LastError = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class PushDevice
|
public sealed class PushDevice
|
||||||
{
|
{
|
||||||
public int Id { get; private set; }
|
public int Id { get; private set; }
|
||||||
public int UserId { get; private set; }
|
public int UserId { get; private set; }
|
||||||
public string FcmToken { get; private set; } = null!;
|
|
||||||
}
|
}
|
||||||
@@ -26,11 +26,9 @@ 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 CanEditAs(int userId, UserRole role) => role == UserRole.Admin || IsAuthor(userId);
|
public bool CanEdit(int userId) => IsAuthor(userId) && IsEditable;
|
||||||
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,
|
||||||
@@ -39,9 +37,9 @@ public sealed class Proposal : IHasCreatedAt
|
|||||||
_ => false,
|
_ => false,
|
||||||
};
|
};
|
||||||
|
|
||||||
public void Edit(int actorId, UserRole role, string title, string description, int categoryId)
|
public void Edit(int actorId, string title, string description, int categoryId)
|
||||||
{
|
{
|
||||||
if (!CanEditAs(actorId, role) || !IsEditable)
|
if (!CanEdit(actorId))
|
||||||
throw new InvalidOperationException("Návrh nelze upravit.");
|
throw new InvalidOperationException("Návrh nelze upravit.");
|
||||||
|
|
||||||
SetDetails(title, description, categoryId);
|
SetDetails(title, description, categoryId);
|
||||||
@@ -49,7 +47,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 (!CanReview(role) || !CanTransitionTo(target))
|
if (role != UserRole.Management || !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,6 +6,9 @@ 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; }
|
||||||
@@ -18,10 +21,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 RowVersion { get; private set; }
|
public int FailedLoginCount { 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}";
|
||||||
@@ -38,17 +41,32 @@ public sealed class User : IHasCreatedAt
|
|||||||
|
|
||||||
public static string NormalizeEmail(string email) => email.Trim().ToUpperInvariant();
|
public static string NormalizeEmail(string email) => email.Trim().ToUpperInvariant();
|
||||||
|
|
||||||
public void ConfirmEmail() => EmailConfirmed = true;
|
public bool IsLockedOut(DateTime now) => LockoutUntil is { } until && until > now;
|
||||||
|
|
||||||
public void SetEmailConfirmed(bool confirmed) => EmailConfirmed = confirmed;
|
/// <summary>Neúspěšné přihlášení; po <see cref="MaxFailedLogins"/> pokusech se účet na 15 minut zamkne.</summary>
|
||||||
|
public void RegisterFailedLogin(DateTime now)
|
||||||
public void ChangeEmail(string email)
|
|
||||||
{
|
{
|
||||||
Email = email.Trim();
|
FailedLoginCount++;
|
||||||
EmailNormalized = NormalizeEmail(email);
|
if (FailedLoginCount >= MaxFailedLogins)
|
||||||
|
{
|
||||||
|
LockoutUntil = now + LockoutDuration;
|
||||||
|
FailedLoginCount = 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void ChangePasswordHash(string passwordHash) => PasswordHash = passwordHash;
|
public void RegisterSuccessfulLogin()
|
||||||
|
{
|
||||||
|
FailedLoginCount = 0;
|
||||||
|
LockoutUntil = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ConfirmEmail() => EmailConfirmed = true;
|
||||||
|
|
||||||
|
public void ChangePasswordHash(string passwordHash)
|
||||||
|
{
|
||||||
|
PasswordHash = passwordHash;
|
||||||
|
RegisterSuccessfulLogin();
|
||||||
|
}
|
||||||
|
|
||||||
public void UpdateProfile(string firstName, string lastName, string? phone, bool emailNotificationsEnabled)
|
public void UpdateProfile(string firstName, string lastName, string? phone, bool emailNotificationsEnabled)
|
||||||
{
|
{
|
||||||
@@ -61,14 +79,4 @@ 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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
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,121 +0,0 @@
|
|||||||
using System.Data;
|
|
||||||
using Helpdesk.Application.Abstractions;
|
|
||||||
using Helpdesk.Application.Common;
|
|
||||||
using Helpdesk.Application.Notifications;
|
|
||||||
using Helpdesk.Domain.Notifications;
|
|
||||||
using Helpdesk.Infrastructure.Email;
|
|
||||||
using Helpdesk.Infrastructure.Notifications;
|
|
||||||
using Helpdesk.Infrastructure.Persistence;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using Microsoft.Extensions.Hosting;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
|
|
||||||
namespace Helpdesk.Infrastructure.Background;
|
|
||||||
|
|
||||||
internal sealed partial class NotificationDispatcher(
|
|
||||||
IServiceScopeFactory scopes, IEmailSender email, TimeProvider clock, ILogger<NotificationDispatcher> logger,
|
|
||||||
FirebasePushSender? push = null) : BackgroundService
|
|
||||||
{
|
|
||||||
private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(2);
|
|
||||||
private readonly bool emailEnabled = email is not LoggingEmailSender;
|
|
||||||
|
|
||||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
||||||
{
|
|
||||||
if (!emailEnabled && push is null)
|
|
||||||
return;
|
|
||||||
|
|
||||||
while (!stoppingToken.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (await DeliverNextAsync(stoppingToken))
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
catch (Exception failure) when (!stoppingToken.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
LogDispatchFailure(failure.GetType().Name);
|
|
||||||
}
|
|
||||||
|
|
||||||
await Task.Delay(PollInterval, clock, stoppingToken);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task<bool> DeliverNextAsync(CancellationToken ct)
|
|
||||||
{
|
|
||||||
using var scope = scopes.CreateScope();
|
|
||||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
|
||||||
await using var transaction = await db.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
|
|
||||||
var now = clock.GetUtcNow().UtcDateTime;
|
|
||||||
var rows = await db.NotificationDeliveries.FromSql($"""
|
|
||||||
SELECT * FROM notification_delivery
|
|
||||||
WHERE status = 'PENDING' AND next_attempt_at <= {now}
|
|
||||||
AND (({emailEnabled} AND channel = 'EMAIL') OR ({push is not null} AND channel = 'PUSH'))
|
|
||||||
ORDER BY next_attempt_at, id LIMIT 1 FOR UPDATE SKIP LOCKED
|
|
||||||
""").ToListAsync(ct);
|
|
||||||
if (rows.SingleOrDefault() is not { } delivery)
|
|
||||||
return false;
|
|
||||||
|
|
||||||
var recipient = await (
|
|
||||||
from notification in NotificationVisibility.VisibleToRecipients(db).AsNoTracking()
|
|
||||||
join user in db.Users on notification.UserId equals user.Id
|
|
||||||
where notification.Id == delivery.NotificationId
|
|
||||||
select new { Notification = notification, user.Id, user.Email, user.EmailConfirmed, user.EmailNotificationsEnabled }
|
|
||||||
).SingleOrDefaultAsync(ct);
|
|
||||||
|
|
||||||
if (recipient is null)
|
|
||||||
delivery.Skip();
|
|
||||||
else if (delivery.Channel == DeliveryChannel.Email)
|
|
||||||
{
|
|
||||||
if (recipient.EmailConfirmed && recipient.EmailNotificationsEnabled)
|
|
||||||
await SendEmailAsync(delivery, recipient.Notification, recipient.Email, ct);
|
|
||||||
else
|
|
||||||
delivery.Skip();
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
await SendPushAsync(db, delivery, recipient.Id, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
await db.SaveChangesAsync(ct);
|
|
||||||
await transaction.CommitAsync(ct);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task SendEmailAsync(NotificationDelivery delivery, Notification notification, string address, CancellationToken ct)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await email.SendAsync(address, notification.Title, notification.Message, ct);
|
|
||||||
delivery.RecordSent(clock.GetUtcNow().UtcDateTime);
|
|
||||||
}
|
|
||||||
catch (EmailDeliveryException failure)
|
|
||||||
{
|
|
||||||
delivery.RecordFailure(clock.GetUtcNow().UtcDateTime, failure.Reason, failure.Retryable);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task SendPushAsync(HelpdeskDbContext db, NotificationDelivery delivery, int userId, CancellationToken ct)
|
|
||||||
{
|
|
||||||
var devices = db.PushDevices.Where(d => d.UserId == userId);
|
|
||||||
var tokens = await devices.Select(d => d.FcmToken).ToArrayAsync(ct);
|
|
||||||
if (tokens.Length == 0)
|
|
||||||
{
|
|
||||||
delivery.Skip();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var result = await push!.SendAsync(tokens, ct);
|
|
||||||
foreach (var invalidToken in result.InvalidTokens)
|
|
||||||
await devices.Where(d => d.FcmToken == invalidToken).ExecuteDeleteAsync(ct);
|
|
||||||
|
|
||||||
var now = clock.GetUtcNow().UtcDateTime;
|
|
||||||
if (result.Sent)
|
|
||||||
delivery.RecordSent(now);
|
|
||||||
else
|
|
||||||
delivery.RecordFailure(now, result.FailureReason, result.Retryable);
|
|
||||||
}
|
|
||||||
|
|
||||||
[LoggerMessage(Level = LogLevel.Error, Message = "Zpracování notifikační fronty selhalo ({FailureType}).")]
|
|
||||||
private partial void LogDispatchFailure(string failureType);
|
|
||||||
}
|
|
||||||
@@ -3,21 +3,17 @@ using Helpdesk.Application.Issues;
|
|||||||
using Helpdesk.Infrastructure.Background;
|
using Helpdesk.Infrastructure.Background;
|
||||||
using Helpdesk.Infrastructure.Email;
|
using Helpdesk.Infrastructure.Email;
|
||||||
using Helpdesk.Infrastructure.Files;
|
using Helpdesk.Infrastructure.Files;
|
||||||
using Helpdesk.Infrastructure.Notifications;
|
|
||||||
using Helpdesk.Infrastructure.Persistence;
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
using Helpdesk.Infrastructure.Security;
|
using Helpdesk.Infrastructure.Security;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Hosting;
|
|
||||||
using MimeKit;
|
|
||||||
|
|
||||||
namespace Helpdesk.Infrastructure;
|
namespace Helpdesk.Infrastructure;
|
||||||
|
|
||||||
public static class DependencyInjection
|
public static class DependencyInjection
|
||||||
{
|
{
|
||||||
public static IServiceCollection AddInfrastructure(
|
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
|
||||||
this IServiceCollection services, IConfiguration configuration, IHostEnvironment environment)
|
|
||||||
{
|
{
|
||||||
var connectionString = configuration.GetConnectionString("Helpdesk")
|
var connectionString = configuration.GetConnectionString("Helpdesk")
|
||||||
?? throw new InvalidOperationException("Chybí připojovací řetězec ConnectionStrings:Helpdesk.");
|
?? throw new InvalidOperationException("Chybí připojovací řetězec ConnectionStrings:Helpdesk.");
|
||||||
@@ -37,38 +33,12 @@ public static class DependencyInjection
|
|||||||
services.AddSingleton<IPasswordHasher, BCryptPasswordHasher>();
|
services.AddSingleton<IPasswordHasher, BCryptPasswordHasher>();
|
||||||
services.AddSingleton<ITokenService, JwtTokenService>();
|
services.AddSingleton<ITokenService, JwtTokenService>();
|
||||||
services.AddSingleton<IRevokedTokenStore, RevokedTokenStore>();
|
services.AddSingleton<IRevokedTokenStore, RevokedTokenStore>();
|
||||||
AddEmailSender(services, configuration.GetSection("Smtp"), environment);
|
services.AddSingleton<IEmailSender, LoggingEmailSender>();
|
||||||
var firebaseCredentials = configuration["Firebase:ServiceAccountJson"];
|
|
||||||
if (!string.IsNullOrWhiteSpace(firebaseCredentials))
|
|
||||||
services.AddSingleton(_ => FirebasePushSender.Create(firebaseCredentials));
|
|
||||||
services.AddSingleton<IAttachmentStore, FileAttachmentStore>();
|
services.AddSingleton<IAttachmentStore, FileAttachmentStore>();
|
||||||
|
|
||||||
services.AddHostedService<RevokedTokenStoreLoader>();
|
services.AddHostedService<RevokedTokenStoreLoader>();
|
||||||
services.AddHostedService<AdminSeeder>();
|
services.AddHostedService<AdminSeeder>();
|
||||||
services.AddHostedService<AuthTokenCleanupService>();
|
services.AddHostedService<AuthTokenCleanupService>();
|
||||||
services.AddHostedService<NotificationDispatcher>();
|
|
||||||
services.AddHostedService<AttachmentStorageMonitor>();
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void AddEmailSender(IServiceCollection services, IConfigurationSection configuration, IHostEnvironment environment)
|
|
||||||
{
|
|
||||||
if (environment.IsDevelopment() && string.IsNullOrWhiteSpace(configuration["Mailbox"]) &&
|
|
||||||
string.IsNullOrWhiteSpace(configuration["Password"]))
|
|
||||||
{
|
|
||||||
services.AddSingleton<IEmailSender, LoggingEmailSender>();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
services.AddOptions<SmtpOptions>()
|
|
||||||
.Bind(configuration)
|
|
||||||
.Validate(options => !string.IsNullOrWhiteSpace(options.Host) && options.Port is >= 1 and <= 65535,
|
|
||||||
"Nastavte platný SMTP server a port.")
|
|
||||||
.Validate(options => MailboxAddress.TryParse(options.Mailbox, out var mailbox) &&
|
|
||||||
mailbox.Address == options.Mailbox && mailbox.Address.Contains('@'),
|
|
||||||
"Nastavte celou e-mailovou adresu SMTP schránky.")
|
|
||||||
.Validate(options => !string.IsNullOrWhiteSpace(options.Password), "Nastavte heslo SMTP schránky.")
|
|
||||||
.ValidateOnStart();
|
|
||||||
services.AddSingleton<IEmailSender, SmtpEmailSender>();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,19 +1,27 @@
|
|||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
namespace Helpdesk.Infrastructure.Email;
|
namespace Helpdesk.Infrastructure.Email;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Vývojová náhrada odesílání e-mailů, pokud schránka SMTP není nakonfigurována.
|
/// Vývojová náhrada odesílání e-mailů – obsah zapíše do logu (odkaz pro ověření e-mailu je tak vidět
|
||||||
|
/// v <c>docker compose logs api</c>). Odesílání přes SMTP (MailKit + Mailpit) přijde s notifikacemi.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal sealed partial class LoggingEmailSender(ILogger<LoggingEmailSender> logger) : IEmailSender
|
internal sealed partial class LoggingEmailSender(ILogger<LoggingEmailSender> logger, IHostEnvironment environment) : IEmailSender
|
||||||
{
|
{
|
||||||
public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
|
public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
LogEmail(to, subject, body);
|
if (environment.IsDevelopment())
|
||||||
|
LogEmail(to, subject, body);
|
||||||
|
else
|
||||||
|
LogMissingTransport();
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
[LoggerMessage(Level = LogLevel.Information, Message = "E-mail pro {To} – {Subject}:\n{Body}")]
|
[LoggerMessage(Level = LogLevel.Information, Message = "E-mail pro {To} – {Subject}:\n{Body}")]
|
||||||
private partial void LogEmail(string to, string subject, string body);
|
private partial void LogEmail(string to, string subject, string body);
|
||||||
|
|
||||||
|
[LoggerMessage(Level = LogLevel.Warning, Message = "E-mail nebyl odeslán. Pro toto prostředí není nakonfigurován poštovní transport.")]
|
||||||
|
private partial void LogMissingTransport();
|
||||||
}
|
}
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
using System.Net.Sockets;
|
|
||||||
using Helpdesk.Application.Abstractions;
|
|
||||||
using Helpdesk.Application.Common;
|
|
||||||
using MailKit;
|
|
||||||
using MailKit.Net.Smtp;
|
|
||||||
using MailKit.Security;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
using MimeKit;
|
|
||||||
|
|
||||||
namespace Helpdesk.Infrastructure.Email;
|
|
||||||
|
|
||||||
internal sealed class SmtpOptions
|
|
||||||
{
|
|
||||||
public string Host { get; set; } = "smtp.seznam.cz";
|
|
||||||
public int Port { get; set; } = 465;
|
|
||||||
public string Mailbox { get; set; } = "";
|
|
||||||
public string Password { get; set; } = "";
|
|
||||||
}
|
|
||||||
|
|
||||||
internal sealed partial class SmtpEmailSender(IOptions<SmtpOptions> options, ILogger<SmtpEmailSender> logger) : IEmailSender
|
|
||||||
{
|
|
||||||
public async Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
if (!MailboxAddress.TryParse(to, out var recipient))
|
|
||||||
{
|
|
||||||
LogDeliveryFailure("InvalidRecipient");
|
|
||||||
throw new EmailDeliveryException("SMTP_INVALID_RECIPIENT", retryable: false);
|
|
||||||
}
|
|
||||||
|
|
||||||
var settings = options.Value;
|
|
||||||
using var message = new MimeMessage { Subject = subject, Body = new TextPart("plain") { Text = body } };
|
|
||||||
message.From.Add(MailboxAddress.Parse(settings.Mailbox));
|
|
||||||
message.To.Add(recipient);
|
|
||||||
|
|
||||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
|
||||||
timeout.CancelAfter(TimeSpan.FromSeconds(15));
|
|
||||||
using var client = new SmtpClient();
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await client.ConnectAsync(settings.Host, settings.Port, SecureSocketOptions.SslOnConnect, timeout.Token);
|
|
||||||
await client.AuthenticateAsync(settings.Mailbox, settings.Password, timeout.Token);
|
|
||||||
await client.SendAsync(message, timeout.Token);
|
|
||||||
}
|
|
||||||
catch (Exception exception) when (!cancellationToken.IsCancellationRequested &&
|
|
||||||
exception is (IOException or SocketException or CommandException or ProtocolException or
|
|
||||||
AuthenticationException or SslHandshakeException or NotSupportedException or TimeoutException or
|
|
||||||
OperationCanceledException))
|
|
||||||
{
|
|
||||||
LogDeliveryFailure(exception.GetType().Name);
|
|
||||||
if (exception is SmtpCommandException command)
|
|
||||||
{
|
|
||||||
var status = (int)command.StatusCode;
|
|
||||||
throw new EmailDeliveryException($"SMTP_{status}", retryable: status is < 500 or >= 600);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new EmailDeliveryException($"SMTP_{exception.GetType().Name}", retryable: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Doručení e-mailu přes SMTP selhalo ({FailureType}).")]
|
|
||||||
private partial void LogDeliveryFailure(string failureType);
|
|
||||||
}
|
|
||||||
@@ -8,16 +8,16 @@ namespace Helpdesk.Infrastructure.Files;
|
|||||||
|
|
||||||
internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) : IAttachmentStore
|
internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) : IAttachmentStore
|
||||||
{
|
{
|
||||||
internal static readonly string UploadDirectory = Path.Combine(AppContext.BaseDirectory, "uploads");
|
private readonly string directory = 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 FieldValidationException("files", "Příloha musí mít velikost od 1 B do 10 MB.");
|
throw new BadRequestException("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 FieldValidationException("files", "Neplatný název přílohy.");
|
throw new BadRequestException("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 FieldValidationException("files", "Tento typ přílohy není povolen."),
|
_ => throw new BadRequestException("Tento typ přílohy není povolen."),
|
||||||
};
|
};
|
||||||
|
|
||||||
Directory.CreateDirectory(UploadDirectory);
|
Directory.CreateDirectory(directory);
|
||||||
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 FieldValidationException("files", "Velikost přílohy neodpovídá požadavku.");
|
throw new BadRequestException("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 FieldValidationException("files", "Velikost přílohy neodpovídá požadavku.");
|
throw new BadRequestException("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 FieldValidationException("files", "Obsah přílohy neodpovídá její příponě.");
|
throw new BadRequestException("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(UploadDirectory, key)
|
? Path.Combine(directory, 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)
|
||||||
|
|||||||
@@ -10,8 +10,6 @@
|
|||||||
<PackageReference Include="MySqlConnector" />
|
<PackageReference Include="MySqlConnector" />
|
||||||
<PackageReference Include="EFCore.NamingConventions" />
|
<PackageReference Include="EFCore.NamingConventions" />
|
||||||
<PackageReference Include="BCrypt.Net-Next" />
|
<PackageReference Include="BCrypt.Net-Next" />
|
||||||
<PackageReference Include="MailKit" />
|
|
||||||
<PackageReference Include="FirebaseAdmin" />
|
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Caching.Memory" />
|
<PackageReference Include="Microsoft.Extensions.Caching.Memory" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
|
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
|
||||||
|
|||||||
@@ -1,110 +0,0 @@
|
|||||||
using System.Security.Cryptography;
|
|
||||||
using FirebaseAdmin;
|
|
||||||
using FirebaseAdmin.Messaging;
|
|
||||||
using Google.Apis.Auth.OAuth2;
|
|
||||||
using Google.Apis.Auth.OAuth2.Responses;
|
|
||||||
using Helpdesk.Domain;
|
|
||||||
|
|
||||||
namespace Helpdesk.Infrastructure.Notifications;
|
|
||||||
|
|
||||||
internal sealed record PushDeliveryResult(bool Sent, bool Retryable, string FailureReason, IReadOnlyList<string> InvalidTokens);
|
|
||||||
|
|
||||||
internal sealed class FirebasePushSender(FirebaseApp app) : IDisposable
|
|
||||||
{
|
|
||||||
public static FirebasePushSender Create(string serviceAccountJson)
|
|
||||||
{
|
|
||||||
ServiceAccountCredential credential;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
credential = CredentialFactory.FromJson<ServiceAccountCredential>(serviceAccountJson);
|
|
||||||
}
|
|
||||||
catch (Exception exception) when (
|
|
||||||
exception is ArgumentException or InvalidOperationException or CryptographicException or Newtonsoft.Json.JsonException)
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException("Nastavte platný JSON klíče servisního účtu Firebase.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(credential.ProjectId))
|
|
||||||
throw new InvalidOperationException("Klíč servisního účtu Firebase musí obsahovat project_id.");
|
|
||||||
|
|
||||||
var app = FirebaseApp.Create(new AppOptions
|
|
||||||
{
|
|
||||||
Credential = credential.ToGoogleCredential(),
|
|
||||||
ProjectId = credential.ProjectId,
|
|
||||||
});
|
|
||||||
return new FirebasePushSender(app);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<PushDeliveryResult> SendAsync(string[] tokens, CancellationToken ct)
|
|
||||||
{
|
|
||||||
var messaging = FirebaseMessaging.GetMessaging(app);
|
|
||||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
||||||
timeout.CancelAfter(TimeSpan.FromSeconds(15));
|
|
||||||
var invalidTokens = new List<string>();
|
|
||||||
var sent = false;
|
|
||||||
var retryable = false;
|
|
||||||
var reason = "FCM_NO_ACCEPTED_DEVICE";
|
|
||||||
|
|
||||||
foreach (var batch in tokens.Chunk(500))
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var result = await messaging.SendEachForMulticastAsync(new MulticastMessage
|
|
||||||
{
|
|
||||||
#pragma warning disable CS0618 // API zařízení podle návrhu přijímá registrační tokeny FCM.
|
|
||||||
Tokens = batch,
|
|
||||||
#pragma warning restore CS0618
|
|
||||||
Notification = new Notification
|
|
||||||
{
|
|
||||||
Title = "NTBug",
|
|
||||||
Body = "V aplikaci máte novou notifikaci.",
|
|
||||||
},
|
|
||||||
}, timeout.Token);
|
|
||||||
|
|
||||||
sent |= result.SuccessCount > 0;
|
|
||||||
for (var i = 0; i < result.Responses.Count; i++)
|
|
||||||
{
|
|
||||||
if (result.Responses[i].Exception is not { } failure)
|
|
||||||
continue;
|
|
||||||
if (IsInvalidToken(failure))
|
|
||||||
invalidTokens.Add(batch[i]);
|
|
||||||
|
|
||||||
if (!retryable)
|
|
||||||
reason = FailureReason(failure);
|
|
||||||
retryable |= IsRetryable(failure);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (FirebaseMessagingException failure)
|
|
||||||
{
|
|
||||||
if (!retryable)
|
|
||||||
reason = FailureReason(failure);
|
|
||||||
retryable |= IsRetryable(failure);
|
|
||||||
}
|
|
||||||
catch (TokenResponseException)
|
|
||||||
{
|
|
||||||
return new PushDeliveryResult(sent, true, "FCM_AUTHENTICATION_FAILED", invalidTokens);
|
|
||||||
}
|
|
||||||
catch (Exception failure) when (!ct.IsCancellationRequested &&
|
|
||||||
failure is HttpRequestException or IOException or OperationCanceledException)
|
|
||||||
{
|
|
||||||
return new PushDeliveryResult(sent, true, $"FCM_{failure.GetType().Name}", invalidTokens);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return new PushDeliveryResult(sent, retryable, reason, invalidTokens);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static bool IsInvalidToken(FirebaseMessagingException failure) =>
|
|
||||||
failure.MessagingErrorCode == MessagingErrorCode.Unregistered ||
|
|
||||||
(failure.MessagingErrorCode == MessagingErrorCode.InvalidArgument &&
|
|
||||||
failure.Message.Contains("registration token", StringComparison.OrdinalIgnoreCase));
|
|
||||||
|
|
||||||
private static bool IsRetryable(FirebaseMessagingException failure) =>
|
|
||||||
failure.MessagingErrorCode is MessagingErrorCode.Unavailable or MessagingErrorCode.Internal or MessagingErrorCode.QuotaExceeded ||
|
|
||||||
failure.ErrorCode is ErrorCode.Unavailable or ErrorCode.Internal or ErrorCode.ResourceExhausted or ErrorCode.DeadlineExceeded;
|
|
||||||
|
|
||||||
private static string FailureReason(FirebaseMessagingException failure) =>
|
|
||||||
$"FCM_{failure.MessagingErrorCode?.ToCode() ?? failure.ErrorCode.ToCode()}";
|
|
||||||
|
|
||||||
public void Dispose() => app.Delete();
|
|
||||||
}
|
|
||||||
@@ -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 není žádný aktivní administrátor.
|
/// Při startu vytvoří účet administrátora z <c>ADMIN_EMAIL</c> a <c>ADMIN_PASSWORD</c>, pokud ještě neexistuje.
|
||||||
/// 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,8 +29,7 @@ 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 ||
|
if (await db.Users.AnyAsync(u => u.EmailNormalized == normalized, cancellationToken))
|
||||||
(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,7 +16,6 @@ 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")
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
using System.Data;
|
using System.Data;
|
||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
using Helpdesk.Application.Common;
|
|
||||||
using Helpdesk.Application.Statistics;
|
|
||||||
using Helpdesk.Domain.Auth;
|
using Helpdesk.Domain.Auth;
|
||||||
using Helpdesk.Domain.Catalogs;
|
using Helpdesk.Domain.Catalogs;
|
||||||
using Helpdesk.Domain.Issues;
|
using Helpdesk.Domain.Issues;
|
||||||
@@ -12,7 +10,6 @@ using Helpdesk.Infrastructure.Security;
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.EntityFrameworkCore.Storage;
|
using Microsoft.EntityFrameworkCore.Storage;
|
||||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
using MySqlConnector;
|
|
||||||
|
|
||||||
namespace Helpdesk.Infrastructure.Persistence;
|
namespace Helpdesk.Infrastructure.Persistence;
|
||||||
|
|
||||||
@@ -30,7 +27,6 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
|||||||
public DbSet<ProposalCategory> ProposalCategories => Set<ProposalCategory>();
|
public DbSet<ProposalCategory> ProposalCategories => Set<ProposalCategory>();
|
||||||
public DbSet<Issue> Issues => Set<Issue>();
|
public DbSet<Issue> Issues => Set<Issue>();
|
||||||
public DbSet<IssueEvent> IssueEvents => Set<IssueEvent>();
|
public DbSet<IssueEvent> IssueEvents => Set<IssueEvent>();
|
||||||
public IQueryable<IssueTiming> IssueTimings => Set<IssueTiming>();
|
|
||||||
public DbSet<Attachment> Attachments => Set<Attachment>();
|
public DbSet<Attachment> Attachments => Set<Attachment>();
|
||||||
public DbSet<Proposal> Proposals => Set<Proposal>();
|
public DbSet<Proposal> Proposals => Set<Proposal>();
|
||||||
public DbSet<ProposalEvent> ProposalEvents => Set<ProposalEvent>();
|
public DbSet<ProposalEvent> ProposalEvents => Set<ProposalEvent>();
|
||||||
@@ -40,49 +36,9 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
|||||||
public DbSet<NotificationDelivery> NotificationDeliveries => Set<NotificationDelivery>();
|
public DbSet<NotificationDelivery> NotificationDeliveries => Set<NotificationDelivery>();
|
||||||
public DbSet<PushDevice> PushDevices => Set<PushDevice>();
|
public DbSet<PushDevice> PushDevices => Set<PushDevice>();
|
||||||
|
|
||||||
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
|
public Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct) =>
|
||||||
{
|
|
||||||
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
|
|
||||||
{
|
|
||||||
return await base.SaveChangesAsync(cancellationToken);
|
|
||||||
}
|
|
||||||
catch (DbUpdateException exception) when (
|
|
||||||
exception.InnerException is MySqlException { ErrorCode: MySqlErrorCode.DuplicateKeyEntry } &&
|
|
||||||
exception.Entries is [var entry] && entry.Entity is (IssueCategory or ProposalCategory))
|
|
||||||
{
|
|
||||||
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> 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ů.
|
||||||
@@ -99,12 +55,6 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
|||||||
modelBuilder.ApplyConfiguration(new ProposalCategoryConfiguration());
|
modelBuilder.ApplyConfiguration(new ProposalCategoryConfiguration());
|
||||||
modelBuilder.ApplyConfiguration(new IssueConfiguration());
|
modelBuilder.ApplyConfiguration(new IssueConfiguration());
|
||||||
modelBuilder.ApplyConfiguration(new IssueEventConfiguration());
|
modelBuilder.ApplyConfiguration(new IssueEventConfiguration());
|
||||||
modelBuilder.Entity<IssueTiming>().HasNoKey().ToSqlQuery("""
|
|
||||||
SELECT issue_id,
|
|
||||||
TIMESTAMPDIFF(MICROSECOND, created_at, first_assigned_at) AS microseconds_to_assignment,
|
|
||||||
TIMESTAMPDIFF(MICROSECOND, created_at, closed_at) AS microseconds_to_closure
|
|
||||||
FROM v_issue_lifecycle
|
|
||||||
""");
|
|
||||||
modelBuilder.ApplyConfiguration(new AttachmentConfiguration());
|
modelBuilder.ApplyConfiguration(new AttachmentConfiguration());
|
||||||
modelBuilder.ApplyConfiguration(new ProposalConfiguration());
|
modelBuilder.ApplyConfiguration(new ProposalConfiguration());
|
||||||
modelBuilder.ApplyConfiguration(new ProposalEventConfiguration());
|
modelBuilder.ApplyConfiguration(new ProposalEventConfiguration());
|
||||||
@@ -112,18 +62,9 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
|||||||
modelBuilder.Entity<ProposalScore>().HasNoKey().ToView("v_proposal_score");
|
modelBuilder.Entity<ProposalScore>().HasNoKey().ToView("v_proposal_score");
|
||||||
modelBuilder.ApplyConfiguration(new NotificationConfiguration());
|
modelBuilder.ApplyConfiguration(new NotificationConfiguration());
|
||||||
modelBuilder.ApplyConfiguration(new NotificationDeliveryConfiguration());
|
modelBuilder.ApplyConfiguration(new NotificationDeliveryConfiguration());
|
||||||
var pushDevice = modelBuilder.Entity<PushDevice>();
|
modelBuilder.Entity<PushDevice>().ToTable("push_device");
|
||||||
pushDevice.ToTable("push_device");
|
|
||||||
pushDevice.Property(x => x.FcmToken).HasMaxLength(512);
|
|
||||||
pushDevice.HasIndex(x => x.FcmToken).IsUnique();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct) =>
|
|
||||||
Database.ExecuteSqlInterpolatedAsync($"""
|
|
||||||
INSERT INTO push_device (user_id, fcm_token) VALUES ({userId}, {token})
|
|
||||||
ON DUPLICATE KEY UPDATE user_id = VALUES(user_id)
|
|
||||||
""", ct);
|
|
||||||
|
|
||||||
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
|
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
|
||||||
{
|
{
|
||||||
// Všechny časy jsou v DB v UTC; při čtení jim nastavíme Kind = Utc, aby se v JSON serializovaly se "Z".
|
// Všechny časy jsou v DB v UTC; při čtení jim nastavíme Kind = Utc, aby se v JSON serializovaly se "Z".
|
||||||
|
|||||||
@@ -73,7 +73,6 @@ internal sealed class NotificationDeliveryConfiguration : IEntityTypeConfigurati
|
|||||||
b.ToTable("notification_delivery");
|
b.ToTable("notification_delivery");
|
||||||
b.Property(x => x.Channel).HasConversion<EnumCodeConverter<DeliveryChannel>>().HasMaxLength(10);
|
b.Property(x => x.Channel).HasConversion<EnumCodeConverter<DeliveryChannel>>().HasMaxLength(10);
|
||||||
b.Property(x => x.Status).HasConversion<EnumCodeConverter<DeliveryStatus>>().HasMaxLength(10);
|
b.Property(x => x.Status).HasConversion<EnumCodeConverter<DeliveryStatus>>().HasMaxLength(10);
|
||||||
b.Property(x => x.LastError).HasMaxLength(1000);
|
|
||||||
b.HasOne(x => x.Notification).WithMany().HasForeignKey(x => x.NotificationId);
|
b.HasOne(x => x.Notification).WithMany().HasForeignKey(x => x.NotificationId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
using System.Security.Cryptography;
|
|
||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
|
|
||||||
namespace Helpdesk.Infrastructure.Security;
|
namespace Helpdesk.Infrastructure.Security;
|
||||||
@@ -7,15 +6,8 @@ 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)
|
public bool Verify(string password, string passwordHash) => BCrypt.Net.BCrypt.Verify(password, passwordHash);
|
||||||
{
|
|
||||||
var hasPassword = !string.IsNullOrEmpty(passwordHash);
|
|
||||||
var matches = BCrypt.Net.BCrypt.Verify(password, hasPassword ? passwordHash : dummyHash);
|
|
||||||
return hasPassword && matches;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -26,9 +26,8 @@ internal sealed class RevokedTokenStore(TimeProvider clock) : IRevokedTokenStore
|
|||||||
|
|
||||||
public void Add(string jti, DateTime expiresAt)
|
public void Add(string jti, DateTime expiresAt)
|
||||||
{
|
{
|
||||||
var rejectUntil = expiresAt + JwtTokenService.ClockSkew;
|
if (expiresAt > clock.GetUtcNow().UtcDateTime)
|
||||||
if (rejectUntil > clock.GetUtcNow().UtcDateTime)
|
_revoked[jti] = expiresAt;
|
||||||
_revoked[jti] = rejectUntil;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void PruneOccasionally()
|
private void PruneOccasionally()
|
||||||
@@ -53,10 +52,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 earliestExpiry = clock.GetUtcNow().UtcDateTime - JwtTokenService.ClockSkew;
|
var now = clock.GetUtcNow().UtcDateTime;
|
||||||
|
|
||||||
var revoked = await db.AuthTokens.AsNoTracking()
|
var revoked = await db.AuthTokens.AsNoTracking()
|
||||||
.Where(t => t.TokenType == TokenType.Access && t.RevokedAt != null && t.ExpiresAt > earliestExpiry)
|
.Where(t => t.TokenType == TokenType.Access && t.RevokedAt != null && t.ExpiresAt > now)
|
||||||
.Select(t => new { t.Jti, t.ExpiresAt })
|
.Select(t => new { t.Jti, t.ExpiresAt })
|
||||||
.ToListAsync(cancellationToken);
|
.ToListAsync(cancellationToken);
|
||||||
|
|
||||||
|
|||||||
@@ -1,292 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
@@ -1,113 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,169 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,219 +0,0 @@
|
|||||||
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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,105 +0,0 @@
|
|||||||
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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,196 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,157 +0,0 @@
|
|||||||
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}.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
<?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,11 +37,46 @@ 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 UserTests
|
public class UserLockoutTests
|
||||||
{
|
{
|
||||||
|
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]", User.Create("[email protected]", "hash", "Jan", "Novák", UserRole.Student).EmailNormalized);
|
Assert.Equal("[email protected]", NewUser().EmailNormalized);
|
||||||
}
|
}
|
||||||
|
|
||||||
public class RegistrationRoleTests
|
public class RegistrationRoleTests
|
||||||
|
|||||||
@@ -21,18 +21,15 @@ public sealed class IssueTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData(IssueStatus.Received, UserRole.Management)]
|
[InlineData(IssueStatus.Received)]
|
||||||
[InlineData(IssueStatus.Assigned, UserRole.Management)]
|
[InlineData(IssueStatus.Assigned)]
|
||||||
[InlineData(IssueStatus.InProgress, UserRole.Management)]
|
[InlineData(IssueStatus.InProgress)]
|
||||||
[InlineData(IssueStatus.Received, UserRole.Admin)]
|
public void ManagementCanAssignOrReassign(IssueStatus from)
|
||||||
[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, role));
|
Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.Assign, Manager, UserRole.Management));
|
||||||
issue.Assign(Manager, role, Replacement, UserRole.Management, IssuePriority.High);
|
issue.Assign(Manager, UserRole.Management, 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);
|
||||||
@@ -41,17 +38,12 @@ 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.Confirm, Replacement, UserRole.Admin, IssueStatus.Resolved)]
|
[InlineData(IssueStatus.PendingVerification, IssueAction.Reopen, Reporter, UserRole.Admin, IssueStatus.InProgress)]
|
||||||
[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)
|
||||||
{
|
{
|
||||||
@@ -71,7 +63,6 @@ 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(
|
||||||
@@ -111,12 +102,10 @@ 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.True(issue.CanRead(Replacement, UserRole.Admin));
|
Assert.False(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,14 +35,12 @@ public sealed class ProposalTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ReviewRequiresManagementOrAdminAndRejectionRequiresNote()
|
public void ReviewRequiresManagementAndRejectionRequiresNote()
|
||||||
{
|
{
|
||||||
var proposal = At(ProposalStatus.Submitted);
|
var proposal = At(ProposalStatus.Submitted);
|
||||||
Assert.Throws<InvalidOperationException>(() => proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Student, null));
|
Assert.Throws<InvalidOperationException>(() => proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Admin, null));
|
||||||
Assert.Throws<ArgumentException>(() => proposal.ChangeStatus(ProposalStatus.Rejected, UserRole.Admin, " "));
|
Assert.Throws<ArgumentException>(() => proposal.ChangeStatus(ProposalStatus.Rejected, UserRole.Management, " "));
|
||||||
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]
|
||||||
@@ -51,25 +49,22 @@ 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 AuthorAndAdminEditAndOtherUsersVoteOnlyInEligibleStates(ProposalStatus state, bool mayEdit, bool mayVote)
|
public void AuthorEditsAndOtherUserVotesOnlyInEligibleStates(ProposalStatus state, bool mayEdit, bool mayVote)
|
||||||
{
|
{
|
||||||
var proposal = At(state);
|
var proposal = At(state);
|
||||||
Assert.Equal(mayEdit, proposal.IsEditable);
|
Assert.Equal(mayEdit, proposal.CanEdit(Author));
|
||||||
|
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, UserRole.Student, "Změna", "Popis", 1));
|
Assert.Throws<InvalidOperationException>(() => proposal.Edit(Voter, "Změna", "Popis", 1));
|
||||||
if (mayEdit)
|
if (mayEdit)
|
||||||
{
|
{
|
||||||
proposal.Edit(Author, UserRole.Student, "Změna", "Popis", 1);
|
proposal.Edit(Author, "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, UserRole.Student, "Změna", "Popis", 1));
|
Assert.Throws<InvalidOperationException>(() => proposal.Edit(Author, "Změna", "Popis", 1));
|
||||||
Assert.Throws<InvalidOperationException>(() => proposal.Edit(Voter, UserRole.Admin, "Změna", "Popis", 1));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +0,0 @@
|
|||||||
-- Registrační token FCM rozlišuje velikost písmen.
|
|
||||||
ALTER TABLE push_device
|
|
||||||
MODIFY fcm_token VARCHAR(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL;
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
CREATE INDEX ix_proposal_created_at ON proposal (created_at);
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
ALTER TABLE app_user
|
|
||||||
ADD COLUMN is_deleted BOOLEAN NOT NULL DEFAULT FALSE;
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
ALTER TABLE app_user
|
|
||||||
ADD COLUMN row_version INT NOT NULL DEFAULT 0;
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
ALTER TABLE app_user
|
|
||||||
DROP COLUMN IF EXISTS failed_login_count,
|
|
||||||
DROP COLUMN IF EXISTS lockout_until;
|
|
||||||
+4
-29
@@ -11,35 +11,10 @@ APP_DB_PASSWORD=change-me-app
|
|||||||
JWT_SIGNING_KEY=change-me-to-a-random-string-of-at-least-32-bytes
|
JWT_SIGNING_KEY=change-me-to-a-random-string-of-at-least-32-bytes
|
||||||
ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
|
ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
|
||||||
|
|
||||||
# Volitelný účet administrátora vytvořený při prvním startu API.
|
# Účet administrátora – vytvoří se při prvním startu API, pokud neexistuje.
|
||||||
ADMIN_EMAIL=admin@domain.local
|
ADMIN_EMAIL=admin@univerzita.cz
|
||||||
ADMIN_PASSWORD=change-me-admin
|
ADMIN_PASSWORD=change-me-admin
|
||||||
|
|
||||||
# HTTP adresa a port API na hostiteli, kam se reverse proxy připojuje.
|
|
||||||
# Loopback použijte pro reverse proxy běžící přímo na stejném hostiteli.
|
|
||||||
PROXY_UPSTREAM_BIND_ADDRESS=127.0.0.1
|
|
||||||
API_HTTP_PORT=8080
|
|
||||||
# Port webové aplikace na hostiteli (stejná adresa jako API).
|
|
||||||
WEB_HTTP_PORT=8081
|
|
||||||
# Adresa reverse proxy tak, jak ji API a web vidí jako bezprostředního klienta.
|
|
||||||
TRUSTED_REVERSE_PROXY_IP=
|
|
||||||
|
|
||||||
# Veřejná HTTPS adresa webu pro odkazy v e-mailech a povolené univerzitní domény.
|
|
||||||
# Lokálně bez proxy: http://localhost:8081 (odkazy z e-mailů pak vedou na web v Dockeru).
|
|
||||||
PUBLIC_BASE_URL= #https://helpdesk.domain.local
|
|
||||||
STUDENT_EMAIL_DOMAIN= #student.domain.local
|
|
||||||
TEACHER_EMAIL_DOMAIN= #domain.local
|
|
||||||
|
|
||||||
# Email Profi. V Production vyplňte celou adresu schránky a její heslo.
|
|
||||||
SMTP_HOST=smtp.seznam.cz
|
|
||||||
SMTP_PORT=465
|
|
||||||
SMTP_MAILBOX=
|
|
||||||
# Jednoduché uvozovky zachovají ve skutečném hesle např. znak $.
|
|
||||||
SMTP_PASSWORD=''
|
|
||||||
|
|
||||||
# Jednořádkový JSON klíče servisního účtu Firebase v jednoduchých uvozovkách.
|
|
||||||
FIREBASE_SERVICE_ACCOUNT_JSON=''
|
|
||||||
|
|
||||||
# Development = bez proxy
|
|
||||||
# Production = s reverse proxy
|
|
||||||
ASPNETCORE_ENVIRONMENT=Development
|
ASPNETCORE_ENVIRONMENT=Development
|
||||||
|
|
||||||
|
API_PORT=8080
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
FROM mariadb:11.4
|
|
||||||
COPY --chmod=0644 01-accounts.sh /docker-entrypoint-initdb.d/01-accounts.sh
|
|
||||||
@@ -1,12 +1,11 @@
|
|||||||
# Vývojové spuštění: docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build
|
# Vývojové spuštění backendu: 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
|
# Topologie odpovídá kap. 15 návrhu; proxy (nginx + HTTPS), web a mailpit přibudou v dalších fázích.
|
||||||
# (/ včetně /swagger → web, /api/* → api).
|
|
||||||
|
|
||||||
name: helpdesk
|
name: helpdesk
|
||||||
|
|
||||||
services:
|
services:
|
||||||
db:
|
db:
|
||||||
build: ./db-init
|
image: mariadb:11.4
|
||||||
environment:
|
environment:
|
||||||
MARIADB_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:?}
|
MARIADB_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:?}
|
||||||
MARIADB_DATABASE: helpdesk
|
MARIADB_DATABASE: helpdesk
|
||||||
@@ -15,6 +14,7 @@ services:
|
|||||||
APP_DB_PASSWORD: ${APP_DB_PASSWORD:?}
|
APP_DB_PASSWORD: ${APP_DB_PASSWORD:?}
|
||||||
volumes:
|
volumes:
|
||||||
- db-data:/var/lib/mysql
|
- db-data:/var/lib/mysql
|
||||||
|
- ./db-init:/docker-entrypoint-initdb.d:ro
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
|
test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
|
||||||
interval: 5s
|
interval: 5s
|
||||||
@@ -44,16 +44,6 @@ services:
|
|||||||
ConnectionStrings__Helpdesk: "Server=db;Database=helpdesk;User=helpdesk_app;Password=${APP_DB_PASSWORD}"
|
ConnectionStrings__Helpdesk: "Server=db;Database=helpdesk;User=helpdesk_app;Password=${APP_DB_PASSWORD}"
|
||||||
Jwt__SigningKey: ${JWT_SIGNING_KEY:?}
|
Jwt__SigningKey: ${JWT_SIGNING_KEY:?}
|
||||||
Encryption__Key: ${ENCRYPTION_KEY:?}
|
Encryption__Key: ${ENCRYPTION_KEY:?}
|
||||||
Registration__WebBaseUrl: ${PUBLIC_BASE_URL:-https://helpdesk.localhost}
|
|
||||||
Registration__StudentEmailDomains__0: ${STUDENT_EMAIL_DOMAIN:-student.univerzita.cz}
|
|
||||||
Registration__TeacherEmailDomains__0: ${TEACHER_EMAIL_DOMAIN:-univerzita.cz}
|
|
||||||
Smtp__Host: ${SMTP_HOST:-smtp.seznam.cz}
|
|
||||||
Smtp__Port: ${SMTP_PORT:-465}
|
|
||||||
Smtp__Mailbox: ${SMTP_MAILBOX:-}
|
|
||||||
Smtp__Password: ${SMTP_PASSWORD:-}
|
|
||||||
Firebase__ServiceAccountJson: ${FIREBASE_SERVICE_ACCOUNT_JSON:-}
|
|
||||||
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:
|
||||||
@@ -61,46 +51,16 @@ services:
|
|||||||
depends_on:
|
depends_on:
|
||||||
migrator:
|
migrator:
|
||||||
condition: service_completed_successfully
|
condition: service_completed_successfully
|
||||||
|
# Dočasně publikováno přímo; po přidání nginx proxy bude API dostupné jen přes ni.
|
||||||
ports:
|
ports:
|
||||||
- "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${API_HTTP_PORT:-8080}:8080"
|
- "8080:8080"
|
||||||
networks:
|
networks: [frontend, backend]
|
||||||
frontend:
|
|
||||||
backend:
|
|
||||||
web-api:
|
|
||||||
aliases: [api-web]
|
|
||||||
|
|
||||||
web:
|
|
||||||
build:
|
|
||||||
context: ..
|
|
||||||
dockerfile: web/Dockerfile
|
|
||||||
environment:
|
|
||||||
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Development}
|
|
||||||
Api__BaseUrl: http://api-web:8080/
|
|
||||||
ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-}
|
|
||||||
volumes:
|
|
||||||
# Klíče pro šifrování cookie – bez nich by restart kontejneru odhlásil všechny uživatele.
|
|
||||||
- web-keys:/app/keys
|
|
||||||
depends_on:
|
|
||||||
- api
|
|
||||||
ports:
|
|
||||||
- "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${WEB_HTTP_PORT:-8081}:8080"
|
|
||||||
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:
|
||||||
uploads:
|
uploads:
|
||||||
web-keys:
|
|
||||||
+117
-128
@@ -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 systému, všechny akce nad závadami a návrhy, 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ů |
|
||||||
|
|
||||||
- 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,26 +86,23 @@ 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 hlášení | 🔸 vlastní ve stavu *Přijata* | 🔸 vlastní ve stavu *Přijata* | 🔸 vlastní ve stavu *Přijata* | 🔸 libovolné ve stavu *Přijata* |
|
| Upravit vlastní hlášení | 🔸 jen 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 | 🔸 ve stavu příslušného přechodu |
|
| Zahájit řešení, předat k ověření | — | 🔸 jen přiřazené jemu | 🔸 jen přiřazené jemu | — |
|
||||||
| 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 |
|
| Zamítnout závadu (s důvodem) | — | 🔸 jen přiřazené jemu | 🔸 přiřazené jemu nebo nepřiřazené ve stavu *Přijata* | — |
|
||||||
| Potvrdit vyřešení / znovu otevřít | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 ve stavu *Čeká na ověření* |
|
| Potvrdit vyřešení / znovu otevřít | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen 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 |
|
| Komentovat závadu | 🔸 hlásič | 🔸 hlásič nebo řešitel | 🔸 hlásič nebo řešitel; ostatní jen čtení | 🔸 hlásič |
|
||||||
| 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í | 🔸 | 🔸 | 🔸 |
|
||||||
| Upravit návrh ve stavu *Podán* | 🔸 autor | 🔸 autor | 🔸 autor | ✅ |
|
| Hodnotit návrhy (změna stavu, vyjádření) | — | — | ✅ | — |
|
||||||
| Hodnotit návrhy (změna stavu, vyjádření) | — | — | ✅ | ✅ |
|
| Statistiky a výkazy | — | — | ✅ | — |
|
||||||
| 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
|
||||||
@@ -113,10 +110,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 univerzitním e-mailem. Příjemce ověří e-mail a nastaví heslo přes jednorázový odkaz. |
|
| FR-01 | Registrace e-mailem a heslem; po registraci ověření e-mailu odkazem. |
|
||||||
| 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á, 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-04 | Administrátor vyhledává uživatele, mění jejich roli, deaktivuje účty. |
|
||||||
| 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
|
||||||
@@ -125,7 +122,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í 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-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-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. |
|
||||||
@@ -137,13 +134,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í a administrátor hodnotí návrhy, mění jejich stav (*V posouzení, Přijat, Zamítnut, Realizován*) a připojují vyjádření. |
|
| FR-23 | Vedení hodnotí návrhy – mění stav (*V posouzení, Přijat, Zamítnut, Realizován*) a připojuje 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í 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-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-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. |
|
||||||
|
|
||||||
@@ -156,7 +153,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 na `/swagger` pro administrátory přihlášené na webu. Volání API ze Swaggeru se autorizují access tokenem. |
|
| NFR-04 | Dokumentace API | Swagger UI (OpenAPI) dostupné na `/swagger`, včetně autorizace 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`. |
|
||||||
@@ -201,7 +198,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 --- UC5 & UC6 & UC7 & UC12 & UC20 & UC21 & UC22 & UC23
|
A --- 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í).*
|
||||||
@@ -232,16 +229,16 @@ stateDiagram-v2
|
|||||||
state "Zamítnuta" as REJECTED
|
state "Zamítnuta" as REJECTED
|
||||||
|
|
||||||
[*] --> RECEIVED : hlásič vytvoří
|
[*] --> RECEIVED : hlásič vytvoří
|
||||||
RECEIVED --> ASSIGNED : vedení nebo admin přiřadí řešitele
|
RECEIVED --> ASSIGNED : vedení přiřadí řešitele
|
||||||
ASSIGNED --> ASSIGNED : vedení nebo admin přeřadí
|
ASSIGNED --> ASSIGNED : vedení přeřadí
|
||||||
ASSIGNED --> IN_PROGRESS : řešitel nebo admin zahájí
|
ASSIGNED --> IN_PROGRESS : řešitel zahájí
|
||||||
IN_PROGRESS --> ASSIGNED : vedení nebo admin přeřadí
|
IN_PROGRESS --> ASSIGNED : vedení přeřadí
|
||||||
IN_PROGRESS --> PENDING_VERIFICATION : řešitel nebo admin předá k ověření
|
IN_PROGRESS --> PENDING_VERIFICATION : řešitel předá k ověření
|
||||||
PENDING_VERIFICATION --> RESOLVED : hlásič nebo admin potvrdí
|
PENDING_VERIFICATION --> RESOLVED : hlásič potvrdí
|
||||||
PENDING_VERIFICATION --> IN_PROGRESS : hlásič nebo admin znovu otevře
|
PENDING_VERIFICATION --> IN_PROGRESS : hlásič znovu otevře
|
||||||
RECEIVED --> REJECTED : vedení nebo admin zamítne
|
RECEIVED --> REJECTED : vedení zamítne
|
||||||
ASSIGNED --> REJECTED : řešitel nebo admin zamítne
|
ASSIGNED --> REJECTED : řešitel zamítne
|
||||||
IN_PROGRESS --> REJECTED : řešitel nebo admin zamítne
|
IN_PROGRESS --> REJECTED : řešitel zamítne
|
||||||
RESOLVED --> [*]
|
RESOLVED --> [*]
|
||||||
REJECTED --> [*]
|
REJECTED --> [*]
|
||||||
```
|
```
|
||||||
@@ -251,14 +248,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í / admin | řešitel (správce budov / vedení / admin) | `assignee_id`, událost `ASSIGNED` | řešitel: `ISSUE_ASSIGNED`; hlásič: změna stavu |
|
| 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 |
|
||||||
| 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 |
|
| 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` |
|
||||||
| T4 | Přiřazena → **V řešení** | přiřazený řešitel / admin | — | událost `STATUS_CHANGED` | hlásič |
|
| T4 | Přiřazena → **V řešení** | přiřazený řešitel | — | 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č |
|
| T5 | V řešení → **Čeká na ověření** | přiřazený řešitel | volitelná poznámka | událost `STATUS_CHANGED` | hlásič |
|
||||||
| T6 | Čeká na ověření → **Vyřešena** | hlásič / admin | — | událost `STATUS_CHANGED` (= čas uzavření) | řešitel |
|
| T6 | Čeká na ověření → **Vyřešena** | hlásič | — | událost `STATUS_CHANGED` (= čas uzavření) | řešitel |
|
||||||
| 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` |
|
| 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` |
|
||||||
| 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č |
|
| 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č |
|
||||||
| T9 | Přijata → **Zamítnuta** | vedení / 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č |
|
||||||
|
|
||||||
**Obecná pravidla**
|
**Obecná pravidla**
|
||||||
|
|
||||||
@@ -303,19 +300,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í nebo admin
|
SUBMITTED --> UNDER_REVIEW : vedení
|
||||||
SUBMITTED --> ACCEPTED : vedení nebo admin
|
SUBMITTED --> ACCEPTED : vedení
|
||||||
SUBMITTED --> REJECTED : vedení nebo admin (s vyjádřením)
|
SUBMITTED --> REJECTED : vedení (s vyjádřením)
|
||||||
UNDER_REVIEW --> ACCEPTED : vedení nebo admin
|
UNDER_REVIEW --> ACCEPTED : vedení
|
||||||
UNDER_REVIEW --> REJECTED : vedení nebo admin (s vyjádřením)
|
UNDER_REVIEW --> REJECTED : vedení (s vyjádřením)
|
||||||
ACCEPTED --> IMPLEMENTED : vedení nebo admin
|
ACCEPTED --> IMPLEMENTED : vedení
|
||||||
REJECTED --> [*]
|
REJECTED --> [*]
|
||||||
IMPLEMENTED --> [*]
|
IMPLEMENTED --> [*]
|
||||||
```
|
```
|
||||||
|
|
||||||
- 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.
|
- 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.
|
||||||
- Autor nebo administrátor může návrh upravit, dokud je ve stavu *Podán* (událost `UPDATED`).
|
- Autor může návrh upravit, dokud je ve stavu *Podán* (událost `UPDATED`).
|
||||||
- Každá změna se zapisuje do `proposal_event`. Při změně stavu dostane autor notifikaci, pokud stav nezměnil sám.
|
- Každá změna se zapisuje do `proposal_event`, autor dostane notifikaci.
|
||||||
|
|
||||||
### 7.2 Pravidla hlasování
|
### 7.2 Pravidla hlasování
|
||||||
|
|
||||||
@@ -323,8 +320,8 @@ stateDiagram-v2
|
|||||||
|---|---|
|
|---|---|
|
||||||
| Každý uživatel má jeden hlas (na návrh) | Primární klíč `proposal_vote (proposal_id, user_id)` – druhý hlas fyzicky nelze uložit |
|
| Každý uživatel má jeden hlas (na návrh) | Primární klíč `proposal_vote (proposal_id, user_id)` – druhý hlas fyzicky nelze uložit |
|
||||||
| Hlas pro / proti | `value` = `+1` / `-1` (CHECK omezení) |
|
| Hlas pro / proti | `value` = `+1` / `-1` (CHECK omezení) |
|
||||||
| Hlas lze změnit | `PUT /api/v1/proposals/{id}/vote` s novou hodnotou → UPDATE (upsert) |
|
| Hlas lze změnit | `PUT /api/proposals/{id}/vote` s novou hodnotou → UPDATE (upsert) |
|
||||||
| Hlas lze zrušit | `DELETE /api/v1/proposals/{id}/vote` → DELETE |
|
| Hlas lze zrušit | `DELETE /api/proposals/{id}/vote` → DELETE |
|
||||||
| Autor nehlasuje pro vlastní návrh | Kontrola v aplikační vrstvě → 403 |
|
| Autor nehlasuje pro vlastní návrh | Kontrola v aplikační vrstvě → 403 |
|
||||||
| Hlasovat lze jen o otevřených návrzích | Stav *Podán* nebo *V posouzení*; po rozhodnutí vedení je hlasování uzavřeno (409) |
|
| Hlasovat lze jen o otevřených návrzích | Stav *Podán* nebo *V posouzení*; po rozhodnutí vedení je hlasování uzavřeno (409) |
|
||||||
| Pořadí podle podpory | Pohled `v_proposal_score` (počet pro, proti, skóre = součet) |
|
| Pořadí podle podpory | Pohled `v_proposal_score` (počet pro, proti, skóre = součet) |
|
||||||
@@ -357,7 +354,7 @@ sequenceDiagram
|
|||||||
participant SMTP as SMTP server
|
participant SMTP as SMTP server
|
||||||
participant FCM as Firebase Cloud Messaging
|
participant FCM as Firebase Cloud Messaging
|
||||||
|
|
||||||
C->>API: POST /api/v1/issues/42/assign
|
C->>API: POST /api/issues/42/assign
|
||||||
API->>DB: BEGIN; UPDATE issue; INSERT issue_event;<br/>INSERT notification (×N);<br/>INSERT notification_delivery (EMAIL, PUSH); COMMIT
|
API->>DB: BEGIN; UPDATE issue; INSERT issue_event;<br/>INSERT notification (×N);<br/>INSERT notification_delivery (EMAIL, PUSH); COMMIT
|
||||||
API-->>C: 200 OK
|
API-->>C: 200 OK
|
||||||
loop každých pár sekund
|
loop každých pár sekund
|
||||||
@@ -374,10 +371,9 @@ sequenceDiagram
|
|||||||
end
|
end
|
||||||
```
|
```
|
||||||
|
|
||||||
- **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).
|
- **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/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 přes Firebase Admin SDK posílá obecné upozornění. Podrobnosti klient načte z API po přihlášení.
|
- **Push:** mobilní aplikace po přihlášení zaregistruje FCM token (`POST /api/devices`); backend odesílá přes Firebase Admin SDK.
|
||||||
- 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í
|
||||||
@@ -392,7 +388,7 @@ sequenceDiagram
|
|||||||
| Výpadek backendu během odesílání | řádek zůstal `PENDING` | po restartu jej dispatcher zpracuje znovu (doručení *alespoň jednou*; výjimečně může e-mail přijít dvakrát) | — |
|
| Výpadek backendu během odesílání | řádek zůstal `PENDING` | po restartu jej dispatcher zpracuje znovu (doručení *alespoň jednou*; výjimečně může e-mail přijít dvakrát) | — |
|
||||||
| Push dorazil, ale telefon byl offline / notifikaci uživatel zavřel | nelze zjistit | mobilní aplikace při spuštění a návratu do popředí načte nepřečtené notifikace z API | — |
|
| Push dorazil, ale telefon byl offline / notifikaci uživatel zavřel | nelze zjistit | mobilní aplikace při spuštění a návratu do popředí načte nepřečtené notifikace z API | — |
|
||||||
|
|
||||||
- **Administrátor** má přehled nedoručených notifikací (`GET /api/v1/admin/notification-deliveries?status=FAILED`) s důvodem chyby a může doručení ručně zopakovat (`POST …/{id}/retry` – vrátí stav na `PENDING`).
|
- **Administrátor** má přehled nedoručených notifikací (`GET /api/admin/notification-deliveries?status=FAILED`) s důvodem chyby a může doručení ručně zopakovat (`POST …/{id}/retry` – vrátí stav na `PENDING`).
|
||||||
- `FOR UPDATE SKIP LOCKED` (MariaDB 10.6+) zajistí, že jeden záznam nezpracují dvě instance dispatcheru současně.
|
- `FOR UPDATE SKIP LOCKED` (MariaDB 10.6+) zajistí, že jeden záznam nezpracují dvě instance dispatcheru současně.
|
||||||
- Úspěšná uživatelská operace nikdy neselže kvůli nedostupnému SMTP nebo FCM. Odeslání probíhá asynchronně z fronty v DB (outbox pattern).
|
- Úspěšná uživatelská operace nikdy neselže kvůli nedostupnému SMTP nebo FCM. Odeslání probíhá asynchronně z fronty v DB (outbox pattern).
|
||||||
|
|
||||||
@@ -411,8 +407,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<br/>+ Swagger UI]
|
WEB[Webová aplikace<br/>ASP.NET Core MVC]
|
||||||
API[Backend REST API<br/>ASP.NET Core Web API<br/>+ OpenAPI]
|
API[Backend REST API<br/>ASP.NET Core Web API<br/>+ Swagger]
|
||||||
DB[(MariaDB 11)]
|
DB[(MariaDB 11)]
|
||||||
FILES[[Volume: přílohy]]
|
FILES[[Volume: přílohy]]
|
||||||
end
|
end
|
||||||
@@ -423,7 +419,7 @@ flowchart TB
|
|||||||
BROWSER -- HTTPS --> PROXY
|
BROWSER -- HTTPS --> PROXY
|
||||||
MOB -- "HTTPS, JWT" --> PROXY
|
MOB -- "HTTPS, JWT" --> PROXY
|
||||||
PROXY --> WEB
|
PROXY --> WEB
|
||||||
PROXY -- "/api/*" --> API
|
PROXY -- /api, /swagger --> API
|
||||||
WEB -- "REST, JWT" --> API
|
WEB -- "REST, JWT" --> API
|
||||||
API --> DB
|
API --> DB
|
||||||
API --> FILES
|
API --> FILES
|
||||||
@@ -448,8 +444,8 @@ Fyzické nasazení (sítě, porty, úložiště, tajné klíče) popisuje kapito
|
|||||||
|
|
||||||
### 9.3 Autorizace
|
### 9.3 Autorizace
|
||||||
|
|
||||||
1. **Podle role** – atributy jako `[Authorize(Roles = Roles.ManagementOrAdmin)]` a autorizační politiky. Role je v JWT jako claim `role`.
|
1. **Podle role** – atribut `[Authorize(Roles = "MANAGEMENT")]` / politiky (např. `CanAssignIssues`, `CanEvaluateProposals`, `IsAdmin`). Role je v JWT jako claim `role`.
|
||||||
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.
|
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.
|
||||||
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.
|
||||||
@@ -471,7 +467,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`), podrobnosti v přihlášené aplikaci |
|
| Push | Firebase Cloud Messaging (`FirebaseMessagingService`), deep link na detail závady |
|
||||||
| 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)
|
||||||
@@ -511,11 +507,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). Nové heslo má 8–64 znaků a nejvýše 72 bajtů v UTF-8. |
|
| Hesla | Hash BCrypt (knihovna BCrypt.Net-Next, work factor 12; sůl je součástí hashe). Min. délka hesla 8 znaků. |
|
||||||
| 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. |
|
| 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/auth/*`. |
|
||||||
| 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ě. 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. |
|
| 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ě. |
|
||||||
| 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. |
|
||||||
@@ -542,9 +538,9 @@ Všechny tokeny jsou JWT podle [RFC 7519](https://www.rfc-editor.org/rfc/rfc7519
|
|||||||
| Token | Hlavička `typ` | `auth_token.token_type` | Platnost | Claimy | `aud` | Kde se ověřuje |
|
| Token | Hlavička `typ` | `auth_token.token_type` | Platnost | Claimy | `aud` | Kde se ověřuje |
|
||||||
|---|---|---|---|---|---|---|
|
|---|---|---|---|---|---|---|
|
||||||
| Access token | `at+jwt` | `ACCESS` | 15 min | `iss`, `sub`, `aud`, `iat`, `exp`, `jti`, `role` | `helpdesk-api` | každý požadavek na API |
|
| Access token | `at+jwt` | `ACCESS` | 15 min | `iss`, `sub`, `aud`, `iat`, `exp`, `jti`, `role` | `helpdesk-api` | každý požadavek na API |
|
||||||
| Refresh token | `refresh+jwt` | `REFRESH` | 14 dní | `iss`, `sub`, `aud`, `iat`, `exp`, `jti` | `helpdesk-auth` | jen `/api/v1/auth/refresh` a `/api/v1/auth/logout` |
|
| Refresh token | `refresh+jwt` | `REFRESH` | 14 dní | `iss`, `sub`, `aud`, `iat`, `exp`, `jti` | `helpdesk-auth` | jen `/auth/refresh` a `/auth/logout` |
|
||||||
| Ověření e-mailu | `email-confirm+jwt` | `EMAIL_CONFIRM` | 24 h | `iss`, `sub`, `aud`, `iat`, `exp`, `jti` | `helpdesk-auth` | `/api/v1/auth/confirm-email` – jednorázový |
|
| Ověření e-mailu | `email-confirm+jwt` | `EMAIL_CONFIRM` | 24 h | `iss`, `sub`, `aud`, `iat`, `exp`, `jti` | `helpdesk-auth` | `/auth/confirm-email` – jednorázový |
|
||||||
| Reset hesla | `password-reset+jwt` | `PASSWORD_RESET` | 1 h | `iss`, `sub`, `aud`, `iat`, `exp`, `jti` | `helpdesk-auth` | `/api/v1/auth/reset-password` – jednorázový |
|
| Reset hesla | `password-reset+jwt` | `PASSWORD_RESET` | 1 h | `iss`, `sub`, `aud`, `iat`, `exp`, `jti` | `helpdesk-auth` | `/auth/reset-password` – jednorázový |
|
||||||
|
|
||||||
Příklad access tokenu (dekódovaná hlavička a tělo):
|
Příklad access tokenu (dekódovaná hlavička a tělo):
|
||||||
|
|
||||||
@@ -574,7 +570,7 @@ Příklad access tokenu (dekódovaná hlavička a tělo):
|
|||||||
| `jti` | náhodný GUID v4 (nepatrná pravděpodobnost kolize) | 4.1.7 | registrovaný | `jti` (primární klíč) |
|
| `jti` | náhodný GUID v4 (nepatrná pravděpodobnost kolize) | 4.1.7 | registrovaný | `jti` (primární klíč) |
|
||||||
| `role` | role uživatele (`app_user.role`) | 4.3 | soukromý | — |
|
| `role` | role uživatele (`app_user.role`) | 4.3 | soukromý | — |
|
||||||
|
|
||||||
- Do tokenů se **nedávají osobní údaje** (e-mail, jméno, telefon). JWT je jen podepsaný, ne šifrovaný, takže jeho obsah přečte každý, kdo token získá (RFC 7519, kap. 12). Údaje o uživateli vrací `GET /api/v1/users/me`.
|
- Do tokenů se **nedávají osobní údaje** (e-mail, jméno, telefon). JWT je jen podepsaný, ne šifrovaný, takže jeho obsah přečte každý, kdo token získá (RFC 7519, kap. 12). Údaje o uživateli vrací `GET /users/me`.
|
||||||
- Tokeny se přenášejí jen přes HTTPS (RFC 7519, kap. 12).
|
- Tokeny se přenášejí jen přes HTTPS (RFC 7519, kap. 12).
|
||||||
- Claim `nbf` (4.1.5) se nepoužívá, protože tokeny platí hned od vydání.
|
- Claim `nbf` (4.1.5) se nepoužívá, protože tokeny platí hned od vydání.
|
||||||
|
|
||||||
@@ -582,10 +578,10 @@ Příklad access tokenu (dekódovaná hlavička a tělo):
|
|||||||
|
|
||||||
| Akce | Změna v `auth_token` | `revoke_reason` |
|
| Akce | Změna v `auth_token` | `revoke_reason` |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Přihlášení (`/api/v1/auth/login`) | INSERT access + refresh tokenu | — |
|
| Přihlášení (`/auth/login`) | INSERT access + refresh tokenu | — |
|
||||||
| Obnova tokenů (`/api/v1/auth/refresh`) | použitý refresh token zneplatněn, INSERT nového páru | `USED` |
|
| Obnova tokenů (`/auth/refresh`) | použitý refresh token zneplatněn, INSERT nového páru | `USED` |
|
||||||
| Odhlášení (`/api/v1/auth/logout`) | zneplatněn access + refresh token tohoto zařízení, ostatní zařízení fungují dál | `LOGOUT` |
|
| Odhlášení (`/auth/logout`) | zneplatněn access + refresh token tohoto zařízení, ostatní zařízení fungují dál | `LOGOUT` |
|
||||||
| Odhlásit ze všech zařízení (`/api/v1/auth/logout-all`) | zneplatněny všechny platné tokeny uživatele | `LOGOUT_ALL` |
|
| Odhlásit ze všech zařízení (`/auth/logout-all`) | zneplatněny všechny platné tokeny uživatele | `LOGOUT_ALL` |
|
||||||
| Změna nebo reset hesla | zneplatněny všechny platné tokeny uživatele | `PASSWORD_CHANGED` |
|
| Změna nebo reset hesla | zneplatněny všechny platné tokeny uživatele | `PASSWORD_CHANGED` |
|
||||||
| Změna role administrátorem | zneplatněny všechny tokeny; uživatel se přihlásí znovu a dostane token s novou rolí | `ROLE_CHANGED` |
|
| Změna role administrátorem | zneplatněny všechny tokeny; uživatel se přihlásí znovu a dostane token s novou rolí | `ROLE_CHANGED` |
|
||||||
| Deaktivace účtu administrátorem | zneplatněny všechny platné tokeny uživatele | `ACCOUNT_DEACTIVATED` |
|
| Deaktivace účtu administrátorem | zneplatněny všechny platné tokeny uživatele | `ACCOUNT_DEACTIVATED` |
|
||||||
@@ -600,7 +596,7 @@ Příklad access tokenu (dekódovaná hlavička a tělo):
|
|||||||
Každý token, který přijde na server, projde těmito kontrolami. Pokud kterákoli selže, server vrátí 401 („If any of the listed steps fail, then the JWT MUST be rejected“).
|
Každý token, který přijde na server, projde těmito kontrolami. Pokud kterákoli selže, server vrátí 401 („If any of the listed steps fail, then the JWT MUST be rejected“).
|
||||||
|
|
||||||
1. Formát JWS a správný podpis. Přijímá se **jen algoritmus HS256**, tokeny s `alg: none` nebo jiným algoritmem se odmítnou.
|
1. Formát JWS a správný podpis. Přijímá se **jen algoritmus HS256**, tokeny s `alg: none` nebo jiným algoritmem se odmítnou.
|
||||||
2. `typ` v hlavičce odpovídá endpointu (např. `/api/v1/issues` přijme jen `at+jwt`).
|
2. `typ` v hlavičce odpovídá endpointu (např. `/api/issues` přijme jen `at+jwt`).
|
||||||
3. `iss` je naše API a `aud` odpovídá druhu tokenu.
|
3. `iss` je naše API a `aud` odpovídá druhu tokenu.
|
||||||
4. Token není prošlý (`exp`). Povolená odchylka hodin (`ClockSkew`) je **30 s**. Výchozí hodnota v .NET je 5 minut, takže se musí nastavit ručně.
|
4. Token není prošlý (`exp`). Povolená odchylka hodin (`ClockSkew`) je **30 s**. Výchozí hodnota v .NET je 5 minut, takže se musí nastavit ručně.
|
||||||
5. Token s tímto `jti` není v `auth_token` zneplatněný (`revoked_at IS NULL`).
|
5. Token s tímto `jti` není v `auth_token` zneplatněný (`revoked_at IS NULL`).
|
||||||
@@ -619,7 +615,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 uloží nový pár tokenů ve stejné databázové transakci.
|
- **Změněn 1 řádek** → token se používá poprvé, server vydá nový pár tokenů.
|
||||||
- **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ž.
|
||||||
@@ -631,13 +627,13 @@ sequenceDiagram
|
|||||||
participant S as Server
|
participant S as Server
|
||||||
|
|
||||||
Note over U,A: Oba mají refresh token R1 (jti = r1)
|
Note over U,A: Oba mají refresh token R1 (jti = r1)
|
||||||
A->>S: POST /api/v1/auth/refresh (R1)
|
A->>S: POST /auth/refresh (R1)
|
||||||
S->>S: UPDATE r1 → USED (1 řádek)
|
S->>S: UPDATE r1 → USED (1 řádek)
|
||||||
S-->>A: nový pár tokenů (a2, r2)
|
S-->>A: nový pár tokenů (a2, r2)
|
||||||
U->>S: POST /api/v1/auth/refresh (R1)
|
U->>S: POST /auth/refresh (R1)
|
||||||
S->>S: UPDATE r1 → 0 řádků = token už byl použit<br/>všechny tokeny uživatele → REUSE_DETECTED
|
S->>S: UPDATE r1 → 0 řádků = token už byl použit<br/>všechny tokeny uživatele → REUSE_DETECTED
|
||||||
S-->>U: 401 → přihlásí se znovu
|
S-->>U: 401 → přihlásí se znovu
|
||||||
A->>S: GET /api/v1/issues (access token a2)
|
A->>S: GET /api/issues (access token a2)
|
||||||
S-->>A: 401 – a2 je zneplatněný
|
S-->>A: 401 – a2 je zneplatněný
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -647,17 +643,13 @@ sequenceDiagram
|
|||||||
|
|
||||||
## 11. Návrh REST API
|
## 11. Návrh REST API
|
||||||
|
|
||||||
Aplikační API má základní cestu **`/api/v1`**. Připojte tento prefix před cesty v tabulkách. Výsledkem je například `POST /api/v1/auth/register` nebo `GET /api/v1/statistics/overview?from=&to=`. Výchozí formát je JSON. Chyby mají formát **ProblemDetails** (RFC 9457). Stránkování používá `?page=1&pageSize=20` a vrací `{ items: [...], totalCount, page, pageSize }`.
|
Všechny endpointy mají prefix `/api`, formát JSON, chyby ve formátu **ProblemDetails** (RFC 9457). Seznamy jsou stránkované: `?page=1&pageSize=20`, odpověď `{ items: [...], totalCount, page, pageSize }`. Dokumentace: Swagger UI na `/swagger`.
|
||||||
|
|
||||||
Čí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 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, 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/register` | anonym | Registrace (e-mail, heslo, jméno, příjmení) |
|
||||||
| POST | `/auth/confirm-email` | anonym | Ověření e-mailu a nastavení hesla v jedné transakci (`{ token, newPassword }`) |
|
| POST | `/auth/confirm-email` | anonym | Ověření e-mailu tokenem |
|
||||||
| 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 |
|
||||||
@@ -669,21 +661,21 @@ Swagger UI je na webu na `/swagger`. UI i jeho OpenAPI dokument na `/swagger/v1/
|
|||||||
### 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 a vyučující vidí jen vlastní. |
|
| 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í. |
|
||||||
| 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í / admin | Detail vč. `allowedActions` a `rowVersion` |
|
| GET | `/issues/{id}` | účastník / správce / vedení | Detail vč. `allowedActions` a `rowVersion` |
|
||||||
| PUT | `/issues/{id}` | hlásič / admin | Úprava ve stavu Přijata s `rowVersion` |
|
| PUT | `/issues/{id}` | hlásič | Úprava ve stavu Přijata s `rowVersion` |
|
||||||
| POST | `/issues/{id}/assign` | vedení / admin | `{ assigneeId, priority?, rowVersion }` (T2, T3) |
|
| POST | `/issues/{id}/assign` | vedení | `{ assigneeId, priority?, rowVersion }` (T2, T3) |
|
||||||
| POST | `/issues/{id}/start` | řešitel / admin | `{ rowVersion }` (T4) |
|
| POST | `/issues/{id}/start` | řešitel | `{ rowVersion }` (T4) |
|
||||||
| POST | `/issues/{id}/submit-for-verification` | řešitel / admin | `{ rowVersion, note? }` (T5) |
|
| POST | `/issues/{id}/submit-for-verification` | řešitel | `{ rowVersion, note? }` (T5) |
|
||||||
| POST | `/issues/{id}/confirm` | hlásič / admin | `{ rowVersion }` (T6) |
|
| POST | `/issues/{id}/confirm` | hlásič | `{ rowVersion }` (T6) |
|
||||||
| POST | `/issues/{id}/reopen` | hlásič / admin | `{ rowVersion, reason }` (T7) |
|
| POST | `/issues/{id}/reopen` | hlásič | `{ rowVersion, reason }` (T7) |
|
||||||
| POST | `/issues/{id}/reject` | řešitel / vedení / admin | `{ rowVersion, reason }` (T8, T9) |
|
| POST | `/issues/{id}/reject` | řešitel / vedení | `{ 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 / admin | `{ text }` – zapíše událost `COMMENTED` |
|
| POST | `/issues/{id}/comments` | hlásič, řešitel | `{ text }` – zapíše událost `COMMENTED` |
|
||||||
| POST | `/issues/{id}/attachments` | hlásič / řešitel / admin | `multipart/form-data`, 1–5 souborů v poli `files` |
|
| POST | `/issues/{id}/attachments` | hlásič, řešitel | `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í / admin | Možní řešitelé s počtem otevřených závad |
|
| GET | `/users/assignable` | vedení | 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`.
|
||||||
@@ -694,10 +686,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 / admin | Úprava ve stavu Podán |
|
| PUT | `/proposals/{id}` | autor | Ú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í / admin | `{ status, note? }` |
|
| POST | `/proposals/{id}/status` | vedení | `{ status, note? }` |
|
||||||
|
|
||||||
### Notifikace a zařízení
|
### Notifikace a zařízení
|
||||||
| Metoda | Endpoint | Role | Popis |
|
| Metoda | Endpoint | Role | Popis |
|
||||||
@@ -712,12 +704,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í / admin | Souhrnné KPI: počty podle stavu, průměrná doba do přiřazení a do uzavření |
|
| 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/issues/by-category` | vedení / admin | Počty a průměrná doba řešení podle kategorie |
|
| GET | `/statistics/issues/by-category` | vedení | Počty a průměrná doba řešení podle kategorie |
|
||||||
| GET | `/statistics/issues/by-building` | vedení / admin | Podle budovy |
|
| GET | `/statistics/issues/by-building` | vedení | Podle budovy |
|
||||||
| GET | `/statistics/issues/by-assignee` | vedení / admin | Vytížení řešitelů (otevřené / uzavřené) |
|
| GET | `/statistics/issues/by-assignee` | vedení | Vytížení řešitelů (otevřené / uzavřené) |
|
||||||
| GET | `/statistics/issues/trend?granularity=month` | vedení / admin | Nové vs. uzavřené závady v čase |
|
| GET | `/statistics/issues/trend?granularity=month` | vedení | Nové vs. uzavřené závady v čase |
|
||||||
| GET | `/statistics/proposals/top?limit=10` | vedení / admin | Nejpodporovanější návrhy |
|
| GET | `/statistics/proposals/top?limit=10` | vedení | Nejpodporovanější návrhy |
|
||||||
|
|
||||||
### Číselníky a administrace
|
### Číselníky a administrace
|
||||||
| Metoda | Endpoint | Role | Popis |
|
| Metoda | Endpoint | Role | Popis |
|
||||||
@@ -725,11 +717,6 @@ 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 |
|
||||||
@@ -780,6 +767,8 @@ 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 {
|
||||||
@@ -949,7 +938,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.
|
||||||
- **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).
|
- 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`.
|
||||||
- *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)`.
|
||||||
|
|
||||||
@@ -983,9 +972,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í nebo administrátora) 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í) 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` a `app_user.row_version` (EF Core concurrency token).
|
- **Optimistické zamykání**: `issue.row_version` (EF Core concurrency token).
|
||||||
- **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.
|
- **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.
|
||||||
- **Č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`).
|
||||||
@@ -1042,13 +1031,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í, admin |
|
| Detail závady (stav, časová osa, akce podle `allowedActions`, komentáře, přílohy) | ✅ | ✅ | účastníci, správce, vedení |
|
||||||
| 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í, admin |
|
| Centrální přehled závad (tabulka, filtry, hromadný přehled) | ✅ | — | správce budov, vedení |
|
||||||
| 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í, admin |
|
| Hodnocení návrhů (fronta podaných návrhů) | ✅ | — | vedení |
|
||||||
| Statistiky (KPI dlaždice, grafy, filtr období) | ✅ | — | vedení, admin |
|
| Statistiky (KPI dlaždice, grafy, filtr období) | ✅ | — | vedení |
|
||||||
| 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 |
|
||||||
@@ -1134,9 +1123,9 @@ flowchart LR
|
|||||||
end
|
end
|
||||||
|
|
||||||
BROWSER -- "HTTPS 443" --> PROXY
|
BROWSER -- "HTTPS 443" --> PROXY
|
||||||
MOBILE -- "HTTPS 443 /api/v1/*" --> PROXY
|
MOBILE -- "HTTPS 443 /api" --> PROXY
|
||||||
PROXY -- "HTTP 8080 /" --> WEB
|
PROXY -- "HTTP 8080 /" --> WEB
|
||||||
PROXY -- "HTTP 8080 /api/*" --> API
|
PROXY -- "HTTP 8080 /api, /swagger" --> 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
|
||||||
@@ -1156,7 +1145,7 @@ flowchart LR
|
|||||||
- `backend` – api, migrator, db. Je označená jako `internal: true`, takže kontejnery v ní nemají přístup do internetu a nejsou dostupné zvenku.
|
- `backend` – api, migrator, db. Je označená jako `internal: true`, takže kontejnery v ní nemají přístup do internetu a nejsou dostupné zvenku.
|
||||||
- **Databáze je dostupná jen pro `api` a `migrator`.** Webový kontejner ani proxy k ní nemají síťovou cestu. Web pracuje s daty výhradně přes REST API.
|
- **Databáze je dostupná jen pro `api` a `migrator`.** Webový kontejner ani proxy k ní nemají síťovou cestu. Web pracuje s daty výhradně přes REST API.
|
||||||
- **`api` je jediná služba v obou sítích.** Odchozí spojení k SMTP a FCM vede přes síť `frontend`.
|
- **`api` je jediná služba v obou sítích.** Odchozí spojení k SMTP a FCM vede přes síť `frontend`.
|
||||||
- **Mobilní aplikace** komunikuje se stejnou adresou jako web (`https://<doména>/api/v1/...`). Push notifikace k ní doručuje FCM, ne náš server.
|
- **Mobilní aplikace** komunikuje se stejnou adresou jako web (`https://<doména>/api/...`). Push notifikace k ní doručuje FCM, ne náš server.
|
||||||
|
|
||||||
### 15.2 Síťová komunikace
|
### 15.2 Síťová komunikace
|
||||||
|
|
||||||
@@ -1164,9 +1153,9 @@ 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 (`/`), administrátorské Swagger UI (`/swagger`) |
|
| proxy | web | HTTP 8080 | frontend | stránky (`/`) |
|
||||||
| proxy | api | HTTP 8080 | frontend | `/api/*` |
|
| proxy | api | HTTP 8080 | frontend | `/api/*`, `/swagger` |
|
||||||
| 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`) | 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` |
|
||||||
| api | SMTP server | SMTP 587 (STARTTLS) | internet, odchozí | e-mailové notifikace |
|
| api | SMTP server | SMTP 587 (STARTTLS) | internet, odchozí | e-mailové notifikace |
|
||||||
@@ -1178,8 +1167,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` | administrátorské Swagger UI na `/swagger`, klíče Data Protection pro šifrované cookie |
|
| `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) |
|
||||||
| `api` | vlastní (`dotnet/aspnet`) | frontend, backend | interně 8080 | `uploads` | OpenAPI pro administrátory, `GET /health`, vytvoření admin účtu z env |
|
| `api` | vlastní (`dotnet/aspnet`) | frontend, backend | interně 8080 | `uploads` | Swagger na `/swagger`, `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í |
|
||||||
@@ -1247,10 +1236,10 @@ Možná rozšíření (mimo rozsah zadání): automatické potvrzení vyřešen
|
|||||||
| Fáze | Týden | Náplň |
|
| Fáze | Týden | Náplň |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| **1. Návrh** | 1–2 | Tento dokument, databázové schéma, založení Git repozitáře a struktury projektů; zapracování připomínek z obhajoby (v1.1) |
|
| **1. Návrh** | 1–2 | Tento dokument, databázové schéma, založení Git repozitáře a struktury projektů; zapracování připomínek z obhajoby (v1.1) |
|
||||||
| **2. Implementace** | 3 | Backend: `Helpdesk.Migrator` (DbUp), entity a EF Core mapování, autentizace (registrace, login, JWT s `jti`, refresh, blokování tokenů), role, REST API `/api/v1`, Swagger |
|
| **2. Implementace** | 3 | Backend: `Helpdesk.Migrator` (DbUp), entity a EF Core mapování, autentizace (registrace, login, JWT s `jti`, refresh, blokování tokenů), role, Swagger |
|
||||||
| | 4 | Backend: závady – stavový automat, události, přílohy, komentáře; unit testy automatu |
|
| | 4 | Backend: závady – stavový automat, události, přílohy, komentáře; unit testy automatu |
|
||||||
| | 5 | Backend: návrhy a hlasování, notifikace (in-app, e-mail, push, opakování nedoručených), statistiky |
|
| | 5 | Backend: návrhy a hlasování, notifikace (in-app, e-mail, push, opakování nedoručených), statistiky |
|
||||||
| | 6 | Webová aplikace: všechny obrazovky včetně statistik a administrace, napojení na API v1 |
|
| | 6 | Webová aplikace: všechny obrazovky včetně statistik a administrace |
|
||||||
| | 7 | Mobilní aplikace nad API v1: přihlášení, hlášení s fotkou, detail a komentáře, návrhy, push notifikace |
|
| | 7 | Mobilní aplikace: přihlášení, hlášení s fotkou, detail a komentáře, návrhy, push notifikace |
|
||||||
| **3. Testování a nasazení** | 8 | Integrační testy, ladění, Docker Compose + HTTPS, ověření verzovaných URL přes proxy |
|
| **3. Testování a nasazení** | 8 | Integrační testy, ladění, Docker Compose + HTTPS |
|
||||||
| | 9 | Uživatelská příručka, technická dokumentace, finální nasazení a předvedení |
|
| | 9 | Uživatelská příručka, technická dokumentace, finální nasazení a předvedení |
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
# NTBug pro Android
|
||||||
|
|
||||||
|
Nativní český klient univerzitního helpdesku pro Android 8.0+ (API 26), napsaný v Kotlinu a Jetpack Compose / Material 3. Aplikace podporuje světlý i tmavý motiv, systémové okraje, posouvání formulářů a klávesnici.
|
||||||
|
|
||||||
|
## Spuštění
|
||||||
|
|
||||||
|
1. Použijte Android Studio **Meerkat (2024.3.1) nebo novější s podporou AGP 8.9.x**. Staré Android Studio Flamingo podporuje nejvýše AGP 8.0.x a tento projekt v něm nelze synchronizovat. V Android Studiu otevřete **tuto složku `mobile`** jako projekt.
|
||||||
|
2. Použijte Gradle JDK 17 nebo novější kompatibilní s Gradle 8.12.1. Doporučený je JDK 17; Gradle wrapper je součástí repozitáře.
|
||||||
|
3. Nainstalujte Android SDK Platform 35 a Build Tools 35.0.0. Android Studio SDK vyhledá automaticky, případně nastavte `sdk.dir` v necommitovaném `local.properties`.
|
||||||
|
4. Spusťte modul `app` na emulátoru nebo připojeném telefonu.
|
||||||
|
|
||||||
|
Příkazová řádka ve Windows, ze složky `mobile`:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\gradlew.bat :app:assembleDebug
|
||||||
|
.\gradlew.bat :app:testDebugUnitTest :app:lintDebug
|
||||||
|
# Pro spuštěný emulátor nebo připojené testovací zařízení:
|
||||||
|
.\gradlew.bat :app:connectedDebugAndroidTest
|
||||||
|
```
|
||||||
|
|
||||||
|
Na Linuxu/macOS použijte `sh ./gradlew`. Debug APK se vytvoří v `app/build/outputs/apk/debug/app-debug.apk`. Release sestavení vyžaduje vlastní podpisový klíč; klíče ani hesla do repozitáře nepatří.
|
||||||
|
|
||||||
|
### Chyba „Latest supported version is AGP 8.0.2“
|
||||||
|
|
||||||
|
Tato hláška označuje omezení nainstalovaného Android Studia. Aktualizujte IDE přes **Help → Check for Updates**, případně nainstalujte stabilní verzi z [oficiální stránky](https://developer.android.com/studio). Projekt používá AGP 8.9.2, Gradle wrapper 8.12.1 a SDK 35; po aktualizaci otevřete složku `mobile` a zvolte **File → Sync Project with Gradle Files**. V **Settings → Build, Execution, Deployment → Build Tools → Gradle** používejte Gradle wrapper projektu a Gradle JDK 17 (nebo kompatibilní novější JDK).
|
||||||
|
|
||||||
|
Samotná změna AGP na 8.0.2 není vhodná: API 35 oficiálně vyžaduje minimálně AGP 8.6.0 a bylo by nutné společně upravit SDK i knihovny. Přehled podporovaných kombinací: [Android Studio a AGP](https://developer.android.com/build/releases/about-agp).
|
||||||
|
|
||||||
|
## Skutečný server a ukázka
|
||||||
|
|
||||||
|
**Přihlásit se** používá REST API. Nejprve spusťte backend podle hlavního README. Přes **Nastavení serveru** zadejte adresu:
|
||||||
|
|
||||||
|
| Prostředí | Příklad |
|
||||||
|
|---|---|
|
||||||
|
| Android emulátor, backend na stejném počítači | `http://10.0.2.2:8080/` |
|
||||||
|
| Android emulátor při `API_PORT=8081` | `http://10.0.2.2:8081/` |
|
||||||
|
| Telefon na stejné Wi-Fi jako počítač | `http://192.168.1.100:8080/` (skutečná LAN adresa počítače, dostupný port 8080) |
|
||||||
|
| Nasazený server | `https://helpdesk.example.cz/` |
|
||||||
|
|
||||||
|
Docker ve výchozím stavu zpřístupňuje API na portu `8080`. Je-li obsazený, přidejte do `deploy/.env` například `API_PORT=8081` a spusťte backend znovu. Swagger pak otevřete na <http://localhost:8081/swagger>; v mobilní aplikaci změňte port adresy serveru na `8081` (také při připojení telefonu přes Wi-Fi).
|
||||||
|
|
||||||
|
Přijímá se kořen serveru i URL končící `/api/`. Při změně serveru se místní relace smaže. HTTP je povoleno pouze v debug variantě, release vyžaduje HTTPS a standardně ověřený certifikát. Vypínání kontroly TLS není implementované.
|
||||||
|
|
||||||
|
Výchozí backend umožňuje registraci domén `student.univerzita.cz` a `univerzita.cz`. Domény lze změnit na serveru. Po registraci ověřte e-mail; současný backend zapisuje odkaz do logu místo skutečného odeslání. V aplikaci lze vložit celý ověřovací/resetovací odkaz nebo samotný token. Automatické Android App Links zatím nejsou nastavené.
|
||||||
|
|
||||||
|
**Prohlédnout ukázku** je samostatný režim, výrazně označený na každé obrazovce. Obsahuje ukázková hlášení a návrhy a umožňuje vytváření, úpravy přijatých hlášení, komentáře, přílohy, hlasování a čtení oznámení. Data jsou pouze v paměti, zaniknou po ukončení ukázky nebo procesu. Ukázka se nikdy nezapne automaticky při chybě serveru. Hraje roli studenta; pracovní fronta správce je dostupná v připojeném režimu podle role z API.
|
||||||
|
|
||||||
|
## Rozsah a stav API
|
||||||
|
|
||||||
|
| Funkce | Mobilní klient | Backend v tomto repozitáři |
|
||||||
|
|---|---|---|
|
||||||
|
| Přihlášení, registrace, ověření e-mailu, obnova hesla | Hotovo | Implementován |
|
||||||
|
| Obnova relace, odhlášení / všechna zařízení | Hotovo | Implementován |
|
||||||
|
| Profil, telefon, e-mailové notifikace | Hotovo | Implementován |
|
||||||
|
| Budovy a kategorie formulářů | Hotovo | Implementován |
|
||||||
|
| Nástěnka, seznam a detail vlastních závad, filtry, stránkování | Hotovo, budoucí API adaptér + ukázka | Zatím pouze návrh |
|
||||||
|
| Nová závada, úprava přijaté závady, fotografie a soubory | Hotovo, budoucí API adaptér + ukázka | Zatím pouze návrh |
|
||||||
|
| Komentáře, časová osa, stažení příloh | Hotovo, budoucí API adaptér + ukázka | Zatím pouze návrh |
|
||||||
|
| Pracovní fronta řešitele a serverem povolené změny stavu | Hotovo, podle `allowedActions` | Zatím pouze návrh |
|
||||||
|
| Seznam, detail, nový návrh, hlas pro/proti/zrušení | Hotovo, budoucí API adaptér + ukázka | Zatím pouze návrh |
|
||||||
|
| Seznam oznámení, označení přečtení a otevření záznamu | Hotovo, budoucí API adaptér + ukázka | Zatím pouze návrh |
|
||||||
|
| Push notifikace (Firebase Cloud Messaging) | Nezapojeno | Chybí `/devices` a doručování |
|
||||||
|
|
||||||
|
Při chybějícím endpointu aplikace zobrazí vysvětlení, nesimuluje úspěch. Funkce závad, návrhů a oznámení proto nyní lze celé projít v ukázce. Jejich skutečná integrace potřebuje implementaci serveru a sjednocení detailních DTO, která návrhový dokument dosud nedefinuje. Administrační a analytické obrazovky patří podle návrhu webové části.
|
||||||
|
|
||||||
|
Budoucí adaptér vychází z [návrhu REST API](../docs/navrh-aplikace.md#11-návrh-rest-api). Přesný **předpokládaný** tvar odpovědí a požadavků je v `data/Models.kt` a rozhraní endpointů v `data/RemoteRepository.kt`:
|
||||||
|
|
||||||
|
- JSON v camelCase; seznamy `{ items, totalCount, page, pageSize }`, stránka po 20 položkách.
|
||||||
|
- Detail závady obsahuje názvy budovy/kategorie/osob, `rowVersion` jako celé číslo, `allowedActions` a přílohy `{ id, fileName, contentType }`. Události se čtou samostatně přes `GET /issues/{id}/events` jako pole `{ id, authorName, type, text, createdAt }`.
|
||||||
|
- `allowedActions` může obsahovat endpointové kódy `start`, `submit-for-verification`, `confirm`, `reopen`, `reject`, `comment`, `attachments`, `edit` nebo odpovídající kódy `START_WORK`, `SUBMIT_FOR_VERIFICATION`, `CONFIRM_RESOLUTION`, `ADD_COMMENT`, `ADD_ATTACHMENT`, `EDIT`. Pravidla a povolené přechody zůstávají na serveru.
|
||||||
|
- Vytvoření hlášení posílá `{ title, description, categoryId, buildingId, location }`; úprava přidává `rowVersion`. Přechody posílají `rowVersion`, důvod v `reason` a poznámku v `note`. Konflikt 409 znovu načte detail.
|
||||||
|
- Přílohy se nahrávají samostatně jako multipart pole `files` na již vytvořené hlášení, nejvýše 5 × 10 MB, JPG/PNG/HEIC/HEIF/PDF/DOCX. Při selhání uploadu zůstane hlášení uložené a aplikace vyzve k doplnění příloh v detailu; nevytvoří druhé hlášení.
|
||||||
|
- Návrh obsahuje `score`, `myVote` (`1`, `-1` nebo `null`), `note` a údaje autora. Vlastní návrh neumožňuje hlasování.
|
||||||
|
- Oznámení obsahuje `isRead`, volitelné `issueId` / `proposalId`, datum, název a text.
|
||||||
|
- Datum/čas používá ISO 8601 s časovou zónou. Chyby odpovídají `ProblemDetails`, včetně validačního `errors`.
|
||||||
|
|
||||||
|
## Struktura a bezpečnost
|
||||||
|
|
||||||
|
- `ui/`: ViewModel, neměnný StateFlow, navigace, účet a profil, téma.
|
||||||
|
- `ui/features/`: funkční Compose obrazovky bez závislosti na síťové vrstvě; fotoaparát přes systémovou aplikaci, přílohy přes systémový výběr souborů.
|
||||||
|
- `data/`: kontrakty, Retrofit/OkHttp adaptér, ukázkový repozitář, šifrované úložiště relace.
|
||||||
|
- `src/test/`: JUnit testy autentizace, rotace tokenů a chyb proti MockWebServer, ukázkové mutace a limity příloh.
|
||||||
|
- `src/androidTest/`: Compose testy hlavních uživatelských scénářů.
|
||||||
|
|
||||||
|
Hesla se neukládají. Tokeny a profil relace jsou šifrované AES-GCM, klíč zůstává v Android Keystore; zálohování aplikace je vypnuté. Jednorázové refresh tokeny se rotují pod mutexem, dokončení rotace není přerušeno změnou obrazovky; při nejednoznačném výsledku se vyžádá nové přihlášení. Automatické síťové opakování a přesměrování jsou vypnuté. Odhlášení se pokusí zneplatnit tokeny na serveru a vždy smaže místní relaci; pokud server odhlášení nepotvrdí, aplikace to oznámí.
|
||||||
|
|
||||||
|
Fotografie nevyžadují široký přístup k úložišti ani vlastní oprávnění CAMERA: používá se systémový fotoaparát a omezený `FileProvider`. Stažené přílohy se ukládají do soukromé cache a otevírají přes dočasné oprávnění URI. Neodeslané přílohy se ukládají do cache a obnovují přes uložená metadata, takže se zachovají při otočení telefonu i obnovení aktivity; velká data se nevkládají do Android Bundle. Pokud systém cache mezitím odstraní, aplikace vyzve k opětovnému výběru souborů. Aplikace nemá offline frontu ani automatické odesílání na pozadí.
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
plugins {
|
||||||
|
id("com.android.application")
|
||||||
|
id("org.jetbrains.kotlin.android")
|
||||||
|
id("org.jetbrains.kotlin.plugin.compose")
|
||||||
|
id("org.jetbrains.kotlin.plugin.serialization")
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "cz.ntbug.mobile"
|
||||||
|
compileSdk = 35
|
||||||
|
|
||||||
|
defaultConfig {
|
||||||
|
applicationId = "cz.ntbug.mobile"
|
||||||
|
minSdk = 26
|
||||||
|
targetSdk = 35
|
||||||
|
versionCode = 1
|
||||||
|
versionName = "0.1.0"
|
||||||
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
|
vectorDrawables.useSupportLibrary = true
|
||||||
|
}
|
||||||
|
buildTypes {
|
||||||
|
debug { applicationIdSuffix = ".debug" }
|
||||||
|
release {
|
||||||
|
isMinifyEnabled = true
|
||||||
|
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
|
}
|
||||||
|
kotlinOptions { jvmTarget = "17" }
|
||||||
|
buildFeatures { compose = true; buildConfig = true }
|
||||||
|
packaging { resources.excludes += "/META-INF/{AL2.0,LGPL2.1}" }
|
||||||
|
testOptions { unitTests.isReturnDefaultValues = true }
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
val composeBom = platform("androidx.compose:compose-bom:2025.04.01")
|
||||||
|
implementation(composeBom)
|
||||||
|
androidTestImplementation(composeBom)
|
||||||
|
implementation("androidx.core:core-ktx:1.16.0")
|
||||||
|
implementation("androidx.activity:activity-compose:1.10.1")
|
||||||
|
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.9.0")
|
||||||
|
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.9.0")
|
||||||
|
implementation("androidx.navigation:navigation-compose:2.9.0")
|
||||||
|
implementation("androidx.compose.ui:ui")
|
||||||
|
implementation("androidx.compose.ui:ui-tooling-preview")
|
||||||
|
implementation("androidx.compose.material3:material3")
|
||||||
|
implementation("androidx.compose.material:material-icons-extended")
|
||||||
|
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
|
||||||
|
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0")
|
||||||
|
implementation("com.squareup.retrofit2:retrofit:2.11.0")
|
||||||
|
implementation("com.squareup.retrofit2:converter-kotlinx-serialization:2.11.0")
|
||||||
|
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
||||||
|
implementation("io.coil-kt:coil-compose:2.7.0")
|
||||||
|
debugImplementation("androidx.compose.ui:ui-tooling")
|
||||||
|
testImplementation("junit:junit:4.13.2")
|
||||||
|
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2")
|
||||||
|
testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0")
|
||||||
|
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
|
||||||
|
androidTestImplementation("androidx.test.ext:junit:1.2.1")
|
||||||
|
androidTestImplementation("androidx.test:runner:1.6.2")
|
||||||
|
androidTestImplementation("androidx.test.espresso:espresso-core:3.6.1")
|
||||||
|
debugImplementation("androidx.compose.ui:ui-test-manifest")
|
||||||
|
}
|
||||||
Vendored
+2
@@ -0,0 +1,2 @@
|
|||||||
|
# Retrofit reads generic service signatures and annotations at runtime.
|
||||||
|
-keepattributes Signature,InnerClasses,EnclosingMethod,RuntimeVisibleAnnotations,RuntimeVisibleParameterAnnotations
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
package cz.ntbug.mobile
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import androidx.compose.ui.graphics.asAndroidBitmap
|
||||||
|
import androidx.compose.ui.test.*
|
||||||
|
import androidx.compose.ui.test.junit4.createAndroidComposeRule
|
||||||
|
import androidx.core.view.WindowCompat
|
||||||
|
import androidx.core.view.WindowInsetsCompat
|
||||||
|
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||||
|
import androidx.test.filters.LargeTest
|
||||||
|
import androidx.test.platform.app.InstrumentationRegistry
|
||||||
|
import org.junit.Rule
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.rules.ExternalResource
|
||||||
|
import org.junit.rules.RuleChain
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
/** Exercises the shipped app through its public UI, without a backend or test-only routes. */
|
||||||
|
@RunWith(AndroidJUnit4::class)
|
||||||
|
@LargeTest
|
||||||
|
class MobileSmokeTest {
|
||||||
|
private val compose = createAndroidComposeRule<MainActivity>()
|
||||||
|
|
||||||
|
private val cleanSession = object : ExternalResource() {
|
||||||
|
override fun before() {
|
||||||
|
// Run before Activity creation, so a previous real session cannot start network work.
|
||||||
|
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||||
|
check(context.getSharedPreferences("ntbug_session", Context.MODE_PRIVATE).edit().clear().commit())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@get:Rule
|
||||||
|
val rules: RuleChain = RuleChain.outerRule(cleanSession).around(compose)
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun demoShowsDashboardAndLoadedIssues() {
|
||||||
|
enterDemo()
|
||||||
|
|
||||||
|
compose.onNodeWithText("UKÁZKOVÝ REŽIM").assertIsDisplayed()
|
||||||
|
compose.onNodeWithText("Nahlásit závadu").assertIsDisplayed()
|
||||||
|
compose.waitForIdle()
|
||||||
|
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||||
|
val screenshot = File(requireNotNull(context.getExternalFilesDir(null)), "dashboard.png")
|
||||||
|
screenshot.outputStream().use { output ->
|
||||||
|
check(compose.onRoot().captureToImage().asAndroidBitmap().compress(Bitmap.CompressFormat.PNG, 100, output))
|
||||||
|
}
|
||||||
|
scrollTo("Nefunkční projektor v B-205")
|
||||||
|
compose.onNodeWithText("Nefunkční projektor v B-205").assertIsDisplayed()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun proposalVoteCanBeCastAndRemoved() {
|
||||||
|
enterDemo()
|
||||||
|
compose.onNodeWithText("Nápady").performClick()
|
||||||
|
awaitText("Návrhy na zlepšení")
|
||||||
|
scrollTo("Více zásuvek ve studovně")
|
||||||
|
compose.onNodeWithText("Více zásuvek ve studovně").performClick()
|
||||||
|
awaitText("Detail nápadu")
|
||||||
|
scrollTo("Co si o návrhu myslíte?")
|
||||||
|
|
||||||
|
compose.onNodeWithText("42").assertIsDisplayed()
|
||||||
|
compose.onNode(hasText("Pro") and hasClickAction()).performClick()
|
||||||
|
awaitText("43")
|
||||||
|
compose.onNode(hasText("Pro") and hasClickAction()).assertIsSelected()
|
||||||
|
|
||||||
|
compose.onNode(hasText("Pro") and hasClickAction()).performClick()
|
||||||
|
awaitText("42")
|
||||||
|
compose.onNode(hasText("Pro") and hasClickAction()).assertIsNotSelected()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun issueRequiresCategoryAndPersistsCreationAndComment() {
|
||||||
|
val title = "Testovací závada ve studovně"
|
||||||
|
val comment = "Upřesnění: zásuvka je u okna."
|
||||||
|
enterDemo()
|
||||||
|
compose.onNodeWithText("Nahlásit závadu").performClick()
|
||||||
|
awaitText("Nové hlášení")
|
||||||
|
|
||||||
|
scrollTo("Název závady *")
|
||||||
|
field("Název závady *").performTextInput(title)
|
||||||
|
scrollTo("Co se stalo? *")
|
||||||
|
field("Co se stalo? *").performTextInput("Zásuvka u stolu nefunguje ani s jinou nabíječkou.")
|
||||||
|
hideKeyboard()
|
||||||
|
scrollTo("Odeslat hlášení")
|
||||||
|
compose.onNodeWithText("Odeslat hlášení").performClick()
|
||||||
|
|
||||||
|
// Title and description are valid; the missing category must still block creation.
|
||||||
|
compose.onNodeWithText("Vyplňte název, popis a vyberte kategorii závady.").assertExists()
|
||||||
|
compose.onNodeWithText("Nové hlášení").assertIsDisplayed()
|
||||||
|
|
||||||
|
scrollTo("Kategorie *")
|
||||||
|
compose.onNodeWithText("Kategorie *").performClick()
|
||||||
|
compose.onNodeWithText("Elektroinstalace").performClick()
|
||||||
|
scrollTo("Odeslat hlášení")
|
||||||
|
compose.onNodeWithText("Odeslat hlášení").performClick()
|
||||||
|
awaitText("Detail hlášení")
|
||||||
|
awaitText(title)
|
||||||
|
compose.onNodeWithText("Přijata").assertExists()
|
||||||
|
|
||||||
|
scrollTo("Napsat komentář")
|
||||||
|
field("Napsat komentář").performTextInput(comment)
|
||||||
|
hideKeyboard()
|
||||||
|
scrollTo("Odeslat komentář")
|
||||||
|
compose.onNodeWithText("Odeslat komentář").performClick()
|
||||||
|
awaitText("Komentář byl přidán.")
|
||||||
|
|
||||||
|
// Reload removes the editor's local state; the comment must come from repository data.
|
||||||
|
compose.onNodeWithContentDescription("Obnovit").performClick()
|
||||||
|
compose.waitForIdle()
|
||||||
|
scrollTo(comment)
|
||||||
|
compose.onNodeWithText(comment).assertIsDisplayed()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun profileCanEndDemoAndNewDemoStartsFresh() {
|
||||||
|
enterDemo()
|
||||||
|
compose.onNodeWithText("Profil").performClick()
|
||||||
|
awaitText("[email protected]")
|
||||||
|
compose.onNodeWithText("Ukončit ukázku").performScrollTo().performClick()
|
||||||
|
|
||||||
|
awaitText("Vítejte v NTBug")
|
||||||
|
compose.onNodeWithText("Prohlédnout ukázku").performScrollTo().assertIsDisplayed()
|
||||||
|
enterDemo()
|
||||||
|
compose.onNodeWithText("Ahoj, Jana.").assertIsDisplayed()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun enterDemo() {
|
||||||
|
awaitText("Prohlédnout ukázku")
|
||||||
|
compose.onNodeWithText("Prohlédnout ukázku").performScrollTo().performClick()
|
||||||
|
awaitText("Ahoj, Jana.")
|
||||||
|
compose.waitForIdle()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun awaitText(text: String) {
|
||||||
|
compose.waitUntil(timeoutMillis = 15_000) {
|
||||||
|
compose.onAllNodesWithText(text).fetchSemanticsNodes().isNotEmpty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun scrollTo(text: String) {
|
||||||
|
compose.onNode(hasScrollToIndexAction()).performScrollToNode(hasText(text))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun field(label: String): SemanticsNodeInteraction =
|
||||||
|
compose.onNode(hasSetTextAction() and hasText(label))
|
||||||
|
|
||||||
|
private fun hideKeyboard() {
|
||||||
|
compose.runOnUiThread {
|
||||||
|
WindowCompat.getInsetsController(compose.activity.window, compose.activity.window.decorView)
|
||||||
|
.hide(WindowInsetsCompat.Type.ime())
|
||||||
|
}
|
||||||
|
compose.waitForIdle()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
|
||||||
|
<application android:usesCleartextTraffic="true" tools:replace="android:usesCleartextTraffic" />
|
||||||
|
</manifest>
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-feature android:name="android.hardware.camera" android:required="false" />
|
||||||
|
<application
|
||||||
|
android:allowBackup="false"
|
||||||
|
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||||
|
android:icon="@drawable/ic_ntbug"
|
||||||
|
android:label="@string/app_name"
|
||||||
|
android:supportsRtl="true"
|
||||||
|
android:theme="@style/Theme.NTBug"
|
||||||
|
android:usesCleartextTraffic="false">
|
||||||
|
<activity
|
||||||
|
android:name=".MainActivity"
|
||||||
|
android:exported="true"
|
||||||
|
android:windowSoftInputMode="adjustResize">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
<provider
|
||||||
|
android:name="androidx.core.content.FileProvider"
|
||||||
|
android:authorities="${applicationId}.files"
|
||||||
|
android:exported="false"
|
||||||
|
android:grantUriPermissions="true">
|
||||||
|
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
|
||||||
|
</provider>
|
||||||
|
</application>
|
||||||
|
</manifest>
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package cz.ntbug.mobile
|
||||||
|
|
||||||
|
import android.os.Bundle
|
||||||
|
import androidx.activity.ComponentActivity
|
||||||
|
import androidx.activity.compose.setContent
|
||||||
|
import androidx.activity.enableEdgeToEdge
|
||||||
|
import cz.ntbug.mobile.ui.NTBugApp
|
||||||
|
import cz.ntbug.mobile.ui.NTBugTheme
|
||||||
|
|
||||||
|
class MainActivity : ComponentActivity() {
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
enableEdgeToEdge()
|
||||||
|
setContent { NTBugTheme { NTBugApp() } }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
package cz.ntbug.mobile.data
|
||||||
|
|
||||||
|
import java.time.Instant
|
||||||
|
|
||||||
|
/** Explicit, ephemeral demonstration. This repository never sends data to a server. */
|
||||||
|
class DemoRepository : HelpdeskRepository {
|
||||||
|
private var user = User(1, "[email protected]", "Jana", "Nováková", role = "STUDENT")
|
||||||
|
private val catalog = Catalogs(
|
||||||
|
listOf(Building(1, "A", "Budova A", "Univerzitní kampus"), Building(2, "B", "Budova B", "Univerzitní kampus"), Building(3, "K", "Knihovna")),
|
||||||
|
listOf(Category(1, "Technické vybavení"), Category(2, "Elektroinstalace"), Category(3, "Voda a topení"), Category(4, "Úklid a prostředí"), Category(5, "Ostatní")),
|
||||||
|
listOf(Category(1, "Studium"), Category(2, "Služby"), Category(3, "Prostředí"), Category(4, "Ostatní")),
|
||||||
|
)
|
||||||
|
private val issueItems = mutableListOf(
|
||||||
|
Issue(104, "Nefunkční projektor v B-205", "Projektor po zapnutí bliká a nezobrazuje obraz. Vyzkoušeli jsme také jiný HDMI kabel.", "IN_PROGRESS", 1, "Technické vybavení", 2, "Budova B", "Učebna B-205, 2. patro", 1, "Jana Nováková", "Petr Svoboda", "2026-11-03T09:15:00Z", 3, listOf("comment", "attachments"),
|
||||||
|
listOf(IssueEvent(1, "Jana Nováková", "CREATED", "Závada byla přijata.", "2026-11-03T09:15:00Z"), IssueEvent(2, "Vedení školy", "ASSIGNED", "Přiřazeno správci Petr Svoboda.", "2026-11-03T11:30:00Z"), IssueEvent(3, "Petr Svoboda", "COMMENTED", "Projektor zkontroluji a objednám náhradní lampu.", "2026-11-04T08:30:00Z"))),
|
||||||
|
Issue(103, "Nesvítí světlo na chodbě", "Na chodbě u učebny A-112 nesvítí jedno ze stropních světel.", "PENDING_VERIFICATION", 2, "Elektroinstalace", 1, "Budova A", "Chodba, 1. patro", 1, "Jana Nováková", "Petr Svoboda", "2026-11-02T13:00:00Z", 4, listOf("confirm", "reopen", "comment", "attachments"),
|
||||||
|
listOf(IssueEvent(4, "Jana Nováková", "CREATED", "Závada byla přijata.", "2026-11-02T13:00:00Z"), IssueEvent(5, "Petr Svoboda", "STATUS_CHANGED", "Svítidlo je opravené. Prosím o ověření.", "2026-11-04T14:00:00Z"))),
|
||||||
|
Issue(102, "Uvolněná klika u studovny", "Klika u vstupu do tiché studovny se viklá.", "RECEIVED", 5, "Ostatní", 3, "Knihovna", "Tichá studovna", 1, "Jana Nováková", null, "2026-11-01T10:00:00Z", 1, listOf("edit", "comment", "attachments"),
|
||||||
|
listOf(IssueEvent(6, "Jana Nováková", "CREATED", "Závada byla přijata.", "2026-11-01T10:00:00Z"))),
|
||||||
|
Issue(101, "Kapající kohoutek", "Na toaletách v přízemí kapala voda z kohoutku.", "RESOLVED", 3, "Voda a topení", 1, "Budova A", "Toalety v přízemí", 1, "Jana Nováková", "Petr Svoboda", "2026-10-27T08:00:00Z", 5, emptyList(),
|
||||||
|
listOf(IssueEvent(7, "Jana Nováková", "CREATED", "Závada byla přijata.", "2026-10-27T08:00:00Z"), IssueEvent(8, "Jana Nováková", "STATUS_CHANGED", "Vyřešení potvrzeno. Děkuji za opravu!", "2026-10-29T10:00:00Z"))),
|
||||||
|
)
|
||||||
|
private val proposalItems = mutableListOf(
|
||||||
|
Proposal(21, "Více zásuvek ve studovně", "Doplňme zásuvky ke stolům v knihovně, abychom mohli pohodlně pracovat na notebooku i během delšího studia.", 3, "Prostředí", 2, "Adam Dvořák", "UNDER_REVIEW", 42, null, "2026-10-30T10:00:00Z", "Ověřujeme možnosti doplnění zásuvek."),
|
||||||
|
Proposal(22, "Delší otevírací doba knihovny", "Během zkouškového období bychom uvítali otevření knihovny až do 22 hodin.", 2, "Služby", 3, "Tereza Malá", "SUBMITTED", 28, null, "2026-11-02T12:00:00Z"),
|
||||||
|
Proposal(23, "Stojany na kola u budovy B", "Kryté stojany by zpříjemnily dojíždění do školy na kole.", 3, "Prostředí", 1, "Jana Nováková", "ACCEPTED", 17, null, "2026-10-28T09:00:00Z", "Návrh byl přijat. Instalaci plánujeme na jaro."),
|
||||||
|
)
|
||||||
|
private val noticeItems = mutableListOf(
|
||||||
|
Notice(1, "Ověřte opravu světla", "Správce dokončil opravu. Potvrďte, zda světlo na chodbě opět funguje.", "2026-11-04T14:00:00Z", false, issueId = 103),
|
||||||
|
Notice(2, "Nový komentář u projektoru", "Petr Svoboda přidal zprávu k vašemu hlášení.", "2026-11-04T08:30:00Z", false, issueId = 104),
|
||||||
|
Notice(3, "Váš návrh byl přijat", "Stojany na kola u budovy B získaly podporu vedení.", "2026-11-03T09:00:00Z", true, proposalId = 23),
|
||||||
|
)
|
||||||
|
private val uploadedFiles = mutableMapOf<Int, Upload>()
|
||||||
|
private var nextAttachmentId = 1
|
||||||
|
|
||||||
|
override suspend fun login(email: String, password: String): User = user
|
||||||
|
override suspend fun register(email: String, password: String, firstName: String, lastName: String) = Unit
|
||||||
|
override suspend fun confirmEmail(token: String) = Unit
|
||||||
|
override suspend fun forgotPassword(email: String) = Unit
|
||||||
|
override suspend fun resetPassword(token: String, newPassword: String) = Unit
|
||||||
|
override suspend fun restoreUser(): User = user
|
||||||
|
override suspend fun logout(allDevices: Boolean) = Unit
|
||||||
|
override suspend fun updateProfile(update: ProfileUpdate): User {
|
||||||
|
require(update.firstName.isNotBlank() && update.lastName.isNotBlank()) { "Vyplňte jméno a příjmení." }
|
||||||
|
user = user.copy(firstName = update.firstName.trim(), lastName = update.lastName.trim(), phone = update.phone?.trim()?.takeIf(String::isNotBlank), emailNotificationsEnabled = update.emailNotificationsEnabled)
|
||||||
|
return user
|
||||||
|
}
|
||||||
|
override suspend fun catalogs(): Catalogs = catalog
|
||||||
|
override suspend fun issues(page: Int, query: String, status: String?, assigned: Boolean): Page<Issue> = paginate(
|
||||||
|
issueItems.filter { (status == null || it.status == status) && (it.title.contains(query, true) || it.description.contains(query, true)) && !assigned }, page,
|
||||||
|
)
|
||||||
|
override suspend fun issue(id: Int): Issue = issueItems.firstOrNull { it.id == id } ?: throw ApiException(404, "Hlášení nebylo nalezeno.")
|
||||||
|
override suspend fun createIssue(issue: NewIssue): Issue {
|
||||||
|
require(issue.title.isNotBlank() && issue.description.isNotBlank()) { "Vyplňte název a popis závady." }
|
||||||
|
val category = catalog.issueCategories.firstOrNull { it.id == issue.categoryId } ?: throw IllegalArgumentException("Vyberte kategorii.")
|
||||||
|
val building = issue.buildingId?.let { id -> catalog.buildings.first { it.id == id } }
|
||||||
|
val created = Issue((issueItems.maxOfOrNull { it.id } ?: 0) + 1, issue.title.trim(), issue.description.trim(), "RECEIVED", category.id, category.name, building?.id, building?.name, issue.location.trim(), user.id, name(), null, now(), 1, listOf("edit", "comment", "attachments"),
|
||||||
|
listOf(IssueEvent(nextEventId(), name(), "CREATED", "Závada byla přijata.", now())))
|
||||||
|
issueItems.add(0, created)
|
||||||
|
addNotice("Hlášení bylo přijato", created.title, issueId = created.id)
|
||||||
|
return created
|
||||||
|
}
|
||||||
|
override suspend fun updateIssue(id: Int, issue: NewIssue, rowVersion: Int): Issue {
|
||||||
|
require(issue.title.isNotBlank() && issue.description.isNotBlank()) { "Vyplňte název a popis závady." }
|
||||||
|
val category = catalog.issueCategories.firstOrNull { it.id == issue.categoryId } ?: throw IllegalArgumentException("Vyberte kategorii.")
|
||||||
|
val building = issue.buildingId?.let { buildingId -> catalog.buildings.first { it.id == buildingId } }
|
||||||
|
changeIssue(id) { old ->
|
||||||
|
if (old.rowVersion != rowVersion) throw ApiException(409, "Záznam se mezitím změnil. Obnovte jej.")
|
||||||
|
if (old.reporterId != user.id || old.status != "RECEIVED") throw ApiException(403, "Upravit lze pouze vlastní hlášení ve stavu Přijata.")
|
||||||
|
old.copy(title = issue.title.trim(), description = issue.description.trim(), categoryId = category.id, categoryName = category.name,
|
||||||
|
buildingId = building?.id, buildingName = building?.name, location = issue.location.trim(),
|
||||||
|
events = old.events + IssueEvent(nextEventId(), name(), "UPDATED", "Hlášení bylo upraveno.", now()))
|
||||||
|
}
|
||||||
|
return this.issue(id)
|
||||||
|
}
|
||||||
|
override suspend fun addAttachments(id: Int, files: List<Upload>) {
|
||||||
|
validateUploads(files)
|
||||||
|
changeIssue(id) { old ->
|
||||||
|
ensureAllowed(old, "attachments")
|
||||||
|
old.copy(attachments = old.attachments + files.map { upload ->
|
||||||
|
val attachmentId = nextAttachmentId++
|
||||||
|
uploadedFiles[attachmentId] = upload.copy(bytes = upload.bytes.copyOf())
|
||||||
|
Attachment(attachmentId, upload.name, upload.mimeType)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override suspend fun downloadAttachment(id: Int): Upload = uploadedFiles[id]?.let { it.copy(bytes = it.bytes.copyOf()) }
|
||||||
|
?: throw ApiException(404, "Příloha není v této ukázkové relaci dostupná.")
|
||||||
|
override suspend fun comment(id: Int, text: String) {
|
||||||
|
require(text.isNotBlank()) { "Napište komentář." }
|
||||||
|
changeIssue(id) { old ->
|
||||||
|
ensureAllowed(old, "comment")
|
||||||
|
old.copy(events = old.events + IssueEvent(nextEventId(), name(), "COMMENTED", text.trim(), now()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override suspend fun issueAction(id: Int, action: String, rowVersion: Int, reason: String) {
|
||||||
|
changeIssue(id) { old ->
|
||||||
|
if (old.rowVersion != rowVersion) throw ApiException(409, "Záznam se mezitím změnil. Obnovte jej.")
|
||||||
|
ensureAllowed(old, action)
|
||||||
|
if (action in listOf("reopen", "reject")) require(reason.isNotBlank()) { "Uveďte důvod." }
|
||||||
|
val status = when (action) {
|
||||||
|
"start", "reopen" -> "IN_PROGRESS"
|
||||||
|
"submit-for-verification" -> "PENDING_VERIFICATION"
|
||||||
|
"confirm" -> "RESOLVED"
|
||||||
|
"reject" -> "REJECTED"
|
||||||
|
else -> throw IllegalArgumentException("Neznámá akce.")
|
||||||
|
}
|
||||||
|
val actions = when (status) {
|
||||||
|
"RESOLVED", "REJECTED" -> emptyList()
|
||||||
|
"PENDING_VERIFICATION" -> listOf("confirm", "reopen", "comment", "attachments")
|
||||||
|
else -> listOf("comment", "attachments")
|
||||||
|
}
|
||||||
|
old.copy(status = status, allowedActions = actions, events = old.events + IssueEvent(nextEventId(), name(), "STATUS_CHANGED", reason.ifBlank { if (status == "RESOLVED") "Vyřešení bylo potvrzeno." else "Změna stavu hlášení." }, now()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override suspend fun proposals(page: Int, query: String, sort: String): Page<Proposal> {
|
||||||
|
val filtered = proposalItems.filter { it.title.contains(query, true) || it.description.contains(query, true) }
|
||||||
|
return paginate(if (sort == "newest") filtered.sortedByDescending { it.createdAt } else filtered.sortedByDescending { it.score }, page)
|
||||||
|
}
|
||||||
|
override suspend fun proposal(id: Int): Proposal = proposalItems.firstOrNull { it.id == id } ?: throw ApiException(404, "Návrh nebyl nalezen.")
|
||||||
|
override suspend fun createProposal(proposal: NewProposal): Proposal {
|
||||||
|
require(proposal.title.isNotBlank() && proposal.description.isNotBlank()) { "Vyplňte název a popis návrhu." }
|
||||||
|
val category = catalog.proposalCategories.firstOrNull { it.id == proposal.categoryId } ?: throw IllegalArgumentException("Vyberte oblast.")
|
||||||
|
val created = Proposal((proposalItems.maxOfOrNull { it.id } ?: 0) + 1, proposal.title.trim(), proposal.description.trim(), category.id, category.name, user.id, name(), "SUBMITTED", 0, null, now())
|
||||||
|
proposalItems.add(0, created)
|
||||||
|
return created
|
||||||
|
}
|
||||||
|
override suspend fun vote(id: Int, value: Int?) {
|
||||||
|
require(value == null || value == 1 || value == -1) { "Neplatná hodnota hlasu." }
|
||||||
|
val proposal = proposal(id)
|
||||||
|
if (proposal.authorId == user.id) throw ApiException(403, "Pro vlastní návrh nemůžete hlasovat.")
|
||||||
|
val index = proposalItems.indexOfFirst { it.id == id }
|
||||||
|
proposalItems[index] = proposal.copy(score = proposal.score - (proposal.myVote ?: 0) + (value ?: 0), myVote = value)
|
||||||
|
}
|
||||||
|
override suspend fun notices(page: Int): Page<Notice> = paginate(noticeItems.sortedByDescending { it.createdAt }, page)
|
||||||
|
override suspend fun readNotice(id: Int) {
|
||||||
|
val index = noticeItems.indexOfFirst { it.id == id }
|
||||||
|
if (index >= 0) noticeItems[index] = noticeItems[index].copy(isRead = true)
|
||||||
|
}
|
||||||
|
override suspend fun readAllNotices() { noticeItems.replaceAll { it.copy(isRead = true) } }
|
||||||
|
|
||||||
|
private fun changeIssue(id: Int, change: (Issue) -> Issue) {
|
||||||
|
val index = issueItems.indexOfFirst { it.id == id }
|
||||||
|
if (index < 0) throw ApiException(404, "Hlášení nebylo nalezeno.")
|
||||||
|
val old = issueItems[index]
|
||||||
|
issueItems[index] = change(old).copy(rowVersion = old.rowVersion + 1)
|
||||||
|
}
|
||||||
|
private fun ensureAllowed(issue: Issue, action: String) {
|
||||||
|
if (action !in issue.allowedActions) throw ApiException(403, "Tato akce není u hlášení povolena.")
|
||||||
|
}
|
||||||
|
private fun addNotice(title: String, text: String, issueId: Int? = null, proposalId: Int? = null) {
|
||||||
|
noticeItems.add(0, Notice((noticeItems.maxOfOrNull { it.id } ?: 0) + 1, title, text, now(), false, issueId, proposalId))
|
||||||
|
}
|
||||||
|
private fun nextEventId() = (issueItems.flatMap { it.events }.maxOfOrNull { it.id } ?: 0) + 1
|
||||||
|
private fun name() = "${user.firstName} ${user.lastName}"
|
||||||
|
private fun now() = Instant.now().toString()
|
||||||
|
private fun <T> paginate(items: List<T>, page: Int): Page<T> {
|
||||||
|
require(page > 0) { "Neplatné číslo stránky." }
|
||||||
|
return Page(items.drop((page - 1) * 20).take(20), items.size, page, 20)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
package cz.ntbug.mobile.data
|
||||||
|
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class User(
|
||||||
|
val id: Int, val email: String, val firstName: String, val lastName: String,
|
||||||
|
val phone: String? = null, val role: String, val emailNotificationsEnabled: Boolean = true,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class AuthSession(
|
||||||
|
val accessToken: String, val accessTokenExpiresAt: String,
|
||||||
|
val refreshToken: String, val refreshTokenExpiresAt: String, val user: User,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class Building(val id: Int, val code: String, val name: String, val address: String? = null, val isActive: Boolean = true)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class Category(val id: Int, val name: String, val description: String? = null, val isActive: Boolean = true)
|
||||||
|
|
||||||
|
data class Catalogs(val buildings: List<Building>, val issueCategories: List<Category>, val proposalCategories: List<Category>)
|
||||||
|
|
||||||
|
/** Contract for the planned issue endpoints; the current server does not expose them yet. */
|
||||||
|
@Serializable
|
||||||
|
data class Issue(
|
||||||
|
val id: Int, val title: String, val description: String, val status: String,
|
||||||
|
val categoryId: Int, val categoryName: String, val buildingId: Int? = null,
|
||||||
|
val buildingName: String? = null, val location: String = "", val reporterId: Int,
|
||||||
|
val reporterName: String, val assigneeName: String? = null, val createdAt: String,
|
||||||
|
val rowVersion: Int = 1, val allowedActions: List<String> = emptyList(),
|
||||||
|
val events: List<IssueEvent> = emptyList(), val attachments: List<Attachment> = emptyList(),
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class IssueEvent(val id: Int, val authorName: String, val type: String, val text: String, val createdAt: String)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class Attachment(val id: Int, val fileName: String, val contentType: String)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class Proposal(
|
||||||
|
val id: Int, val title: String, val description: String, val categoryId: Int,
|
||||||
|
val categoryName: String, val authorId: Int, val authorName: String, val status: String,
|
||||||
|
val score: Int, val myVote: Int? = null, val createdAt: String, val note: String? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class Notice(
|
||||||
|
val id: Int, val title: String, val text: String, val createdAt: String, val isRead: Boolean,
|
||||||
|
val issueId: Int? = null, val proposalId: Int? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class Page<T>(val items: List<T>, val totalCount: Int, val page: Int = 1, val pageSize: Int = 20)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class NewIssue(val title: String, val description: String, val categoryId: Int, val buildingId: Int?, val location: String)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class NewProposal(val title: String, val description: String, val categoryId: Int)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class ProfileUpdate(val firstName: String, val lastName: String, val phone: String?, val emailNotificationsEnabled: Boolean)
|
||||||
|
|
||||||
|
data class Upload(val name: String, val mimeType: String, val bytes: ByteArray)
|
||||||
|
|
||||||
|
class ApiException(val status: Int, message: String) : Exception(message)
|
||||||
|
|
||||||
|
interface HelpdeskRepository {
|
||||||
|
suspend fun login(email: String, password: String): User
|
||||||
|
suspend fun register(email: String, password: String, firstName: String, lastName: String)
|
||||||
|
suspend fun confirmEmail(token: String)
|
||||||
|
suspend fun forgotPassword(email: String)
|
||||||
|
suspend fun resetPassword(token: String, newPassword: String)
|
||||||
|
suspend fun restoreUser(): User?
|
||||||
|
suspend fun logout(allDevices: Boolean = false)
|
||||||
|
suspend fun updateProfile(update: ProfileUpdate): User
|
||||||
|
suspend fun catalogs(): Catalogs
|
||||||
|
suspend fun issues(page: Int = 1, query: String = "", status: String? = null, assigned: Boolean = false): Page<Issue>
|
||||||
|
suspend fun issue(id: Int): Issue
|
||||||
|
suspend fun createIssue(issue: NewIssue): Issue
|
||||||
|
suspend fun updateIssue(id: Int, issue: NewIssue, rowVersion: Int): Issue
|
||||||
|
suspend fun addAttachments(id: Int, files: List<Upload>)
|
||||||
|
suspend fun downloadAttachment(id: Int): Upload
|
||||||
|
suspend fun comment(id: Int, text: String)
|
||||||
|
suspend fun issueAction(id: Int, action: String, rowVersion: Int, reason: String = "")
|
||||||
|
suspend fun proposals(page: Int = 1, query: String = "", sort: String = "score"): Page<Proposal>
|
||||||
|
suspend fun proposal(id: Int): Proposal
|
||||||
|
suspend fun createProposal(proposal: NewProposal): Proposal
|
||||||
|
suspend fun vote(id: Int, value: Int?)
|
||||||
|
suspend fun notices(page: Int = 1): Page<Notice>
|
||||||
|
suspend fun readNotice(id: Int)
|
||||||
|
suspend fun readAllNotices()
|
||||||
|
}
|
||||||
@@ -0,0 +1,325 @@
|
|||||||
|
package cz.ntbug.mobile.data
|
||||||
|
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.currentCoroutineContext
|
||||||
|
import kotlinx.coroutines.ensureActive
|
||||||
|
import kotlinx.coroutines.NonCancellable
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import kotlinx.serialization.SerializationException
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
|
import kotlinx.serialization.json.jsonArray
|
||||||
|
import kotlinx.serialization.json.jsonObject
|
||||||
|
import kotlinx.serialization.json.jsonPrimitive
|
||||||
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
|
import okhttp3.MultipartBody
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
|
import okhttp3.ResponseBody
|
||||||
|
import retrofit2.HttpException
|
||||||
|
import retrofit2.Retrofit
|
||||||
|
import retrofit2.converter.kotlinx.serialization.asConverterFactory
|
||||||
|
import retrofit2.http.Body
|
||||||
|
import retrofit2.http.DELETE
|
||||||
|
import retrofit2.http.GET
|
||||||
|
import retrofit2.http.Header
|
||||||
|
import retrofit2.http.Multipart
|
||||||
|
import retrofit2.http.POST
|
||||||
|
import retrofit2.http.PUT
|
||||||
|
import retrofit2.http.Part
|
||||||
|
import retrofit2.http.Path
|
||||||
|
import retrofit2.http.Query
|
||||||
|
import retrofit2.http.Streaming
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.io.IOException
|
||||||
|
import java.net.URI
|
||||||
|
import java.net.URLDecoder
|
||||||
|
import java.time.Instant
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
/** Accept an origin or an existing /api base URL; Retrofit needs the trailing slash. */
|
||||||
|
fun normalizeBaseUrl(value: String): String {
|
||||||
|
val uri = try { URI(value.trim()) } catch (_: Exception) { throw IllegalArgumentException("Zadejte platnou adresu serveru.") }
|
||||||
|
require(uri.scheme in listOf("https", "http") && !uri.host.isNullOrBlank() && uri.rawUserInfo == null && uri.rawQuery == null && uri.rawFragment == null) {
|
||||||
|
"Adresa musí začínat https:// (pro místní vývoj http://) a nesmí obsahovat přihlašovací údaje, dotaz ani fragment."
|
||||||
|
}
|
||||||
|
val base = value.trim().trimEnd('/')
|
||||||
|
return if (uri.path.trimEnd('/').endsWith("/api")) "$base/" else "$base/api/"
|
||||||
|
}
|
||||||
|
|
||||||
|
class RemoteRepository(baseUrl: String, private val store: SessionPersistence) : HelpdeskRepository {
|
||||||
|
private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }
|
||||||
|
private val client = OkHttpClient.Builder()
|
||||||
|
.connectTimeout(15, TimeUnit.SECONDS)
|
||||||
|
.readTimeout(30, TimeUnit.SECONDS)
|
||||||
|
.writeTimeout(45, TimeUnit.SECONDS)
|
||||||
|
// Token rotation and mutations must never be replayed automatically.
|
||||||
|
.retryOnConnectionFailure(false)
|
||||||
|
.followRedirects(false)
|
||||||
|
.followSslRedirects(false)
|
||||||
|
.build()
|
||||||
|
private val api = Retrofit.Builder().baseUrl(normalizeBaseUrl(baseUrl)).client(client)
|
||||||
|
.addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
|
||||||
|
.build().create(HelpdeskApi::class.java)
|
||||||
|
private val refreshLock = Mutex()
|
||||||
|
@Volatile private var session: AuthSession? = store.read()
|
||||||
|
|
||||||
|
override suspend fun login(email: String, password: String): User = mapped {
|
||||||
|
val response = api.login(LoginRequest(email.trim(), password))
|
||||||
|
store.write(response)
|
||||||
|
session = response
|
||||||
|
response.user
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun register(email: String, password: String, firstName: String, lastName: String) = mapped {
|
||||||
|
api.register(RegisterRequest(email.trim(), password, firstName.trim(), lastName.trim()))
|
||||||
|
Unit
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun confirmEmail(token: String) = mapped { api.confirmEmail(TokenRequest(token.trim())) }
|
||||||
|
override suspend fun forgotPassword(email: String) = mapped { api.forgotPassword(EmailRequest(email.trim())) }
|
||||||
|
override suspend fun resetPassword(token: String, newPassword: String) = mapped {
|
||||||
|
api.resetPassword(ResetRequest(token.trim(), newPassword))
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun restoreUser(): User? {
|
||||||
|
if (session == null) return null
|
||||||
|
return try {
|
||||||
|
val user = authorized { api.me(it) }
|
||||||
|
refreshLock.withLock {
|
||||||
|
session?.copy(user = user)?.also { store.write(it); session = it }
|
||||||
|
}
|
||||||
|
user
|
||||||
|
} catch (error: ApiException) {
|
||||||
|
if (error.status == 401) { clearSession(); null } else throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun logout(allDevices: Boolean) {
|
||||||
|
try {
|
||||||
|
if (session != null) authorized { bearer ->
|
||||||
|
if (allDevices) api.logoutAll(bearer)
|
||||||
|
else api.logout(bearer, RefreshRequest(requireSession().refreshToken))
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
refreshLock.withLock { clearSession() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun updateProfile(update: ProfileUpdate): User {
|
||||||
|
val user = authorized { api.updateMe(it, update) }
|
||||||
|
refreshLock.withLock {
|
||||||
|
session?.copy(user = user)?.also { store.write(it); session = it }
|
||||||
|
}
|
||||||
|
return user
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun catalogs(): Catalogs = Catalogs(
|
||||||
|
authorized { api.buildings(it) }, authorized { api.issueCategories(it) }, authorized { api.proposalCategories(it) },
|
||||||
|
)
|
||||||
|
|
||||||
|
override suspend fun issues(page: Int, query: String, status: String?, assigned: Boolean): Page<Issue> = authorized(planned = true) {
|
||||||
|
api.issues(it, page, query.takeIf(String::isNotBlank), status, !assigned, if (assigned) requireSession().user.id else null)
|
||||||
|
}
|
||||||
|
override suspend fun issue(id: Int): Issue = authorized(planned = true) { bearer ->
|
||||||
|
val issue = api.issue(bearer, id)
|
||||||
|
issue.copy(events = api.events(bearer, id))
|
||||||
|
}
|
||||||
|
override suspend fun createIssue(issue: NewIssue): Issue = authorized(planned = true) { api.createIssue(it, issue) }
|
||||||
|
override suspend fun updateIssue(id: Int, issue: NewIssue, rowVersion: Int): Issue = authorized(planned = true) {
|
||||||
|
api.updateIssue(it, id, UpdateIssueRequest(issue.title, issue.description, issue.categoryId, issue.buildingId, issue.location, rowVersion))
|
||||||
|
}
|
||||||
|
override suspend fun addAttachments(id: Int, files: List<Upload>) {
|
||||||
|
validateUploads(files)
|
||||||
|
if (files.isEmpty()) return
|
||||||
|
authorized(planned = true) { bearer ->
|
||||||
|
api.attachments(bearer, id, files.map { file ->
|
||||||
|
MultipartBody.Part.createFormData("files", file.name, file.bytes.toRequestBody(file.mimeType.toMediaType()))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override suspend fun downloadAttachment(id: Int): Upload = authorized(planned = true) { bearer ->
|
||||||
|
val response = api.downloadAttachment(bearer, id)
|
||||||
|
if (!response.isSuccessful) throw HttpException(response)
|
||||||
|
val responseBody = response.body() ?: throw ApiException(0, "Server nevrátil obsah přílohy.")
|
||||||
|
val fileName = attachmentFileName(response.headers()["Content-Disposition"], id)
|
||||||
|
responseBody.use { body ->
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
if (body.contentLength() > MAX_ATTACHMENT_BYTES) throw ApiException(413, "Příloha je větší než povolených 10 MB.")
|
||||||
|
val bytes = body.byteStream().use { stream ->
|
||||||
|
val output = ByteArrayOutputStream()
|
||||||
|
val buffer = ByteArray(8192)
|
||||||
|
var total = 0
|
||||||
|
while (true) {
|
||||||
|
currentCoroutineContext().ensureActive()
|
||||||
|
val count = stream.read(buffer)
|
||||||
|
if (count < 0) break
|
||||||
|
total += count
|
||||||
|
if (total > MAX_ATTACHMENT_BYTES) throw ApiException(413, "Příloha je větší než povolených 10 MB.")
|
||||||
|
output.write(buffer, 0, count)
|
||||||
|
}
|
||||||
|
output.toByteArray()
|
||||||
|
}
|
||||||
|
Upload(fileName, body.contentType()?.toString()?.substringBefore(';') ?: "application/octet-stream", bytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override suspend fun comment(id: Int, text: String) = authorized(planned = true) { api.comment(it, id, CommentRequest(text.trim())) }
|
||||||
|
override suspend fun issueAction(id: Int, action: String, rowVersion: Int, reason: String) {
|
||||||
|
require(action in listOf("start", "submit-for-verification", "confirm", "reopen", "reject")) { "Neznámá akce závady." }
|
||||||
|
authorized(planned = true) { api.issueAction(it, id, action, ActionRequest(rowVersion, reason.trim(), reason.trim())) }
|
||||||
|
}
|
||||||
|
override suspend fun proposals(page: Int, query: String, sort: String): Page<Proposal> = authorized(planned = true) {
|
||||||
|
api.proposals(it, page, query.takeIf(String::isNotBlank), sort)
|
||||||
|
}
|
||||||
|
override suspend fun proposal(id: Int): Proposal = authorized(planned = true) { api.proposal(it, id) }
|
||||||
|
override suspend fun createProposal(proposal: NewProposal): Proposal = authorized(planned = true) { api.createProposal(it, proposal) }
|
||||||
|
override suspend fun vote(id: Int, value: Int?) {
|
||||||
|
require(value == null || value == 1 || value == -1) { "Hlas musí být pro, proti nebo zrušen." }
|
||||||
|
authorized(planned = true) { if (value == null) api.removeVote(it, id) else api.vote(it, id, VoteRequest(value)) }
|
||||||
|
}
|
||||||
|
override suspend fun notices(page: Int): Page<Notice> = authorized(planned = true) { api.notices(it, page) }
|
||||||
|
override suspend fun readNotice(id: Int) = authorized(planned = true) { api.readNotice(it, id) }
|
||||||
|
override suspend fun readAllNotices() = authorized(planned = true) { api.readAllNotices(it) }
|
||||||
|
|
||||||
|
private fun requireSession(): AuthSession = session ?: throw ApiException(401, "Přihlášení vypršelo. Přihlaste se znovu.")
|
||||||
|
private fun clearSession() { session = null; store.clear() }
|
||||||
|
|
||||||
|
private suspend fun token(): String {
|
||||||
|
val current = requireSession()
|
||||||
|
val expiresSoon = runCatching { Instant.parse(current.accessTokenExpiresAt).isBefore(Instant.now().plusSeconds(30)) }.getOrDefault(false)
|
||||||
|
return if (expiresSoon) refresh(current.accessToken) else current.accessToken
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One refresh per old access token, even when several screens receive 401 together. */
|
||||||
|
private suspend fun refresh(oldAccessToken: String): String = refreshLock.withLock {
|
||||||
|
val current = requireSession()
|
||||||
|
if (current.accessToken != oldAccessToken) return@withLock current.accessToken
|
||||||
|
// Changing a screen/search must not cancel token rotation halfway through.
|
||||||
|
// Finish and persist the single-use response before releasing the mutex.
|
||||||
|
withContext(NonCancellable) {
|
||||||
|
try {
|
||||||
|
val renewed = api.refresh(RefreshRequest(current.refreshToken))
|
||||||
|
store.write(renewed)
|
||||||
|
session = renewed
|
||||||
|
renewed.accessToken
|
||||||
|
} catch (error: Exception) {
|
||||||
|
// Even an IO/storage failure may happen after server-side rotation.
|
||||||
|
// Require a fresh login instead of replaying an uncertain refresh token.
|
||||||
|
clearSession()
|
||||||
|
throw ApiException(401, "Přihlášení se nepodařilo bezpečně obnovit. Přihlaste se znovu.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun <T> authorized(planned: Boolean = false, block: suspend (String) -> T): T = mapped(planned) {
|
||||||
|
val access = token()
|
||||||
|
try { block("Bearer $access") }
|
||||||
|
catch (error: HttpException) {
|
||||||
|
if (error.code() != 401) throw error
|
||||||
|
val renewed = refresh(access)
|
||||||
|
try { block("Bearer $renewed") }
|
||||||
|
catch (second: HttpException) {
|
||||||
|
if (second.code() == 401) refreshLock.withLock {
|
||||||
|
if (session?.accessToken == renewed) clearSession()
|
||||||
|
}
|
||||||
|
throw second
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun <T> mapped(planned: Boolean = false, block: suspend () -> T): T = try { block() }
|
||||||
|
catch (error: CancellationException) { throw error }
|
||||||
|
catch (error: HttpException) {
|
||||||
|
val fallback = when (error.code()) {
|
||||||
|
400 -> "Zkontrolujte vyplněné údaje."
|
||||||
|
401 -> "Přihlášení vypršelo nebo jsou přihlašovací údaje nesprávné."
|
||||||
|
403 -> "K této akci nemáte oprávnění."
|
||||||
|
404, 501 -> if (planned) "Tato funkce nebo záznam zatím není na serveru dostupný. Backend musí doplnit API pro závady, návrhy a oznámení." else "Požadovaný záznam nebyl nalezen."
|
||||||
|
409 -> "Záznam se mezitím změnil. Obnovte jej a zkuste akci znovu."
|
||||||
|
413 -> "Přílohy jsou příliš velké. Limit je 10 MB na soubor."
|
||||||
|
429 -> "Příliš mnoho požadavků. Zkuste to za chvíli."
|
||||||
|
else -> "Server je dočasně nedostupný (${error.code()}). Zkuste to později."
|
||||||
|
}
|
||||||
|
val body = runCatching { error.response()?.errorBody()?.string() }.getOrNull()
|
||||||
|
val message = if (planned && error.code() in listOf(404, 501)) fallback else problemMessage(body) ?: fallback
|
||||||
|
throw ApiException(error.code(), message)
|
||||||
|
}
|
||||||
|
catch (error: SerializationException) { throw ApiException(0, "Server vrátil odpověď v neočekávaném formátu.") }
|
||||||
|
catch (error: IOException) { throw ApiException(0, "K serveru se nelze připojit. Zkontrolujte internet a adresu serveru.") }
|
||||||
|
|
||||||
|
private fun problemMessage(body: String?): String? = runCatching {
|
||||||
|
val problem = json.parseToJsonElement(body ?: return null).jsonObject
|
||||||
|
val validation = problem["errors"]?.jsonObject?.values?.flatMap { it.jsonArray.map { item -> item.jsonPrimitive.content } }?.distinct()
|
||||||
|
validation?.takeIf(List<String>::isNotEmpty)?.joinToString("\n")
|
||||||
|
?: problem["detail"]?.jsonPrimitive?.content?.takeIf(String::isNotBlank)
|
||||||
|
?: problem["title"]?.jsonPrimitive?.content?.takeIf(String::isNotBlank)
|
||||||
|
}.getOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun validateUploads(files: List<Upload>) {
|
||||||
|
require(files.size <= 5) { "Najednou můžete přiložit nejvýše 5 souborů." }
|
||||||
|
val allowed = setOf("image/jpeg", "image/png", "image/heic", "image/heif", "application/pdf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
|
||||||
|
files.forEach {
|
||||||
|
require(it.bytes.isNotEmpty() && it.bytes.size <= 10 * 1024 * 1024) { "Každý soubor musí mít velikost 1 B až 10 MB." }
|
||||||
|
require(it.mimeType in allowed) { "Povolené formáty příloh jsou JPG, PNG, HEIC, PDF a DOCX." }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Serializable private data class LoginRequest(val email: String, val password: String)
|
||||||
|
@Serializable private data class RegisterRequest(val email: String, val password: String, val firstName: String, val lastName: String)
|
||||||
|
@Serializable private data class RefreshRequest(val refreshToken: String)
|
||||||
|
@Serializable private data class TokenRequest(val token: String)
|
||||||
|
@Serializable private data class EmailRequest(val email: String)
|
||||||
|
@Serializable private data class ResetRequest(val token: String, val newPassword: String)
|
||||||
|
@Serializable private data class CommentRequest(val text: String)
|
||||||
|
@Serializable private data class ActionRequest(val rowVersion: Int, val reason: String, val note: String)
|
||||||
|
@Serializable private data class VoteRequest(val value: Int)
|
||||||
|
@Serializable private data class UpdateIssueRequest(val title: String, val description: String, val categoryId: Int, val buildingId: Int?, val location: String, val rowVersion: Int)
|
||||||
|
|
||||||
|
private const val MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024
|
||||||
|
|
||||||
|
private fun attachmentFileName(disposition: String?, id: Int): String {
|
||||||
|
val utf8 = disposition?.let { Regex("filename\\*=UTF-8''([^;]+)", RegexOption.IGNORE_CASE).find(it)?.groupValues?.get(1) }
|
||||||
|
val encodedName = utf8?.let { runCatching { URLDecoder.decode(it.replace("+", "%2B"), "UTF-8") }.getOrNull() }
|
||||||
|
val plainName = disposition?.let { Regex("filename=\\\"([^\\\"]+)\\\"|filename=([^;]+)", RegexOption.IGNORE_CASE).find(it)?.groupValues?.drop(1)?.firstOrNull(String::isNotEmpty) }
|
||||||
|
return (encodedName ?: plainName)?.trim()?.substringAfterLast('/')?.substringAfterLast('\\')
|
||||||
|
?.filter { it.code >= 32 && it.code != 127 }?.take(150)?.takeIf { it.isNotBlank() && it != "." && it != ".." }
|
||||||
|
?: "attachment-$id"
|
||||||
|
}
|
||||||
|
|
||||||
|
private interface HelpdeskApi {
|
||||||
|
@POST("auth/login") suspend fun login(@Body request: LoginRequest): AuthSession
|
||||||
|
@POST("auth/register") suspend fun register(@Body request: RegisterRequest): User
|
||||||
|
@POST("auth/refresh") suspend fun refresh(@Body request: RefreshRequest): AuthSession
|
||||||
|
@POST("auth/confirm-email") suspend fun confirmEmail(@Body request: TokenRequest)
|
||||||
|
@POST("auth/forgot-password") suspend fun forgotPassword(@Body request: EmailRequest)
|
||||||
|
@POST("auth/reset-password") suspend fun resetPassword(@Body request: ResetRequest)
|
||||||
|
@POST("auth/logout") suspend fun logout(@Header("Authorization") bearer: String, @Body request: RefreshRequest)
|
||||||
|
@POST("auth/logout-all") suspend fun logoutAll(@Header("Authorization") bearer: String)
|
||||||
|
@GET("users/me") suspend fun me(@Header("Authorization") bearer: String): User
|
||||||
|
@PUT("users/me") suspend fun updateMe(@Header("Authorization") bearer: String, @Body request: ProfileUpdate): User
|
||||||
|
@GET("buildings") suspend fun buildings(@Header("Authorization") bearer: String): List<Building>
|
||||||
|
@GET("issue-categories") suspend fun issueCategories(@Header("Authorization") bearer: String): List<Category>
|
||||||
|
@GET("proposal-categories") suspend fun proposalCategories(@Header("Authorization") bearer: String): List<Category>
|
||||||
|
@GET("issues") suspend fun issues(@Header("Authorization") bearer: String, @Query("page") page: Int, @Query("q") query: String?, @Query("status") status: String?, @Query("mine") mine: Boolean, @Query("assigneeId") assignee: Int?, @Query("pageSize") size: Int = 20): Page<Issue>
|
||||||
|
@GET("issues/{id}") suspend fun issue(@Header("Authorization") bearer: String, @Path("id") id: Int): Issue
|
||||||
|
@GET("issues/{id}/events") suspend fun events(@Header("Authorization") bearer: String, @Path("id") id: Int): List<IssueEvent>
|
||||||
|
@POST("issues") suspend fun createIssue(@Header("Authorization") bearer: String, @Body request: NewIssue): Issue
|
||||||
|
@PUT("issues/{id}") suspend fun updateIssue(@Header("Authorization") bearer: String, @Path("id") id: Int, @Body request: UpdateIssueRequest): Issue
|
||||||
|
@Multipart @POST("issues/{id}/attachments") suspend fun attachments(@Header("Authorization") bearer: String, @Path("id") id: Int, @Part files: List<MultipartBody.Part>)
|
||||||
|
@Streaming @GET("attachments/{id}") suspend fun downloadAttachment(@Header("Authorization") bearer: String, @Path("id") id: Int): retrofit2.Response<ResponseBody>
|
||||||
|
@POST("issues/{id}/comments") suspend fun comment(@Header("Authorization") bearer: String, @Path("id") id: Int, @Body request: CommentRequest)
|
||||||
|
@POST("issues/{id}/{action}") suspend fun issueAction(@Header("Authorization") bearer: String, @Path("id") id: Int, @Path("action") action: String, @Body request: ActionRequest)
|
||||||
|
@GET("proposals") suspend fun proposals(@Header("Authorization") bearer: String, @Query("page") page: Int, @Query("q") query: String?, @Query("sort") sort: String, @Query("pageSize") size: Int = 20): Page<Proposal>
|
||||||
|
@GET("proposals/{id}") suspend fun proposal(@Header("Authorization") bearer: String, @Path("id") id: Int): Proposal
|
||||||
|
@POST("proposals") suspend fun createProposal(@Header("Authorization") bearer: String, @Body request: NewProposal): Proposal
|
||||||
|
@PUT("proposals/{id}/vote") suspend fun vote(@Header("Authorization") bearer: String, @Path("id") id: Int, @Body request: VoteRequest)
|
||||||
|
@DELETE("proposals/{id}/vote") suspend fun removeVote(@Header("Authorization") bearer: String, @Path("id") id: Int)
|
||||||
|
@GET("notifications") suspend fun notices(@Header("Authorization") bearer: String, @Query("page") page: Int, @Query("pageSize") size: Int = 20): Page<Notice>
|
||||||
|
@POST("notifications/{id}/read") suspend fun readNotice(@Header("Authorization") bearer: String, @Path("id") id: Int)
|
||||||
|
@POST("notifications/read-all") suspend fun readAllNotices(@Header("Authorization") bearer: String)
|
||||||
|
}
|
||||||
Loaded 100 of 209 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user