Compare commits
13
Commits
0865831746
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a61e7a0f99 | ||
|
|
722d318898 | ||
|
|
e9782a1413 | ||
|
|
9fe713fc10 | ||
|
|
0215af0749 | ||
|
|
52fb8af684 | ||
|
|
5470818841 | ||
|
|
4f95c8a379 | ||
|
|
ee5f1d3d10 | ||
|
|
bd8eb65e56 | ||
|
|
91d0c06c83 | ||
|
|
fcf7cd0596 | ||
|
|
232d48c7fc |
No files matched your search
@@ -22,6 +22,53 @@ public sealed class AdminUsersController(UserService users, ICurrentUser current
|
|||||||
CancellationToken ct = default) =>
|
CancellationToken ct = default) =>
|
||||||
users.SearchAsync(q, role, page, pageSize, ct);
|
users.SearchAsync(q, role, page, pageSize, ct);
|
||||||
|
|
||||||
|
[HttpGet("{id:int}")]
|
||||||
|
public Task<AdminUserDetailsDto> Get(int id, CancellationToken ct) => users.GetAdminAsync(id, ct);
|
||||||
|
|
||||||
|
[HttpPost]
|
||||||
|
[ProducesResponseType<AdminUserDetailsDto>(StatusCodes.Status201Created)]
|
||||||
|
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
|
public async Task<ActionResult<AdminUserDetailsDto>> Create(SaveAdminUserRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var user = await users.CreateAsync(currentUser, request, ct);
|
||||||
|
return CreatedAtAction(nameof(Get), new { id = user.Id }, user);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPut("{id:int}")]
|
||||||
|
[ProducesResponseType<AdminUserDetailsDto>(StatusCodes.Status200OK)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
|
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||||
|
public async Task<IActionResult> Update(int id, SaveAdminUserRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var result = await users.UpdateAsync(currentUser, id, request, ct);
|
||||||
|
return result is null ? NoContent() : Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/email-confirmation")]
|
||||||
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
|
public async Task<IActionResult> SendEmailConfirmation(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await users.SendEmailConfirmationAsync(id, ct);
|
||||||
|
return NoContent();
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpDelete("{id:int}")]
|
||||||
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
|
public async Task<IActionResult> Delete(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await users.DeleteAsync(currentUser, id, ct);
|
||||||
|
return NoContent();
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("bulk")]
|
||||||
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
|
public async Task<IActionResult> Bulk(BulkAdminUsersRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await users.BulkUpdateAsync(currentUser, request, ct);
|
||||||
|
return NoContent();
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Změna role – uživatel bude odhlášen a po přihlášení dostane token s novou rolí.</summary>
|
/// <summary>Změna role – uživatel bude odhlášen a po přihlášení dostane token s novou rolí.</summary>
|
||||||
[HttpPut("{id:int}/role")]
|
[HttpPut("{id:int}/role")]
|
||||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
@@ -36,6 +83,7 @@ public sealed class AdminUsersController(UserService users, ICurrentUser current
|
|||||||
/// <summary>Aktivace / deaktivace účtu. Deaktivace zneplatní všechny tokeny uživatele.</summary>
|
/// <summary>Aktivace / deaktivace účtu. Deaktivace zneplatní všechny tokeny uživatele.</summary>
|
||||||
[HttpPut("{id:int}/active")]
|
[HttpPut("{id:int}/active")]
|
||||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
|
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||||
public async Task<IActionResult> SetActive(int id, SetActiveRequest request, CancellationToken ct)
|
public async Task<IActionResult> SetActive(int id, SetActiveRequest request, CancellationToken ct)
|
||||||
|
|||||||
@@ -15,8 +15,8 @@ namespace Helpdesk.Api.Controllers;
|
|||||||
[Produces("application/json")]
|
[Produces("application/json")]
|
||||||
public sealed class AuthController(AuthService auth) : ControllerBase
|
public sealed class AuthController(AuthService auth) : ControllerBase
|
||||||
{
|
{
|
||||||
/// <summary>Registrace e-mailem a heslem. Role (student / vyučující) se určí podle domény e-mailu.</summary>
|
/// <summary>Registrace e-mailem. Role (student / vyučující) se určí podle domény e-mailu.</summary>
|
||||||
/// <remarks>Po registraci přijde e-mail s odkazem pro ověření; bez ověření se nelze přihlásit.</remarks>
|
/// <remarks>Heslo se nastavuje až po otevření ověřovacího odkazu z e-mailu.</remarks>
|
||||||
[HttpPost("register")]
|
[HttpPost("register")]
|
||||||
[ProducesResponseType<UserDto>(StatusCodes.Status201Created)]
|
[ProducesResponseType<UserDto>(StatusCodes.Status201Created)]
|
||||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
@@ -28,11 +28,11 @@ public sealed class AuthController(AuthService auth) : ControllerBase
|
|||||||
return Created($"/{ApiRoutes.V1}/users/me", user);
|
return Created($"/{ApiRoutes.V1}/users/me", user);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Ověření e-mailu tokenem z registračního e-mailu (jednorázový).</summary>
|
/// <summary>Ověří e-mail jednorázovým tokenem a nastaví heslo k účtu.</summary>
|
||||||
[HttpPost("confirm-email")]
|
[HttpPost("confirm-email")]
|
||||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
public async Task<IActionResult> ConfirmEmail(EmailTokenRequest request, CancellationToken ct)
|
public async Task<IActionResult> ConfirmEmail(ConfirmEmailRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
await auth.ConfirmEmailAsync(request, ct);
|
await auth.ConfirmEmailAsync(request, ct);
|
||||||
return NoContent();
|
return NoContent();
|
||||||
@@ -42,8 +42,15 @@ public sealed class AuthController(AuthService auth) : ControllerBase
|
|||||||
[HttpPost("login")]
|
[HttpPost("login")]
|
||||||
[ProducesResponseType<AuthResponse>(StatusCodes.Status200OK)]
|
[ProducesResponseType<AuthResponse>(StatusCodes.Status200OK)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status429TooManyRequests)]
|
||||||
public Task<AuthResponse> Login(LoginRequest request, CancellationToken ct) => auth.LoginAsync(request, ct);
|
public async Task<ActionResult<AuthResponse>> Login(LoginRequest request, [FromServices] LoginRateLimiter limiter, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (!limiter.TryAcquire(HttpContext, request.Email))
|
||||||
|
return Problem(statusCode: StatusCodes.Status429TooManyRequests,
|
||||||
|
title: "Příliš mnoho pokusů o přihlášení. Zkuste to za chvíli.");
|
||||||
|
|
||||||
|
return await auth.LoginAsync(request, ct);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Výměna refresh tokenu za nový pár tokenů. Použitý refresh token se zneplatní.</summary>
|
/// <summary>Výměna refresh tokenu za nový pár tokenů. Použitý refresh token se zneplatní.</summary>
|
||||||
/// <remarks>Opakované použití už vyměněného refresh tokenu zneplatní všechny tokeny uživatele.</remarks>
|
/// <remarks>Opakované použití už vyměněného refresh tokenu zneplatní všechny tokeny uživatele.</remarks>
|
||||||
@@ -62,7 +69,7 @@ public sealed class AuthController(AuthService auth) : ControllerBase
|
|||||||
return NoContent();
|
return NoContent();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Odhlášení ze všech zařízení – zneplatní všechny tokeny uživatele.</summary>
|
/// <summary>Odhlášení ze všech zařízení. Zneplatní tokeny a odstraní registrace pro push.</summary>
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[HttpPost("logout-all")]
|
[HttpPost("logout-all")]
|
||||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ public sealed class IssuesController(IssueService issues) : ControllerBase
|
|||||||
[RequestSizeLimit(AttachmentLimits.MaxRequestBytes)]
|
[RequestSizeLimit(AttachmentLimits.MaxRequestBytes)]
|
||||||
[RequestFormLimits(MultipartBodyLengthLimit = AttachmentLimits.MaxRequestBytes)]
|
[RequestFormLimits(MultipartBodyLengthLimit = AttachmentLimits.MaxRequestBytes)]
|
||||||
[ProducesResponseType<IssueDetail>(StatusCodes.Status201Created)]
|
[ProducesResponseType<IssueDetail>(StatusCodes.Status201Created)]
|
||||||
|
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status413PayloadTooLarge)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status413PayloadTooLarge)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status415UnsupportedMediaType)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status415UnsupportedMediaType)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status429TooManyRequests)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status429TooManyRequests)]
|
||||||
@@ -55,7 +56,7 @@ public sealed class IssuesController(IssueService issues) : ControllerBase
|
|||||||
var form = await ReadFormAsync(ct);
|
var form = await ReadFormAsync(ct);
|
||||||
request = new CreateIssueRequest(
|
request = new CreateIssueRequest(
|
||||||
form["title"].ToString(), form["description"].ToString(),
|
form["title"].ToString(), form["description"].ToString(),
|
||||||
ReadId(form, "categoryId") ?? throw new BadRequestException("Kategorie je povinná."),
|
ReadId(form, "categoryId") ?? 0,
|
||||||
ReadId(form, "buildingId"), form["locationDetail"].ToString());
|
ReadId(form, "buildingId"), form["locationDetail"].ToString());
|
||||||
uploads = ReadUploads(form.Files);
|
uploads = ReadUploads(form.Files);
|
||||||
}
|
}
|
||||||
@@ -87,6 +88,7 @@ public sealed class IssuesController(IssueService issues) : ControllerBase
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpPut("{id:int}")]
|
[HttpPut("{id:int}")]
|
||||||
|
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
public Task<IssueDetail> Edit(int id, EditIssueRequest request, CancellationToken ct) =>
|
public Task<IssueDetail> Edit(int id, EditIssueRequest request, CancellationToken ct) =>
|
||||||
issues.EditAsync(id, request, ct);
|
issues.EditAsync(id, request, ct);
|
||||||
|
|
||||||
@@ -160,16 +162,16 @@ public sealed class IssuesController(IssueService issues) : ControllerBase
|
|||||||
if (string.IsNullOrWhiteSpace(value))
|
if (string.IsNullOrWhiteSpace(value))
|
||||||
return null;
|
return null;
|
||||||
if (!int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var id))
|
if (!int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var id))
|
||||||
throw new BadRequestException($"Neplatná hodnota {key}.");
|
throw new FieldValidationException(key, "Zadejte platné ID.");
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static AttachmentUpload[] ReadUploads(IFormFileCollection files)
|
private static AttachmentUpload[] ReadUploads(IFormFileCollection files)
|
||||||
{
|
{
|
||||||
if (files.Count > AttachmentLimits.MaxFiles)
|
if (files.Count > AttachmentLimits.MaxFiles)
|
||||||
throw new BadRequestException("Najednou lze přiložit nejvýše pět souborů.");
|
throw new FieldValidationException("files", "Najednou lze přiložit nejvýše pět souborů.");
|
||||||
if (files.Any(file => file.Name != "files"))
|
if (files.Any(file => file.Name != "files"))
|
||||||
throw new BadRequestException("Přílohy patří do pole files.");
|
throw new FieldValidationException("files", "Přílohy patří do pole files.");
|
||||||
|
|
||||||
return files.Select(file => new AttachmentUpload(file.FileName, file.Length, file.OpenReadStream)).ToArray();
|
return files.Select(file => new AttachmentUpload(file.FileName, file.Length, file.OpenReadStream)).ToArray();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ internal sealed class AppExceptionHandler(IProblemDetailsService problemDetails)
|
|||||||
Status = StatusCodes.Status400BadRequest,
|
Status = StatusCodes.Status400BadRequest,
|
||||||
Title = "Neplatná vstupní data.",
|
Title = "Neplatná vstupní data.",
|
||||||
},
|
},
|
||||||
AppException app => new ProblemDetails { Status = app.StatusCode, Title = app.Message },
|
AppException app => new ProblemDetails { Status = app.StatusCode, Title = app.Message, Type = app.ProblemType },
|
||||||
BadHttpRequestException request => new ProblemDetails { Status = request.StatusCode },
|
BadHttpRequestException request => new ProblemDetails { Status = request.StatusCode },
|
||||||
_ => null,
|
_ => null,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -43,4 +43,10 @@ public static class RateLimitPolicies
|
|||||||
{
|
{
|
||||||
public const string Auth = "auth";
|
public const string Auth = "auth";
|
||||||
public const string IssueWrites = "issue-writes";
|
public const string IssueWrites = "issue-writes";
|
||||||
|
|
||||||
|
public static string ClientIp(HttpContext context)
|
||||||
|
{
|
||||||
|
var address = context.Connection.RemoteIpAddress;
|
||||||
|
return (address is { IsIPv4MappedToIPv6: true } ? address.MapToIPv4() : address)?.ToString() ?? "unknown";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
using System.Threading.RateLimiting;
|
||||||
|
using Helpdesk.Domain.Users;
|
||||||
|
|
||||||
|
namespace Helpdesk.Api.Infrastructure;
|
||||||
|
|
||||||
|
public sealed class LoginRateLimiter : IDisposable
|
||||||
|
{
|
||||||
|
private readonly PartitionedRateLimiter<(string, string)> attempts =
|
||||||
|
PartitionedRateLimiter.Create<(string, string), (string, string)>(key =>
|
||||||
|
RateLimitPartition.GetFixedWindowLimiter(key,
|
||||||
|
_ => new FixedWindowRateLimiterOptions { PermitLimit = 5, Window = TimeSpan.FromMinutes(1) }));
|
||||||
|
|
||||||
|
public bool TryAcquire(HttpContext context, string? email)
|
||||||
|
{
|
||||||
|
var trimmed = email?.Trim();
|
||||||
|
var normalized = trimmed is { Length: > 0 and <= 254 } ? User.NormalizeEmail(trimmed) : string.Empty;
|
||||||
|
using var lease = attempts.AttemptAcquire((RateLimitPolicies.ClientIp(context), normalized));
|
||||||
|
return lease.IsAcquired;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose() => attempts.Dispose();
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ using Microsoft.OpenApi;
|
|||||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||||
using Helpdesk.Api.Controllers;
|
using Helpdesk.Api.Controllers;
|
||||||
using Helpdesk.Application.Issues;
|
using Helpdesk.Application.Issues;
|
||||||
|
using Helpdesk.Application.Users;
|
||||||
|
|
||||||
namespace Helpdesk.Api.Infrastructure;
|
namespace Helpdesk.Api.Infrastructure;
|
||||||
|
|
||||||
@@ -34,6 +35,7 @@ public static class SwaggerSetup
|
|||||||
[new OpenApiSecuritySchemeReference(SchemeId, document)] = [],
|
[new OpenApiSecuritySchemeReference(SchemeId, document)] = [],
|
||||||
});
|
});
|
||||||
options.OperationFilter<IssueRequestBody>();
|
options.OperationFilter<IssueRequestBody>();
|
||||||
|
options.SchemaFilter<UserStateRequestSchema>();
|
||||||
|
|
||||||
var xml = Path.Combine(AppContext.BaseDirectory, "Helpdesk.Api.xml");
|
var xml = Path.Combine(AppContext.BaseDirectory, "Helpdesk.Api.xml");
|
||||||
if (File.Exists(xml))
|
if (File.Exists(xml))
|
||||||
@@ -43,6 +45,30 @@ public static class SwaggerSetup
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal sealed class UserStateRequestSchema : ISchemaFilter
|
||||||
|
{
|
||||||
|
public void Apply(IOpenApiSchema schema, SchemaFilterContext context)
|
||||||
|
{
|
||||||
|
string[] fields = context.Type switch
|
||||||
|
{
|
||||||
|
var type when type == typeof(UpdateProfileRequest) => ["emailNotificationsEnabled"],
|
||||||
|
var type when type == typeof(SetActiveRequest) => ["isActive"],
|
||||||
|
var type when type == typeof(SaveAdminUserRequest) => ["isActive", "emailConfirmed", "emailNotificationsEnabled"],
|
||||||
|
_ => [],
|
||||||
|
};
|
||||||
|
if (fields.Length == 0 || schema is not OpenApiSchema { Properties: { } properties } request)
|
||||||
|
return;
|
||||||
|
|
||||||
|
request.Required ??= new HashSet<string>();
|
||||||
|
foreach (var field in fields)
|
||||||
|
{
|
||||||
|
request.Required.Add(field);
|
||||||
|
if (properties[field] is OpenApiSchema property)
|
||||||
|
property.Type = JsonSchemaType.Boolean;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
internal sealed class IssueRequestBody : IOperationFilter
|
internal sealed class IssueRequestBody : IOperationFilter
|
||||||
{
|
{
|
||||||
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
||||||
|
|||||||
@@ -49,17 +49,13 @@ if (trustedProxies.Length > 0)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 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 =>
|
options.AddPolicy(RateLimitPolicies.Auth, http => RateLimitPartition.GetFixedWindowLimiter(
|
||||||
{
|
RateLimitPolicies.ClientIp(http),
|
||||||
var address = http.Connection.RemoteIpAddress;
|
_ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) }));
|
||||||
if (address is { IsIPv4MappedToIPv6: true })
|
|
||||||
address = address.MapToIPv4();
|
|
||||||
return RateLimitPartition.GetFixedWindowLimiter(address?.ToString() ?? "unknown",
|
|
||||||
_ => 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",
|
||||||
_ => new SlidingWindowRateLimiterOptions
|
_ => new SlidingWindowRateLimiterOptions
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ public interface IAppDbContext
|
|||||||
|
|
||||||
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
|
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
|
||||||
Task<IDbContextTransaction> BeginWriteAsync(CancellationToken ct);
|
Task<IDbContextTransaction> BeginWriteAsync(CancellationToken ct);
|
||||||
|
Task<User?> LockUserAsync(int id, CancellationToken ct);
|
||||||
Task<Proposal?> LockProposalAsync(int id, CancellationToken ct);
|
Task<Proposal?> LockProposalAsync(int id, CancellationToken ct);
|
||||||
Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct);
|
Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct);
|
||||||
}
|
}
|
||||||
@@ -38,7 +39,7 @@ public interface IAppDbContext
|
|||||||
public interface IPasswordHasher
|
public interface IPasswordHasher
|
||||||
{
|
{
|
||||||
string Hash(string password);
|
string Hash(string password);
|
||||||
bool Verify(string password, string passwordHash);
|
bool Verify(string password, string? passwordHash);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Vydaný JWT: serializovaný token a záznam pro tabulku <c>auth_token</c>.</summary>
|
/// <summary>Vydaný JWT: serializovaný token a záznam pro tabulku <c>auth_token</c>.</summary>
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
|
using System.Text;
|
||||||
using FluentValidation;
|
using FluentValidation;
|
||||||
using Helpdesk.Application.Users;
|
using Helpdesk.Application.Users;
|
||||||
|
|
||||||
namespace Helpdesk.Application.Auth;
|
namespace Helpdesk.Application.Auth;
|
||||||
|
|
||||||
public sealed record RegisterRequest(string Email, string Password, string FirstName, string LastName);
|
public sealed record RegisterRequest(string Email, string FirstName, string LastName);
|
||||||
|
|
||||||
public sealed record LoginRequest(string Email, string Password);
|
public sealed record LoginRequest(string Email, string Password);
|
||||||
|
|
||||||
/// <summary>Refresh token – pro <c>/auth/refresh</c> i <c>/auth/logout</c>.</summary>
|
/// <summary>Refresh token – pro <c>/auth/refresh</c> i <c>/auth/logout</c>.</summary>
|
||||||
public sealed record RefreshTokenRequest(string RefreshToken);
|
public sealed record RefreshTokenRequest(string RefreshToken);
|
||||||
|
|
||||||
/// <summary>Token z odkazu v e-mailu (ověření e-mailu).</summary>
|
public sealed record ConfirmEmailRequest(string Token, string NewPassword);
|
||||||
public sealed record EmailTokenRequest(string Token);
|
|
||||||
|
|
||||||
public sealed record ForgotPasswordRequest(string Email);
|
public sealed record ForgotPasswordRequest(string Email);
|
||||||
|
|
||||||
@@ -26,11 +26,15 @@ public sealed record AuthResponse(
|
|||||||
|
|
||||||
internal static class PasswordRules
|
internal static class PasswordRules
|
||||||
{
|
{
|
||||||
public const int MinLength = 8;
|
private const int MinLength = 8;
|
||||||
public const int MaxLength = 64; // BCrypt zpracuje nejvýše 72 bajtů
|
private const int MaxLength = 64;
|
||||||
|
private const int MaxUtf8Bytes = 72;
|
||||||
|
|
||||||
public static IRuleBuilderOptions<T, string> ValidPassword<T>(this IRuleBuilder<T, string> rule) =>
|
public static IRuleBuilderOptions<T, string?> ValidPassword<T>(this IRuleBuilderInitial<T, string?> rule) =>
|
||||||
rule.NotEmpty().MinimumLength(MinLength).MaximumLength(MaxLength);
|
rule.Cascade(CascadeMode.Stop)
|
||||||
|
.NotEmpty().MinimumLength(MinLength).MaximumLength(MaxLength)
|
||||||
|
.Must(password => Encoding.UTF8.GetByteCount(password!) <= MaxUtf8Bytes)
|
||||||
|
.WithMessage("Heslo může mít nejvýše 72 bajtů v UTF-8.");
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class RegisterRequestValidator : AbstractValidator<RegisterRequest>
|
public sealed class RegisterRequestValidator : AbstractValidator<RegisterRequest>
|
||||||
@@ -38,12 +42,20 @@ public sealed class RegisterRequestValidator : AbstractValidator<RegisterRequest
|
|||||||
public RegisterRequestValidator()
|
public RegisterRequestValidator()
|
||||||
{
|
{
|
||||||
RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(254);
|
RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(254);
|
||||||
RuleFor(x => x.Password).ValidPassword();
|
|
||||||
RuleFor(x => x.FirstName).NotEmpty().MaximumLength(100);
|
RuleFor(x => x.FirstName).NotEmpty().MaximumLength(100);
|
||||||
RuleFor(x => x.LastName).NotEmpty().MaximumLength(100);
|
RuleFor(x => x.LastName).NotEmpty().MaximumLength(100);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public sealed class ConfirmEmailRequestValidator : AbstractValidator<ConfirmEmailRequest>
|
||||||
|
{
|
||||||
|
public ConfirmEmailRequestValidator()
|
||||||
|
{
|
||||||
|
RuleFor(x => x.Token).NotEmpty();
|
||||||
|
RuleFor(x => x.NewPassword).ValidPassword();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public sealed class LoginRequestValidator : AbstractValidator<LoginRequest>
|
public sealed class LoginRequestValidator : AbstractValidator<LoginRequest>
|
||||||
{
|
{
|
||||||
public LoginRequestValidator()
|
public LoginRequestValidator()
|
||||||
|
|||||||
@@ -17,8 +17,8 @@ public sealed class AuthService(
|
|||||||
TokenRevocationService revocation,
|
TokenRevocationService revocation,
|
||||||
IEmailSender emailSender,
|
IEmailSender emailSender,
|
||||||
IOptions<RegistrationOptions> registrationOptions,
|
IOptions<RegistrationOptions> registrationOptions,
|
||||||
TimeProvider clock,
|
|
||||||
IValidator<RegisterRequest> registerValidator,
|
IValidator<RegisterRequest> registerValidator,
|
||||||
|
IValidator<ConfirmEmailRequest> confirmEmailValidator,
|
||||||
IValidator<LoginRequest> loginValidator,
|
IValidator<LoginRequest> loginValidator,
|
||||||
IValidator<ResetPasswordRequest> resetPasswordValidator)
|
IValidator<ResetPasswordRequest> resetPasswordValidator)
|
||||||
{
|
{
|
||||||
@@ -29,61 +29,65 @@ public sealed class AuthService(
|
|||||||
await registerValidator.ValidateAndThrowAsync(request, ct);
|
await registerValidator.ValidateAndThrowAsync(request, ct);
|
||||||
|
|
||||||
var role = _registration.ResolveRole(request.Email)
|
var role = _registration.ResolveRole(request.Email)
|
||||||
?? throw new BadRequestException("Registrace je možná jen s univerzitním e-mailem.");
|
?? throw new FieldValidationException(nameof(request.Email), "Registrace je možná jen s univerzitním e-mailem.");
|
||||||
|
|
||||||
var normalized = User.NormalizeEmail(request.Email);
|
var normalized = User.NormalizeEmail(request.Email);
|
||||||
var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized, ct);
|
var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized, ct);
|
||||||
if (user is null)
|
if (user is null)
|
||||||
{
|
{
|
||||||
user = User.Create(request.Email, passwordHasher.Hash(request.Password), request.FirstName, request.LastName, role);
|
user = User.Create(request.Email, "", request.FirstName, request.LastName, role);
|
||||||
db.Users.Add(user);
|
db.Users.Add(user);
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
}
|
}
|
||||||
else if (!user.IsActive || user.EmailConfirmed || !passwordHasher.Verify(request.Password, user.PasswordHash))
|
else if (!user.IsActive || user.EmailConfirmed)
|
||||||
{
|
{
|
||||||
throw new ConflictException("Účet s tímto e-mailem už existuje.");
|
throw new ConflictException("Účet s tímto e-mailem už existuje.");
|
||||||
}
|
}
|
||||||
|
|
||||||
await SendEmailTokenAsync(user, TokenType.EmailConfirm, ct);
|
await SendEmailConfirmationAsync(user, ct);
|
||||||
return UserDto.From(user);
|
return UserDto.From(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task ConfirmEmailAsync(EmailTokenRequest request, CancellationToken ct)
|
internal Task<bool> SendEmailConfirmationAsync(User user, CancellationToken ct) =>
|
||||||
|
SendEmailTokenAsync(user, TokenType.EmailConfirm, ct);
|
||||||
|
|
||||||
|
public async Task ConfirmEmailAsync(ConfirmEmailRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
|
await confirmEmailValidator.ValidateAndThrowAsync(request, ct);
|
||||||
|
|
||||||
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
var user = await ConsumeEmailTokenAsync(request.Token, TokenType.EmailConfirm, ct);
|
var user = await ConsumeEmailTokenAsync(request.Token, TokenType.EmailConfirm, ct);
|
||||||
|
var revoked = await StageDisconnectAsync(user.Id, RevokeReason.PasswordChanged, ct);
|
||||||
|
user.ChangePasswordHash(passwordHasher.Hash(request.NewPassword));
|
||||||
user.ConfirmEmail();
|
user.ConfirmEmail();
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
|
revocation.Publish(revoked);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<AuthResponse> LoginAsync(LoginRequest request, CancellationToken ct)
|
public async Task<AuthResponse> LoginAsync(LoginRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
await loginValidator.ValidateAndThrowAsync(request, ct);
|
await loginValidator.ValidateAndThrowAsync(request, ct);
|
||||||
|
|
||||||
var now = clock.GetUtcNow().UtcDateTime;
|
|
||||||
var normalized = User.NormalizeEmail(request.Email);
|
var normalized = User.NormalizeEmail(request.Email);
|
||||||
var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized, ct);
|
var account = await db.Users.Where(u => u.EmailNormalized == normalized && u.IsActive && !u.IsDeleted && u.EmailConfirmed)
|
||||||
|
.Select(u => new { u.Id, u.EmailNormalized, u.PasswordHash }).SingleOrDefaultAsync(ct);
|
||||||
|
|
||||||
// Neexistující účet a špatné heslo vracejí stejnou chybu – nelze tak zjišťovat registrované e-maily.
|
|
||||||
const string invalidCredentials = "Neplatný e-mail nebo heslo.";
|
const string invalidCredentials = "Neplatný e-mail nebo heslo.";
|
||||||
if (user is null)
|
var passwordHash = account?.EmailNormalized == normalized ? account.PasswordHash : null;
|
||||||
|
if (!passwordHasher.Verify(request.Password, passwordHash) || account is null)
|
||||||
throw new UnauthorizedException(invalidCredentials);
|
throw new UnauthorizedException(invalidCredentials);
|
||||||
if (user.IsLockedOut(now))
|
|
||||||
throw new UnauthorizedException("Účet je po opakovaných neúspěšných pokusech dočasně zamčen. Zkuste to později.");
|
|
||||||
|
|
||||||
if (!passwordHasher.Verify(request.Password, user.PasswordHash))
|
// Po ověření hesla ověříme pod zámkem, že se účet mezitím nezměnil.
|
||||||
{
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
user.RegisterFailedLogin(now);
|
var user = await db.LockUserAsync(account.Id, ct);
|
||||||
await db.SaveChangesAsync(ct);
|
if (user is not { IsActive: true, IsDeleted: false, EmailConfirmed: true } ||
|
||||||
|
user.EmailNormalized != normalized || user.PasswordHash != passwordHash)
|
||||||
throw new UnauthorizedException(invalidCredentials);
|
throw new UnauthorizedException(invalidCredentials);
|
||||||
}
|
|
||||||
|
|
||||||
if (!user.IsActive)
|
var response = await IssueTokenPairAsync(user, ct);
|
||||||
throw new ForbiddenException("Účet je deaktivován.");
|
await transaction.CommitAsync(ct);
|
||||||
if (!user.EmailConfirmed)
|
return response;
|
||||||
throw new ForbiddenException("E-mail ještě nebyl ověřen. Použijte odkaz z registračního e-mailu.");
|
|
||||||
|
|
||||||
user.RegisterSuccessfulLogin();
|
|
||||||
return await IssueTokenPairAsync(user, ct);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -95,22 +99,22 @@ 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.");
|
||||||
|
|
||||||
// Původní token zůstane zamčený, dokud není nový pár uložený.
|
// Stejný zámek účtu používá jeho správa, takže během zneplatnění nevznikne nová relace.
|
||||||
await using (var transaction = await db.BeginWriteAsync(ct))
|
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))
|
if (await revocation.TryConsumeAsync(token.Jti, TokenType.Refresh, ct))
|
||||||
{
|
{
|
||||||
var user = await db.Users.SingleOrDefaultAsync(u => u.Id == token.UserId, ct);
|
|
||||||
if (user is null || !user.IsActive)
|
|
||||||
throw new UnauthorizedException("Účet neexistuje nebo je deaktivován.");
|
|
||||||
|
|
||||||
var response = await IssueTokenPairAsync(user, ct);
|
var response = await IssueTokenPairAsync(user, ct);
|
||||||
await transaction.CommitAsync(ct);
|
await transaction.CommitAsync(ct);
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
await revocation.RevokeAllAsync(token.UserId, RevokeReason.ReuseDetected, ct);
|
var revoked = await StageDisconnectAsync(user.Id, RevokeReason.ReuseDetected, ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
|
revocation.Publish(revoked);
|
||||||
throw new UnauthorizedException("Refresh token už byl použit. Přihlaste se znovu.");
|
throw new UnauthorizedException("Refresh token už byl použit. Přihlaste se znovu.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -126,8 +130,15 @@ public sealed class AuthService(
|
|||||||
await revocation.RevokeAsync(currentUser.Id, jtis, RevokeReason.Logout, ct);
|
await revocation.RevokeAsync(currentUser.Id, jtis, RevokeReason.Logout, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task LogoutAllAsync(ICurrentUser currentUser, CancellationToken ct) =>
|
public async Task LogoutAllAsync(ICurrentUser currentUser, CancellationToken ct)
|
||||||
revocation.RevokeAllAsync(currentUser.Id, RevokeReason.LogoutAll, ct);
|
{
|
||||||
|
var userId = currentUser.Id;
|
||||||
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
|
await db.LockUserAsync(userId, ct);
|
||||||
|
var revoked = await StageDisconnectAsync(userId, RevokeReason.LogoutAll, ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
|
revocation.Publish(revoked);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Vždy uspěje, i pro neexistující e-mail – odpověď neprozradí, zda účet existuje.</summary>
|
/// <summary>Vždy uspěje, i pro neexistující e-mail – odpověď neprozradí, zda účet existuje.</summary>
|
||||||
public async Task ForgotPasswordAsync(ForgotPasswordRequest request, CancellationToken ct)
|
public async Task ForgotPasswordAsync(ForgotPasswordRequest request, CancellationToken ct)
|
||||||
@@ -151,12 +162,22 @@ public sealed class AuthService(
|
|||||||
{
|
{
|
||||||
await resetPasswordValidator.ValidateAndThrowAsync(request, ct);
|
await resetPasswordValidator.ValidateAndThrowAsync(request, ct);
|
||||||
|
|
||||||
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
var user = await ConsumeEmailTokenAsync(request.Token, TokenType.PasswordReset, ct);
|
var user = await ConsumeEmailTokenAsync(request.Token, TokenType.PasswordReset, ct);
|
||||||
|
var revoked = await StageDisconnectAsync(user.Id, RevokeReason.PasswordChanged, ct);
|
||||||
// Nejdřív zneplatnit stará přihlášení – kdyby uložení hesla selhalo, nic se tím neotevře.
|
|
||||||
await revocation.RevokeAllAsync(user.Id, RevokeReason.PasswordChanged, ct);
|
|
||||||
user.ChangePasswordHash(passwordHasher.Hash(request.NewPassword));
|
user.ChangePasswordHash(passwordHasher.Hash(request.NewPassword));
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
|
revocation.Publish(revoked);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Volat v transakci se zámkem účtu, který používá i registrace zařízení.
|
||||||
|
private async Task<List<TokenRevocationService.RevokedAccessToken>> StageDisconnectAsync(
|
||||||
|
int userId, RevokeReason reason, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var revoked = await revocation.StageRevokeAllAsync([userId], reason, ct);
|
||||||
|
await db.PushDevices.Where(device => device.UserId == userId).ExecuteDeleteAsync(ct);
|
||||||
|
return revoked;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<AuthResponse> IssueTokenPairAsync(User user, CancellationToken ct)
|
private async Task<AuthResponse> IssueTokenPairAsync(User user, CancellationToken ct)
|
||||||
@@ -172,21 +193,33 @@ public sealed class AuthService(
|
|||||||
UserDto.From(user));
|
UserDto.From(user));
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task SendEmailTokenAsync(User user, TokenType type, CancellationToken ct)
|
private async Task<bool> SendEmailTokenAsync(User user, TokenType type, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var issued = tokens.Issue(user, type);
|
IssuedToken issued;
|
||||||
|
await using (var transaction = await db.BeginWriteAsync(ct))
|
||||||
|
{
|
||||||
|
await db.LockUserAsync(user.Id, ct);
|
||||||
|
var current = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == user.Id, ct);
|
||||||
|
if (current is null || !current.IsActive || current.EmailNormalized != user.EmailNormalized ||
|
||||||
|
(type == TokenType.EmailConfirm && current.EmailConfirmed))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
issued = tokens.Issue(current, type);
|
||||||
db.AuthTokens.Add(issued.Record);
|
db.AuthTokens.Add(issued.Record);
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
|
}
|
||||||
|
|
||||||
var baseUrl = _registration.WebBaseUrl.TrimEnd('/');
|
var baseUrl = _registration.WebBaseUrl.TrimEnd('/');
|
||||||
var (subject, path, text) = type switch
|
var (subject, path, text) = type switch
|
||||||
{
|
{
|
||||||
TokenType.EmailConfirm => ("Ověření e-mailu", "confirm-email", "Pro dokončení registrace ověřte svůj e-mail"),
|
TokenType.EmailConfirm => ("Ověření e-mailu", "confirm-email", "Ověřte svůj e-mail a nastavte heslo k účtu"),
|
||||||
TokenType.PasswordReset => ("Obnova hesla", "reset-password", "Nové heslo nastavíte"),
|
TokenType.PasswordReset => ("Obnova hesla", "reset-password", "Nové heslo nastavíte"),
|
||||||
_ => throw new ArgumentOutOfRangeException(nameof(type)),
|
_ => throw new ArgumentOutOfRangeException(nameof(type)),
|
||||||
};
|
};
|
||||||
var link = $"{baseUrl}/{path}?token={Uri.EscapeDataString(issued.Token)}";
|
var link = $"{baseUrl}/{path}?token={Uri.EscapeDataString(issued.Token)}";
|
||||||
await emailSender.SendAsync(user.Email, subject, $"{text} na adrese:\n{link}", ct);
|
await emailSender.SendAsync(user.Email, subject, $"{text} na adrese:\n{link}", ct);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<User> ConsumeEmailTokenAsync(string token, TokenType type, CancellationToken ct)
|
private async Task<User> ConsumeEmailTokenAsync(string token, TokenType type, CancellationToken ct)
|
||||||
@@ -194,10 +227,11 @@ public sealed class AuthService(
|
|||||||
const string invalid = "Odkaz je neplatný, už byl použit nebo vypršel.";
|
const string invalid = "Odkaz je neplatný, už byl použit nebo vypršel.";
|
||||||
|
|
||||||
var validated = await tokens.ValidateAsync(token ?? "", type) ?? throw new BadRequestException(invalid);
|
var validated = await tokens.ValidateAsync(token ?? "", type) ?? throw new BadRequestException(invalid);
|
||||||
if (!await revocation.TryConsumeAsync(validated.Jti, type, ct))
|
var user = await db.LockUserAsync(validated.UserId, ct);
|
||||||
|
if (user is null || !user.IsActive || (type == TokenType.EmailConfirm && user.EmailConfirmed) ||
|
||||||
|
!await revocation.TryConsumeAsync(validated.Jti, type, ct))
|
||||||
throw new BadRequestException(invalid);
|
throw new BadRequestException(invalid);
|
||||||
|
|
||||||
return await db.Users.SingleOrDefaultAsync(u => u.Id == validated.UserId && u.IsActive, ct)
|
return user;
|
||||||
?? throw new BadRequestException(invalid);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -31,35 +31,37 @@ public sealed class TokenRevocationService(IAppDbContext db, IRevokedTokenStore
|
|||||||
.ExecuteUpdateAsync(s => s
|
.ExecuteUpdateAsync(s => s
|
||||||
.SetProperty(t => t.RevokedAt, now)
|
.SetProperty(t => t.RevokedAt, now)
|
||||||
.SetProperty(t => t.RevokeReason, reason), ct);
|
.SetProperty(t => t.RevokeReason, reason), ct);
|
||||||
await AddRevokedAccessTokensToStoreAsync(userId, now, ct);
|
Publish(await LoadRevokedAccessTokensAsync([userId], now, ct));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Zneplatní všechny platné tokeny uživatele – jeden UPDATE (kap. 10.1).</summary>
|
internal async Task<List<RevokedAccessToken>> StageRevokeAllAsync(int[] userIds, RevokeReason reason, CancellationToken ct)
|
||||||
public async Task RevokeAllAsync(int userId, RevokeReason reason, CancellationToken ct)
|
|
||||||
{
|
{
|
||||||
var now = Now();
|
var now = Now();
|
||||||
await db.AuthTokens
|
await db.AuthTokens
|
||||||
.Where(t => t.UserId == userId && t.RevokedAt == null)
|
.Where(t => userIds.Contains(t.UserId) && t.RevokedAt == null)
|
||||||
.ExecuteUpdateAsync(s => s
|
.ExecuteUpdateAsync(s => s
|
||||||
.SetProperty(t => t.RevokedAt, now)
|
.SetProperty(t => t.RevokedAt, now)
|
||||||
.SetProperty(t => t.RevokeReason, reason), ct);
|
.SetProperty(t => t.RevokeReason, reason), ct);
|
||||||
await AddRevokedAccessTokensToStoreAsync(userId, now, ct);
|
return await LoadRevokedAccessTokensAsync(userIds, now, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Access tokeny se ověřují proti paměťové evidenci, aby API nemuselo při každém
|
// Access tokeny se ověřují proti paměťové evidenci, aby API nemuselo při každém
|
||||||
// požadavku dotazovat DB. Zneplatněné řádky poznáme podle právě zapsaného revoked_at.
|
// požadavku dotazovat DB. Zneplatněné řádky poznáme podle právě zapsaného revoked_at.
|
||||||
private async Task AddRevokedAccessTokensToStoreAsync(int userId, DateTime revokedAt, CancellationToken ct)
|
private Task<List<RevokedAccessToken>> LoadRevokedAccessTokensAsync(int[] userIds, DateTime revokedAt, CancellationToken ct) =>
|
||||||
{
|
db.AuthTokens
|
||||||
var revoked = await db.AuthTokens
|
|
||||||
.AsNoTracking()
|
.AsNoTracking()
|
||||||
.Where(t => t.UserId == userId && t.TokenType == TokenType.Access && t.RevokedAt == revokedAt)
|
.Where(t => userIds.Contains(t.UserId) && t.TokenType == TokenType.Access && t.RevokedAt == revokedAt)
|
||||||
.Select(t => new { t.Jti, t.ExpiresAt })
|
.Select(t => new RevokedAccessToken(t.Jti, t.ExpiresAt))
|
||||||
.ToListAsync(ct);
|
.ToListAsync(ct);
|
||||||
|
|
||||||
|
internal void Publish(IEnumerable<RevokedAccessToken> revoked)
|
||||||
|
{
|
||||||
foreach (var token in revoked)
|
foreach (var token in revoked)
|
||||||
store.Add(token.Jti, token.ExpiresAt);
|
store.Add(token.Jti, token.ExpiresAt);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal sealed record RevokedAccessToken(string Jti, DateTime ExpiresAt);
|
||||||
|
|
||||||
// DATETIME(6) má přesnost na mikrosekundy – zaokrouhlením zajistíme, že hodnota
|
// DATETIME(6) má přesnost na mikrosekundy – zaokrouhlením zajistíme, že hodnota
|
||||||
// zapsaná do DB je stejná jako ta, podle které pak hledáme.
|
// zapsaná do DB je stejná jako ta, podle které pak hledáme.
|
||||||
private DateTime Now()
|
private DateTime Now()
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
|
using FluentValidation;
|
||||||
|
using FluentValidation.Results;
|
||||||
|
|
||||||
namespace Helpdesk.Application.Common;
|
namespace Helpdesk.Application.Common;
|
||||||
|
|
||||||
/// <summary>Chyba aplikační vrstvy; API ji převádí na ProblemDetails s odpovídajícím HTTP stavem.</summary>
|
/// <summary>Chyba aplikační vrstvy; API ji převádí na ProblemDetails s odpovídajícím HTTP stavem.</summary>
|
||||||
public abstract class AppException(string message) : Exception(message)
|
public abstract class AppException(string message, string? problemType = null) : Exception(message)
|
||||||
{
|
{
|
||||||
public abstract int StatusCode { get; }
|
public abstract int StatusCode { get; }
|
||||||
|
public string? ProblemType { get; } = problemType;
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class NotFoundException(string message) : AppException(message)
|
public sealed class NotFoundException(string message) : AppException(message)
|
||||||
@@ -11,7 +15,13 @@ public sealed class NotFoundException(string message) : AppException(message)
|
|||||||
public override int StatusCode => 404;
|
public override int StatusCode => 404;
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class ConflictException(string message) : AppException(message)
|
public sealed class ConflictException(string message, string? problemType = null) : AppException(message, problemType)
|
||||||
|
{
|
||||||
|
public override int StatusCode => 409;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class AccountVersionConflictException()
|
||||||
|
: AppException("Účet se mezitím změnil. Načtěte jeho aktuální údaje a změny zadejte znovu.", "urn:ntbug:account-version-conflict")
|
||||||
{
|
{
|
||||||
public override int StatusCode => 409;
|
public override int StatusCode => 409;
|
||||||
}
|
}
|
||||||
@@ -31,8 +41,13 @@ public sealed class BadRequestException(string message) : AppException(message)
|
|||||||
public override int StatusCode => 400;
|
public override int StatusCode => 400;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public sealed class FieldValidationException(string field, string message)
|
||||||
|
: ValidationException([new ValidationFailure(field, message)])
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
public sealed class EmailDeliveryException(string reason, bool retryable)
|
public sealed class EmailDeliveryException(string reason, bool retryable)
|
||||||
: AppException("E-mail se nepodařilo odeslat. Zkuste požadavek později.")
|
: AppException("E-mail se nepodařilo odeslat. Zkuste požadavek později.", "urn:ntbug:email-delivery-failed")
|
||||||
{
|
{
|
||||||
public string Reason { get; } = reason;
|
public string Reason { get; } = reason;
|
||||||
public bool Retryable { get; } = retryable;
|
public bool Retryable { get; } = retryable;
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
|
using FluentValidation;
|
||||||
|
using FluentValidation.Results;
|
||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
using Helpdesk.Application.Common;
|
using Helpdesk.Application.Common;
|
||||||
using Helpdesk.Application.Notifications;
|
using Helpdesk.Application.Notifications;
|
||||||
@@ -44,11 +46,17 @@ public sealed partial class IssueService(
|
|||||||
CheckVersion(issue, request.RowVersion);
|
CheckVersion(issue, request.RowVersion);
|
||||||
var assignee = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == request.AssigneeId && u.IsActive, ct);
|
var assignee = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == request.AssigneeId && u.IsActive, ct);
|
||||||
if (assignee is null || !Issue.CanBeAssigned(assignee.Role))
|
if (assignee is null || !Issue.CanBeAssigned(assignee.Role))
|
||||||
throw new BadRequestException("Vyberte aktivního správce budov, člena vedení nebo administrátora.");
|
throw new FieldValidationException(nameof(request.AssigneeId), "Vyberte aktivního správce budov, člena vedení nebo administrátora.");
|
||||||
if (issue.AssigneeId == assignee.Id)
|
if (issue.AssigneeId == assignee.Id)
|
||||||
throw new ConflictException("Závada je již přiřazena tomuto řešiteli.");
|
throw new ConflictException("Závada je již přiřazena tomuto řešiteli.");
|
||||||
|
|
||||||
IssuePriority? priority = request.Priority is null ? null : ParseCode<IssuePriority>(request.Priority);
|
IssuePriority? priority = null;
|
||||||
|
if (request.Priority is { } code)
|
||||||
|
{
|
||||||
|
if (!EnumCode.TryParse<IssuePriority>(code, out var selected))
|
||||||
|
throw new FieldValidationException(nameof(request.Priority), "Vyberte platnou prioritu.");
|
||||||
|
priority = selected;
|
||||||
|
}
|
||||||
var from = issue.Status;
|
var from = issue.Status;
|
||||||
issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority);
|
issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority);
|
||||||
AddEvent(issue, IssueEventType.Assigned, from, actor, assignee.FullName);
|
AddEvent(issue, IssueEventType.Assigned, from, actor, assignee.FullName);
|
||||||
@@ -65,8 +73,8 @@ public sealed partial class IssueService(
|
|||||||
var (issue, actor) = await LoadActionAsync(id, action, ct);
|
var (issue, actor) = await LoadActionAsync(id, action, ct);
|
||||||
CheckVersion(issue, version);
|
CheckVersion(issue, version);
|
||||||
note = action is IssueAction.Reopen or IssueAction.Reject
|
note = action is IssueAction.Reopen or IssueAction.Reject
|
||||||
? RequiredText(note, "Důvod", MaxTextBytes)
|
? RequiredText(note, nameof(IssueReasonRequest.Reason), "Důvod")
|
||||||
: OptionalText(note, "Poznámka", MaxTextBytes);
|
: OptionalText(note, nameof(VerifyIssueRequest.Note), "Poznámka");
|
||||||
|
|
||||||
var from = issue.Status;
|
var from = issue.Status;
|
||||||
issue.Transition(action, actor.Id, actor.Role, note);
|
issue.Transition(action, actor.Id, actor.Role, note);
|
||||||
@@ -87,7 +95,7 @@ public sealed partial class IssueService(
|
|||||||
public async Task<IssueEventDto> CommentAsync(int id, CommentRequest request, CancellationToken ct)
|
public async Task<IssueEventDto> CommentAsync(int id, CommentRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var (issue, actor) = await LoadActionAsync(id, IssueAction.Comment, ct);
|
var (issue, actor) = await LoadActionAsync(id, IssueAction.Comment, ct);
|
||||||
var text = RequiredText(request.Text, "Komentář", MaxTextBytes);
|
var text = RequiredText(request.Text, nameof(request.Text), "Komentář");
|
||||||
issue.RecordParticipation(IssueAction.Comment, actor.Id, actor.Role);
|
issue.RecordParticipation(IssueAction.Comment, actor.Id, actor.Role);
|
||||||
var entry = AddEvent(issue, IssueEventType.Commented, null, actor, text);
|
var entry = AddEvent(issue, IssueEventType.Commented, null, actor, text);
|
||||||
int[] recipients = issue.AssigneeId is int assignee ? [issue.ReporterId, assignee] : [issue.ReporterId];
|
int[] recipients = issue.AssigneeId is int assignee ? [issue.ReporterId, assignee] : [issue.ReporterId];
|
||||||
@@ -102,7 +110,7 @@ public sealed partial class IssueService(
|
|||||||
var (issue, actor) = await LoadActionAsync(id, IssueAction.AddAttachments, ct);
|
var (issue, actor) = await LoadActionAsync(id, IssueAction.AddAttachments, ct);
|
||||||
var uploads = await readUploads(ct);
|
var uploads = await readUploads(ct);
|
||||||
if (uploads.Length == 0)
|
if (uploads.Length == 0)
|
||||||
throw new BadRequestException("Vyberte alespoň jeden soubor.");
|
throw new FieldValidationException("files", "Vyberte alespoň jeden soubor.");
|
||||||
|
|
||||||
issue.RecordParticipation(IssueAction.AddAttachments, actor.Id, actor.Role);
|
issue.RecordParticipation(IssueAction.AddAttachments, actor.Id, actor.Role);
|
||||||
var attachments = await SaveWithAttachmentsAsync(issue, uploads, ct);
|
var attachments = await SaveWithAttachmentsAsync(issue, uploads, ct);
|
||||||
@@ -113,7 +121,7 @@ public sealed partial class IssueService(
|
|||||||
Issue issue, IReadOnlyList<AttachmentUpload> uploads, CancellationToken ct)
|
Issue issue, IReadOnlyList<AttachmentUpload> uploads, CancellationToken ct)
|
||||||
{
|
{
|
||||||
if (uploads.Count > AttachmentLimits.MaxFiles)
|
if (uploads.Count > AttachmentLimits.MaxFiles)
|
||||||
throw new BadRequestException("Najednou lze přiložit nejvýše pět souborů.");
|
throw new FieldValidationException("files", "Najednou lze přiložit nejvýše pět souborů.");
|
||||||
|
|
||||||
var attachments = new List<Attachment>(uploads.Count);
|
var attachments = new List<Attachment>(uploads.Count);
|
||||||
var saving = false;
|
var saving = false;
|
||||||
@@ -172,18 +180,31 @@ public sealed partial class IssueService(
|
|||||||
|
|
||||||
private async Task ValidateDetailsAsync(CreateIssueRequest request, Issue? original, CancellationToken ct)
|
private async Task ValidateDetailsAsync(CreateIssueRequest request, Issue? original, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var title = RequiredText(request.Title, "Název", MaxTextBytes);
|
var errors = new List<ValidationFailure>();
|
||||||
RequiredText(request.Description, "Popis", MaxTextBytes);
|
var title = request.Title?.Trim();
|
||||||
if (title.Length > 200 || request.LocationDetail?.Trim().Length > 255)
|
if (string.IsNullOrEmpty(title))
|
||||||
throw new BadRequestException("Název smí mít nejvýše 200 znaků a upřesnění místa 255 znaků.");
|
errors.Add(new(nameof(request.Title), "Zadejte název."));
|
||||||
|
else if (title.Length > 200)
|
||||||
|
errors.Add(new(nameof(request.Title), "Název může mít nejvýše 200 znaků."));
|
||||||
|
|
||||||
|
var description = request.Description?.Trim();
|
||||||
|
if (string.IsNullOrEmpty(description))
|
||||||
|
errors.Add(new(nameof(request.Description), "Popište závadu."));
|
||||||
|
else if (Encoding.UTF8.GetByteCount(description) > MaxTextBytes)
|
||||||
|
errors.Add(new(nameof(request.Description), "Popis je příliš dlouhý."));
|
||||||
|
if (request.LocationDetail?.Trim().Length > 255)
|
||||||
|
errors.Add(new(nameof(request.LocationDetail), "Upřesnění místa může mít nejvýše 255 znaků."));
|
||||||
|
|
||||||
if (original?.CategoryId != request.CategoryId &&
|
if (original?.CategoryId != request.CategoryId &&
|
||||||
!await db.IssueCategories.AnyAsync(c => c.Id == request.CategoryId && c.IsActive, ct))
|
!await db.IssueCategories.AnyAsync(c => c.Id == request.CategoryId && c.IsActive, ct))
|
||||||
throw new BadRequestException("Vyberte aktivní kategorii závady.");
|
errors.Add(new(nameof(request.CategoryId), "Vyberte aktivní kategorii závady."));
|
||||||
|
|
||||||
if (request.BuildingId is int buildingId && original?.BuildingId != buildingId &&
|
if (request.BuildingId is int buildingId && original?.BuildingId != buildingId &&
|
||||||
!await db.Buildings.AnyAsync(b => b.Id == buildingId && b.IsActive, ct))
|
!await db.Buildings.AnyAsync(b => b.Id == buildingId && b.IsActive, ct))
|
||||||
throw new BadRequestException("Vyberte aktivní budovu.");
|
errors.Add(new(nameof(request.BuildingId), "Vyberte aktivní budovu."));
|
||||||
|
|
||||||
|
if (errors.Count > 0)
|
||||||
|
throw new ValidationException(errors);
|
||||||
}
|
}
|
||||||
|
|
||||||
private IssueEvent AddEvent(Issue issue, IssueEventType type, IssueStatus? fromStatus, User actor, string? note)
|
private IssueEvent AddEvent(Issue issue, IssueEventType type, IssueStatus? fromStatus, User actor, string? note)
|
||||||
@@ -201,30 +222,33 @@ public sealed partial class IssueService(
|
|||||||
}
|
}
|
||||||
catch (DbUpdateConcurrencyException)
|
catch (DbUpdateConcurrencyException)
|
||||||
{
|
{
|
||||||
throw new ConflictException("Závada se mezitím změnila. Načtěte aktuální stav.");
|
throw IssueVersionConflict();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void CheckVersion(Issue issue, int? supplied)
|
private static void CheckVersion(Issue issue, int? supplied)
|
||||||
{
|
{
|
||||||
if (supplied is null or < 0)
|
if (supplied is null or < 0)
|
||||||
throw new BadRequestException("Zadejte platnou hodnotu rowVersion.");
|
throw new FieldValidationException(nameof(IssueVersionRequest.RowVersion), "Zadejte platnou verzi závady.");
|
||||||
if (issue.RowVersion != supplied)
|
if (issue.RowVersion != supplied)
|
||||||
throw new ConflictException("Závada se mezitím změnila. Načtěte aktuální stav.");
|
throw IssueVersionConflict();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static ConflictException IssueVersionConflict() =>
|
||||||
|
new("Závada se mezitím změnila. Načtěte aktuální stav.", "urn:ntbug:issue-version-conflict");
|
||||||
|
|
||||||
private const int MaxTextBytes = 65_535;
|
private const int MaxTextBytes = 65_535;
|
||||||
|
|
||||||
private static string RequiredText(string? input, string name, int maxBytes) =>
|
private static string RequiredText(string? input, string field, string label) =>
|
||||||
OptionalText(input, name, maxBytes) ?? throw new BadRequestException($"{name}: hodnota je povinná.");
|
OptionalText(input, field, label) ?? throw new FieldValidationException(field, $"{label}: hodnota je povinná.");
|
||||||
|
|
||||||
private static string? OptionalText(string? input, string name, int maxBytes)
|
private static string? OptionalText(string? input, string field, string label)
|
||||||
{
|
{
|
||||||
var text = input?.Trim();
|
var text = input?.Trim();
|
||||||
if (string.IsNullOrEmpty(text))
|
if (string.IsNullOrEmpty(text))
|
||||||
return null;
|
return null;
|
||||||
if (Encoding.UTF8.GetByteCount(text) > maxBytes)
|
if (Encoding.UTF8.GetByteCount(text) > MaxTextBytes)
|
||||||
throw new BadRequestException($"{name}: hodnota je příliš dlouhá.");
|
throw new FieldValidationException(field, $"{label}: hodnota je příliš dlouhá.");
|
||||||
return text;
|
return text;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ public sealed class NotificationService(IAppDbContext db, ICurrentUser currentUs
|
|||||||
private IQueryable<Notification> Inbox()
|
private IQueryable<Notification> Inbox()
|
||||||
{
|
{
|
||||||
var userId = currentUser.Id;
|
var userId = currentUser.Id;
|
||||||
return db.Notifications.Where(n => n.UserId == userId);
|
return NotificationVisibility.VisibleToRecipients(db).Where(n => n.UserId == userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Task<int> MarkUnreadRowsAsync(IQueryable<Notification> query, CancellationToken ct)
|
private Task<int> MarkUnreadRowsAsync(IQueryable<Notification> query, CancellationToken ct)
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
using Helpdesk.Application.Abstractions;
|
||||||
|
using Helpdesk.Domain.Issues;
|
||||||
|
using Helpdesk.Domain.Notifications;
|
||||||
|
using Helpdesk.Domain.Users;
|
||||||
|
|
||||||
|
namespace Helpdesk.Application.Notifications;
|
||||||
|
|
||||||
|
public static class NotificationVisibility
|
||||||
|
{
|
||||||
|
internal static readonly UserRole[] ReadAllIssueRoles = Enum.GetValues<UserRole>().Where(Issue.CanReadAll).ToArray();
|
||||||
|
|
||||||
|
public static IQueryable<Notification> VisibleToRecipients(IAppDbContext db) =>
|
||||||
|
db.Notifications.Where(n => db.Users.Any(u => u.Id == n.UserId && u.IsActive && !u.IsDeleted &&
|
||||||
|
(n.IssueId == null || ReadAllIssueRoles.Contains(u.Role) ||
|
||||||
|
db.Issues.Any(issue => issue.Id == n.IssueId && issue.ReporterId == u.Id))));
|
||||||
|
}
|
||||||
@@ -14,9 +14,7 @@ public sealed class NotificationWriter(IAppDbContext db, TimeProvider clock)
|
|||||||
CancellationToken ct)
|
CancellationToken ct)
|
||||||
{
|
{
|
||||||
var reporterId = issue.ReporterId;
|
var reporterId = issue.ReporterId;
|
||||||
var eligibleUsers = db.Users.Where(u =>
|
var eligibleUsers = db.Users.Where(u => u.Id == reporterId || NotificationVisibility.ReadAllIssueRoles.Contains(u.Role));
|
||||||
u.Id == reporterId || u.Role == UserRole.FacilityManager || u.Role == UserRole.Management ||
|
|
||||||
u.Role == UserRole.Admin);
|
|
||||||
return QueueAsync(eligibleUsers, actorId, recipientIds,
|
return QueueAsync(eligibleUsers, actorId, recipientIds,
|
||||||
id => new Notification(issue, id, type, title, issue.Title), ct);
|
id => new Notification(issue, id, type, title, issue.Title), ct);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,27 @@
|
|||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
using Helpdesk.Application.Common;
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Domain.Auth;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
namespace Helpdesk.Application.Notifications;
|
namespace Helpdesk.Application.Notifications;
|
||||||
|
|
||||||
public sealed class PushDeviceService(IAppDbContext db, ICurrentUser currentUser)
|
public sealed class PushDeviceService(IAppDbContext db, ICurrentUser currentUser)
|
||||||
{
|
{
|
||||||
public Task RegisterAsync(string token, CancellationToken ct)
|
public async Task RegisterAsync(string token, CancellationToken ct)
|
||||||
{
|
{
|
||||||
ValidateToken(token);
|
ValidateToken(token);
|
||||||
return db.RegisterPushDeviceAsync(currentUser.Id, token, ct);
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
|
var user = await db.LockUserAsync(currentUser.Id, ct);
|
||||||
|
if (user is not { IsActive: true, IsDeleted: false })
|
||||||
|
throw new UnauthorizedException("Účet není aktivní.");
|
||||||
|
|
||||||
|
// Po čekání na zámek mohl správce relaci odhlásit a odstranit všechna její zařízení.
|
||||||
|
if (!await db.AuthTokens.AnyAsync(t => t.Jti == currentUser.TokenId && t.UserId == user.Id &&
|
||||||
|
t.TokenType == TokenType.Access && t.RevokedAt == null, ct))
|
||||||
|
throw new UnauthorizedException("Přihlášení vypršelo. Přihlaste se znovu.");
|
||||||
|
|
||||||
|
await db.RegisterPushDeviceAsync(user.Id, token, ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task UnregisterAsync(string token, CancellationToken ct)
|
public async Task UnregisterAsync(string token, CancellationToken ct)
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using FluentValidation;
|
using FluentValidation;
|
||||||
|
using Helpdesk.Application.Auth;
|
||||||
using Helpdesk.Domain;
|
using Helpdesk.Domain;
|
||||||
using Helpdesk.Domain.Users;
|
using Helpdesk.Domain.Users;
|
||||||
|
|
||||||
@@ -18,7 +19,7 @@ public sealed record UserDto(
|
|||||||
user.Id, user.Email, user.FirstName, user.LastName, user.Phone, user.Role.ToCode(), user.EmailNotificationsEnabled);
|
user.Id, user.Email, user.FirstName, user.LastName, user.Phone, user.Role.ToCode(), user.EmailNotificationsEnabled);
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed record UpdateProfileRequest(string FirstName, string LastName, string? Phone, bool EmailNotificationsEnabled);
|
public sealed record UpdateProfileRequest(string FirstName, string LastName, string? Phone, bool? EmailNotificationsEnabled);
|
||||||
|
|
||||||
public sealed class UpdateProfileRequestValidator : AbstractValidator<UpdateProfileRequest>
|
public sealed class UpdateProfileRequestValidator : AbstractValidator<UpdateProfileRequest>
|
||||||
{
|
{
|
||||||
@@ -28,6 +29,7 @@ public sealed class UpdateProfileRequestValidator : AbstractValidator<UpdateProf
|
|||||||
RuleFor(x => x.LastName).NotEmpty().MaximumLength(100);
|
RuleFor(x => x.LastName).NotEmpty().MaximumLength(100);
|
||||||
RuleFor(x => x.Phone).MaximumLength(30).Matches(@"^\+?[0-9 ]+$").When(x => !string.IsNullOrWhiteSpace(x.Phone))
|
RuleFor(x => x.Phone).MaximumLength(30).Matches(@"^\+?[0-9 ]+$").When(x => !string.IsNullOrWhiteSpace(x.Phone))
|
||||||
.WithMessage("Telefon smí obsahovat jen číslice, mezery a úvodní +.");
|
.WithMessage("Telefon smí obsahovat jen číslice, mezery a úvodní +.");
|
||||||
|
RuleFor(x => x.EmailNotificationsEnabled).NotNull().WithMessage("Uveďte, zda mají být e-mailové notifikace zapnuté.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,4 +46,38 @@ public sealed record AdminUserDto(
|
|||||||
|
|
||||||
public sealed record ChangeRoleRequest(string Role);
|
public sealed record ChangeRoleRequest(string Role);
|
||||||
|
|
||||||
public sealed record SetActiveRequest(bool IsActive);
|
public sealed record SetActiveRequest(bool? IsActive);
|
||||||
|
|
||||||
|
public sealed class SetActiveRequestValidator : AbstractValidator<SetActiveRequest>
|
||||||
|
{
|
||||||
|
public SetActiveRequestValidator()
|
||||||
|
{
|
||||||
|
RuleFor(x => x.IsActive).NotNull().WithMessage("Uveďte, zda má být účet aktivní.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record AdminUserDetailsDto(int Id, string Email, string FirstName, string LastName, string? Phone,
|
||||||
|
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, int RowVersion,
|
||||||
|
bool? VerificationEmailSent = null)
|
||||||
|
{
|
||||||
|
public static AdminUserDetailsDto From(User user) => new(user.Id, user.Email, user.FirstName, user.LastName, user.Phone,
|
||||||
|
user.Role.ToCode(), user.IsActive, user.EmailConfirmed, user.EmailNotificationsEnabled, user.RowVersion);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record SaveAdminUserRequest(string Email, string FirstName, string LastName, string? Phone,
|
||||||
|
string Role, bool? IsActive, bool? EmailConfirmed, bool? EmailNotificationsEnabled, string? Password, int? RowVersion = null);
|
||||||
|
|
||||||
|
public sealed class SaveAdminUserRequestValidator : AbstractValidator<SaveAdminUserRequest>
|
||||||
|
{
|
||||||
|
public SaveAdminUserRequestValidator()
|
||||||
|
{
|
||||||
|
RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(254);
|
||||||
|
RuleFor(x => x.Role).NotEmpty();
|
||||||
|
RuleFor(x => x.IsActive).NotNull().WithMessage("Uveďte, zda má být účet aktivní.");
|
||||||
|
RuleFor(x => x.EmailConfirmed).NotNull().WithMessage("Uveďte, zda má být e-mail ověřený.");
|
||||||
|
RuleFor(x => x.EmailNotificationsEnabled).NotNull().WithMessage("Uveďte, zda mají být e-mailové notifikace zapnuté.");
|
||||||
|
RuleFor(x => x.Password).ValidPassword().When(x => x.Password is not null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record BulkAdminUsersRequest(int[] UserIds, string Action, string? Role);
|
||||||
@@ -13,7 +13,11 @@ namespace Helpdesk.Application.Users;
|
|||||||
public sealed class UserService(
|
public sealed class UserService(
|
||||||
IAppDbContext db,
|
IAppDbContext db,
|
||||||
TokenRevocationService revocation,
|
TokenRevocationService revocation,
|
||||||
IValidator<UpdateProfileRequest> profileValidator)
|
AuthService auth,
|
||||||
|
IValidator<UpdateProfileRequest> profileValidator,
|
||||||
|
IValidator<SaveAdminUserRequest> adminUserValidator,
|
||||||
|
IValidator<SetActiveRequest> activeValidator,
|
||||||
|
IPasswordHasher passwordHasher)
|
||||||
{
|
{
|
||||||
public async Task<UserDto> GetMeAsync(ICurrentUser currentUser, CancellationToken ct) =>
|
public async Task<UserDto> GetMeAsync(ICurrentUser currentUser, CancellationToken ct) =>
|
||||||
UserDto.From(await GetAsync(currentUser.Id, ct));
|
UserDto.From(await GetAsync(currentUser.Id, ct));
|
||||||
@@ -22,9 +26,13 @@ public sealed class UserService(
|
|||||||
{
|
{
|
||||||
await profileValidator.ValidateAndThrowAsync(request, ct);
|
await profileValidator.ValidateAndThrowAsync(request, ct);
|
||||||
|
|
||||||
var user = await GetAsync(currentUser.Id, ct);
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
user.UpdateProfile(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled);
|
var user = RequireAccount(await db.LockUserAsync(currentUser.Id, ct), currentUser.Id);
|
||||||
|
if (!user.IsActive)
|
||||||
|
throw new UnauthorizedException("Účet není aktivní.");
|
||||||
|
user.UpdateProfile(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled!.Value);
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
return UserDto.From(user);
|
return UserDto.From(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,7 +41,7 @@ public sealed class UserService(
|
|||||||
page = Math.Max(page, 1);
|
page = Math.Max(page, 1);
|
||||||
pageSize = Math.Clamp(pageSize, 1, 100);
|
pageSize = Math.Clamp(pageSize, 1, 100);
|
||||||
|
|
||||||
var query = db.Users.AsNoTracking();
|
var query = db.Users.AsNoTracking().Where(u => !u.IsDeleted);
|
||||||
if (!string.IsNullOrWhiteSpace(q))
|
if (!string.IsNullOrWhiteSpace(q))
|
||||||
{
|
{
|
||||||
var term = q.Trim();
|
var term = q.Trim();
|
||||||
@@ -46,9 +54,13 @@ public sealed class UserService(
|
|||||||
}
|
}
|
||||||
|
|
||||||
var total = await query.CountAsync(ct);
|
var total = await query.CountAsync(ct);
|
||||||
|
var offset = (long)(page - 1) * pageSize;
|
||||||
|
if (offset >= total)
|
||||||
|
return new PagedResult<AdminUserDto>([], total, page, pageSize);
|
||||||
|
|
||||||
var users = await query
|
var users = await query
|
||||||
.OrderBy(u => u.LastName).ThenBy(u => u.FirstName).ThenBy(u => u.Id)
|
.OrderBy(u => u.LastName).ThenBy(u => u.FirstName).ThenBy(u => u.Id)
|
||||||
.Skip((page - 1) * pageSize).Take(pageSize)
|
.Skip((int)offset).Take(pageSize)
|
||||||
.ToListAsync(ct);
|
.ToListAsync(ct);
|
||||||
|
|
||||||
var items = users
|
var items = users
|
||||||
@@ -58,39 +70,214 @@ public sealed class UserService(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Změna role zneplatní tokeny uživatele – po novém přihlášení dostane token s novou rolí.</summary>
|
/// <summary>Změna role zneplatní tokeny uživatele – po novém přihlášení dostane token s novou rolí.</summary>
|
||||||
public async Task ChangeRoleAsync(ICurrentUser admin, int userId, ChangeRoleRequest request, CancellationToken ct)
|
public Task ChangeRoleAsync(ICurrentUser admin, int userId, ChangeRoleRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var role = ParseRole(request.Role);
|
var role = ParseRole(request.Role);
|
||||||
if (userId == admin.Id)
|
return UpdateAccountsAsync(admin, [userId], user => ChangeRole(user, role), ct);
|
||||||
throw new ConflictException("Administrátor nemůže změnit roli sám sobě.");
|
|
||||||
|
|
||||||
var user = await GetAsync(userId, ct);
|
|
||||||
if (user.Role == role)
|
|
||||||
return;
|
|
||||||
|
|
||||||
await revocation.RevokeAllAsync(user.Id, RevokeReason.RoleChanged, ct);
|
|
||||||
user.ChangeRole(role);
|
|
||||||
await db.SaveChangesAsync(ct);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task SetActiveAsync(ICurrentUser admin, int userId, SetActiveRequest request, CancellationToken ct)
|
public async Task SetActiveAsync(ICurrentUser admin, int userId, SetActiveRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
if (userId == admin.Id && !request.IsActive)
|
await activeValidator.ValidateAndThrowAsync(request, ct);
|
||||||
throw new ConflictException("Administrátor nemůže deaktivovat sám sebe.");
|
var isActive = request.IsActive!.Value;
|
||||||
|
if (userId == admin.Id && isActive)
|
||||||
var user = await GetAsync(userId, ct);
|
|
||||||
if (user.IsActive == request.IsActive)
|
|
||||||
return;
|
return;
|
||||||
|
await UpdateAccountsAsync(admin, [userId], user => SetActive(user, isActive), ct);
|
||||||
|
}
|
||||||
|
|
||||||
if (!request.IsActive)
|
public async Task<AdminUserDetailsDto> GetAdminAsync(int id, CancellationToken ct) =>
|
||||||
await revocation.RevokeAllAsync(user.Id, RevokeReason.AccountDeactivated, ct);
|
AdminUserDetailsDto.From(await GetAsync(id, ct));
|
||||||
user.SetActive(request.IsActive);
|
|
||||||
|
public async Task<AdminUserDetailsDto> CreateAsync(ICurrentUser admin, SaveAdminUserRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await ValidateAsync(request, ct);
|
||||||
|
var confirmed = request.EmailConfirmed!.Value;
|
||||||
|
if (confirmed && string.IsNullOrWhiteSpace(request.Password))
|
||||||
|
throw new BadRequestException("Při ručním ověření e-mailu zadejte počáteční heslo.");
|
||||||
|
var role = ParseRole(request.Role);
|
||||||
|
var passwordHash = confirmed ? passwordHasher.Hash(request.Password!) : "";
|
||||||
|
var user = User.Create(request.Email, passwordHash, request.FirstName, request.LastName, role);
|
||||||
|
ApplyProfile(user, request, confirmed);
|
||||||
|
user.SetActive(request.IsActive!.Value);
|
||||||
|
|
||||||
|
await using (var transaction = await db.BeginWriteAsync(ct))
|
||||||
|
{
|
||||||
|
RequireAdministrator(await db.LockUserAsync(admin.Id, ct));
|
||||||
|
db.Users.Add(user);
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
|
}
|
||||||
|
return await AccountSavedAsync(user, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<AdminUserDetailsDto?> UpdateAsync(ICurrentUser admin, int userId, SaveAdminUserRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await ValidateAsync(request, ct);
|
||||||
|
if (request.RowVersion is null or < 0)
|
||||||
|
throw new BadRequestException("Zadejte platnou verzi účtu (rowVersion).");
|
||||||
|
|
||||||
|
var role = ParseRole(request.Role);
|
||||||
|
var passwordHash = request.Password is null ? null : passwordHasher.Hash(request.Password);
|
||||||
|
var sendLink = false;
|
||||||
|
var updated = await UpdateAccountsAsync(admin, [userId], user =>
|
||||||
|
{
|
||||||
|
if (user.RowVersion != request.RowVersion)
|
||||||
|
throw new AccountVersionConflictException();
|
||||||
|
|
||||||
|
var emailChanged = user.EmailNormalized != User.NormalizeEmail(request.Email);
|
||||||
|
var confirmed = !emailChanged && request.EmailConfirmed!.Value;
|
||||||
|
if (confirmed && passwordHash is null && user.PasswordHash.Length == 0)
|
||||||
|
throw new BadRequestException("Při ručním ověření e-mailu zadejte počáteční heslo.");
|
||||||
|
var confirmationChanged = user.EmailConfirmed != confirmed;
|
||||||
|
var roleChanged = ChangeRole(user, role);
|
||||||
|
var activeChanged = SetActive(user, request.IsActive!.Value);
|
||||||
|
ApplyProfile(user, request, confirmed);
|
||||||
|
sendLink = emailChanged && user.IsActive;
|
||||||
|
if (passwordHash is not null)
|
||||||
|
{
|
||||||
|
user.ChangePasswordHash(passwordHash);
|
||||||
|
return RevokeReason.PasswordChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (emailChanged || confirmationChanged)
|
||||||
|
return RevokeReason.LogoutAll;
|
||||||
|
return roleChanged ?? activeChanged;
|
||||||
|
}, ct);
|
||||||
|
return sendLink ? await AccountSavedAsync(updated.Single(), ct) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task SendEmailConfirmationAsync(int userId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var user = await GetAsync(userId, ct);
|
||||||
|
if (!user.IsActive || user.EmailConfirmed)
|
||||||
|
throw new ConflictException("Ověřovací odkaz lze poslat pouze aktivnímu účtu s neověřeným e-mailem.");
|
||||||
|
|
||||||
|
if (!await auth.SendEmailConfirmationAsync(user, ct))
|
||||||
|
throw new ConflictException("Účet se mezitím změnil. Obnovte jeho detail.");
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task DeleteAsync(ICurrentUser admin, int userId, CancellationToken ct) =>
|
||||||
|
UpdateAccountsAsync(admin, [userId], Delete, ct);
|
||||||
|
|
||||||
|
public Task BulkUpdateAsync(ICurrentUser admin, BulkAdminUsersRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (request.UserIds is not { Length: >= 1 and <= 100 } || request.UserIds.Any(id => id <= 0))
|
||||||
|
throw new BadRequestException("Vyberte 1 až 100 uživatelů.");
|
||||||
|
|
||||||
|
var role = request.Action == "role" ? ParseRole(request.Role ?? "") : default;
|
||||||
|
return request.Action switch
|
||||||
|
{
|
||||||
|
"activate" => UpdateAccountsAsync(admin, request.UserIds, user => SetActive(user, true), ct),
|
||||||
|
"deactivate" => UpdateAccountsAsync(admin, request.UserIds, user => SetActive(user, false), ct),
|
||||||
|
"role" => UpdateAccountsAsync(admin, request.UserIds, user => ChangeRole(user, role), ct),
|
||||||
|
"delete" => UpdateAccountsAsync(admin, request.UserIds, Delete, ct),
|
||||||
|
_ => throw new BadRequestException("Vyberte platnou hromadnou akci."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<List<User>> UpdateAccountsAsync(ICurrentUser admin, int[] ids, Func<User, RevokeReason?> update, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (ids.Contains(admin.Id))
|
||||||
|
throw new ConflictException("Vlastní účet upravujte v nastavení profilu.");
|
||||||
|
|
||||||
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
|
var users = new List<User>();
|
||||||
|
// Stejné pořadí při překryvu výběrů. Zámek správce brání souběžnému odebrání role.
|
||||||
|
foreach (var id in ids.Append(admin.Id).Distinct().Order())
|
||||||
|
{
|
||||||
|
var user = await db.LockUserAsync(id, ct);
|
||||||
|
if (id == admin.Id)
|
||||||
|
RequireAdministrator(user);
|
||||||
|
else
|
||||||
|
users.Add(RequireAccount(user, id));
|
||||||
|
}
|
||||||
|
|
||||||
|
var changes = new List<(int Id, RevokeReason Reason)>();
|
||||||
|
foreach (var user in users)
|
||||||
|
{
|
||||||
|
if (update(user) is { } reason)
|
||||||
|
changes.Add((user.Id, reason));
|
||||||
|
}
|
||||||
|
|
||||||
|
var revoked = new List<TokenRevocationService.RevokedAccessToken>();
|
||||||
|
foreach (var group in changes.GroupBy(change => change.Reason))
|
||||||
|
revoked.AddRange(await revocation.StageRevokeAllAsync(group.Select(change => change.Id).ToArray(), group.Key, ct));
|
||||||
|
var disconnectedIds = users.Where(user => user.IsDeleted).Select(user => user.Id)
|
||||||
|
.Concat(changes.Where(change => change.Reason == RevokeReason.PasswordChanged).Select(change => change.Id))
|
||||||
|
.ToArray();
|
||||||
|
if (disconnectedIds.Length > 0)
|
||||||
|
await db.PushDevices.Where(device => disconnectedIds.Contains(device.UserId)).ExecuteDeleteAsync(ct);
|
||||||
|
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
|
revocation.Publish(revoked);
|
||||||
|
return users;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<AdminUserDetailsDto> AccountSavedAsync(User user, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var result = AdminUserDetailsDto.From(user);
|
||||||
|
if (!user.IsActive || user.EmailConfirmed)
|
||||||
|
return result;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return result with { VerificationEmailSent = await auth.SendEmailConfirmationAsync(user, ct) };
|
||||||
|
}
|
||||||
|
catch (EmailDeliveryException)
|
||||||
|
{
|
||||||
|
// Účet je již uložený a ověřovací e-mail lze poslat znovu.
|
||||||
|
return result with { VerificationEmailSent = false };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ValidateAsync(SaveAdminUserRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await adminUserValidator.ValidateAndThrowAsync(request, ct);
|
||||||
|
await profileValidator.ValidateAndThrowAsync(
|
||||||
|
new UpdateProfileRequest(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled), ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ApplyProfile(User user, SaveAdminUserRequest request, bool confirmed)
|
||||||
|
{
|
||||||
|
user.UpdateProfile(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled!.Value);
|
||||||
|
user.ChangeEmail(request.Email);
|
||||||
|
user.SetEmailConfirmed(confirmed);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static RevokeReason? ChangeRole(User user, UserRole role)
|
||||||
|
{
|
||||||
|
if (user.Role == role)
|
||||||
|
return null;
|
||||||
|
user.ChangeRole(role);
|
||||||
|
return RevokeReason.RoleChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static RevokeReason? SetActive(User user, bool active)
|
||||||
|
{
|
||||||
|
var wasActive = user.IsActive;
|
||||||
|
user.SetActive(active);
|
||||||
|
return wasActive && !active ? RevokeReason.AccountDeactivated : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static RevokeReason? Delete(User user)
|
||||||
|
{
|
||||||
|
user.Delete();
|
||||||
|
return RevokeReason.AccountDeactivated;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<User> GetAsync(int id, CancellationToken ct) =>
|
private async Task<User> GetAsync(int id, CancellationToken ct) =>
|
||||||
await db.Users.SingleOrDefaultAsync(u => u.Id == id, ct)
|
RequireAccount(await db.Users.SingleOrDefaultAsync(u => u.Id == id, ct), id);
|
||||||
?? throw new NotFoundException($"Uživatel {id} neexistuje.");
|
|
||||||
|
private static User RequireAccount(User? user, int id) => user is { IsDeleted: false }
|
||||||
|
? user
|
||||||
|
: throw new NotFoundException($"Uživatel {id} neexistuje.");
|
||||||
|
|
||||||
|
private static void RequireAdministrator(User? user)
|
||||||
|
{
|
||||||
|
if (user is not { Role: UserRole.Admin, IsActive: true, IsDeleted: false })
|
||||||
|
throw new ForbiddenException("K této akci potřebujete aktivní účet administrátora.");
|
||||||
|
}
|
||||||
|
|
||||||
private static UserRole ParseRole(string code) =>
|
private static UserRole ParseRole(string code) =>
|
||||||
EnumCode.TryParse<UserRole>(code, out var role)
|
EnumCode.TryParse<UserRole>(code, out var role)
|
||||||
|
|||||||
@@ -6,9 +6,6 @@ namespace Helpdesk.Domain.Users;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class User : IHasCreatedAt
|
public sealed class User : IHasCreatedAt
|
||||||
{
|
{
|
||||||
public const int MaxFailedLogins = 5;
|
|
||||||
public static readonly TimeSpan LockoutDuration = TimeSpan.FromMinutes(15);
|
|
||||||
|
|
||||||
private User() { } // EF Core
|
private User() { } // EF Core
|
||||||
|
|
||||||
public int Id { get; private set; }
|
public int Id { get; private set; }
|
||||||
@@ -21,10 +18,10 @@ public sealed class User : IHasCreatedAt
|
|||||||
public string? Phone { get; private set; }
|
public string? Phone { get; private set; }
|
||||||
public UserRole Role { get; private set; }
|
public UserRole Role { get; private set; }
|
||||||
public bool IsActive { get; private set; } = true;
|
public bool IsActive { get; private set; } = true;
|
||||||
|
public bool IsDeleted { get; private set; }
|
||||||
public bool EmailConfirmed { get; private set; }
|
public bool EmailConfirmed { get; private set; }
|
||||||
public bool EmailNotificationsEnabled { get; private set; } = true;
|
public bool EmailNotificationsEnabled { get; private set; } = true;
|
||||||
public int FailedLoginCount { get; private set; }
|
public int RowVersion { get; private set; }
|
||||||
public DateTime? LockoutUntil { get; private set; }
|
|
||||||
public DateTime CreatedAt { get; set; }
|
public DateTime CreatedAt { get; set; }
|
||||||
|
|
||||||
public string FullName => $"{FirstName} {LastName}";
|
public string FullName => $"{FirstName} {LastName}";
|
||||||
@@ -41,33 +38,18 @@ public sealed class User : IHasCreatedAt
|
|||||||
|
|
||||||
public static string NormalizeEmail(string email) => email.Trim().ToUpperInvariant();
|
public static string NormalizeEmail(string email) => email.Trim().ToUpperInvariant();
|
||||||
|
|
||||||
public bool IsLockedOut(DateTime now) => LockoutUntil is { } until && until > now;
|
|
||||||
|
|
||||||
/// <summary>Neúspěšné přihlášení; po <see cref="MaxFailedLogins"/> pokusech se účet na 15 minut zamkne.</summary>
|
|
||||||
public void RegisterFailedLogin(DateTime now)
|
|
||||||
{
|
|
||||||
FailedLoginCount++;
|
|
||||||
if (FailedLoginCount >= MaxFailedLogins)
|
|
||||||
{
|
|
||||||
LockoutUntil = now + LockoutDuration;
|
|
||||||
FailedLoginCount = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void RegisterSuccessfulLogin()
|
|
||||||
{
|
|
||||||
FailedLoginCount = 0;
|
|
||||||
LockoutUntil = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void ConfirmEmail() => EmailConfirmed = true;
|
public void ConfirmEmail() => EmailConfirmed = true;
|
||||||
|
|
||||||
public void ChangePasswordHash(string passwordHash)
|
public void SetEmailConfirmed(bool confirmed) => EmailConfirmed = confirmed;
|
||||||
|
|
||||||
|
public void ChangeEmail(string email)
|
||||||
{
|
{
|
||||||
PasswordHash = passwordHash;
|
Email = email.Trim();
|
||||||
RegisterSuccessfulLogin();
|
EmailNormalized = NormalizeEmail(email);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void ChangePasswordHash(string passwordHash) => PasswordHash = passwordHash;
|
||||||
|
|
||||||
public void UpdateProfile(string firstName, string lastName, string? phone, bool emailNotificationsEnabled)
|
public void UpdateProfile(string firstName, string lastName, string? phone, bool emailNotificationsEnabled)
|
||||||
{
|
{
|
||||||
FirstName = firstName.Trim();
|
FirstName = firstName.Trim();
|
||||||
@@ -79,4 +61,14 @@ public sealed class User : IHasCreatedAt
|
|||||||
public void ChangeRole(UserRole role) => Role = role;
|
public void ChangeRole(UserRole role) => Role = role;
|
||||||
|
|
||||||
public void SetActive(bool isActive) => IsActive = isActive;
|
public void SetActive(bool isActive) => IsActive = isActive;
|
||||||
|
|
||||||
|
public void Delete()
|
||||||
|
{
|
||||||
|
UpdateProfile("Smazaný", "uživatel", null, false);
|
||||||
|
ChangeEmail($"deleted:{Id.ToString(System.Globalization.CultureInfo.InvariantCulture)}");
|
||||||
|
ChangePasswordHash("");
|
||||||
|
SetEmailConfirmed(false);
|
||||||
|
SetActive(false);
|
||||||
|
IsDeleted = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
using Helpdesk.Infrastructure.Files;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace Helpdesk.Infrastructure.Background;
|
||||||
|
|
||||||
|
internal sealed partial class AttachmentStorageMonitor(TimeProvider clock, ILogger<AttachmentStorageMonitor> logger) : BackgroundService
|
||||||
|
{
|
||||||
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||||
|
{
|
||||||
|
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(5), clock);
|
||||||
|
do
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var path = Directory.Exists(FileAttachmentStore.UploadDirectory)
|
||||||
|
? FileAttachmentStore.UploadDirectory
|
||||||
|
: AppContext.BaseDirectory;
|
||||||
|
var drive = new DriveInfo(path);
|
||||||
|
var available = drive.AvailableFreeSpace;
|
||||||
|
if (available < drive.TotalSize / 10)
|
||||||
|
LogLowSpace(available / (1024 * 1024));
|
||||||
|
}
|
||||||
|
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
|
||||||
|
{
|
||||||
|
LogCheckFailed(exception);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (await timer.WaitForNextTickAsync(stoppingToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
[LoggerMessage(Level = LogLevel.Warning, Message = "Na úložišti příloh zbývá méně než 10 % volného místa ({FreeMiB} MiB).")]
|
||||||
|
private partial void LogLowSpace(long freeMiB);
|
||||||
|
|
||||||
|
[LoggerMessage(Level = LogLevel.Warning, Message = "Volné místo na úložišti příloh se nepodařilo zjistit.")]
|
||||||
|
private partial void LogCheckFailed(Exception exception);
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
using System.Data;
|
using System.Data;
|
||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
using Helpdesk.Application.Common;
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Application.Notifications;
|
||||||
using Helpdesk.Domain.Notifications;
|
using Helpdesk.Domain.Notifications;
|
||||||
using Helpdesk.Infrastructure.Email;
|
using Helpdesk.Infrastructure.Email;
|
||||||
using Helpdesk.Infrastructure.Notifications;
|
using Helpdesk.Infrastructure.Notifications;
|
||||||
@@ -56,13 +57,13 @@ internal sealed partial class NotificationDispatcher(
|
|||||||
return false;
|
return false;
|
||||||
|
|
||||||
var recipient = await (
|
var recipient = await (
|
||||||
from notification in db.Notifications.AsNoTracking()
|
from notification in NotificationVisibility.VisibleToRecipients(db).AsNoTracking()
|
||||||
join user in db.Users on notification.UserId equals user.Id
|
join user in db.Users on notification.UserId equals user.Id
|
||||||
where notification.Id == delivery.NotificationId
|
where notification.Id == delivery.NotificationId
|
||||||
select new { Notification = notification, user.Id, user.Email, user.IsActive, user.EmailConfirmed, user.EmailNotificationsEnabled }
|
select new { Notification = notification, user.Id, user.Email, user.EmailConfirmed, user.EmailNotificationsEnabled }
|
||||||
).SingleAsync(ct);
|
).SingleOrDefaultAsync(ct);
|
||||||
|
|
||||||
if (!recipient.IsActive)
|
if (recipient is null)
|
||||||
delivery.Skip();
|
delivery.Skip();
|
||||||
else if (delivery.Channel == DeliveryChannel.Email)
|
else if (delivery.Channel == DeliveryChannel.Email)
|
||||||
{
|
{
|
||||||
@@ -73,7 +74,7 @@ internal sealed partial class NotificationDispatcher(
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
await SendPushAsync(db, delivery, recipient.Notification, recipient.Id, ct);
|
await SendPushAsync(db, delivery, recipient.Id, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
@@ -94,8 +95,7 @@ internal sealed partial class NotificationDispatcher(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task SendPushAsync(
|
private async Task SendPushAsync(HelpdeskDbContext db, NotificationDelivery delivery, int userId, CancellationToken ct)
|
||||||
HelpdeskDbContext db, NotificationDelivery delivery, Notification notification, int userId, CancellationToken ct)
|
|
||||||
{
|
{
|
||||||
var devices = db.PushDevices.Where(d => d.UserId == userId);
|
var devices = db.PushDevices.Where(d => d.UserId == userId);
|
||||||
var tokens = await devices.Select(d => d.FcmToken).ToArrayAsync(ct);
|
var tokens = await devices.Select(d => d.FcmToken).ToArrayAsync(ct);
|
||||||
@@ -105,7 +105,7 @@ internal sealed partial class NotificationDispatcher(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var result = await push!.SendAsync(notification, tokens, ct);
|
var result = await push!.SendAsync(tokens, ct);
|
||||||
foreach (var invalidToken in result.InvalidTokens)
|
foreach (var invalidToken in result.InvalidTokens)
|
||||||
await devices.Where(d => d.FcmToken == invalidToken).ExecuteDeleteAsync(ct);
|
await devices.Where(d => d.FcmToken == invalidToken).ExecuteDeleteAsync(ct);
|
||||||
|
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ public static class DependencyInjection
|
|||||||
services.AddHostedService<AdminSeeder>();
|
services.AddHostedService<AdminSeeder>();
|
||||||
services.AddHostedService<AuthTokenCleanupService>();
|
services.AddHostedService<AuthTokenCleanupService>();
|
||||||
services.AddHostedService<NotificationDispatcher>();
|
services.AddHostedService<NotificationDispatcher>();
|
||||||
|
services.AddHostedService<AttachmentStorageMonitor>();
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,16 +8,16 @@ namespace Helpdesk.Infrastructure.Files;
|
|||||||
|
|
||||||
internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) : IAttachmentStore
|
internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) : IAttachmentStore
|
||||||
{
|
{
|
||||||
private readonly string directory = Path.Combine(AppContext.BaseDirectory, "uploads");
|
internal static readonly string UploadDirectory = Path.Combine(AppContext.BaseDirectory, "uploads");
|
||||||
|
|
||||||
public async Task<StoredAttachment> SaveAsync(AttachmentUpload upload, CancellationToken ct)
|
public async Task<StoredAttachment> SaveAsync(AttachmentUpload upload, CancellationToken ct)
|
||||||
{
|
{
|
||||||
if (upload.SizeBytes is <= 0 or > AttachmentLimits.MaxFileBytes)
|
if (upload.SizeBytes is <= 0 or > AttachmentLimits.MaxFileBytes)
|
||||||
throw new BadRequestException("Příloha musí mít velikost od 1 B do 10 MB.");
|
throw new FieldValidationException("files", "Příloha musí mít velikost od 1 B do 10 MB.");
|
||||||
|
|
||||||
var name = Path.GetFileName(upload.FileName.Replace('\\', '/')).Trim();
|
var name = Path.GetFileName(upload.FileName.Replace('\\', '/')).Trim();
|
||||||
if (name.Length is 0 or > 255 || name.Any(char.IsControl))
|
if (name.Length is 0 or > 255 || name.Any(char.IsControl))
|
||||||
throw new BadRequestException("Neplatný název přílohy.");
|
throw new FieldValidationException("files", "Neplatný název přílohy.");
|
||||||
|
|
||||||
var extension = Path.GetExtension(name).ToLowerInvariant();
|
var extension = Path.GetExtension(name).ToLowerInvariant();
|
||||||
var contentType = extension switch
|
var contentType = extension switch
|
||||||
@@ -27,10 +27,10 @@ internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) :
|
|||||||
".heic" => "image/heic",
|
".heic" => "image/heic",
|
||||||
".pdf" => "application/pdf",
|
".pdf" => "application/pdf",
|
||||||
".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||||
_ => throw new BadRequestException("Tento typ přílohy není povolen."),
|
_ => throw new FieldValidationException("files", "Tento typ přílohy není povolen."),
|
||||||
};
|
};
|
||||||
|
|
||||||
Directory.CreateDirectory(directory);
|
Directory.CreateDirectory(UploadDirectory);
|
||||||
var key = Guid.NewGuid().ToString("D");
|
var key = Guid.NewGuid().ToString("D");
|
||||||
var path = FilePath(key);
|
var path = FilePath(key);
|
||||||
|
|
||||||
@@ -49,16 +49,16 @@ internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) :
|
|||||||
{
|
{
|
||||||
written += read;
|
written += read;
|
||||||
if (written > upload.SizeBytes)
|
if (written > upload.SizeBytes)
|
||||||
throw new BadRequestException("Velikost přílohy neodpovídá požadavku.");
|
throw new FieldValidationException("files", "Velikost přílohy neodpovídá požadavku.");
|
||||||
await output.WriteAsync(buffer.AsMemory(0, read), ct);
|
await output.WriteAsync(buffer.AsMemory(0, read), ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (written != upload.SizeBytes)
|
if (written != upload.SizeBytes)
|
||||||
throw new BadRequestException("Velikost přílohy neodpovídá požadavku.");
|
throw new FieldValidationException("files", "Velikost přílohy neodpovídá požadavku.");
|
||||||
|
|
||||||
output.Position = 0;
|
output.Position = 0;
|
||||||
if (!await HasExpectedFormatAsync(output, extension, ct))
|
if (!await HasExpectedFormatAsync(output, extension, ct))
|
||||||
throw new BadRequestException("Obsah přílohy neodpovídá její příponě.");
|
throw new FieldValidationException("files", "Obsah přílohy neodpovídá její příponě.");
|
||||||
|
|
||||||
return new StoredAttachment(name, key, contentType, written);
|
return new StoredAttachment(name, key, contentType, written);
|
||||||
}
|
}
|
||||||
@@ -97,7 +97,7 @@ internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) :
|
|||||||
}
|
}
|
||||||
|
|
||||||
private string FilePath(string key) => Guid.TryParseExact(key, "D", out _)
|
private string FilePath(string key) => Guid.TryParseExact(key, "D", out _)
|
||||||
? Path.Combine(directory, key)
|
? Path.Combine(UploadDirectory, key)
|
||||||
: throw new InvalidOperationException("Neplatný klíč souboru přílohy.");
|
: throw new InvalidOperationException("Neplatný klíč souboru přílohy.");
|
||||||
|
|
||||||
private static async Task<bool> HasExpectedFormatAsync(Stream stream, string extension, CancellationToken ct)
|
private static async Task<bool> HasExpectedFormatAsync(Stream stream, string extension, CancellationToken ct)
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
using System.Globalization;
|
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using FirebaseAdmin;
|
using FirebaseAdmin;
|
||||||
using FirebaseAdmin.Messaging;
|
using FirebaseAdmin.Messaging;
|
||||||
using Google.Apis.Auth.OAuth2;
|
using Google.Apis.Auth.OAuth2;
|
||||||
using Google.Apis.Auth.OAuth2.Responses;
|
using Google.Apis.Auth.OAuth2.Responses;
|
||||||
using Helpdesk.Domain;
|
using Helpdesk.Domain;
|
||||||
using Notification = Helpdesk.Domain.Notifications.Notification;
|
|
||||||
|
|
||||||
namespace Helpdesk.Infrastructure.Notifications;
|
namespace Helpdesk.Infrastructure.Notifications;
|
||||||
|
|
||||||
@@ -37,17 +35,8 @@ internal sealed class FirebasePushSender(FirebaseApp app) : IDisposable
|
|||||||
return new FirebasePushSender(app);
|
return new FirebasePushSender(app);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<PushDeliveryResult> SendAsync(Notification notification, string[] tokens, CancellationToken ct)
|
public async Task<PushDeliveryResult> SendAsync(string[] tokens, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var data = new Dictionary<string, string>
|
|
||||||
{
|
|
||||||
["notificationId"] = notification.Id.ToString(CultureInfo.InvariantCulture),
|
|
||||||
};
|
|
||||||
if (notification.IssueId is int issueId)
|
|
||||||
data["issueId"] = issueId.ToString(CultureInfo.InvariantCulture);
|
|
||||||
if (notification.ProposalId is int proposalId)
|
|
||||||
data["proposalId"] = proposalId.ToString(CultureInfo.InvariantCulture);
|
|
||||||
|
|
||||||
var messaging = FirebaseMessaging.GetMessaging(app);
|
var messaging = FirebaseMessaging.GetMessaging(app);
|
||||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||||
timeout.CancelAfter(TimeSpan.FromSeconds(15));
|
timeout.CancelAfter(TimeSpan.FromSeconds(15));
|
||||||
@@ -65,12 +54,11 @@ internal sealed class FirebasePushSender(FirebaseApp app) : IDisposable
|
|||||||
#pragma warning disable CS0618 // API zařízení podle návrhu přijímá registrační tokeny FCM.
|
#pragma warning disable CS0618 // API zařízení podle návrhu přijímá registrační tokeny FCM.
|
||||||
Tokens = batch,
|
Tokens = batch,
|
||||||
#pragma warning restore CS0618
|
#pragma warning restore CS0618
|
||||||
Notification = new FirebaseAdmin.Messaging.Notification
|
Notification = new Notification
|
||||||
{
|
{
|
||||||
Title = notification.Title,
|
Title = "NTBug",
|
||||||
Body = notification.Message,
|
Body = "V aplikaci máte novou notifikaci.",
|
||||||
},
|
},
|
||||||
Data = data,
|
|
||||||
}, timeout.Token);
|
}, timeout.Token);
|
||||||
|
|
||||||
sent |= result.SuccessCount > 0;
|
sent |= result.SuccessCount > 0;
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ using Microsoft.Extensions.Logging;
|
|||||||
namespace Helpdesk.Infrastructure.Persistence;
|
namespace Helpdesk.Infrastructure.Persistence;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Při startu vytvoří účet administrátora z <c>ADMIN_EMAIL</c> a <c>ADMIN_PASSWORD</c>, pokud ještě neexistuje.
|
/// Při startu vytvoří účet administrátora z <c>ADMIN_EMAIL</c> a <c>ADMIN_PASSWORD</c>, pokud není žádný aktivní administrátor.
|
||||||
/// Admin není v migracích, aby hash hesla vznikl stejným algoritmem jako u ostatních uživatelů.
|
/// Admin není v migracích, aby hash hesla vznikl stejným algoritmem jako u ostatních uživatelů.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal sealed partial class AdminSeeder(
|
internal sealed partial class AdminSeeder(
|
||||||
@@ -29,7 +29,8 @@ internal sealed partial class AdminSeeder(
|
|||||||
var hasher = scope.ServiceProvider.GetRequiredService<IPasswordHasher>();
|
var hasher = scope.ServiceProvider.GetRequiredService<IPasswordHasher>();
|
||||||
|
|
||||||
var normalized = User.NormalizeEmail(email);
|
var normalized = User.NormalizeEmail(email);
|
||||||
if (await db.Users.AnyAsync(u => u.EmailNormalized == normalized, cancellationToken))
|
if (await db.Users.AnyAsync(u => u.EmailNormalized == normalized ||
|
||||||
|
(u.Role == UserRole.Admin && u.IsActive), cancellationToken))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
var admin = User.Create(email, hasher.Hash(password), "Administrátor", "Systému", UserRole.Admin);
|
var admin = User.Create(email, hasher.Hash(password), "Administrátor", "Systému", UserRole.Admin);
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ internal sealed class UserConfiguration(FieldEncryptor encryptor) : IEntityTypeC
|
|||||||
b.Property(u => u.Email).HasMaxLength(254);
|
b.Property(u => u.Email).HasMaxLength(254);
|
||||||
b.Property(u => u.EmailNormalized).HasMaxLength(254);
|
b.Property(u => u.EmailNormalized).HasMaxLength(254);
|
||||||
b.HasIndex(u => u.EmailNormalized).IsUnique();
|
b.HasIndex(u => u.EmailNormalized).IsUnique();
|
||||||
|
b.Property(u => u.RowVersion).IsConcurrencyToken();
|
||||||
b.Property(u => u.Role).HasConversion<EnumCodeConverter<UserRole>>().HasMaxLength(30);
|
b.Property(u => u.Role).HasConversion<EnumCodeConverter<UserRole>>().HasMaxLength(30);
|
||||||
b.Property(u => u.Phone)
|
b.Property(u => u.Phone)
|
||||||
.HasColumnName("phone_encrypted")
|
.HasColumnName("phone_encrypted")
|
||||||
|
|||||||
@@ -42,6 +42,16 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
|||||||
|
|
||||||
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
|
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
|
foreach (var entry in ChangeTracker.Entries<User>())
|
||||||
|
{
|
||||||
|
if (entry.State == EntityState.Modified && entry.Properties.Any(property =>
|
||||||
|
property.IsModified && property.Metadata.Name != nameof(User.RowVersion)))
|
||||||
|
{
|
||||||
|
var version = entry.Property(user => user.RowVersion);
|
||||||
|
version.CurrentValue = checked(version.OriginalValue + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
return await base.SaveChangesAsync(cancellationToken);
|
return await base.SaveChangesAsync(cancellationToken);
|
||||||
@@ -52,11 +62,27 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
|||||||
{
|
{
|
||||||
throw new ConflictException("Kategorie se stejným názvem již existuje.");
|
throw new ConflictException("Kategorie se stejným názvem již existuje.");
|
||||||
}
|
}
|
||||||
|
catch (DbUpdateException exception) when (
|
||||||
|
exception.InnerException is MySqlException { ErrorCode: MySqlErrorCode.DuplicateKeyEntry } &&
|
||||||
|
exception.Entries is [var entry] && entry.Entity is User)
|
||||||
|
{
|
||||||
|
throw new ConflictException("Účet s tímto e-mailem už existuje.");
|
||||||
|
}
|
||||||
|
catch (DbUpdateConcurrencyException exception) when (exception.Entries is [var entry] && entry.Entity is User)
|
||||||
|
{
|
||||||
|
throw new AccountVersionConflictException();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task<IDbContextTransaction> BeginWriteAsync(CancellationToken ct) =>
|
public Task<IDbContextTransaction> BeginWriteAsync(CancellationToken ct) =>
|
||||||
Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
|
Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
|
||||||
|
|
||||||
|
public async Task<User?> LockUserAsync(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var rows = await Users.FromSql($"SELECT * FROM app_user WHERE id = {id} FOR UPDATE").ToListAsync(ct);
|
||||||
|
return rows.SingleOrDefault();
|
||||||
|
}
|
||||||
|
|
||||||
public async Task<Proposal?> LockProposalAsync(int id, CancellationToken ct)
|
public async Task<Proposal?> LockProposalAsync(int id, CancellationToken ct)
|
||||||
{
|
{
|
||||||
// Všechny zápisy nad návrhem zamykají stejný řádek před čtením stavu a hlasů.
|
// Všechny zápisy nad návrhem zamykají stejný řádek před čtením stavu a hlasů.
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
|
|
||||||
namespace Helpdesk.Infrastructure.Security;
|
namespace Helpdesk.Infrastructure.Security;
|
||||||
@@ -6,8 +7,15 @@ namespace Helpdesk.Infrastructure.Security;
|
|||||||
internal sealed class BCryptPasswordHasher : IPasswordHasher
|
internal sealed class BCryptPasswordHasher : IPasswordHasher
|
||||||
{
|
{
|
||||||
private const int WorkFactor = 12;
|
private const int WorkFactor = 12;
|
||||||
|
private readonly string dummyHash = BCrypt.Net.BCrypt.HashPassword(
|
||||||
|
Convert.ToHexString(RandomNumberGenerator.GetBytes(32)), WorkFactor);
|
||||||
|
|
||||||
public string Hash(string password) => BCrypt.Net.BCrypt.HashPassword(password, WorkFactor);
|
public string Hash(string password) => BCrypt.Net.BCrypt.HashPassword(password, WorkFactor);
|
||||||
|
|
||||||
public bool Verify(string password, string passwordHash) => BCrypt.Net.BCrypt.Verify(password, passwordHash);
|
public bool Verify(string password, string? passwordHash)
|
||||||
|
{
|
||||||
|
var hasPassword = !string.IsNullOrEmpty(passwordHash);
|
||||||
|
var matches = BCrypt.Net.BCrypt.Verify(password, hasPassword ? passwordHash : dummyHash);
|
||||||
|
return hasPassword && matches;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -26,8 +26,9 @@ internal sealed class RevokedTokenStore(TimeProvider clock) : IRevokedTokenStore
|
|||||||
|
|
||||||
public void Add(string jti, DateTime expiresAt)
|
public void Add(string jti, DateTime expiresAt)
|
||||||
{
|
{
|
||||||
if (expiresAt > clock.GetUtcNow().UtcDateTime)
|
var rejectUntil = expiresAt + JwtTokenService.ClockSkew;
|
||||||
_revoked[jti] = expiresAt;
|
if (rejectUntil > clock.GetUtcNow().UtcDateTime)
|
||||||
|
_revoked[jti] = rejectUntil;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void PruneOccasionally()
|
private void PruneOccasionally()
|
||||||
@@ -52,10 +53,10 @@ internal sealed class RevokedTokenStoreLoader(IServiceScopeFactory scopes, IRevo
|
|||||||
{
|
{
|
||||||
using var scope = scopes.CreateScope();
|
using var scope = scopes.CreateScope();
|
||||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
var now = clock.GetUtcNow().UtcDateTime;
|
var earliestExpiry = clock.GetUtcNow().UtcDateTime - JwtTokenService.ClockSkew;
|
||||||
|
|
||||||
var revoked = await db.AuthTokens.AsNoTracking()
|
var revoked = await db.AuthTokens.AsNoTracking()
|
||||||
.Where(t => t.TokenType == TokenType.Access && t.RevokedAt != null && t.ExpiresAt > now)
|
.Where(t => t.TokenType == TokenType.Access && t.RevokedAt != null && t.ExpiresAt > earliestExpiry)
|
||||||
.Select(t => new { t.Jti, t.ExpiresAt })
|
.Select(t => new { t.Jti, t.ExpiresAt })
|
||||||
.ToListAsync(cancellationToken);
|
.ToListAsync(cancellationToken);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,292 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Nodes;
|
||||||
|
using Helpdesk.Application.Abstractions;
|
||||||
|
using Helpdesk.Application.Auth;
|
||||||
|
using Helpdesk.Application.Catalogs;
|
||||||
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Application.Issues;
|
||||||
|
using Helpdesk.Application.Notifications;
|
||||||
|
using Helpdesk.Application.Users;
|
||||||
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.IdentityModel.JsonWebTokens;
|
||||||
|
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||||
|
{
|
||||||
|
private const string Users = "/api/v1/admin/users";
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AdminMustExplicitlySendAccountStateWhenCreatingOrUpdatingAnAccount()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||||
|
var request = new SaveAdminUserRequest("[email protected]", "Test", "Uživatel", null,
|
||||||
|
"STUDENT", true, true, true, Password);
|
||||||
|
var body = JsonSerializer.SerializeToNode(request, JsonSerializerOptions.Web)!.AsObject();
|
||||||
|
string[] fields = ["isActive", "emailConfirmed", "emailNotificationsEnabled"];
|
||||||
|
|
||||||
|
foreach (var field in fields)
|
||||||
|
{
|
||||||
|
var omitted = body.DeepClone().AsObject();
|
||||||
|
omitted.Remove(field);
|
||||||
|
var validation = await ReadAsync<ValidationProblemDetails>(admin.PostAsJsonAsync(Users, omitted, Cancellation),
|
||||||
|
HttpStatusCode.BadRequest);
|
||||||
|
Assert.Equal(field, Assert.Single(validation.Errors.Keys));
|
||||||
|
}
|
||||||
|
|
||||||
|
var created = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
var path = $"{Users}/{created.Id}";
|
||||||
|
var edit = request with { RowVersion = created.RowVersion, Password = null, FirstName = "Upravené jméno" };
|
||||||
|
body = JsonSerializer.SerializeToNode(edit, JsonSerializerOptions.Web)!.AsObject();
|
||||||
|
foreach (var field in fields)
|
||||||
|
{
|
||||||
|
var omitted = body.DeepClone().AsObject();
|
||||||
|
omitted.Remove(field);
|
||||||
|
var validation = await ReadAsync<ValidationProblemDetails>(admin.PutAsJsonAsync(path, omitted, Cancellation),
|
||||||
|
HttpStatusCode.BadRequest);
|
||||||
|
Assert.Equal(field, Assert.Single(validation.Errors.Keys));
|
||||||
|
|
||||||
|
omitted[field] = null;
|
||||||
|
validation = await ReadAsync<ValidationProblemDetails>(admin.PutAsJsonAsync(path, omitted, Cancellation),
|
||||||
|
HttpStatusCode.BadRequest);
|
||||||
|
Assert.Equal(field, Assert.Single(validation.Errors.Keys));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Equal(created, await ReadAsync<AdminUserDetailsDto>(admin.GetAsync(path, Cancellation)));
|
||||||
|
var disabled = edit with { IsActive = false, EmailConfirmed = false, EmailNotificationsEnabled = false };
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync(path, disabled, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
var saved = await ReadAsync<AdminUserDetailsDto>(admin.GetAsync(path, Cancellation));
|
||||||
|
Assert.Equal((edit.FirstName, false, false, false),
|
||||||
|
(saved.FirstName, saved.IsActive, saved.EmailConfirmed, saved.EmailNotificationsEnabled));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AdminCanCreateEditAndAnonymizeAccountsWhileKeepingIssueHistory()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
var administrator = await LoginAsync(anonymous, AdminEmail);
|
||||||
|
using var admin = fixture.CreateClient(administrator.AccessToken);
|
||||||
|
var request = new SaveAdminUserRequest("[email protected]", "Jan", "Novák", "+420 123 456 789",
|
||||||
|
"STUDENT", true, true, false, Password);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
var created = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
var path = $"{Users}/{created.Id}";
|
||||||
|
Assert.Equal(created, await ReadAsync<AdminUserDetailsDto>(admin.GetAsync(path, Cancellation)));
|
||||||
|
Assert.Null(created.VerificationEmailSent);
|
||||||
|
await ExpectAsync(admin.PostAsync(path + "/email-confirmation", null, Cancellation), HttpStatusCode.Conflict);
|
||||||
|
await ExpectAsync(admin.PostAsJsonAsync(Users, request with { Email = "[email protected]" }, Cancellation), HttpStatusCode.Conflict);
|
||||||
|
|
||||||
|
var login = await LoginAsync(anonymous, request.Email);
|
||||||
|
using var student = fixture.CreateClient(login.AccessToken);
|
||||||
|
await ExpectAsync(student.DeleteAsync(path, Cancellation), HttpStatusCode.Forbidden);
|
||||||
|
var category = (await ReadAsync<CategoryDto[]>(student.GetAsync("/api/v1/issue-categories", Cancellation)))[0];
|
||||||
|
var issue = await ReadAsync<IssueDetail>(student.PostAsJsonAsync("/api/v1/issues",
|
||||||
|
new CreateIssueRequest("Rozbitý zámek", "Učebnu nelze otevřít.", category.Id, null, null), Cancellation), HttpStatusCode.Created);
|
||||||
|
|
||||||
|
var edit = request with
|
||||||
|
{
|
||||||
|
Email = "[email protected]", FirstName = "Jana", Role = "TEACHER",
|
||||||
|
Password = "New-password-for-test", RowVersion = created.RowVersion,
|
||||||
|
};
|
||||||
|
var saved = await ReadAsync<AdminUserDetailsDto>(admin.PutAsJsonAsync(path, edit, Cancellation));
|
||||||
|
Assert.False(saved.EmailConfirmed);
|
||||||
|
Assert.True(saved.VerificationEmailSent);
|
||||||
|
await ExpectAsync(student.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(edit.Email, Password), Cancellation),
|
||||||
|
HttpStatusCode.Unauthorized);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(edit.Email, edit.Password!), Cancellation),
|
||||||
|
HttpStatusCode.Unauthorized);
|
||||||
|
await ConfirmEmailAsync(anonymous, await fixture.TakeConfirmationTokenAsync(edit.Email), password: edit.Password!);
|
||||||
|
var edited = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login",
|
||||||
|
new LoginRequest(edit.Email, edit.Password!), Cancellation));
|
||||||
|
Assert.Equal((created.Id, edit.Email, edit.FirstName, edit.Role), (edited.User.Id, edited.User.Email, edited.User.FirstName, edited.User.Role));
|
||||||
|
using var teacher = fixture.CreateClient(edited.AccessToken);
|
||||||
|
await ExpectAsync(teacher.PostAsJsonAsync("/api/v1/devices", new { token = "test-device-token" }, Cancellation),
|
||||||
|
HttpStatusCode.NoContent);
|
||||||
|
|
||||||
|
await ExpectAsync(admin.DeleteAsync(path, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(admin.GetAsync(path, Cancellation), HttpStatusCode.NotFound);
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync(path + "/active", new SetActiveRequest(true), Cancellation), HttpStatusCode.NotFound);
|
||||||
|
await ExpectAsync(teacher.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/refresh", new RefreshTokenRequest(edited.RefreshToken), Cancellation),
|
||||||
|
HttpStatusCode.Unauthorized);
|
||||||
|
var list = await ReadAsync<PagedResult<AdminUserDto>>(admin.GetAsync(Users, Cancellation));
|
||||||
|
Assert.DoesNotContain(list.Items, user => user.Id == created.Id);
|
||||||
|
var issuePath = $"/api/v1/issues/{issue.Id}";
|
||||||
|
Assert.Equal(created.Id, (await ReadAsync<IssueDetail>(admin.GetAsync(issuePath, Cancellation))).ReporterId);
|
||||||
|
var entry = Assert.Single(await ReadAsync<IssueEventDto[]>(admin.GetAsync(issuePath + "/events", Cancellation)));
|
||||||
|
Assert.Equal((created.Id, "Smazaný uživatel"), (entry.ActorId, entry.ActorName));
|
||||||
|
var replacement = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request with { Email = edit.Email }, Cancellation),
|
||||||
|
HttpStatusCode.Created);
|
||||||
|
Assert.NotEqual(created.Id, replacement.Id);
|
||||||
|
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
var retained = await db.Users.AsNoTracking().SingleAsync(user => user.Id == created.Id, Cancellation);
|
||||||
|
Assert.True(retained.IsDeleted);
|
||||||
|
Assert.False(retained.IsActive);
|
||||||
|
Assert.Null(retained.Phone);
|
||||||
|
Assert.Empty(retained.PasswordHash);
|
||||||
|
Assert.NotEqual(edit.Email, retained.Email);
|
||||||
|
Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == created.Id, Cancellation));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AdminCreationSendsAnActivationLinkAndFailedDeliveryCanBeRetried()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||||
|
var request = new SaveAdminUserRequest("[email protected]", "Test", "Uživatel", null,
|
||||||
|
"STUDENT", true, false, false, null);
|
||||||
|
var created = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
Assert.True(created.VerificationEmailSent);
|
||||||
|
Assert.False(created.EmailConfirmed);
|
||||||
|
var originalToken = await fixture.TakeConfirmationTokenAsync(request.Email);
|
||||||
|
|
||||||
|
var moved = request with { Email = "[email protected]", Password = null, RowVersion = created.RowVersion };
|
||||||
|
var updated = await ReadAsync<AdminUserDetailsDto>(admin.PutAsJsonAsync($"{Users}/{created.Id}", moved, Cancellation));
|
||||||
|
Assert.True(updated.VerificationEmailSent);
|
||||||
|
await ConfirmEmailAsync(anonymous, originalToken, HttpStatusCode.BadRequest);
|
||||||
|
await ConfirmEmailAsync(anonymous, await fixture.TakeConfirmationTokenAsync(moved.Email));
|
||||||
|
Assert.Equal(created.Id, (await LoginAsync(anonymous, moved.Email)).User.Id);
|
||||||
|
|
||||||
|
var retry = request with { Email = "[email protected]" };
|
||||||
|
fixture.FailNextEmail(retry.Email, "SMTP_UNAVAILABLE", retryable: true);
|
||||||
|
var saved = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, retry, Cancellation), HttpStatusCode.Created);
|
||||||
|
Assert.False(saved.VerificationEmailSent);
|
||||||
|
Assert.Equal(retry.Email, (await ReadAsync<AdminUserDetailsDto>(admin.GetAsync($"{Users}/{saved.Id}", Cancellation))).Email);
|
||||||
|
await ExpectAsync(admin.PostAsync($"{Users}/{saved.Id}/email-confirmation", null, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ConfirmEmailAsync(anonymous, await fixture.TakeConfirmationTokenAsync(retry.Email));
|
||||||
|
Assert.Equal(saved.Id, (await LoginAsync(anonymous, retry.Email)).User.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task StaleAccountEditCannotRestoreAnOldRoleOrReactivateAnAccount()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||||
|
var request = new SaveAdminUserRequest("[email protected]", "Test", "Uživatel", null,
|
||||||
|
"FACILITY_MANAGER", true, true, false, Password);
|
||||||
|
var created = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
var path = $"{Users}/{created.Id}";
|
||||||
|
var edit = request with { Password = null, Phone = "+420 123 456 789" };
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync(path + "/role", new ChangeRoleRequest("STUDENT"), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
var conflict = await ReadAsync<ProblemDetails>(
|
||||||
|
admin.PutAsJsonAsync(path, edit with { RowVersion = created.RowVersion }, Cancellation), HttpStatusCode.Conflict);
|
||||||
|
Assert.Equal("urn:ntbug:account-version-conflict", conflict.Type);
|
||||||
|
var current = await ReadAsync<AdminUserDetailsDto>(admin.GetAsync(path, Cancellation));
|
||||||
|
Assert.Equal("STUDENT", current.Role);
|
||||||
|
Assert.Null(current.Phone);
|
||||||
|
Assert.True(current.RowVersion > created.RowVersion);
|
||||||
|
|
||||||
|
edit = edit with { Role = current.Role, RowVersion = current.RowVersion };
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
var refreshed = await ReadAsync<AdminUserDetailsDto>(admin.GetAsync(path, Cancellation));
|
||||||
|
Assert.Equal(edit.Phone, refreshed.Phone);
|
||||||
|
|
||||||
|
await ExpectAsync(admin.PostAsJsonAsync(Users + "/bulk",
|
||||||
|
new BulkAdminUsersRequest([created.Id], "deactivate", null), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync(path, edit with
|
||||||
|
{
|
||||||
|
RowVersion = refreshed.RowVersion, Phone = "+420 987 654 321",
|
||||||
|
}, Cancellation), HttpStatusCode.Conflict);
|
||||||
|
var deactivated = await ReadAsync<AdminUserDetailsDto>(admin.GetAsync(path, Cancellation));
|
||||||
|
Assert.False(deactivated.IsActive);
|
||||||
|
Assert.Equal(edit.Phone, deactivated.Phone);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AdminPasswordResetDisconnectsDevicesAndRejectsLateRegistrationsFromTheOldSession()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
var administrator = await LoginAsync(anonymous, AdminEmail);
|
||||||
|
using var admin = fixture.CreateClient(administrator.AccessToken);
|
||||||
|
var request = new SaveAdminUserRequest("[email protected]", "Test", "Účet", null,
|
||||||
|
"STUDENT", true, true, false, Password);
|
||||||
|
var newPassword = new string('č', 36);
|
||||||
|
var tooLong = newPassword + "a";
|
||||||
|
var creationError = await ReadAsync<ValidationProblemDetails>(admin.PostAsJsonAsync(Users,
|
||||||
|
request with { Password = tooLong }, Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
Assert.Contains("72 bajtů", Assert.Single(creationError.Errors["password"]));
|
||||||
|
var created = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
var originalSession = await LoginAsync(anonymous, created.Email);
|
||||||
|
using var member = fixture.CreateClient(originalSession.AccessToken);
|
||||||
|
const string devices = "/api/v1/devices";
|
||||||
|
await ExpectAsync(member.PostAsJsonAsync(devices, new { token = "old-phone" }, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(member.PostAsJsonAsync(devices, new { token = "old-tablet" }, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(admin.PostAsJsonAsync(devices, new { token = "admin-device" }, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
|
||||||
|
var edit = request with { Password = newPassword, RowVersion = created.RowVersion };
|
||||||
|
var editError = await ReadAsync<ValidationProblemDetails>(admin.PutAsJsonAsync($"{Users}/{created.Id}",
|
||||||
|
edit with { Password = tooLong }, Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
Assert.Contains("72 bajtů", Assert.Single(editError.Errors["password"]));
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync($"{Users}/{created.Id}", edit, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(member.PostAsJsonAsync(devices, new { token = "old-phone" }, Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/refresh", new RefreshTokenRequest(originalSession.RefreshToken),
|
||||||
|
Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
var oldSession = new CurrentSession(created.Id, new JsonWebToken(originalSession.AccessToken).Id);
|
||||||
|
await Assert.ThrowsAsync<UnauthorizedException>(() =>
|
||||||
|
new PushDeviceService(db, oldSession).RegisterAsync("late-registration", Cancellation));
|
||||||
|
Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == created.Id, Cancellation));
|
||||||
|
Assert.True(await db.PushDevices.AnyAsync(device => device.UserId == administrator.User.Id && device.FcmToken == "admin-device", Cancellation));
|
||||||
|
|
||||||
|
var newSession = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login",
|
||||||
|
new LoginRequest(created.Email, newPassword), Cancellation));
|
||||||
|
using var signedIn = fixture.CreateClient(newSession.AccessToken);
|
||||||
|
await ExpectAsync(signedIn.PostAsJsonAsync(devices, new { token = "new-phone" }, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task BulkActionsUpdateAllSelectedAccountsAndRejectTheEntireInvalidSelection()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
var administrator = await LoginAsync(anonymous, AdminEmail);
|
||||||
|
using var admin = fixture.CreateClient(administrator.AccessToken);
|
||||||
|
var request = new SaveAdminUserRequest("[email protected]", "První", "Účet", null, "STUDENT", true, true, false, Password);
|
||||||
|
var first = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
var second = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request with { Email = "[email protected]" }, Cancellation),
|
||||||
|
HttpStatusCode.Created);
|
||||||
|
var both = new[] { first.Id, second.Id };
|
||||||
|
|
||||||
|
await ExpectAsync(admin.PostAsJsonAsync(Users + "/bulk",
|
||||||
|
new BulkAdminUsersRequest([first.Id, int.MaxValue], "deactivate", null), Cancellation), HttpStatusCode.NotFound);
|
||||||
|
Assert.True((await ReadAsync<AdminUserDetailsDto>(admin.GetAsync($"{Users}/{first.Id}", Cancellation))).IsActive);
|
||||||
|
await ExpectAsync(admin.PostAsJsonAsync(Users + "/bulk",
|
||||||
|
new BulkAdminUsersRequest([first.Id, administrator.User.Id], "delete", null), Cancellation), HttpStatusCode.Conflict);
|
||||||
|
await ExpectAsync(admin.PostAsJsonAsync(Users + "/bulk",
|
||||||
|
new BulkAdminUsersRequest(both, "role", "TEACHER"), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
foreach (var id in both)
|
||||||
|
Assert.Equal("TEACHER", (await ReadAsync<AdminUserDetailsDto>(admin.GetAsync($"{Users}/{id}", Cancellation))).Role);
|
||||||
|
|
||||||
|
foreach (var (action, active) in new[] { ("deactivate", false), ("activate", true) })
|
||||||
|
{
|
||||||
|
await ExpectAsync(admin.PostAsJsonAsync(Users + "/bulk",
|
||||||
|
new BulkAdminUsersRequest(both, action, null), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
foreach (var id in both)
|
||||||
|
Assert.Equal(active, (await ReadAsync<AdminUserDetailsDto>(admin.GetAsync($"{Users}/{id}", Cancellation))).IsActive);
|
||||||
|
}
|
||||||
|
|
||||||
|
await ExpectAsync(admin.PostAsJsonAsync(Users + "/bulk",
|
||||||
|
new BulkAdminUsersRequest(both, "delete", null), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
foreach (var id in both)
|
||||||
|
await ExpectAsync(admin.GetAsync($"{Users}/{id}", Cancellation), HttpStatusCode.NotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Task ConfirmEmailAsync(HttpClient client, string token, HttpStatusCode expected = HttpStatusCode.NoContent,
|
||||||
|
string password = Password) =>
|
||||||
|
ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/confirm-email", new ConfirmEmailRequest(token, password), Cancellation), expected);
|
||||||
|
|
||||||
|
private sealed record CurrentSession(int Id, string TokenId) : ICurrentUser;
|
||||||
|
}
|
||||||
@@ -68,6 +68,14 @@ public sealed class AdministrationTests(BackendFixture fixture) : IClassFixture<
|
|||||||
const string profile = "/api/v1/users/me";
|
const string profile = "/api/v1/users/me";
|
||||||
const string phone = "+420 123 456 789";
|
const string phone = "+420 123 456 789";
|
||||||
var request = new UpdateProfileRequest("Jana", "Nováková", phone, false);
|
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,
|
var validation = await ReadAsync<ValidationProblemDetails>(member.PutAsJsonAsync(profile,
|
||||||
request with { Phone = "invalid" }, Cancellation), HttpStatusCode.BadRequest);
|
request with { Phone = "invalid" }, Cancellation), HttpStatusCode.BadRequest);
|
||||||
Assert.Contains("phone", validation.Errors.Keys);
|
Assert.Contains("phone", validation.Errors.Keys);
|
||||||
@@ -88,10 +96,17 @@ public sealed class AdministrationTests(BackendFixture fixture) : IClassFixture<
|
|||||||
var page = await ReadAsync<PagedResult<AdminUserDto>>(admin.GetAsync(search, Cancellation));
|
var page = await ReadAsync<PagedResult<AdminUserDto>>(admin.GetAsync(search, Cancellation));
|
||||||
Assert.Equal(user.Id, Assert.Single(page.Items).Id);
|
Assert.Equal(user.Id, Assert.Single(page.Items).Id);
|
||||||
var activation = $"/api/v1/admin/users/{user.Id}/active";
|
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(admin.PutAsJsonAsync(activation, new SetActiveRequest(false), Cancellation), HttpStatusCode.NoContent);
|
||||||
await ExpectAsync(member.GetAsync(profile, Cancellation), HttpStatusCode.Unauthorized);
|
await ExpectAsync(member.GetAsync(profile, Cancellation), HttpStatusCode.Unauthorized);
|
||||||
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(user.Email, Password), Cancellation),
|
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(user.Email, Password), Cancellation),
|
||||||
HttpStatusCode.Forbidden);
|
HttpStatusCode.Unauthorized);
|
||||||
await ExpectAsync(admin.PutAsJsonAsync(activation, new SetActiveRequest(true), Cancellation), HttpStatusCode.NoContent);
|
await ExpectAsync(admin.PutAsJsonAsync(activation, new SetActiveRequest(true), Cancellation), HttpStatusCode.NoContent);
|
||||||
Assert.Equal(user.Id, (await LoginAsync(anonymous, user.Email)).User.Id);
|
Assert.Equal(user.Id, (await LoginAsync(anonymous, user.Email)).User.Id);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ using System.Net.Http.Json;
|
|||||||
using Helpdesk.Application.Catalogs;
|
using Helpdesk.Application.Catalogs;
|
||||||
using Helpdesk.Application.Issues;
|
using Helpdesk.Application.Issues;
|
||||||
using Helpdesk.Infrastructure.Persistence;
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using static Helpdesk.IntegrationTests.BackendFixture;
|
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||||
@@ -49,7 +50,8 @@ public sealed class AttachmentTests(BackendFixture fixture) : IClassFixture<Back
|
|||||||
using var mixed = new MultipartFormDataContent();
|
using var mixed = new MultipartFormDataContent();
|
||||||
AddFile(mixed, "spravny.pdf", "%PDF-1.7\n%%EOF"u8.ToArray());
|
AddFile(mixed, "spravny.pdf", "%PDF-1.7\n%%EOF"u8.ToArray());
|
||||||
AddFile(mixed, "podvrzeny.png", "obsah nemá formát PNG"u8.ToArray());
|
AddFile(mixed, "podvrzeny.png", "obsah nemá formát PNG"u8.ToArray());
|
||||||
await ExpectAsync(author.PostAsync(path, mixed, Cancellation), HttpStatusCode.BadRequest);
|
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();
|
using var wrongField = new MultipartFormDataContent();
|
||||||
wrongField.Add(new ByteArrayContent(png), "image", "zamek.png");
|
wrongField.Add(new ByteArrayContent(png), "image", "zamek.png");
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
using System.Net;
|
using System.Net;
|
||||||
using System.Net.Http.Json;
|
using System.Net.Http.Json;
|
||||||
|
using Helpdesk.Api.Controllers;
|
||||||
|
using Helpdesk.Application.Abstractions;
|
||||||
using Helpdesk.Application.Auth;
|
using Helpdesk.Application.Auth;
|
||||||
using Helpdesk.Domain.Auth;
|
using Helpdesk.Domain.Auth;
|
||||||
using Helpdesk.Infrastructure.Persistence;
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.IdentityModel.JsonWebTokens;
|
using Microsoft.IdentityModel.JsonWebTokens;
|
||||||
@@ -13,24 +16,66 @@ namespace Helpdesk.IntegrationTests;
|
|||||||
public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||||
{
|
{
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task ChangingPasswordThroughAnEmailLinkRevokesTheOldSession()
|
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();
|
using var anonymous = fixture.CreateClient();
|
||||||
var user = await fixture.RegisterAsync(anonymous);
|
var user = await fixture.RegisterAsync(anonymous);
|
||||||
using var oldSession = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
|
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",
|
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/forgot-password",
|
||||||
new ForgotPasswordRequest(user.Email), Cancellation), HttpStatusCode.NoContent);
|
new ForgotPasswordRequest(user.Email), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
|
||||||
const string newPassword = "New-integration-password";
|
var newPassword = new string('č', 36);
|
||||||
var reset = new ResetPasswordRequest(await fixture.TakeResetTokenAsync(user.Email), newPassword);
|
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.NoContent);
|
||||||
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", reset, Cancellation), HttpStatusCode.BadRequest);
|
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(oldSession.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||||
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login",
|
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login",
|
||||||
new LoginRequest(user.Email, Password), Cancellation), HttpStatusCode.Unauthorized);
|
new LoginRequest(user.Email, legacyPassword), Cancellation), HttpStatusCode.Unauthorized);
|
||||||
var session = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login",
|
var session = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login",
|
||||||
new LoginRequest(user.Email, newPassword), Cancellation));
|
new LoginRequest(user.Email, newPassword), Cancellation));
|
||||||
Assert.Equal(user.Id, session.User.Id);
|
Assert.Equal(user.Id, session.User.Id);
|
||||||
|
Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == user.Id, Cancellation));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -57,6 +102,29 @@ public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFix
|
|||||||
token.RevokeReason == RevokeReason.Logout, Cancellation));
|
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]
|
[Fact]
|
||||||
public async Task ConcurrentRefreshRevokesTheNewPairAndOtherSessions()
|
public async Task ConcurrentRefreshRevokesTheNewPairAndOtherSessions()
|
||||||
{
|
{
|
||||||
@@ -64,6 +132,9 @@ public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFix
|
|||||||
var user = await fixture.RegisterAsync(anonymous);
|
var user = await fixture.RegisterAsync(anonymous);
|
||||||
var session = await LoginAsync(anonymous, user.Email);
|
var session = await LoginAsync(anonymous, user.Email);
|
||||||
var otherSession = 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 refresh = new RefreshTokenRequest(session.RefreshToken);
|
||||||
|
|
||||||
var pause = fixture.TokenSaves.PauseNextSave();
|
var pause = fixture.TokenSaves.PauseNextSave();
|
||||||
@@ -87,11 +158,11 @@ public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFix
|
|||||||
var renewed = await ReadAsync<AuthResponse>(first);
|
var renewed = await ReadAsync<AuthResponse>(first);
|
||||||
await ExpectAsync(duplicate, HttpStatusCode.Unauthorized);
|
await ExpectAsync(duplicate, HttpStatusCode.Unauthorized);
|
||||||
await using var after = fixture.Services.CreateAsyncScope();
|
await using var after = fixture.Services.CreateAsyncScope();
|
||||||
var tokens = after.ServiceProvider.GetRequiredService<HelpdeskDbContext>().AuthTokens;
|
var afterDb = after.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
Assert.False(await tokens.AnyAsync(token => token.UserId == user.Id && token.RevokedAt == null, Cancellation));
|
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);
|
using var renewedClient = fixture.CreateClient(renewed.AccessToken);
|
||||||
using var otherClient = fixture.CreateClient(otherSession.AccessToken);
|
|
||||||
await ExpectAsync(renewedClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
await ExpectAsync(renewedClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||||
await ExpectAsync(otherClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
await ExpectAsync(otherClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ public sealed class BackendFixture : IAsyncLifetime
|
|||||||
.Build();
|
.Build();
|
||||||
private readonly TestEmailSender email = new();
|
private readonly TestEmailSender email = new();
|
||||||
private ApiFactory? factory;
|
private ApiFactory? factory;
|
||||||
|
private int clientNumber;
|
||||||
|
|
||||||
internal TokenSaveGate TokenSaves { get; } = new();
|
internal TokenSaveGate TokenSaves { get; } = new();
|
||||||
internal IServiceProvider Services => factory!.Services;
|
internal IServiceProvider Services => factory!.Services;
|
||||||
@@ -62,7 +63,13 @@ public sealed class BackendFixture : IAsyncLifetime
|
|||||||
|
|
||||||
internal HttpClient CreateClient(string? accessToken = null)
|
internal HttpClient CreateClient(string? accessToken = null)
|
||||||
{
|
{
|
||||||
var client = factory!.CreateClient();
|
// 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)
|
if (accessToken is not null)
|
||||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
|
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
|
||||||
return client;
|
return client;
|
||||||
@@ -75,9 +82,9 @@ public sealed class BackendFixture : IAsyncLifetime
|
|||||||
{
|
{
|
||||||
var address = $"{Guid.NewGuid():N}@student.example.test";
|
var address = $"{Guid.NewGuid():N}@student.example.test";
|
||||||
var user = await ReadAsync<UserDto>(client.PostAsJsonAsync("/api/v1/auth/register",
|
var user = await ReadAsync<UserDto>(client.PostAsJsonAsync("/api/v1/auth/register",
|
||||||
new RegisterRequest(address, Password, "Test", "User"), Cancellation), HttpStatusCode.Created);
|
new RegisterRequest(address, "Test", "User"), Cancellation), HttpStatusCode.Created);
|
||||||
await ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/confirm-email",
|
await ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/confirm-email",
|
||||||
new EmailTokenRequest(await email.TakeTokenAsync(address, "/confirm-email")), Cancellation), HttpStatusCode.NoContent);
|
new ConfirmEmailRequest(await TakeConfirmationTokenAsync(address), Password), Cancellation), HttpStatusCode.NoContent);
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,6 +96,8 @@ public sealed class BackendFixture : IAsyncLifetime
|
|||||||
return await LoginAsync(anonymous, user.Email);
|
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 Task<string> TakeResetTokenAsync(string address) => email.TakeTokenAsync(address, "/reset-password");
|
||||||
|
|
||||||
internal void FailNextEmail(string address, string reason, bool retryable) =>
|
internal void FailNextEmail(string address, string reason, bool retryable) =>
|
||||||
|
|||||||
@@ -68,6 +68,21 @@ public sealed class DatabaseTests(BackendFixture fixture) : IClassFixture<Backen
|
|||||||
var files = uploadSchema.GetProperty("properties").GetProperty("files");
|
var files = uploadSchema.GetProperty("properties").GetProperty("files");
|
||||||
Assert.Equal(5, files.GetProperty("maxItems").GetInt32());
|
Assert.Equal(5, files.GetProperty("maxItems").GetInt32());
|
||||||
Assert.Equal("binary", files.GetProperty("items").GetProperty("format").GetString());
|
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]
|
[Fact]
|
||||||
|
|||||||
@@ -0,0 +1,105 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using Helpdesk.Application.Abstractions;
|
||||||
|
using Helpdesk.Application.Auth;
|
||||||
|
using Helpdesk.Application.Users;
|
||||||
|
using Helpdesk.Domain.Auth;
|
||||||
|
using Helpdesk.Domain.Users;
|
||||||
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
public sealed class EmailConfirmationTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||||
|
{
|
||||||
|
private const string Register = "/api/v1/auth/register";
|
||||||
|
private const string Confirm = "/api/v1/auth/confirm-email";
|
||||||
|
private const string Login = "/api/v1/auth/login";
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task FailedRegistrationEmailCanBeRetriedForTheSameAccount()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
const string address = "[email protected]";
|
||||||
|
var request = new RegisterRequest(address, "Jan", "Novák");
|
||||||
|
fixture.FailNextEmail(address, "SMTP_UNAVAILABLE", retryable: true);
|
||||||
|
|
||||||
|
var failure = await ReadAsync<ProblemDetails>(anonymous.PostAsJsonAsync(Register, request, Cancellation),
|
||||||
|
HttpStatusCode.ServiceUnavailable);
|
||||||
|
Assert.Equal("urn:ntbug:email-delivery-failed", failure.Type);
|
||||||
|
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
var pending = await db.Users.AsNoTracking().SingleAsync(user => user.Email == address, Cancellation);
|
||||||
|
Assert.False(pending.EmailConfirmed);
|
||||||
|
Assert.Empty(pending.PasswordHash);
|
||||||
|
|
||||||
|
var retried = await ReadAsync<UserDto>(anonymous.PostAsJsonAsync(Register, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
Assert.Equal(pending.Id, retried.Id);
|
||||||
|
var token = await fixture.TakeConfirmationTokenAsync(address);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(token, Password), Cancellation),
|
||||||
|
HttpStatusCode.NoContent);
|
||||||
|
Assert.Equal(pending.Id, (await LoginAsync(anonymous, address)).User.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task RegistrationHasNoPasswordUntilTheMailboxOwnerSetsIt()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
const string address = "[email protected]";
|
||||||
|
var user = await ReadAsync<UserDto>(anonymous.PostAsJsonAsync(Register,
|
||||||
|
new RegisterRequest(address, "Jan", "Novák"), Cancellation), HttpStatusCode.Created);
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
var pending = await db.Users.AsNoTracking().SingleAsync(u => u.Id == user.Id, Cancellation);
|
||||||
|
Assert.False(pending.EmailConfirmed);
|
||||||
|
Assert.Empty(pending.PasswordHash);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Login, new LoginRequest(address, Password), Cancellation),
|
||||||
|
HttpStatusCode.Unauthorized);
|
||||||
|
|
||||||
|
var token = await fixture.TakeConfirmationTokenAsync(address);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(token, Password), Cancellation),
|
||||||
|
HttpStatusCode.NoContent);
|
||||||
|
Assert.Equal(user.Id, (await LoginAsync(anonymous, address)).User.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AnExistingConfirmationLinkRequiresANewPasswordAndCanOnlyBeUsedOnce()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
var hasher = scope.ServiceProvider.GetRequiredService<IPasswordHasher>();
|
||||||
|
const string address = "[email protected]";
|
||||||
|
const string oldPassword = "Legacy-unconfirmed-password";
|
||||||
|
var pending = User.Create(address, hasher.Hash(oldPassword), "Eva", "Nováková", UserRole.Student);
|
||||||
|
db.Users.Add(pending);
|
||||||
|
await db.SaveChangesAsync(Cancellation);
|
||||||
|
var original = scope.ServiceProvider.GetRequiredService<ITokenService>().Issue(pending, TokenType.EmailConfirm);
|
||||||
|
db.AuthTokens.Add(original.Record);
|
||||||
|
await db.SaveChangesAsync(Cancellation);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Login, new LoginRequest(address, oldPassword), Cancellation),
|
||||||
|
HttpStatusCode.Unauthorized);
|
||||||
|
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Register, new RegisterRequest(address, "Jiné", "Jméno"), Cancellation),
|
||||||
|
HttpStatusCode.Created);
|
||||||
|
var otherToken = await fixture.TakeConfirmationTokenAsync(address);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new { token = original.Token }, Cancellation),
|
||||||
|
HttpStatusCode.BadRequest);
|
||||||
|
var newPassword = new string('č', 36);
|
||||||
|
var validation = await ReadAsync<ValidationProblemDetails>(anonymous.PostAsJsonAsync(Confirm,
|
||||||
|
new ConfirmEmailRequest(original.Token, newPassword + "a"), Cancellation), HttpStatusCode.BadRequest);
|
||||||
|
Assert.Contains("72 bajtů", Assert.Single(validation.Errors["newPassword"]));
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(original.Token, newPassword), Cancellation),
|
||||||
|
HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(otherToken, oldPassword), Cancellation),
|
||||||
|
HttpStatusCode.BadRequest);
|
||||||
|
await ExpectAsync(anonymous.PostAsJsonAsync(Login, new LoginRequest(address, oldPassword), Cancellation),
|
||||||
|
HttpStatusCode.Unauthorized);
|
||||||
|
var session = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync(Login, new LoginRequest(address, newPassword), Cancellation));
|
||||||
|
Assert.Equal((pending.Id, pending.FirstName, pending.LastName), (session.User.Id, session.User.FirstName, session.User.LastName));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,12 +5,46 @@ using Helpdesk.Application.Common;
|
|||||||
using Helpdesk.Application.Issues;
|
using Helpdesk.Application.Issues;
|
||||||
using Helpdesk.Application.Notifications;
|
using Helpdesk.Application.Notifications;
|
||||||
using Helpdesk.Application.Statistics;
|
using Helpdesk.Application.Statistics;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using static Helpdesk.IntegrationTests.BackendFixture;
|
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||||
|
|
||||||
namespace Helpdesk.IntegrationTests;
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
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]
|
[Fact]
|
||||||
public async Task ReporterAndAssigneesCanResolveAnIssueAndManagementCanReportOnIt()
|
public async Task ReporterAndAssigneesCanResolveAnIssueAndManagementCanReportOnIt()
|
||||||
{
|
{
|
||||||
@@ -52,8 +86,9 @@ public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture<B
|
|||||||
var assignable = await ReadAsync<AssignableUserDto[]>(admin.GetAsync("/api/v1/users/assignable", Cancellation));
|
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 == firstAssignee.User.Id);
|
||||||
Assert.Contains(assignable, user => user.Id == administrator.User.Id);
|
Assert.Contains(assignable, user => user.Id == administrator.User.Id);
|
||||||
await ExpectAsync(firstSolver.PostAsJsonAsync(path + "/start",
|
var conflict = await ReadAsync<ProblemDetails>(firstSolver.PostAsJsonAsync(path + "/start",
|
||||||
new IssueVersionRequest(assign.RowVersion), Cancellation), HttpStatusCode.Conflict);
|
new IssueVersionRequest(assign.RowVersion), Cancellation), HttpStatusCode.Conflict);
|
||||||
|
Assert.Equal("urn:ntbug:issue-version-conflict", conflict.Type);
|
||||||
|
|
||||||
var reporterNotifications = await InboxAsync(reporter, issue.Id);
|
var reporterNotifications = await InboxAsync(reporter, issue.Id);
|
||||||
Assert.Equal("ISSUE_STATUS_CHANGED", Assert.Single(reporterNotifications).Type);
|
Assert.Equal("ISSUE_STATUS_CHANGED", Assert.Single(reporterNotifications).Type);
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ using Helpdesk.Application.Catalogs;
|
|||||||
using Helpdesk.Application.Common;
|
using Helpdesk.Application.Common;
|
||||||
using Helpdesk.Application.Issues;
|
using Helpdesk.Application.Issues;
|
||||||
using Helpdesk.Application.Notifications;
|
using Helpdesk.Application.Notifications;
|
||||||
|
using Helpdesk.Application.Users;
|
||||||
using Helpdesk.Infrastructure.Persistence;
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
@@ -66,6 +67,50 @@ public sealed class NotificationTests(BackendFixture fixture) : IClassFixture<Ba
|
|||||||
Assert.Empty((await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation))).Items);
|
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]
|
[Fact]
|
||||||
public async Task DeviceRegistrationPreservesCaseAndTransfersOwnership()
|
public async Task DeviceRegistrationPreservesCaseAndTransfersOwnership()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
using System.Net;
|
using System.Net;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Helpdesk.Application.Auth;
|
||||||
using Microsoft.AspNetCore.TestHost;
|
using Microsoft.AspNetCore.TestHost;
|
||||||
using static Helpdesk.IntegrationTests.BackendFixture;
|
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||||
|
|
||||||
@@ -16,16 +18,16 @@ public sealed class ProxyRateLimitTests(BackendFixture fixture) : IClassFixture<
|
|||||||
await using var api = fixture.CreateApiBehindProxies(externalProxy, web);
|
await using var api = fixture.CreateApiBehindProxies(externalProxy, web);
|
||||||
|
|
||||||
for (var attempt = 0; attempt < 20; attempt++)
|
for (var attempt = 0; attempt < 20; attempt++)
|
||||||
Assert.Equal(401, await LoginAsync(api.Server, web, firstClient));
|
Assert.Equal(401, await LoginAsync(api.Server, web, firstClient, $"absent-{attempt}@example.test"));
|
||||||
|
|
||||||
Assert.Equal(429, await LoginAsync(api.Server, externalProxy, firstClient));
|
Assert.Equal(429, await LoginAsync(api.Server, externalProxy, firstClient, "[email protected]"));
|
||||||
Assert.Equal(401, await LoginAsync(api.Server, web, secondClient));
|
Assert.Equal(401, await LoginAsync(api.Server, web, secondClient, "[email protected]"));
|
||||||
Assert.Equal(429, await LoginAsync(api.Server, $"::ffff:{firstClient}", secondClient));
|
Assert.Equal(429, await LoginAsync(api.Server, $"::ffff:{firstClient}", secondClient, "[email protected]"));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static async Task<int> LoginAsync(TestServer server, string peer, string client)
|
private static async Task<int> LoginAsync(TestServer server, string peer, string client, string email)
|
||||||
{
|
{
|
||||||
using var body = new MemoryStream("""{"email":"absent@example.test","password":"test-password"}"""u8.ToArray());
|
using var body = new MemoryStream(JsonSerializer.SerializeToUtf8Bytes(new LoginRequest(email, "test-password")));
|
||||||
var response = await server.SendAsync(context =>
|
var response = await server.SendAsync(context =>
|
||||||
{
|
{
|
||||||
context.Connection.RemoteIpAddress = IPAddress.Parse(peer);
|
context.Connection.RemoteIpAddress = IPAddress.Parse(peer);
|
||||||
|
|||||||
@@ -37,46 +37,11 @@ public class EnumCodeTests
|
|||||||
public void Neznamy_kod_neprojde() => Assert.False(EnumCode.TryParse<UserRole>("SUPERUSER", out _));
|
public void Neznamy_kod_neprojde() => Assert.False(EnumCode.TryParse<UserRole>("SUPERUSER", out _));
|
||||||
}
|
}
|
||||||
|
|
||||||
public class UserLockoutTests
|
public class UserTests
|
||||||
{
|
{
|
||||||
private static readonly DateTime Now = new(2026, 10, 29, 10, 0, 0, DateTimeKind.Utc);
|
|
||||||
|
|
||||||
private static User NewUser() => User.Create("[email protected]", "hash", "Jan", "Novák", UserRole.Student);
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Ctyri_neuspesne_pokusy_ucet_nezamknou()
|
|
||||||
{
|
|
||||||
var user = NewUser();
|
|
||||||
for (var i = 0; i < User.MaxFailedLogins - 1; i++)
|
|
||||||
user.RegisterFailedLogin(Now);
|
|
||||||
|
|
||||||
Assert.False(user.IsLockedOut(Now));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Paty_neuspesny_pokus_zamkne_ucet_na_15_minut()
|
|
||||||
{
|
|
||||||
var user = NewUser();
|
|
||||||
for (var i = 0; i < User.MaxFailedLogins; i++)
|
|
||||||
user.RegisterFailedLogin(Now);
|
|
||||||
|
|
||||||
Assert.True(user.IsLockedOut(Now.AddMinutes(14)));
|
|
||||||
Assert.False(user.IsLockedOut(Now.AddMinutes(15)));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Uspesne_prihlaseni_vynuluje_pocitadlo()
|
|
||||||
{
|
|
||||||
var user = NewUser();
|
|
||||||
user.RegisterFailedLogin(Now);
|
|
||||||
user.RegisterSuccessfulLogin();
|
|
||||||
|
|
||||||
Assert.Equal(0, user.FailedLoginCount);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Email_se_normalizuje_pro_jednoznacne_vyhledani() =>
|
public void Email_se_normalizuje_pro_jednoznacne_vyhledani() =>
|
||||||
Assert.Equal("[email protected]", NewUser().EmailNormalized);
|
Assert.Equal("[email protected]", User.Create("[email protected]", "hash", "Jan", "Novák", UserRole.Student).EmailNormalized);
|
||||||
}
|
}
|
||||||
|
|
||||||
public class RegistrationRoleTests
|
public class RegistrationRoleTests
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE app_user
|
||||||
|
ADD COLUMN is_deleted BOOLEAN NOT NULL DEFAULT FALSE;
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE app_user
|
||||||
|
ADD COLUMN row_version INT NOT NULL DEFAULT 0;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
ALTER TABLE app_user
|
||||||
|
DROP COLUMN IF EXISTS failed_login_count,
|
||||||
|
DROP COLUMN IF EXISTS lockout_until;
|
||||||
+19
-15
@@ -113,10 +113,10 @@ Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkr
|
|||||||
### Účty a přístup
|
### Účty a přístup
|
||||||
| ID | Požadavek |
|
| ID | Požadavek |
|
||||||
|---|---|
|
|---|---|
|
||||||
| FR-01 | Registrace e-mailem a heslem; po registraci ověření e-mailu odkazem. |
|
| FR-01 | Registrace univerzitním e-mailem. Příjemce ověří e-mail a nastaví heslo přes jednorázový odkaz. |
|
||||||
| FR-02 | Přihlášení e-mailem a heslem, vydání JWT access tokenu a refresh tokenu; odhlášení zablokuje oba tokeny (podle `jti`); „odhlásit ze všech zařízení“. |
|
| FR-02 | Přihlášení e-mailem a heslem, vydání JWT access tokenu a refresh tokenu; odhlášení zablokuje oba tokeny (podle `jti`); „odhlásit ze všech zařízení“. |
|
||||||
| FR-03 | Obnova zapomenutého hesla přes e-mail. |
|
| FR-03 | Obnova zapomenutého hesla přes e-mail. |
|
||||||
| FR-04 | Administrátor vyhledává uživatele, mění jejich roli, deaktivuje účty. |
|
| FR-04 | Administrátor vyhledává, zakládá a upravuje účty, mění role, aktivuje, deaktivuje a maže účty. Role, stav i smazání může změnit u více účtů najednou. |
|
||||||
| FR-05 | Uživatel upravuje svůj profil (jméno, telefon, zapnutí e-mailových notifikací). |
|
| FR-05 | Uživatel upravuje svůj profil (jméno, telefon, zapnutí e-mailových notifikací). |
|
||||||
|
|
||||||
### Hlášení závad
|
### Hlášení závad
|
||||||
@@ -374,9 +374,10 @@ sequenceDiagram
|
|||||||
end
|
end
|
||||||
```
|
```
|
||||||
|
|
||||||
- **V aplikaci:** tabulka `notification`. Notifikace v aplikaci je doručena vždy, protože vzniká v DB ve stejné transakci jako událost. Klient zobrazuje seznam a počet nepřečtených (`GET /api/v1/notifications/unread-count`, web jej obnovuje periodicky).
|
- **V aplikaci:** notifikace se uloží do tabulky `notification` ve stejné transakci jako událost. Klient zobrazuje seznam a počet nepřečtených (`GET /api/v1/notifications/unread-count`, web jej obnovuje periodicky).
|
||||||
- **E-mail:** SMTP (knihovna MailKit); ve vývoji zachytává e-maily kontejner Mailpit.
|
- **E-mail:** SMTP (knihovna MailKit); ve vývoji zachytává e-maily kontejner Mailpit.
|
||||||
- **Push:** mobilní aplikace po přihlášení zaregistruje FCM token (`POST /api/v1/devices`); backend odesílá přes Firebase Admin SDK.
|
- **Push:** mobilní aplikace po přihlášení zaregistruje FCM token (`POST /api/v1/devices`). Backend přes Firebase Admin SDK posílá obecné upozornění. Podrobnosti klient načte z API po přihlášení.
|
||||||
|
- Při zobrazení notifikace v aplikaci i před doručením e-mailu nebo push backend ověřuje aktuální přístup příjemce k související závadě.
|
||||||
- Pro každou notifikaci se vytvoří řádek `notification_delivery` pro každý externí kanál. Stav kanálu se tak sleduje samostatně: e-mail může selhat, i když push prošel.
|
- Pro každou notifikaci se vytvoří řádek `notification_delivery` pro každý externí kanál. Stav kanálu se tak sleduje samostatně: e-mail může selhat, i když push prošel.
|
||||||
|
|
||||||
### 8.3 Řešení nedoručení
|
### 8.3 Řešení nedoručení
|
||||||
@@ -470,7 +471,7 @@ Detail závady vrací pole `allowedActions` (např. `["START_WORK", "REJECT", "C
|
|||||||
| Síť | Retrofit + OkHttp + kotlinx.serialization; `Authenticator` pro obnovu tokenu, `Interceptor` pro Bearer hlavičku |
|
| Síť | Retrofit + OkHttp + kotlinx.serialization; `Authenticator` pro obnovu tokenu, `Interceptor` pro Bearer hlavičku |
|
||||||
| Úložiště tokenů | DataStore, šifrováno klíčem z Android Keystore |
|
| Úložiště tokenů | DataStore, šifrováno klíčem z Android Keystore |
|
||||||
| Fotky | Systémový fotoaparát / výběr z galerie (Activity Result API), náhledy Coil, zmenšení před odesláním |
|
| Fotky | Systémový fotoaparát / výběr z galerie (Activity Result API), náhledy Coil, zmenšení před odesláním |
|
||||||
| Push | Firebase Cloud Messaging (`FirebaseMessagingService`), deep link na detail závady |
|
| Push | Firebase Cloud Messaging (`FirebaseMessagingService`), podrobnosti v přihlášené aplikaci |
|
||||||
| Min. verze | Android 8.0 (API 26) |
|
| Min. verze | Android 8.0 (API 26) |
|
||||||
|
|
||||||
### 9.6 Struktura repozitáře (Git, EngineRevive)
|
### 9.6 Struktura repozitáře (Git, EngineRevive)
|
||||||
@@ -510,11 +511,11 @@ Větvení: `main` (stabilní), `develop`, feature větve `feature/<nazev>`, merg
|
|||||||
|
|
||||||
| Oblast | Řešení |
|
| Oblast | Řešení |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Hesla | Hash BCrypt (knihovna BCrypt.Net-Next, work factor 12; sůl je součástí hashe). Min. délka hesla 8 znaků. |
|
| Hesla | Hash BCrypt (knihovna BCrypt.Net-Next, work factor 12; sůl je součástí hashe). Nové heslo má 8–64 znaků a nejvýše 72 bajtů v UTF-8. |
|
||||||
| Přihlášení | Ochrana proti hádání hesla: po 5 neúspěšných pokusech zámek účtu na 15 minut (`failed_login_count`, `lockout_until`), rate limiting na `/api/v1/auth/*`. |
|
| Přihlášení | Neúspěšné ověření vrací jednotnou odpověď, BCrypt se provádí i pro neznámý účet. Každá instance API omezuje přihlášení na 5 pokusů za minutu pro dvojici klientská IP a normalizovaný e-mail. Pro `/api/v1/auth/*` platí také limit 20 požadavků za minutu na klientskou IP. |
|
||||||
| Tokeny | Všechny tokeny jsou podepsané JWT podle RFC 7519 s unikátním `jti` a typem v hlavičce. V databázi není žádný token ani jeho hash (kap. 10.1). |
|
| Tokeny | Všechny tokeny jsou podepsané JWT podle RFC 7519 s unikátním `jti` a typem v hlavičce. V databázi není žádný token ani jeho hash (kap. 10.1). |
|
||||||
| Šifrování citlivých údajů | Telefonní číslo uživatele šifrováno AES-256-GCM (EF Core value converter), klíč mimo DB – v proměnné prostředí / Docker secret. Přenos výhradně HTTPS (TLS 1.2+), HSTS. |
|
| Šifrování citlivých údajů | Telefonní číslo uživatele šifrováno AES-256-GCM (EF Core value converter), klíč mimo DB – v proměnné prostředí / Docker secret. Přenos výhradně HTTPS (TLS 1.2+), HSTS. |
|
||||||
| Přílohy | Kontrola typu (přípona + signatura souboru) a velikosti, ukládání pod náhodným GUID mimo webový kořen, stahování jen přes API s kontrolou oprávnění k závadě. |
|
| Přílohy | Kontrola typu (přípona + signatura souboru) a velikosti, ukládání pod náhodným GUID mimo webový kořen, stahování jen přes API s kontrolou oprávnění k závadě. Web nabízí PDF ke stažení. API zapisuje varování do logu, pokud na svazku s přílohami zbývá méně než 10 % volného místa. |
|
||||||
| Zápisy závad | Vytvoření závady, přidání komentáře a nahrání příloh mají společný limit 10 požadavků za minutu na účet a instanci API. Překročení vrací 429. |
|
| Zápisy závad | Vytvoření závady, přidání komentáře a nahrání příloh mají společný limit 10 požadavků za minutu na účet a instanci API. Překročení vrací 429. |
|
||||||
| Vstupy | Validace DTO (FluentValidation), parametrizované dotazy (EF Core), HTML výstup kódován Razorem (XSS), anti-forgery tokeny ve webových formulářích (CSRF). |
|
| Vstupy | Validace DTO (FluentValidation), parametrizované dotazy (EF Core), HTML výstup kódován Razorem (XSS), anti-forgery tokeny ve webových formulářích (CSRF). |
|
||||||
| Tajemství | JWT klíč, DB heslo, šifrovací klíč, SMTP a Firebase přístupy pouze v proměnných prostředí / `.env` mimo Git. |
|
| Tajemství | JWT klíč, DB heslo, šifrovací klíč, SMTP a Firebase přístupy pouze v proměnných prostředí / `.env` mimo Git. |
|
||||||
@@ -655,8 +656,8 @@ Swagger UI je na webu na `/swagger`. UI i jeho OpenAPI dokument na `/swagger/v1/
|
|||||||
### Autentizace a účet
|
### Autentizace a účet
|
||||||
| Metoda | Endpoint | Role | Popis |
|
| Metoda | Endpoint | Role | Popis |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| POST | `/auth/register` | anonym | Registrace (e-mail, heslo, jméno, příjmení) |
|
| POST | `/auth/register` | anonym | Registrace (e-mail, jméno, příjmení) a odeslání ověřovacího odkazu. Po `503` s typem `urn:ntbug:email-delivery-failed` lze stejným požadavkem zopakovat odeslání pro uložený účet. |
|
||||||
| POST | `/auth/confirm-email` | anonym | Ověření e-mailu tokenem |
|
| POST | `/auth/confirm-email` | anonym | Ověření e-mailu a nastavení hesla v jedné transakci (`{ token, newPassword }`) |
|
||||||
| POST | `/auth/login` | anonym | Vrací `accessToken`, `refreshToken`, údaje uživatele a roli |
|
| POST | `/auth/login` | anonym | Vrací `accessToken`, `refreshToken`, údaje uživatele a roli |
|
||||||
| POST | `/auth/refresh` | anonym | Výměna refresh tokenu za nový pár tokenů (starý `jti` se zablokuje) |
|
| POST | `/auth/refresh` | anonym | Výměna refresh tokenu za nový pár tokenů (starý `jti` se zablokuje) |
|
||||||
| POST | `/auth/logout` | přihlášený | Zablokuje `jti` access i refresh tokenu |
|
| POST | `/auth/logout` | přihlášený | Zablokuje `jti` access i refresh tokenu |
|
||||||
@@ -724,6 +725,11 @@ Po přidání komentáře nebo příloh klient znovu načte detail, aby získal
|
|||||||
| GET | `/buildings`, `/issue-categories`, `/proposal-categories` | přihlášený | Číselníky pro formuláře |
|
| GET | `/buildings`, `/issue-categories`, `/proposal-categories` | přihlášený | Číselníky pro formuláře |
|
||||||
| POST / PUT / DELETE | totéž | admin | Správa (DELETE = deaktivace `is_active`) |
|
| POST / PUT / DELETE | totéž | admin | Správa (DELETE = deaktivace `is_active`) |
|
||||||
| GET | `/admin/users?q=&role=` | admin | Vyhledání uživatelů |
|
| GET | `/admin/users?q=&role=` | admin | Vyhledání uživatelů |
|
||||||
|
| POST | `/admin/users` | admin | Založení účtu s ručním ověřením a počátečním heslem, nebo s odkazem pro nastavení hesla příjemcem |
|
||||||
|
| GET / PUT | `/admin/users/{id}` | admin | Detail a úprava účtu s `rowVersion`. Zastaralá verze vrátí 409. Změna adresy aktivního účtu spustí nové ověření. Nové heslo odhlásí relace a odpojí push zařízení. |
|
||||||
|
| POST | `/admin/users/{id}/email-confirmation` | admin | Opětovné odeslání odkazu aktivnímu účtu s neověřeným e-mailem |
|
||||||
|
| DELETE | `/admin/users/{id}` | admin | Znepřístupnění účtu a anonymizace profilu |
|
||||||
|
| POST | `/admin/users/bulk` | admin | Změna role, aktivace, deaktivace nebo smazání vybraných účtů v jedné transakci |
|
||||||
| PUT | `/admin/users/{id}/role` | admin | `{ role: "FACILITY_MANAGER" }` |
|
| PUT | `/admin/users/{id}/role` | admin | `{ role: "FACILITY_MANAGER" }` |
|
||||||
| PUT | `/admin/users/{id}/active` | admin | Aktivace / deaktivace účtu |
|
| PUT | `/admin/users/{id}/active` | admin | Aktivace / deaktivace účtu |
|
||||||
| GET | `/admin/notification-deliveries?status=FAILED` | admin | Nedoručené notifikace s důvodem chyby |
|
| GET | `/admin/notification-deliveries?status=FAILED` | admin | Nedoručené notifikace s důvodem chyby |
|
||||||
@@ -774,8 +780,6 @@ erDiagram
|
|||||||
bool is_active
|
bool is_active
|
||||||
bool email_confirmed
|
bool email_confirmed
|
||||||
bool email_notifications_enabled
|
bool email_notifications_enabled
|
||||||
int failed_login_count
|
|
||||||
datetime lockout_until
|
|
||||||
datetime created_at
|
datetime created_at
|
||||||
}
|
}
|
||||||
auth_token {
|
auth_token {
|
||||||
@@ -945,7 +949,7 @@ V první verzi byla tabulka uživatelů „chobotnice“: vedlo na ni 17 cizích
|
|||||||
- Hlavní tabulky (`issue`, `proposal`, `attachment`, …) obsahují **jen `created_at`**. Je neměnný a potřebný pro řazení a filtrování podle období přes index.
|
- Hlavní tabulky (`issue`, `proposal`, `attachment`, …) obsahují **jen `created_at`**. Je neměnný a potřebný pro řazení a filtrování podle období přes index.
|
||||||
- Všechny ostatní časy životního cyklu (přiřazení, převzetí, uzavření, rozhodnutí vedení, úpravy) jsou v **tabulkách událostí** `issue_event` a `proposal_event`. Jedna řádka = jeden okamžik (`occurred_at`), kdo ho způsobil (`actor_id`) a co se stalo (`event_type`, `from_status` → `to_status`, `note`). Zrušeny byly sloupce `updated_at`, `assigned_at`, `closed_at`, `decided_at`, `rejection_reason`, `decision_note`.
|
- Všechny ostatní časy životního cyklu (přiřazení, převzetí, uzavření, rozhodnutí vedení, úpravy) jsou v **tabulkách událostí** `issue_event` a `proposal_event`. Jedna řádka = jeden okamžik (`occurred_at`), kdo ho způsobil (`actor_id`) a co se stalo (`event_type`, `from_status` → `to_status`, `note`). Zrušeny byly sloupce `updated_at`, `assigned_at`, `closed_at`, `decided_at`, `rejection_reason`, `decision_note`.
|
||||||
- Odvozené časy poskytuje pohled `v_issue_lifecycle` (`first_assigned_at`, `closed_at`, `last_activity_at`). Z něj čerpají statistiky.
|
- Odvozené časy poskytuje pohled `v_issue_lifecycle` (`first_assigned_at`, `closed_at`, `last_activity_at`). Z něj čerpají statistiky.
|
||||||
- Zůstávají jen **funkční časy**, které popisují aktuální stav záznamu a řídí chování systému: `notification.read_at`, `notification_delivery.next_attempt_at` / `sent_at`, `auth_token.issued_at` / `expires_at` / `revoked_at` (odpovídají claimům tokenu), `app_user.lockout_until`.
|
- **Funkční časy** popisují aktuální stav záznamu a řídí chování systému: `notification.read_at`, `notification_delivery.next_attempt_at` / `sent_at`, `auth_token.issued_at` / `expires_at` / `revoked_at` (odpovídají claimům tokenu).
|
||||||
- *Proč ne jedna společná tabulka datumů pro všechny entity:* musela by odkazovat na různé tabulky bez cizího klíče (polymorfní vazba), každý seznam by potřeboval další JOIN a řazení podle data by nevyužilo index. Tabulky událostí pro každou hlavní entitu tyto nevýhody nemají, zachovávají referenční integritu a navíc slouží jako audit.
|
- *Proč ne jedna společná tabulka datumů pro všechny entity:* musela by odkazovat na různé tabulky bez cizího klíče (polymorfní vazba), každý seznam by potřeboval další JOIN a řazení podle data by nevyužilo index. Tabulky událostí pro každou hlavní entitu tyto nevýhody nemají, zachovávají referenční integritu a navíc slouží jako audit.
|
||||||
- `created_at` vyplňuje v EF Core automaticky interceptor `SaveChanges` u entit s rozhraním `IHasCreatedAt`. Výchozí hodnota v DB je `UTC_TIMESTAMP(6)`.
|
- `created_at` vyplňuje v EF Core automaticky interceptor `SaveChanges` u entit s rozhraním `IHasCreatedAt`. Výchozí hodnota v DB je `UTC_TIMESTAMP(6)`.
|
||||||
|
|
||||||
@@ -980,8 +984,8 @@ V první verzi byla tabulka uživatelů „chobotnice“: vedlo na ni 17 cizích
|
|||||||
- **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í nebo administrátora) hlídá aplikační vrstva. V DB by vyžadovala triggery a logika by se rozdělila na dvě místa.
|
||||||
- **Optimistické zamykání**: `issue.row_version` (EF Core concurrency token).
|
- **Optimistické zamykání**: `issue.row_version` a `app_user.row_version` (EF Core concurrency token).
|
||||||
- **Mazání**: uživatelé, závady, návrhy a číselníky se nemažou. Uživatelé a číselníky se deaktivují (`is_active`). `ON DELETE CASCADE` je jen u čistě závislých dat.
|
- **Mazání účtů**: smazaný účet se deaktivuje, jeho profil se anonymizuje a účet se skryje ze správy uživatelů (`is_deleted`). Původní e-mail je volný pro nový účet. Vazby závad, návrhů, hlasů a událostí zůstanou v databázi. Číselníky se deaktivují (`is_active`), závady a návrhy zůstávají v historii.
|
||||||
- **Časy v UTC**, `DATETIME(6)`; převod do místního času dělá klient.
|
- **Časy v UTC**, `DATETIME(6)`; převod do místního času dělá klient.
|
||||||
- **Kódování** `utf8mb4`, engine InnoDB (transakce, cizí klíče).
|
- **Kódování** `utf8mb4`, engine InnoDB (transakce, cizí klíče).
|
||||||
- **Indexy** pokrývají filtry centrálního přehledu, frontu nedoručených notifikací (`status, next_attempt_at`), zneplatnění všech tokenů uživatele (`user_id, revoked_at`) a úklid prošlých tokenů (`expires_at`).
|
- **Indexy** pokrývají filtry centrálního přehledu, frontu nedoručených notifikací (`status, next_attempt_at`), zneplatnění všech tokenů uživatele (`user_id, revoked_at`) a úklid prošlých tokenů (`expires_at`).
|
||||||
|
|||||||
@@ -0,0 +1,328 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Text;
|
||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Helpdesk.Web.Auth;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
|
using Microsoft.AspNetCore.TestHost;
|
||||||
|
using Microsoft.AspNetCore.WebUtilities;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using static Helpdesk.Web.Tests.WebTestSession;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Tests;
|
||||||
|
|
||||||
|
public sealed class AdminUsersTests
|
||||||
|
{
|
||||||
|
private const string UsersPath = "/admin/users";
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(null, "/login")]
|
||||||
|
[InlineData(UserRoles.Student, "/error/403")]
|
||||||
|
[InlineData(UserRoles.Management, "/error/403")]
|
||||||
|
public async Task OnlyAnAdministratorCanListOrChangeUsers(string? role, string redirect)
|
||||||
|
{
|
||||||
|
var backend = new AdminUsersBackend();
|
||||||
|
await using var application = CreateApplication(backend);
|
||||||
|
using var client = CreateClient(application);
|
||||||
|
if (role is not null)
|
||||||
|
SignIn(application.Services, client, role);
|
||||||
|
var ct = TestContext.Current.CancellationToken;
|
||||||
|
|
||||||
|
foreach (var path in new[] { UsersPath, UsersPath + "/new", UsersPath + "/7/edit" })
|
||||||
|
{
|
||||||
|
using var page = await client.GetAsync(path, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, page.StatusCode);
|
||||||
|
Assert.Equal(redirect, page.Headers.Location?.AbsolutePath);
|
||||||
|
}
|
||||||
|
foreach (var action in new[] { "7/role", "7/active", "new", "7/edit", "7/delete", "7/email-confirmation", "bulk" })
|
||||||
|
{
|
||||||
|
using var update = await client.PostAsync($"{UsersPath}/{action}", null, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, update.StatusCode);
|
||||||
|
Assert.Equal(redirect, update.Headers.Location?.AbsolutePath);
|
||||||
|
}
|
||||||
|
Assert.Empty(backend.Requests);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AdministratorCanSearchAndChangeRoleAndActivation()
|
||||||
|
{
|
||||||
|
var backend = new AdminUsersBackend();
|
||||||
|
await using var application = CreateApplication(backend);
|
||||||
|
using var client = CreateClient(application);
|
||||||
|
SignIn(application.Services, client, UserRoles.Admin);
|
||||||
|
var ct = TestContext.Current.CancellationToken;
|
||||||
|
const string query = "?q=Nov%C3%A1k&role=STUDENT&page=2";
|
||||||
|
|
||||||
|
using var list = await client.GetAsync(UsersPath + query, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, list.StatusCode);
|
||||||
|
Assert.True(list.Headers.CacheControl?.NoStore == true);
|
||||||
|
var html = WebUtility.HtmlDecode(await list.Content.ReadAsStringAsync(ct));
|
||||||
|
Assert.Contains("Správa uživatelů", html);
|
||||||
|
Assert.Contains("Strana 2 z 3", html);
|
||||||
|
Assert.Contains("[email protected]", html);
|
||||||
|
Assert.Contains("E-mail neověřený", html);
|
||||||
|
Assert.Contains("Váš účet", html);
|
||||||
|
Assert.DoesNotContain($"{UsersPath}/1/role", html);
|
||||||
|
Assert.DoesNotContain($"{UsersPath}/1/active", html);
|
||||||
|
Assert.Contains($"{UsersPath}/7/role{query}", html);
|
||||||
|
Assert.Contains($"{UsersPath}/7/active{query}", html);
|
||||||
|
var token = AntiforgeryToken(html);
|
||||||
|
|
||||||
|
var search = Assert.Single(backend.Requests);
|
||||||
|
Assert.Equal(HttpMethod.Get, search.Method);
|
||||||
|
var filters = QueryHelpers.ParseQuery(search.Uri.Query);
|
||||||
|
Assert.Equal("Novák", filters["q"].ToString());
|
||||||
|
Assert.Equal("STUDENT", filters["role"].ToString());
|
||||||
|
Assert.Equal("2", filters["page"].ToString());
|
||||||
|
|
||||||
|
var updates = new[]
|
||||||
|
{
|
||||||
|
(Endpoint: "role", Field: "newRole", Value: UserRoles.Teacher, Body: """{"role":"TEACHER"}"""),
|
||||||
|
(Endpoint: "active", Field: "isActive", Value: "false", Body: """{"isActive":false}"""),
|
||||||
|
(Endpoint: "active", Field: "isActive", Value: "true", Body: """{"isActive":true}"""),
|
||||||
|
};
|
||||||
|
foreach (var update in updates)
|
||||||
|
{
|
||||||
|
using var form = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["__RequestVerificationToken"] = token,
|
||||||
|
[update.Field] = update.Value,
|
||||||
|
});
|
||||||
|
using var response = await client.PostAsync($"{UsersPath}/7/{update.Endpoint}{query}", form, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||||
|
Assert.Equal(UsersPath + query, response.Headers.Location?.OriginalString);
|
||||||
|
var request = backend.Requests[^1];
|
||||||
|
Assert.Equal(HttpMethod.Put, request.Method);
|
||||||
|
Assert.Equal($"/api/v1{UsersPath}/7/{update.Endpoint}", request.Uri.AbsolutePath);
|
||||||
|
Assert.Equal(update.Body, request.Body);
|
||||||
|
}
|
||||||
|
Assert.Equal(4, backend.Requests.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("role")]
|
||||||
|
[InlineData("active")]
|
||||||
|
public async Task AdministratorUpdatesRequireAntiforgeryToken(string action)
|
||||||
|
{
|
||||||
|
var backend = new AdminUsersBackend();
|
||||||
|
await using var application = CreateApplication(backend);
|
||||||
|
using var client = CreateClient(application);
|
||||||
|
SignIn(application.Services, client, UserRoles.Admin);
|
||||||
|
using var response = await client.PostAsync($"{UsersPath}/7/{action}", null, TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||||
|
Assert.Empty(backend.Requests);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AdminCanSubmitAccountFormsAndConfirmedBulkDeletion()
|
||||||
|
{
|
||||||
|
var backend = new AdminUsersBackend();
|
||||||
|
await using var application = CreateApplication(backend);
|
||||||
|
using var client = CreateClient(application);
|
||||||
|
SignIn(application.Services, client, UserRoles.Admin);
|
||||||
|
var ct = TestContext.Current.CancellationToken;
|
||||||
|
|
||||||
|
using var createPage = await client.GetAsync(UsersPath + "/new", ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, createPage.StatusCode);
|
||||||
|
var page = WebUtility.HtmlDecode(await createPage.Content.ReadAsStringAsync(ct));
|
||||||
|
Assert.Contains("Počáteční heslo", page);
|
||||||
|
Assert.Contains("Ověřit e-mail ručně", page);
|
||||||
|
Assert.Matches("""<input\b(?=[^>]*id="verification-email")(?=[^>]*checked="checked")[^>]*>""", page);
|
||||||
|
Assert.True(page.IndexOf("Správa uživatelů", StringComparison.Ordinal) < page.IndexOf("Swagger API", StringComparison.Ordinal));
|
||||||
|
var fields = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["__RequestVerificationToken"] = AntiforgeryToken(page),
|
||||||
|
["FirstName"] = "Jan",
|
||||||
|
["LastName"] = "Test",
|
||||||
|
["Email"] = "[email protected]",
|
||||||
|
["Role"] = UserRoles.Student,
|
||||||
|
["Password"] = "Initial-password",
|
||||||
|
["IsActive"] = "true",
|
||||||
|
["EmailConfirmed"] = "true",
|
||||||
|
};
|
||||||
|
using var createForm = new FormUrlEncodedContent(fields);
|
||||||
|
using var created = await client.PostAsync(UsersPath + "/new", createForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, created.StatusCode);
|
||||||
|
var createdRequest = Assert.Single(backend.Requests);
|
||||||
|
Assert.Equal(HttpMethod.Post, createdRequest.Method);
|
||||||
|
Assert.Equal("/api/v1/admin/users", createdRequest.Uri.AbsolutePath);
|
||||||
|
Assert.Contains("\"email\":\"[email protected]\"", createdRequest.Body);
|
||||||
|
Assert.Contains("\"emailConfirmed\":true", createdRequest.Body);
|
||||||
|
|
||||||
|
using var editPage = await client.GetAsync(UsersPath + "/7/edit", ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, editPage.StatusCode);
|
||||||
|
var editHtml = await editPage.Content.ReadAsStringAsync(ct);
|
||||||
|
Assert.Contains("[email protected]", editHtml);
|
||||||
|
Assert.Matches("""<input\b(?=[^>]*name="RowVersion")(?=[^>]*value="3")[^>]*>""", editHtml);
|
||||||
|
fields.Remove("Password");
|
||||||
|
fields["RowVersion"] = "3";
|
||||||
|
using var editForm = new FormUrlEncodedContent(fields);
|
||||||
|
using var edited = await client.PostAsync(UsersPath + "/7/edit", editForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, edited.StatusCode);
|
||||||
|
Assert.Equal(HttpMethod.Put, backend.Requests[^1].Method);
|
||||||
|
Assert.Contains("\"password\":null", backend.Requests[^1].Body);
|
||||||
|
Assert.Contains("\"rowVersion\":3", backend.Requests[^1].Body);
|
||||||
|
|
||||||
|
var bulk = new List<KeyValuePair<string, string>>
|
||||||
|
{
|
||||||
|
new("__RequestVerificationToken", fields["__RequestVerificationToken"]),
|
||||||
|
new("action", "delete"),
|
||||||
|
new("userIds", "7"),
|
||||||
|
new("userIds", "8"),
|
||||||
|
};
|
||||||
|
var count = backend.Requests.Count;
|
||||||
|
using var unconfirmedForm = new FormUrlEncodedContent(bulk);
|
||||||
|
using var unconfirmed = await client.PostAsync(UsersPath + "/bulk", unconfirmedForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, unconfirmed.StatusCode);
|
||||||
|
Assert.Equal(count, backend.Requests.Count);
|
||||||
|
|
||||||
|
bulk.Add(new("confirmDelete", "true"));
|
||||||
|
using var confirmedForm = new FormUrlEncodedContent(bulk);
|
||||||
|
using var confirmed = await client.PostAsync(UsersPath + "/bulk", confirmedForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, confirmed.StatusCode);
|
||||||
|
Assert.Equal("/api/v1/admin/users/bulk", backend.Requests[^1].Uri.AbsolutePath);
|
||||||
|
Assert.Contains("\"userIds\":[7,8]", backend.Requests[^1].Body);
|
||||||
|
Assert.Contains("\"action\":\"delete\"", backend.Requests[^1].Body);
|
||||||
|
|
||||||
|
using var singleForm = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["__RequestVerificationToken"] = fields["__RequestVerificationToken"],
|
||||||
|
["confirmDelete"] = "true",
|
||||||
|
});
|
||||||
|
using var deleted = await client.PostAsync(UsersPath + "/7/delete", singleForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, deleted.StatusCode);
|
||||||
|
Assert.Equal(HttpMethod.Delete, backend.Requests[^1].Method);
|
||||||
|
Assert.Equal("/api/v1/admin/users/7", backend.Requests[^1].Uri.AbsolutePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AdminCanResendVerificationAfterCreationSavedAnAccountButDeliveryFailed()
|
||||||
|
{
|
||||||
|
var backend = new AdminUsersBackend(failVerification: true);
|
||||||
|
await using var application = CreateApplication(backend);
|
||||||
|
using var client = CreateClient(application);
|
||||||
|
SignIn(application.Services, client, UserRoles.Admin);
|
||||||
|
var ct = TestContext.Current.CancellationToken;
|
||||||
|
|
||||||
|
using var createPage = await client.GetAsync(UsersPath + "/new", ct);
|
||||||
|
var page = WebUtility.HtmlDecode(await createPage.Content.ReadAsStringAsync(ct));
|
||||||
|
using var createForm = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["__RequestVerificationToken"] = AntiforgeryToken(page),
|
||||||
|
["FirstName"] = "Jan",
|
||||||
|
["LastName"] = "Novák",
|
||||||
|
["Email"] = "[email protected]",
|
||||||
|
["Role"] = UserRoles.Student,
|
||||||
|
["IsActive"] = "true",
|
||||||
|
["EmailConfirmed"] = "false",
|
||||||
|
});
|
||||||
|
using var created = await client.PostAsync(UsersPath + "/new", createForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, created.StatusCode);
|
||||||
|
Assert.StartsWith(UsersPath + "/7/edit", created.Headers.Location?.OriginalString);
|
||||||
|
|
||||||
|
using var editPage = await client.GetAsync(created.Headers.Location, ct);
|
||||||
|
var edit = WebUtility.HtmlDecode(await editPage.Content.ReadAsStringAsync(ct));
|
||||||
|
Assert.Contains("Účet byl založen.", edit);
|
||||||
|
Assert.Contains("Ověřovací e-mail se nepodařilo odeslat.", edit);
|
||||||
|
Assert.Contains("Poslat ověřovací e-mail", edit);
|
||||||
|
|
||||||
|
using var resendForm = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["__RequestVerificationToken"] = AntiforgeryToken(edit),
|
||||||
|
});
|
||||||
|
using var resent = await client.PostAsync(UsersPath + "/7/email-confirmation", resendForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, resent.StatusCode);
|
||||||
|
Assert.Equal((HttpMethod.Post, "/api/v1/admin/users/7/email-confirmation"),
|
||||||
|
(backend.Requests[^1].Method, backend.Requests[^1].Uri.AbsolutePath));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task StaleEditReloadsTheCurrentAccountAndShowsTheConflict()
|
||||||
|
{
|
||||||
|
var backend = new AdminUsersBackend(staleEdit: true);
|
||||||
|
await using var application = CreateApplication(backend);
|
||||||
|
using var client = CreateClient(application);
|
||||||
|
SignIn(application.Services, client, UserRoles.Admin);
|
||||||
|
var ct = TestContext.Current.CancellationToken;
|
||||||
|
using var editPage = await client.GetAsync(UsersPath + "/7/edit", ct);
|
||||||
|
using var form = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["__RequestVerificationToken"] = AntiforgeryToken(await editPage.Content.ReadAsStringAsync(ct)),
|
||||||
|
["FirstName"] = "Jan",
|
||||||
|
["LastName"] = "Novák",
|
||||||
|
["Email"] = "[email protected]",
|
||||||
|
["Role"] = UserRoles.Admin,
|
||||||
|
["RowVersion"] = "2",
|
||||||
|
});
|
||||||
|
|
||||||
|
using var response = await client.PostAsync(UsersPath + "/7/edit?q=Jan", form, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||||
|
Assert.StartsWith(UsersPath + "/7/edit?q=Jan", response.Headers.Location?.OriginalString);
|
||||||
|
Assert.Contains("\"rowVersion\":2", backend.Requests[^1].Body);
|
||||||
|
|
||||||
|
using var fresh = await client.GetAsync(response.Headers.Location, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, fresh.StatusCode);
|
||||||
|
var html = WebUtility.HtmlDecode(await fresh.Content.ReadAsStringAsync(ct));
|
||||||
|
Assert.Contains("Účet se mezitím změnil.", html);
|
||||||
|
Assert.Matches("""<input\b(?=[^>]*name="RowVersion")(?=[^>]*value="3")[^>]*>""", html);
|
||||||
|
Assert.Contains("value=\"STUDENT\" selected=\"selected\"", html);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static WebApplicationFactory<Program> CreateApplication(AdminUsersBackend backend) =>
|
||||||
|
new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||||
|
builder.ConfigureTestServices(services => services.AddHttpClient(nameof(HelpdeskApiClient))
|
||||||
|
.ConfigurePrimaryHttpMessageHandler(() => backend)));
|
||||||
|
|
||||||
|
private static HttpClient CreateClient(WebApplicationFactory<Program> application) =>
|
||||||
|
application.CreateClient(new WebApplicationFactoryClientOptions
|
||||||
|
{
|
||||||
|
AllowAutoRedirect = false,
|
||||||
|
BaseAddress = new Uri("https://localhost"),
|
||||||
|
});
|
||||||
|
|
||||||
|
private sealed class AdminUsersBackend(bool failVerification = false, bool staleEdit = false) : HttpMessageHandler
|
||||||
|
{
|
||||||
|
public List<(HttpMethod Method, Uri Uri, string? Body)> Requests { get; } = [];
|
||||||
|
|
||||||
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
Assert.Equal("test-access", request.Headers.Authorization?.Parameter);
|
||||||
|
var uri = Assert.IsType<Uri>(request.RequestUri);
|
||||||
|
Requests.Add((request.Method, uri, request.Content is null ? null : await request.Content.ReadAsStringAsync(ct)));
|
||||||
|
if (request.Method == HttpMethod.Post && uri.AbsolutePath == "/api/v1/admin/users" && failVerification)
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.Created)
|
||||||
|
{
|
||||||
|
Content = new StringContent("""
|
||||||
|
{"id":7,"email":"[email protected]","firstName":"Jan","lastName":"Novák","role":"STUDENT","isActive":true,"emailConfirmed":false,"emailNotificationsEnabled":true,"verificationEmailSent":false}
|
||||||
|
""", Encoding.UTF8, "application/json"),
|
||||||
|
};
|
||||||
|
if (request.Method == HttpMethod.Put && uri.AbsolutePath == "/api/v1/admin/users/7" && staleEdit)
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.Conflict)
|
||||||
|
{
|
||||||
|
Content = new StringContent("""
|
||||||
|
{"type":"urn:ntbug:account-version-conflict","title":"Účet se mezitím změnil.","status":409}
|
||||||
|
""", Encoding.UTF8, "application/problem+json"),
|
||||||
|
};
|
||||||
|
if (request.Method != HttpMethod.Get)
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.NoContent);
|
||||||
|
|
||||||
|
if (uri.AbsolutePath == "/api/v1/admin/users/7")
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||||
|
{
|
||||||
|
Content = new StringContent("""
|
||||||
|
{"id":7,"email":"[email protected]","firstName":"Jan","lastName":"Novák","role":"STUDENT","isActive":true,"emailConfirmed":false,"emailNotificationsEnabled":true,"rowVersion":3}
|
||||||
|
""", Encoding.UTF8, "application/json"),
|
||||||
|
};
|
||||||
|
|
||||||
|
Assert.Equal("/api/v1" + UsersPath, uri.AbsolutePath);
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||||
|
{
|
||||||
|
Content = new StringContent("""
|
||||||
|
{"items":[
|
||||||
|
{"id":1,"email":"[email protected]","firstName":"Test","lastName":"Admin","role":"ADMIN","isActive":true,"emailConfirmed":true,"createdAt":"2026-10-03T08:00:00Z"},
|
||||||
|
{"id":7,"email":"[email protected]","firstName":"Jan","lastName":"Novák","role":"STUDENT","isActive":false,"emailConfirmed":false,"createdAt":"2026-10-05T08:00:00Z"}
|
||||||
|
],"totalCount":45,"page":2,"pageSize":20}
|
||||||
|
""", Encoding.UTF8, "application/json"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -100,9 +100,9 @@ public class ModelStateExtensionsTests
|
|||||||
var error = new ApiException(HttpStatusCode.BadRequest, "Neplatná vstupní data.",
|
var error = new ApiException(HttpStatusCode.BadRequest, "Neplatná vstupní data.",
|
||||||
new Dictionary<string, string[]> { ["newPassword"] = ["Heslo musí mít alespoň 8 znaků."] });
|
new Dictionary<string, string[]> { ["newPassword"] = ["Heslo musí mít alespoň 8 znaků."] });
|
||||||
|
|
||||||
modelState.AddApiErrors(error, typeof(ResetPasswordViewModel));
|
modelState.AddApiErrors(error, typeof(EmailPasswordViewModel));
|
||||||
|
|
||||||
Assert.Equal("Heslo musí mít alespoň 8 znaků.", modelState[nameof(ResetPasswordViewModel.NewPassword)]!.Errors.Single().ErrorMessage);
|
Assert.Equal("Heslo musí mít alespoň 8 znaků.", modelState[nameof(EmailPasswordViewModel.NewPassword)]!.Errors.Single().ErrorMessage);
|
||||||
Assert.False(modelState.ContainsKey(string.Empty));
|
Assert.False(modelState.ContainsKey(string.Empty));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Helpdesk.Web.Auth;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
|
using Microsoft.AspNetCore.TestHost;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using static Helpdesk.Web.Tests.WebTestSession;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Tests;
|
||||||
|
|
||||||
|
public sealed class IssueActionFormTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData("assign", "/assign")]
|
||||||
|
[InlineData("transition", "/reject")]
|
||||||
|
[InlineData("edit", "")]
|
||||||
|
public async Task IssueActionsRequireAnExplicitValidVersionAndAcceptZero(string action, string apiAction)
|
||||||
|
{
|
||||||
|
var backend = new IssueBackend();
|
||||||
|
await using var application = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||||
|
builder.ConfigureTestServices(services => services.AddHttpClient(nameof(HelpdeskApiClient))
|
||||||
|
.ConfigurePrimaryHttpMessageHandler(() => backend)));
|
||||||
|
using var client = application.CreateClient(new WebApplicationFactoryClientOptions
|
||||||
|
{
|
||||||
|
AllowAutoRedirect = false,
|
||||||
|
BaseAddress = new Uri("https://localhost"),
|
||||||
|
});
|
||||||
|
SignIn(application.Services, client, UserRoles.Admin);
|
||||||
|
var ct = TestContext.Current.CancellationToken;
|
||||||
|
const string detail = "/issues/42";
|
||||||
|
using var page = await client.GetAsync(detail, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, page.StatusCode);
|
||||||
|
var fields = action switch
|
||||||
|
{
|
||||||
|
"assign" => new Dictionary<string, string> { ["AssigneeId"] = "7", ["Priority"] = "HIGH" },
|
||||||
|
"transition" => new Dictionary<string, string> { ["Action"] = IssueActions.Reject, ["Text"] = "Duplicitní hlášení." },
|
||||||
|
_ => new Dictionary<string, string> { ["Title"] = "Projektor", ["Description"] = "Bliká.", ["CategoryId"] = "2" },
|
||||||
|
};
|
||||||
|
fields["__RequestVerificationToken"] = AntiforgeryToken(await page.Content.ReadAsStringAsync(ct));
|
||||||
|
var route = $"{detail}/{action}";
|
||||||
|
|
||||||
|
using (var missing = new FormUrlEncodedContent(fields))
|
||||||
|
using (var response = await client.PostAsync(route + "?RowVersion=0", missing, ct))
|
||||||
|
{
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||||
|
Assert.Equal(detail, response.Headers.Location?.OriginalString);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var invalidVersion in new[] { "", "abc", "-1", "2147483648" })
|
||||||
|
{
|
||||||
|
fields["RowVersion"] = invalidVersion;
|
||||||
|
using var form = new FormUrlEncodedContent(fields);
|
||||||
|
using var response = await client.PostAsync(route, form, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||||
|
Assert.Equal(detail, response.Headers.Location?.OriginalString);
|
||||||
|
}
|
||||||
|
|
||||||
|
fields["RowVersion"] = "0";
|
||||||
|
if (action == "assign")
|
||||||
|
{
|
||||||
|
fields["Priority"] = "UNKNOWN";
|
||||||
|
using var invalid = new FormUrlEncodedContent(fields);
|
||||||
|
using var response = await client.PostAsync(route, invalid, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||||
|
using var next = await client.GetAsync(detail, ct);
|
||||||
|
Assert.Contains("Vyberte platnou prioritu.", WebUtility.HtmlDecode(await next.Content.ReadAsStringAsync(ct)));
|
||||||
|
fields["Priority"] = "HIGH";
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Empty(backend.Writes);
|
||||||
|
using var valid = new FormUrlEncodedContent(fields);
|
||||||
|
using var accepted = await client.PostAsync(route, valid, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, accepted.StatusCode);
|
||||||
|
var saved = Assert.Single(backend.Writes);
|
||||||
|
Assert.Equal("/api/v1/issues/42" + apiAction, saved.Path);
|
||||||
|
Assert.Equal(0, saved.Body.GetProperty("rowVersion").GetInt32());
|
||||||
|
if (action == "assign")
|
||||||
|
Assert.Equal("HIGH", saved.Body.GetProperty("priority").GetString());
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class IssueBackend : HttpMessageHandler
|
||||||
|
{
|
||||||
|
private const string Detail = """
|
||||||
|
{"id":42,"title":"Projektor","description":"Bliká.","categoryId":2,"status":"RECEIVED","priority":"NORMAL",
|
||||||
|
"reporterId":1,"createdAt":"2026-10-03T08:00:00Z","rowVersion":0,"allowedActions":["ASSIGN","REJECT","EDIT"],"attachments":[]}
|
||||||
|
""";
|
||||||
|
|
||||||
|
public List<(string Path, JsonElement Body)> Writes { get; } = [];
|
||||||
|
|
||||||
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var path = request.RequestUri!.AbsolutePath;
|
||||||
|
var detail = path == "/api/v1/issues/42";
|
||||||
|
if (request.Method != HttpMethod.Get)
|
||||||
|
{
|
||||||
|
Writes.Add((path, await request.Content!.ReadFromJsonAsync<JsonElement>(ct)));
|
||||||
|
detail = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||||
|
{
|
||||||
|
Content = new StringContent(detail ? Detail : "[]", Encoding.UTF8, "application/json"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,7 +3,10 @@ using System.Net.Http.Headers;
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Text.Json.Nodes;
|
using System.Text.Json.Nodes;
|
||||||
using Helpdesk.Web.Api;
|
using Helpdesk.Web.Api;
|
||||||
|
using Helpdesk.Web.Controllers;
|
||||||
using Helpdesk.Web.Models;
|
using Helpdesk.Web.Models;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
namespace Helpdesk.Web.Tests;
|
namespace Helpdesk.Web.Tests;
|
||||||
|
|
||||||
@@ -136,6 +139,27 @@ public class IssueActionsApiTests
|
|||||||
Assert.Equal("image/jpeg", file.ContentType);
|
Assert.Equal("image/jpeg", file.ContentType);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("application/pdf", "attachment")]
|
||||||
|
[InlineData("image/png", "inline")]
|
||||||
|
public async Task Web_pdf_stahuje_a_png_zobrazuje_v_prohlizeci(string contentType, string expectedDisposition)
|
||||||
|
{
|
||||||
|
using var handler = new RecordingHandler("", response =>
|
||||||
|
{
|
||||||
|
response.Content = new ByteArrayContent([1]);
|
||||||
|
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
|
||||||
|
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileNameStar = "příloha" };
|
||||||
|
});
|
||||||
|
var context = new DefaultHttpContext();
|
||||||
|
var controller = new IssuesController(Client(handler)) { ControllerContext = new ControllerContext { HttpContext = context } };
|
||||||
|
|
||||||
|
var result = Assert.IsType<FileStreamResult>(await controller.Attachment(9, CancellationToken.None));
|
||||||
|
using var stream = result.FileStream;
|
||||||
|
var disposition = ContentDispositionHeaderValue.Parse(context.Response.Headers.ContentDisposition.ToString());
|
||||||
|
Assert.Equal(expectedDisposition, disposition.DispositionType);
|
||||||
|
Assert.Equal("příloha", disposition.FileNameStar);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Chyby_poli_z_API_se_spoji_do_jedne_zpravy()
|
public void Chyby_poli_z_API_se_spoji_do_jedne_zpravy()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
|
using Microsoft.AspNetCore.TestHost;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using static Helpdesk.Web.Tests.WebTestSession;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Tests;
|
||||||
|
|
||||||
|
public sealed class RegistrationTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task RegistrationOffersToResendAfterTheBackendReportsEmailDeliveryFailure()
|
||||||
|
{
|
||||||
|
var backend = new RegistrationBackend(failFirstDelivery: true);
|
||||||
|
await using var application = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||||
|
builder.ConfigureTestServices(services => services.AddHttpClient(nameof(AuthApiClient))
|
||||||
|
.ConfigurePrimaryHttpMessageHandler(() => backend)));
|
||||||
|
using var client = application.CreateClient(new WebApplicationFactoryClientOptions
|
||||||
|
{
|
||||||
|
AllowAutoRedirect = false,
|
||||||
|
BaseAddress = new Uri("https://localhost"),
|
||||||
|
});
|
||||||
|
var ct = TestContext.Current.CancellationToken;
|
||||||
|
using var registration = await client.GetAsync("/register", ct);
|
||||||
|
var fields = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["__RequestVerificationToken"] = AntiforgeryToken(await registration.Content.ReadAsStringAsync(ct)),
|
||||||
|
["Email"] = "[email protected]",
|
||||||
|
["FirstName"] = "Jan",
|
||||||
|
["LastName"] = "Novák",
|
||||||
|
};
|
||||||
|
using var initial = new FormUrlEncodedContent(fields);
|
||||||
|
using var failed = await client.PostAsync("/register", initial, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, failed.StatusCode);
|
||||||
|
var retryPage = WebUtility.HtmlDecode(await failed.Content.ReadAsStringAsync(ct));
|
||||||
|
Assert.Contains("Účet je uložený.", retryPage);
|
||||||
|
Assert.Contains("Poslat ověřovací e-mail znovu", retryPage);
|
||||||
|
Assert.Contains("value=\"[email protected]\"", retryPage);
|
||||||
|
|
||||||
|
fields["__RequestVerificationToken"] = AntiforgeryToken(retryPage);
|
||||||
|
using var retry = new FormUrlEncodedContent(fields);
|
||||||
|
using var sent = await client.PostAsync("/register", retry, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, sent.StatusCode);
|
||||||
|
Assert.Contains("Ověřte svůj e-mail", WebUtility.HtmlDecode(await sent.Content.ReadAsStringAsync(ct)));
|
||||||
|
Assert.Equal(2, backend.Requests.Count);
|
||||||
|
Assert.Equal(backend.Requests[0].Body.GetRawText(), backend.Requests[1].Body.GetRawText());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task RegistrationRequestsAnEmailAndConfirmationSetsThePassword()
|
||||||
|
{
|
||||||
|
var backend = new RegistrationBackend();
|
||||||
|
await using var application = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||||
|
builder.ConfigureTestServices(services => services.AddHttpClient(nameof(AuthApiClient))
|
||||||
|
.ConfigurePrimaryHttpMessageHandler(() => backend)));
|
||||||
|
using var client = application.CreateClient(new WebApplicationFactoryClientOptions
|
||||||
|
{
|
||||||
|
AllowAutoRedirect = false,
|
||||||
|
BaseAddress = new Uri("https://localhost"),
|
||||||
|
});
|
||||||
|
var ct = TestContext.Current.CancellationToken;
|
||||||
|
|
||||||
|
using var registration = await client.GetAsync("/register", ct);
|
||||||
|
var registerHtml = await registration.Content.ReadAsStringAsync(ct);
|
||||||
|
Assert.DoesNotContain("type=\"password\"", registerHtml);
|
||||||
|
using var registerForm = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["__RequestVerificationToken"] = AntiforgeryToken(registerHtml),
|
||||||
|
["Email"] = "[email protected]",
|
||||||
|
["FirstName"] = "Jan",
|
||||||
|
["LastName"] = "Novák",
|
||||||
|
});
|
||||||
|
using var registered = await client.PostAsync("/register", registerForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, registered.StatusCode);
|
||||||
|
var start = Assert.Single(backend.Requests);
|
||||||
|
Assert.Equal("/api/v1/auth/register", start.Path);
|
||||||
|
Assert.False(start.Body.TryGetProperty("password", out _));
|
||||||
|
|
||||||
|
using var link = await client.GetAsync("/confirm-email?token=email-token", ct);
|
||||||
|
var confirmHtml = await link.Content.ReadAsStringAsync(ct);
|
||||||
|
Assert.Contains("name=\"NewPassword\"", confirmHtml);
|
||||||
|
Assert.Contains("name=\"ConfirmPassword\"", confirmHtml);
|
||||||
|
Assert.Single(backend.Requests);
|
||||||
|
var form = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["__RequestVerificationToken"] = AntiforgeryToken(confirmHtml),
|
||||||
|
["Token"] = "email-token",
|
||||||
|
["NewPassword"] = "Mailbox-owner-password",
|
||||||
|
["ConfirmPassword"] = "Different-password",
|
||||||
|
};
|
||||||
|
using var invalidForm = new FormUrlEncodedContent(form);
|
||||||
|
using var invalid = await client.PostAsync("/confirm-email", invalidForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, invalid.StatusCode);
|
||||||
|
Assert.Contains("Hesla se neshodují.", WebUtility.HtmlDecode(await invalid.Content.ReadAsStringAsync(ct)));
|
||||||
|
Assert.Single(backend.Requests);
|
||||||
|
|
||||||
|
form["ConfirmPassword"] = form["NewPassword"];
|
||||||
|
using var confirmForm = new FormUrlEncodedContent(form);
|
||||||
|
using var confirmed = await client.PostAsync("/confirm-email", confirmForm, ct);
|
||||||
|
Assert.Equal(HttpStatusCode.Redirect, confirmed.StatusCode);
|
||||||
|
Assert.Equal("/login", confirmed.Headers.Location?.OriginalString);
|
||||||
|
var confirmation = backend.Requests[1];
|
||||||
|
Assert.Equal("/api/v1/auth/confirm-email", confirmation.Path);
|
||||||
|
Assert.Equal("email-token", confirmation.Body.GetProperty("token").GetString());
|
||||||
|
Assert.Equal(form["NewPassword"], confirmation.Body.GetProperty("newPassword").GetString());
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class RegistrationBackend(bool failFirstDelivery = false) : HttpMessageHandler
|
||||||
|
{
|
||||||
|
public List<(string Path, JsonElement Body)> Requests { get; } = [];
|
||||||
|
|
||||||
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
Assert.Equal(HttpMethod.Post, request.Method);
|
||||||
|
var path = request.RequestUri!.AbsolutePath;
|
||||||
|
using var json = JsonDocument.Parse(await request.Content!.ReadAsStringAsync(ct));
|
||||||
|
Requests.Add((path, json.RootElement.Clone()));
|
||||||
|
if (path == "/api/v1/auth/confirm-email")
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.NoContent);
|
||||||
|
|
||||||
|
Assert.Equal("/api/v1/auth/register", path);
|
||||||
|
if (failFirstDelivery && Requests.Count == 1)
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
|
||||||
|
{
|
||||||
|
Content = new StringContent("""
|
||||||
|
{"type":"urn:ntbug:email-delivery-failed","title":"E-mail se nepodařilo odeslat.","status":503}
|
||||||
|
""", Encoding.UTF8, "application/problem+json"),
|
||||||
|
};
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.Created)
|
||||||
|
{
|
||||||
|
Content = new StringContent("""
|
||||||
|
{"id":7,"email":"[email protected]","firstName":"Jan","lastName":"Novák","role":"STUDENT","emailNotificationsEnabled":true}
|
||||||
|
""", Encoding.UTF8, "application/json"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,12 +2,10 @@ using System.Net;
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
using Helpdesk.Web.Api;
|
using Helpdesk.Web.Api;
|
||||||
using Helpdesk.Web.Auth;
|
using Helpdesk.Web.Auth;
|
||||||
using Microsoft.AspNetCore.Authentication;
|
|
||||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
|
||||||
using Microsoft.AspNetCore.Mvc.Testing;
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
using Microsoft.AspNetCore.TestHost;
|
using Microsoft.AspNetCore.TestHost;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Options;
|
using static Helpdesk.Web.Tests.WebTestSession;
|
||||||
|
|
||||||
namespace Helpdesk.Web.Tests;
|
namespace Helpdesk.Web.Tests;
|
||||||
|
|
||||||
@@ -59,20 +57,6 @@ public sealed class SwaggerAccessTests
|
|||||||
Assert.True(document.Headers.CacheControl?.NoStore == true);
|
Assert.True(document.Headers.CacheControl?.NoStore == true);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void SignIn(IServiceProvider services, HttpClient client, string role)
|
|
||||||
{
|
|
||||||
var scheme = CookieAuthenticationDefaults.AuthenticationScheme;
|
|
||||||
var options = services.GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>().Get(scheme);
|
|
||||||
var now = DateTimeOffset.UtcNow;
|
|
||||||
var properties = new AuthenticationProperties { IssuedUtc = now, ExpiresUtc = now.AddHours(1) };
|
|
||||||
AuthCookie.StoreTokens(properties, new TokenSet("test-access", now.AddMinutes(15), "test-refresh", now.AddDays(1)));
|
|
||||||
var user = new UserDto(1, "[email protected]", "Test", "User", null, role, true);
|
|
||||||
var ticket = new AuthenticationTicket(AuthCookie.CreatePrincipal(user), properties, scheme);
|
|
||||||
|
|
||||||
client.DefaultRequestHeaders.Remove("Cookie");
|
|
||||||
client.DefaultRequestHeaders.Add("Cookie", $"{AuthCookie.Name}={options.TicketDataFormat.Protect(ticket)}");
|
|
||||||
}
|
|
||||||
|
|
||||||
private sealed class OpenApiBackend : HttpMessageHandler
|
private sealed class OpenApiBackend : HttpMessageHandler
|
||||||
{
|
{
|
||||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Helpdesk.Web.Auth;
|
||||||
|
using Microsoft.AspNetCore.Authentication;
|
||||||
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Tests;
|
||||||
|
|
||||||
|
internal static class WebTestSession
|
||||||
|
{
|
||||||
|
public static string AntiforgeryToken(string html)
|
||||||
|
{
|
||||||
|
var token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value;
|
||||||
|
Assert.NotEmpty(token);
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void SignIn(IServiceProvider services, HttpClient client, string role)
|
||||||
|
{
|
||||||
|
var scheme = CookieAuthenticationDefaults.AuthenticationScheme;
|
||||||
|
var options = services.GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>().Get(scheme);
|
||||||
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
var properties = new AuthenticationProperties { IssuedUtc = now, ExpiresUtc = now.AddHours(1) };
|
||||||
|
AuthCookie.StoreTokens(properties, new TokenSet("test-access", now.AddMinutes(15), "test-refresh", now.AddDays(1)));
|
||||||
|
var user = new UserDto(1, "[email protected]", "Test", "User", null, role, true);
|
||||||
|
var ticket = new AuthenticationTicket(AuthCookie.CreatePrincipal(user), properties, scheme);
|
||||||
|
|
||||||
|
client.DefaultRequestHeaders.Remove("Cookie");
|
||||||
|
client.DefaultRequestHeaders.Add("Cookie", $"{AuthCookie.Name}={options.TicketDataFormat.Protect(ticket)}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,11 +8,12 @@ namespace Helpdesk.Web.Api;
|
|||||||
/// Neúspěšná odpověď API ve formátu ProblemDetails (RFC 9457). Nese stav, titulek
|
/// Neúspěšná odpověď API ve formátu ProblemDetails (RFC 9457). Nese stav, titulek
|
||||||
/// a u validačních chyb seznam chyb podle polí (klíče jsou názvy vlastností v camelCase).
|
/// a u validačních chyb seznam chyb podle polí (klíče jsou názvy vlastností v camelCase).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class ApiException(HttpStatusCode statusCode, string? title, IReadOnlyDictionary<string, string[]> errors)
|
public sealed class ApiException(HttpStatusCode statusCode, string? title, IReadOnlyDictionary<string, string[]> errors, string? problemType = null)
|
||||||
: Exception(title ?? $"API vrátilo stav {(int)statusCode}.")
|
: Exception(title ?? $"API vrátilo stav {(int)statusCode}.")
|
||||||
{
|
{
|
||||||
public HttpStatusCode StatusCode { get; } = statusCode;
|
public HttpStatusCode StatusCode { get; } = statusCode;
|
||||||
public string? Title { get; } = title;
|
public string? Title { get; } = title;
|
||||||
|
public string? ProblemType { get; } = problemType;
|
||||||
public IReadOnlyDictionary<string, string[]> Errors { get; } = errors;
|
public IReadOnlyDictionary<string, string[]> Errors { get; } = errors;
|
||||||
|
|
||||||
/// <summary>Text pro uživatele. API píše titulky chyb česky, kromě odpovědí bez těla (např. 429).</summary>
|
/// <summary>Text pro uživatele. API píše titulky chyb česky, kromě odpovědí bez těla (např. 429).</summary>
|
||||||
@@ -33,6 +34,7 @@ public sealed class ApiException(HttpStatusCode statusCode, string? title, IRead
|
|||||||
public static async Task<ApiException> FromResponseAsync(HttpResponseMessage response, CancellationToken ct)
|
public static async Task<ApiException> FromResponseAsync(HttpResponseMessage response, CancellationToken ct)
|
||||||
{
|
{
|
||||||
string? title = null;
|
string? title = null;
|
||||||
|
string? type = null;
|
||||||
Dictionary<string, string[]> errors = new(StringComparer.OrdinalIgnoreCase);
|
Dictionary<string, string[]> errors = new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
if (response.Content.Headers.ContentType?.MediaType is { } mediaType && mediaType.Contains("json", StringComparison.OrdinalIgnoreCase))
|
if (response.Content.Headers.ContentType?.MediaType is { } mediaType && mediaType.Contains("json", StringComparison.OrdinalIgnoreCase))
|
||||||
@@ -41,6 +43,7 @@ public sealed class ApiException(HttpStatusCode statusCode, string? title, IRead
|
|||||||
{
|
{
|
||||||
var problem = await response.Content.ReadFromJsonAsync<ProblemBody>(ct);
|
var problem = await response.Content.ReadFromJsonAsync<ProblemBody>(ct);
|
||||||
title = problem?.Title;
|
title = problem?.Title;
|
||||||
|
type = problem?.Type;
|
||||||
if (problem?.Errors is { } fieldErrors)
|
if (problem?.Errors is { } fieldErrors)
|
||||||
{
|
{
|
||||||
foreach (var (field, messages) in fieldErrors)
|
foreach (var (field, messages) in fieldErrors)
|
||||||
@@ -53,10 +56,10 @@ public sealed class ApiException(HttpStatusCode statusCode, string? title, IRead
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return new ApiException(response.StatusCode, title, errors);
|
return new ApiException(response.StatusCode, title, errors, type);
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed record ProblemBody(string? Title, Dictionary<string, string[]>? Errors);
|
private sealed record ProblemBody(string? Title, Dictionary<string, string[]>? Errors, string? Type);
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static class ApiResponse
|
internal static class ApiResponse
|
||||||
|
|||||||
@@ -34,11 +34,11 @@ public sealed record TokenSet(
|
|||||||
|
|
||||||
public sealed record LoginRequest(string Email, string Password);
|
public sealed record LoginRequest(string Email, string Password);
|
||||||
|
|
||||||
public sealed record RegisterRequest(string Email, string Password, string FirstName, string LastName);
|
public sealed record RegisterRequest(string Email, string FirstName, string LastName);
|
||||||
|
|
||||||
public sealed record RefreshTokenRequest(string RefreshToken);
|
public sealed record RefreshTokenRequest(string RefreshToken);
|
||||||
|
|
||||||
public sealed record EmailTokenRequest(string Token);
|
public sealed record ConfirmEmailRequest(string Token, string NewPassword);
|
||||||
|
|
||||||
public sealed record ForgotPasswordRequest(string Email);
|
public sealed record ForgotPasswordRequest(string Email);
|
||||||
|
|
||||||
@@ -46,6 +46,19 @@ public sealed record ResetPasswordRequest(string Token, string NewPassword);
|
|||||||
|
|
||||||
public sealed record UpdateProfileRequest(string FirstName, string LastName, string? Phone, bool EmailNotificationsEnabled);
|
public sealed record UpdateProfileRequest(string FirstName, string LastName, string? Phone, bool EmailNotificationsEnabled);
|
||||||
|
|
||||||
|
public sealed record AdminUserDto(
|
||||||
|
int Id, string Email, string FirstName, string LastName, string Role, bool IsActive, bool EmailConfirmed, DateTimeOffset CreatedAt)
|
||||||
|
{
|
||||||
|
public string FullName => $"{FirstName} {LastName}";
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record AdminUserDetailsDto(int Id, string Email, string FirstName, string LastName, string? Phone,
|
||||||
|
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, int RowVersion,
|
||||||
|
bool? VerificationEmailSent = null);
|
||||||
|
|
||||||
|
public sealed record SaveAdminUserRequest(string Email, string FirstName, string LastName, string? Phone,
|
||||||
|
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, string? Password, int? RowVersion);
|
||||||
|
|
||||||
/// <summary>Stránkovaný seznam z API: <c>{ items, totalCount, page, pageSize }</c>.</summary>
|
/// <summary>Stránkovaný seznam z API: <c>{ items, totalCount, page, pageSize }</c>.</summary>
|
||||||
public sealed record PagedResult<T>(IReadOnlyList<T> Items, int TotalCount, int Page, int PageSize)
|
public sealed record PagedResult<T>(IReadOnlyList<T> Items, int TotalCount, int Page, int PageSize)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -22,9 +22,9 @@ public sealed class AuthApiClient(HttpClient http)
|
|||||||
return await ApiResponse.ReadAsync<UserDto>(response, ct);
|
return await ApiResponse.ReadAsync<UserDto>(response, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task ConfirmEmailAsync(string token, CancellationToken ct)
|
public async Task ConfirmEmailAsync(ConfirmEmailRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
using var response = await http.PostAsJsonAsync("auth/confirm-email", new EmailTokenRequest(token), ct);
|
using var response = await http.PostAsJsonAsync("auth/confirm-email", request, ct);
|
||||||
await ApiResponse.EnsureSuccessAsync(response, ct);
|
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
|
using System.Net;
|
||||||
using System.Net.Http.Headers;
|
using System.Net.Http.Headers;
|
||||||
using System.Net.Http.Json;
|
using System.Net.Http.Json;
|
||||||
using Microsoft.AspNetCore.WebUtilities;
|
using Microsoft.AspNetCore.WebUtilities;
|
||||||
@@ -28,6 +29,66 @@ public sealed class HelpdeskApiClient(HttpClient http)
|
|||||||
return await ApiResponse.ReadAsync<UserDto>(response, ct);
|
return await ApiResponse.ReadAsync<UserDto>(response, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<PagedResult<AdminUserDto>> GetAdminUsersAsync(string? q, string? role, int page, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var parameters = new Dictionary<string, string?>
|
||||||
|
{
|
||||||
|
["q"] = q,
|
||||||
|
["role"] = role,
|
||||||
|
["page"] = page.ToString(CultureInfo.InvariantCulture),
|
||||||
|
};
|
||||||
|
using var response = await http.GetAsync(QueryHelpers.AddQueryString("admin/users", parameters), ct);
|
||||||
|
return await ApiResponse.ReadAsync<PagedResult<AdminUserDto>>(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task ChangeUserRoleAsync(int id, string role, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.PutAsJsonAsync(AdminUserPath(id) + "/role", new { role }, ct);
|
||||||
|
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task SetUserActiveAsync(int id, bool isActive, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.PutAsJsonAsync(AdminUserPath(id) + "/active", new { isActive }, ct);
|
||||||
|
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<AdminUserDetailsDto> GetAdminUserAsync(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.GetAsync(AdminUserPath(id), ct);
|
||||||
|
return await ApiResponse.ReadAsync<AdminUserDetailsDto>(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<AdminUserDetailsDto?> SaveAdminUserAsync(int? id, SaveAdminUserRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = id is int userId
|
||||||
|
? await http.PutAsJsonAsync(AdminUserPath(userId), request, ct)
|
||||||
|
: await http.PostAsJsonAsync("admin/users", request, ct);
|
||||||
|
return response.StatusCode == HttpStatusCode.NoContent
|
||||||
|
? null
|
||||||
|
: await ApiResponse.ReadAsync<AdminUserDetailsDto>(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task SendAdminUserEmailConfirmationAsync(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.PostAsync(AdminUserPath(id) + "/email-confirmation", null, ct);
|
||||||
|
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task DeleteAdminUserAsync(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.DeleteAsync(AdminUserPath(id), ct);
|
||||||
|
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task UpdateAdminUsersAsync(int[] userIds, string action, string? role, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var response = await http.PostAsJsonAsync("admin/users/bulk", new { userIds, action, role }, ct);
|
||||||
|
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string AdminUserPath(int id) => $"admin/users/{id.ToString(CultureInfo.InvariantCulture)}";
|
||||||
|
|
||||||
public async Task<PagedResult<IssueSummary>> GetIssuesAsync(IssueListQuery query, CancellationToken ct)
|
public async Task<PagedResult<IssueSummary>> GetIssuesAsync(IssueListQuery query, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var parameters = new Dictionary<string, string?>
|
var parameters = new Dictionary<string, string?>
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ public static class UserRoles
|
|||||||
public const string Management = "MANAGEMENT";
|
public const string Management = "MANAGEMENT";
|
||||||
public const string Admin = "ADMIN";
|
public const string Admin = "ADMIN";
|
||||||
|
|
||||||
|
public static IReadOnlyList<string> All { get; } = [Student, Teacher, FacilityManager, Management, Admin];
|
||||||
|
|
||||||
public static string DisplayName(string? role) => role switch
|
public static string DisplayName(string? role) => role switch
|
||||||
{
|
{
|
||||||
Student => "Student",
|
Student => "Student",
|
||||||
|
|||||||
@@ -44,7 +44,6 @@ public sealed class AccountController(AuthApiClient authApi, HelpdeskApiClient a
|
|||||||
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Unauthorized
|
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Unauthorized
|
||||||
or HttpStatusCode.Forbidden or HttpStatusCode.TooManyRequests)
|
or HttpStatusCode.Forbidden or HttpStatusCode.TooManyRequests)
|
||||||
{
|
{
|
||||||
// 401 špatné heslo / zamčený účet, 403 neověřený e-mail nebo deaktivovaný účet – API vrací český text.
|
|
||||||
ModelState.AddApiErrors(ex, typeof(LoginViewModel));
|
ModelState.AddApiErrors(ex, typeof(LoginViewModel));
|
||||||
model.Password = "";
|
model.Password = "";
|
||||||
return View(model);
|
return View(model);
|
||||||
@@ -66,39 +65,48 @@ public sealed class AccountController(AuthApiClient authApi, HelpdeskApiClient a
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
var user = await authApi.RegisterAsync(
|
var user = await authApi.RegisterAsync(
|
||||||
new RegisterRequest(model.Email.Trim(), model.Password, model.FirstName.Trim(), model.LastName.Trim()), ct);
|
new RegisterRequest(model.Email.Trim(), model.FirstName.Trim(), model.LastName.Trim()), ct);
|
||||||
return View("RegisterDone", user.Email);
|
return View("RegisterDone", user.Email);
|
||||||
}
|
}
|
||||||
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict or HttpStatusCode.TooManyRequests)
|
catch (ApiException ex) when (ex is { StatusCode: HttpStatusCode.ServiceUnavailable, ProblemType: "urn:ntbug:email-delivery-failed" })
|
||||||
|
{
|
||||||
|
ViewData["VerificationEmailFailed"] = true;
|
||||||
|
ModelState.AddModelError(string.Empty, "Účet je uložený. Ověřovací e-mail se nepodařilo odeslat, zkuste ho prosím poslat znovu.");
|
||||||
|
return View(model);
|
||||||
|
}
|
||||||
|
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict
|
||||||
|
or HttpStatusCode.TooManyRequests or HttpStatusCode.ServiceUnavailable)
|
||||||
{
|
{
|
||||||
// 400 cizí doména nebo validace, 409 účet už existuje.
|
|
||||||
ModelState.AddApiErrors(ex, typeof(RegisterViewModel));
|
ModelState.AddApiErrors(ex, typeof(RegisterViewModel));
|
||||||
model.Password = model.ConfirmPassword = "";
|
|
||||||
return View(model);
|
return View(model);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Odkaz z registračního e-mailu. Token se spotřebuje až tlačítkem, ne samotným otevřením odkazu.</summary>
|
/// <summary>Odkaz z ověřovacího e-mailu. Token se spotřebuje při uložení hesla.</summary>
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
[HttpGet("confirm-email")]
|
[HttpGet("confirm-email")]
|
||||||
public IActionResult ConfirmEmail(string? token) => View(new EmailTokenViewModel { Token = token ?? "" });
|
public IActionResult ConfirmEmail(string? token) => View(new EmailPasswordViewModel { Token = token ?? "" });
|
||||||
|
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
[HttpPost("confirm-email")]
|
[HttpPost("confirm-email")]
|
||||||
public async Task<IActionResult> ConfirmEmail(EmailTokenViewModel model, CancellationToken ct)
|
public async Task<IActionResult> ConfirmEmail(EmailPasswordViewModel model, CancellationToken ct)
|
||||||
{
|
{
|
||||||
if (!ModelState.IsValid)
|
if (!ModelState.IsValid)
|
||||||
|
{
|
||||||
|
model.NewPassword = model.ConfirmPassword = "";
|
||||||
return View(model);
|
return View(model);
|
||||||
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await authApi.ConfirmEmailAsync(model.Token, ct);
|
await authApi.ConfirmEmailAsync(new ConfirmEmailRequest(model.Token, model.NewPassword), ct);
|
||||||
TempData.SetSuccess("E-mail je ověřený. Teď se můžete přihlásit.");
|
TempData.SetSuccess("E-mail je ověřený. Teď se můžete přihlásit nastaveným heslem.");
|
||||||
return RedirectToAction(nameof(Login));
|
return RedirectToAction(nameof(Login));
|
||||||
}
|
}
|
||||||
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.TooManyRequests)
|
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.TooManyRequests)
|
||||||
{
|
{
|
||||||
ModelState.AddModelError(string.Empty, ex.UserMessage);
|
ModelState.AddApiErrors(ex, typeof(EmailPasswordViewModel));
|
||||||
|
model.NewPassword = model.ConfirmPassword = "";
|
||||||
return View(model);
|
return View(model);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -128,11 +136,11 @@ public sealed class AccountController(AuthApiClient authApi, HelpdeskApiClient a
|
|||||||
|
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
[HttpGet("reset-password")]
|
[HttpGet("reset-password")]
|
||||||
public IActionResult ResetPassword(string? token) => View(new ResetPasswordViewModel { Token = token ?? "" });
|
public IActionResult ResetPassword(string? token) => View(new EmailPasswordViewModel { Token = token ?? "" });
|
||||||
|
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
[HttpPost("reset-password")]
|
[HttpPost("reset-password")]
|
||||||
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model, CancellationToken ct)
|
public async Task<IActionResult> ResetPassword(EmailPasswordViewModel model, CancellationToken ct)
|
||||||
{
|
{
|
||||||
if (!ModelState.IsValid)
|
if (!ModelState.IsValid)
|
||||||
{
|
{
|
||||||
@@ -146,7 +154,7 @@ public sealed class AccountController(AuthApiClient authApi, HelpdeskApiClient a
|
|||||||
}
|
}
|
||||||
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.TooManyRequests)
|
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.TooManyRequests)
|
||||||
{
|
{
|
||||||
ModelState.AddApiErrors(ex, typeof(ResetPasswordViewModel));
|
ModelState.AddApiErrors(ex, typeof(EmailPasswordViewModel));
|
||||||
model.NewPassword = model.ConfirmPassword = "";
|
model.NewPassword = model.ConfirmPassword = "";
|
||||||
return View(model);
|
return View(model);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,213 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Net;
|
||||||
|
using System.Security.Claims;
|
||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Helpdesk.Web.Auth;
|
||||||
|
using Helpdesk.Web.Infrastructure;
|
||||||
|
using Helpdesk.Web.Models;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Controllers;
|
||||||
|
|
||||||
|
[Authorize(Roles = UserRoles.Admin)]
|
||||||
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||||
|
[Route("admin/users")]
|
||||||
|
public sealed class AdminUsersController(HelpdeskApiClient api) : Controller
|
||||||
|
{
|
||||||
|
[HttpGet("")]
|
||||||
|
public async Task<IActionResult> Index([FromQuery] AdminUsersQuery query, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var q = string.IsNullOrWhiteSpace(query.Q) ? null : query.Q.Trim();
|
||||||
|
var role = query.Role is { } filter && UserRoles.All.Contains(filter) ? filter : null;
|
||||||
|
var users = await api.GetAdminUsersAsync(q, role, Math.Max(1, query.Page), ct);
|
||||||
|
if (users.Items.Count == 0 && users.Page > 1)
|
||||||
|
return BackToList(new AdminUsersQuery(q, role, Math.Max(1, users.PageCount)));
|
||||||
|
|
||||||
|
return View(new AdminUsersViewModel(users, new AdminUsersQuery(q, role, users.Page), CurrentUserId));
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("new")]
|
||||||
|
public IActionResult New([FromQuery] AdminUsersQuery query) => View("Form", new AdminUserForm { Query = query });
|
||||||
|
|
||||||
|
[HttpPost("new")]
|
||||||
|
public Task<IActionResult> New([FromForm] AdminUserForm model, [FromQuery] AdminUsersQuery query, CancellationToken ct) =>
|
||||||
|
SaveAsync(null, model, query, ct);
|
||||||
|
|
||||||
|
[HttpGet("{id:int}/edit")]
|
||||||
|
public async Task<IActionResult> Edit([FromRoute] int id, [FromQuery] AdminUsersQuery query, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (id == CurrentUserId)
|
||||||
|
return RedirectToAction("Index", "Profile");
|
||||||
|
|
||||||
|
var user = await api.GetAdminUserAsync(id, ct);
|
||||||
|
return View("Form", new AdminUserForm
|
||||||
|
{
|
||||||
|
Id = user.Id,
|
||||||
|
Query = query,
|
||||||
|
RowVersion = user.RowVersion,
|
||||||
|
Email = user.Email,
|
||||||
|
FirstName = user.FirstName,
|
||||||
|
LastName = user.LastName,
|
||||||
|
Phone = user.Phone,
|
||||||
|
Role = user.Role,
|
||||||
|
IsActive = user.IsActive,
|
||||||
|
EmailConfirmed = user.EmailConfirmed,
|
||||||
|
EmailNotificationsEnabled = user.EmailNotificationsEnabled,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/edit")]
|
||||||
|
public Task<IActionResult> Edit([FromRoute] int id, [FromForm] AdminUserForm model, [FromQuery] AdminUsersQuery query,
|
||||||
|
CancellationToken ct) => SaveAsync(id, model, query, ct);
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/email-confirmation")]
|
||||||
|
public async Task<IActionResult> SendEmailConfirmation([FromRoute] int id, [FromQuery] AdminUsersQuery query, CancellationToken ct)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await api.SendAdminUserEmailConfirmationAsync(id, ct);
|
||||||
|
TempData.SetSuccess("Ověřovací e-mail byl odeslán.");
|
||||||
|
}
|
||||||
|
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.Conflict or HttpStatusCode.ServiceUnavailable)
|
||||||
|
{
|
||||||
|
TempData.SetError(ex.AllMessages);
|
||||||
|
}
|
||||||
|
|
||||||
|
return BackToEdit(id, query);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/delete")]
|
||||||
|
public async Task<IActionResult> Delete([FromRoute] int id, [FromForm] bool confirmDelete, [FromQuery] AdminUsersQuery query,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (!confirmDelete)
|
||||||
|
{
|
||||||
|
TempData.SetError("Potvrďte smazání účtu.");
|
||||||
|
return BackToEdit(id, query);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await UpdateAsync(query, () => api.DeleteAdminUserAsync(id, ct), "Účet byl smazán a jeho profil anonymizován.");
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("bulk")]
|
||||||
|
public async Task<IActionResult> Bulk([FromForm] int[] userIds, [FromForm] string? action, [FromForm] string? newRole,
|
||||||
|
[FromForm] bool confirmDelete, [FromQuery] AdminUsersQuery query, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (!ModelState.IsValid || userIds is not { Length: >= 1 } ||
|
||||||
|
action is not ("activate" or "deactivate" or "role" or "delete"))
|
||||||
|
{
|
||||||
|
TempData.SetError("Označte účty a vyberte hromadnou akci.");
|
||||||
|
return BackToList(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (action == "delete" && !confirmDelete)
|
||||||
|
{
|
||||||
|
TempData.SetError("Potvrďte smazání vybraných účtů.");
|
||||||
|
return BackToList(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (action == "role" && (newRole is null || !UserRoles.All.Contains(newRole)))
|
||||||
|
{
|
||||||
|
TempData.SetError("Vyberte roli pro označené účty.");
|
||||||
|
return BackToList(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await UpdateAsync(query, () => api.UpdateAdminUsersAsync(userIds, action, newRole, ct), "Hromadná akce byla provedena.");
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/role")]
|
||||||
|
public async Task<IActionResult> ChangeRole([FromRoute] int id, [FromForm] string? newRole, [FromQuery] AdminUsersQuery query,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (newRole is null || !UserRoles.All.Contains(newRole))
|
||||||
|
{
|
||||||
|
TempData.SetError("Vyberte platnou roli.");
|
||||||
|
return BackToList(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await UpdateAsync(query, () => api.ChangeUserRoleAsync(id, newRole, ct), "Role uživatele byla uložena.");
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/active")]
|
||||||
|
public async Task<IActionResult> SetActive([FromRoute] int id, [FromForm] bool? isActive, [FromQuery] AdminUsersQuery query,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (isActive is not bool active)
|
||||||
|
{
|
||||||
|
TempData.SetError("Vyberte stav účtu.");
|
||||||
|
return BackToList(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await UpdateAsync(query, () => api.SetUserActiveAsync(id, active, ct),
|
||||||
|
active ? "Účet byl aktivován." : "Účet byl deaktivován.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<IActionResult> UpdateAsync(AdminUsersQuery query, Func<Task> update, string success)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await update();
|
||||||
|
TempData.SetSuccess(success);
|
||||||
|
}
|
||||||
|
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict or HttpStatusCode.NotFound)
|
||||||
|
{
|
||||||
|
TempData.SetError(ex.AllMessages);
|
||||||
|
}
|
||||||
|
|
||||||
|
return BackToList(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<IActionResult> SaveAsync(int? id, AdminUserForm model, AdminUsersQuery query, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (id is not null && id == CurrentUserId)
|
||||||
|
return RedirectToAction("Index", "Profile");
|
||||||
|
|
||||||
|
if (id is int userId && model.RowVersion is null or < 0)
|
||||||
|
{
|
||||||
|
TempData.SetError("Formulář nemá platnou verzi účtu. Změny zadejte znovu.");
|
||||||
|
return BackToEdit(userId, query);
|
||||||
|
}
|
||||||
|
|
||||||
|
model.Id = id;
|
||||||
|
model.Query = query;
|
||||||
|
if (id is null && model.EmailConfirmed && string.IsNullOrWhiteSpace(model.Password))
|
||||||
|
ModelState.AddModelError(nameof(model.Password), "Při ručním ověření e-mailu zadejte počáteční heslo.");
|
||||||
|
if (ModelState.IsValid)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await api.SaveAdminUserAsync(id, model.ToRequest(), ct);
|
||||||
|
var message = id is null ? "Účet byl založen." : "Změny účtu byly uloženy.";
|
||||||
|
TempData.SetSuccess(result?.VerificationEmailSent == true ? message + " Ověřovací e-mail byl odeslán." : message);
|
||||||
|
if (result is { VerificationEmailSent: false })
|
||||||
|
{
|
||||||
|
TempData.SetError("Ověřovací e-mail se nepodařilo odeslat. Můžete ho poslat znovu.");
|
||||||
|
return BackToEdit(result.Id, query);
|
||||||
|
}
|
||||||
|
return BackToList(query);
|
||||||
|
}
|
||||||
|
catch (ApiException ex) when (id is int editedUserId && ex is
|
||||||
|
{ StatusCode: HttpStatusCode.Conflict, ProblemType: "urn:ntbug:account-version-conflict" })
|
||||||
|
{
|
||||||
|
TempData.SetError(ex.UserMessage);
|
||||||
|
return BackToEdit(editedUserId, query);
|
||||||
|
}
|
||||||
|
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict)
|
||||||
|
{
|
||||||
|
ModelState.AddApiErrors(ex, typeof(AdminUserForm));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return View("Form", model);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int? CurrentUserId =>
|
||||||
|
int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier), CultureInfo.InvariantCulture, out var id) ? id : null;
|
||||||
|
|
||||||
|
private RedirectToActionResult BackToList(AdminUsersQuery query) =>
|
||||||
|
RedirectToAction(nameof(Index), new { q = query.Q, role = query.Role, page = query.Page });
|
||||||
|
|
||||||
|
private RedirectToActionResult BackToEdit(int id, AdminUsersQuery query) =>
|
||||||
|
RedirectToAction(nameof(Edit), new { id, q = query.Q, role = query.Role, page = query.Page });
|
||||||
|
}
|
||||||
@@ -85,11 +85,13 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller
|
|||||||
|
|
||||||
/// <summary>Změna stavu: zahájit, předat k ověření, potvrdit, znovu otevřít, zamítnout (T4 – T9).</summary>
|
/// <summary>Změna stavu: zahájit, předat k ověření, potvrdit, znovu otevřít, zamítnout (T4 – T9).</summary>
|
||||||
[HttpPost("{id:int}/transition")]
|
[HttpPost("{id:int}/transition")]
|
||||||
public async Task<IActionResult> Transition(int id, IssueActionForm form, CancellationToken ct)
|
public async Task<IActionResult> Transition(int id, [FromForm] IssueActionForm form, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var action = form.Action ?? "";
|
var action = form.Action ?? "";
|
||||||
if (IssueActions.TransitionPath(action) is null)
|
if (IssueActions.TransitionPath(action) is null)
|
||||||
return BadRequest();
|
return BadRequest();
|
||||||
|
if (!ModelState.IsValid || form.RowVersion is not int rowVersion || rowVersion < 0)
|
||||||
|
return BackToDetail(id, error: InvalidActionFormMessage);
|
||||||
|
|
||||||
var text = string.IsNullOrWhiteSpace(form.Text) || !IssueActions.AcceptsText(action) ? null : form.Text.Trim();
|
var text = string.IsNullOrWhiteSpace(form.Text) || !IssueActions.AcceptsText(action) ? null : form.Text.Trim();
|
||||||
if (IssueActions.RequiresReason(action) && text is null)
|
if (IssueActions.RequiresReason(action) && text is null)
|
||||||
@@ -97,7 +99,7 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller
|
|||||||
if (text?.Length > IssueActionForm.MaxTextLength)
|
if (text?.Length > IssueActionForm.MaxTextLength)
|
||||||
return BackToDetail(id, error: $"Text může mít nejvýše {IssueActionForm.MaxTextLength} znaků.");
|
return BackToDetail(id, error: $"Text může mít nejvýše {IssueActionForm.MaxTextLength} znaků.");
|
||||||
|
|
||||||
return await RunAsync(id, () => api.TransitionIssueAsync(id, action, form.RowVersion, text, ct), action switch
|
return await RunAsync(id, () => api.TransitionIssueAsync(id, action, rowVersion, text, ct), action switch
|
||||||
{
|
{
|
||||||
IssueActions.StartWork => "Řešení závady je zahájené.",
|
IssueActions.StartWork => "Řešení závady je zahájené.",
|
||||||
IssueActions.SubmitForVerification => "Závada je předaná k ověření. Hlásič potvrdí, jestli je vyřešená.",
|
IssueActions.SubmitForVerification => "Závada je předaná k ověření. Hlásič potvrdí, jestli je vyřešená.",
|
||||||
@@ -109,13 +111,16 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller
|
|||||||
|
|
||||||
/// <summary>Přiřazení nebo přeřazení řešiteli (T2, T3) – jen vedení.</summary>
|
/// <summary>Přiřazení nebo přeřazení řešiteli (T2, T3) – jen vedení.</summary>
|
||||||
[HttpPost("{id:int}/assign")]
|
[HttpPost("{id:int}/assign")]
|
||||||
public async Task<IActionResult> Assign(int id, IssueActionForm form, CancellationToken ct)
|
public async Task<IActionResult> Assign(int id, [FromForm] IssueActionForm form, CancellationToken ct)
|
||||||
{
|
{
|
||||||
|
if (!ModelState.IsValid || form.RowVersion is not int rowVersion || rowVersion < 0)
|
||||||
|
return BackToDetail(id, error: InvalidActionFormMessage);
|
||||||
if (form.AssigneeId is not { } assigneeId)
|
if (form.AssigneeId is not { } assigneeId)
|
||||||
return BackToDetail(id, error: "Vyberte řešitele.");
|
return BackToDetail(id, error: "Vyberte řešitele.");
|
||||||
var priority = IssuePriorities.All.Contains(form.Priority) ? form.Priority : null;
|
if (form.Priority is not null && !IssuePriorities.All.Contains(form.Priority))
|
||||||
|
return BackToDetail(id, error: "Vyberte platnou prioritu.");
|
||||||
|
|
||||||
return await RunAsync(id, () => api.AssignIssueAsync(id, new AssignIssueRequest(assigneeId, priority, form.RowVersion), ct),
|
return await RunAsync(id, () => api.AssignIssueAsync(id, new AssignIssueRequest(assigneeId, form.Priority, rowVersion), ct),
|
||||||
"Závada je přiřazená řešiteli.");
|
"Závada je přiřazená řešiteli.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -174,21 +179,23 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("{id:int}/edit")]
|
[HttpPost("{id:int}/edit")]
|
||||||
public async Task<IActionResult> Edit(int id, EditIssueViewModel model, CancellationToken ct)
|
public async Task<IActionResult> Edit(int id, [FromForm] EditIssueViewModel model, CancellationToken ct)
|
||||||
{
|
{
|
||||||
model.Id = id;
|
model.Id = id;
|
||||||
|
if (model.RowVersion is not int rowVersion || rowVersion < 0)
|
||||||
|
return BackToDetail(id, error: InvalidActionFormMessage);
|
||||||
if (!ModelState.IsValid)
|
if (!ModelState.IsValid)
|
||||||
return View(await WithCatalogsAsync(model, ct));
|
return View(await WithCatalogsAsync(model, ct));
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await api.EditIssueAsync(id, new EditIssueRequest(model.Title.Trim(), model.Description.Trim(), model.CategoryId!.Value,
|
await api.EditIssueAsync(id, new EditIssueRequest(model.Title.Trim(), model.Description.Trim(), model.CategoryId!.Value,
|
||||||
model.BuildingId, model.LocationDetail?.Trim(), model.RowVersion), ct);
|
model.BuildingId, model.LocationDetail?.Trim(), rowVersion), ct);
|
||||||
return BackToDetail(id, success: "Změny hlášení jsou uložené.");
|
return BackToDetail(id, success: "Změny hlášení jsou uložené.");
|
||||||
}
|
}
|
||||||
catch (ApiException ex) when (ex.StatusCode == HttpStatusCode.Conflict)
|
catch (ApiException ex) when (ex.StatusCode == HttpStatusCode.Conflict)
|
||||||
{
|
{
|
||||||
return BackToDetail(id, error: ConflictMessage);
|
return BackToDetail(id, error: ConflictError(ex));
|
||||||
}
|
}
|
||||||
catch (ApiException ex) when (IsUserError(ex))
|
catch (ApiException ex) when (IsUserError(ex))
|
||||||
{
|
{
|
||||||
@@ -197,9 +204,15 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private const string InvalidActionFormMessage =
|
||||||
|
"Formulář obsahuje chybějící nebo neplatné údaje. Zkontrolujte aktuální detail závady a akci zopakujte.";
|
||||||
|
|
||||||
private const string ConflictMessage =
|
private const string ConflictMessage =
|
||||||
"Závadu mezitím někdo změnil. Níže je její aktuální stav – zkontrolujte ho a akci případně zopakujte.";
|
"Závadu mezitím někdo změnil. Níže je její aktuální stav – zkontrolujte ho a akci případně zopakujte.";
|
||||||
|
|
||||||
|
private static string ConflictError(ApiException ex) =>
|
||||||
|
ex.ProblemType == "urn:ntbug:issue-version-conflict" ? ConflictMessage : ex.UserMessage;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Provede akci a vrátí uživatele na detail se zprávou (Post/Redirect/Get). Chyby, které může
|
/// Provede akci a vrátí uživatele na detail se zprávou (Post/Redirect/Get). Chyby, které může
|
||||||
/// uživatel napravit, ukáže nad detailem; 401/403/404 zpracuje <see cref="ApiExceptionFilter"/>.
|
/// uživatel napravit, ukáže nad detailem; 401/403/404 zpracuje <see cref="ApiExceptionFilter"/>.
|
||||||
@@ -213,8 +226,7 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller
|
|||||||
}
|
}
|
||||||
catch (ApiException ex) when (ex.StatusCode == HttpStatusCode.Conflict)
|
catch (ApiException ex) when (ex.StatusCode == HttpStatusCode.Conflict)
|
||||||
{
|
{
|
||||||
// 409: jiná rowVersion (někdo závadu mezitím změnil), nebo akce v aktuálním stavu už nejde.
|
return BackToDetail(id, error: ConflictError(ex));
|
||||||
return BackToDetail(id, error: ConflictMessage);
|
|
||||||
}
|
}
|
||||||
catch (ApiException ex) when (IsUserError(ex))
|
catch (ApiException ex) when (IsUserError(ex))
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
MINOR = nová část aplikace (závady, návrhy, …), PATCH = opravy.
|
MINOR = nová část aplikace (závady, návrhy, …), PATCH = opravy.
|
||||||
Zobrazuje se v patičce; při sestavení z Gitu se k ní přidá krátký hash commitu.
|
Zobrazuje se v patičce; při sestavení z Gitu se k ní přidá krátký hash commitu.
|
||||||
-->
|
-->
|
||||||
<Version>0.2.0</Version>
|
<Version>0.3.0</Version>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using Helpdesk.Web.Auth;
|
|
||||||
|
|
||||||
namespace Helpdesk.Web.Infrastructure;
|
namespace Helpdesk.Web.Infrastructure;
|
||||||
|
|
||||||
|
|||||||
@@ -43,25 +43,6 @@ public sealed class RegisterViewModel
|
|||||||
[StringLength(100, ErrorMessage = "Příjmení může mít nejvýše 100 znaků.")]
|
[StringLength(100, ErrorMessage = "Příjmení může mít nejvýše 100 znaků.")]
|
||||||
[Display(Name = "Příjmení")]
|
[Display(Name = "Příjmení")]
|
||||||
public string LastName { get; set; } = "";
|
public string LastName { get; set; } = "";
|
||||||
|
|
||||||
[Required(ErrorMessage = "Zadejte heslo.")]
|
|
||||||
[StringLength(PasswordRules.MaxLength, MinimumLength = PasswordRules.MinLength, ErrorMessage = PasswordRules.LengthMessage)]
|
|
||||||
[DataType(DataType.Password)]
|
|
||||||
[Display(Name = "Heslo")]
|
|
||||||
public string Password { get; set; } = "";
|
|
||||||
|
|
||||||
[Required(ErrorMessage = "Zadejte heslo znovu.")]
|
|
||||||
[Compare(nameof(Password), ErrorMessage = "Hesla se neshodují.")]
|
|
||||||
[DataType(DataType.Password)]
|
|
||||||
[Display(Name = "Heslo znovu")]
|
|
||||||
public string ConfirmPassword { get; set; } = "";
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Stránka z odkazu v e-mailu – token se odešle až tlačítkem.</summary>
|
|
||||||
public sealed class EmailTokenViewModel
|
|
||||||
{
|
|
||||||
[Required]
|
|
||||||
public string Token { get; set; } = "";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class ForgotPasswordViewModel
|
public sealed class ForgotPasswordViewModel
|
||||||
@@ -72,7 +53,7 @@ public sealed class ForgotPasswordViewModel
|
|||||||
public string Email { get; set; } = "";
|
public string Email { get; set; } = "";
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class ResetPasswordViewModel
|
public sealed class EmailPasswordViewModel
|
||||||
{
|
{
|
||||||
[Required]
|
[Required]
|
||||||
public string Token { get; set; } = "";
|
public string Token { get; set; } = "";
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using Helpdesk.Web.Api;
|
||||||
|
using Helpdesk.Web.Auth;
|
||||||
|
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||||
|
|
||||||
|
namespace Helpdesk.Web.Models;
|
||||||
|
|
||||||
|
public sealed record AdminUsersViewModel(PagedResult<AdminUserDto> Users, AdminUsersQuery Query, int? CurrentUserId);
|
||||||
|
|
||||||
|
public sealed record AdminUsersQuery(string? Q = null, string? Role = null, int Page = 1);
|
||||||
|
|
||||||
|
public sealed class AdminUserForm
|
||||||
|
{
|
||||||
|
[BindNever]
|
||||||
|
public int? Id { get; set; }
|
||||||
|
|
||||||
|
[BindNever]
|
||||||
|
public AdminUsersQuery Query { get; set; } = new();
|
||||||
|
|
||||||
|
public int? RowVersion { get; set; }
|
||||||
|
|
||||||
|
[Display(Name = "Jméno"), Required(ErrorMessage = "Zadejte jméno."), StringLength(100)]
|
||||||
|
public string FirstName { get; set; } = "";
|
||||||
|
|
||||||
|
[Display(Name = "Příjmení"), Required(ErrorMessage = "Zadejte příjmení."), StringLength(100)]
|
||||||
|
public string LastName { get; set; } = "";
|
||||||
|
|
||||||
|
[Display(Name = "E-mail"), Required(ErrorMessage = "Zadejte e-mail."), EmailAddress(ErrorMessage = "Zadejte platný e-mail."), StringLength(254)]
|
||||||
|
public string Email { get; set; } = "";
|
||||||
|
|
||||||
|
[Display(Name = "Telefon"), StringLength(30)]
|
||||||
|
public string? Phone { get; set; }
|
||||||
|
|
||||||
|
[Display(Name = "Role"), Required(ErrorMessage = "Vyberte roli.")]
|
||||||
|
public string Role { get; set; } = UserRoles.Student;
|
||||||
|
|
||||||
|
[Display(Name = "Heslo"), DataType(DataType.Password)]
|
||||||
|
[StringLength(PasswordRules.MaxLength, MinimumLength = PasswordRules.MinLength, ErrorMessage = PasswordRules.LengthMessage)]
|
||||||
|
public string? Password { get; set; }
|
||||||
|
|
||||||
|
[Display(Name = "Aktivní účet")]
|
||||||
|
public bool IsActive { get; set; } = true;
|
||||||
|
|
||||||
|
[Display(Name = "E-mail je ověřený")]
|
||||||
|
public bool EmailConfirmed { get; set; }
|
||||||
|
|
||||||
|
[Display(Name = "E-mailové notifikace")]
|
||||||
|
public bool EmailNotificationsEnabled { get; set; } = true;
|
||||||
|
|
||||||
|
public SaveAdminUserRequest ToRequest() => new(Email.Trim(), FirstName.Trim(), LastName.Trim(), Phone,
|
||||||
|
Role, IsActive, EmailConfirmed, EmailNotificationsEnabled, Password, RowVersion);
|
||||||
|
}
|
||||||
@@ -53,7 +53,7 @@ public sealed class IssueDetailViewModel
|
|||||||
};
|
};
|
||||||
|
|
||||||
/// <summary>Fotky a PDF otevře prohlížeč rovnou, ostatní (DOCX, HEIC) se stáhnou.</summary>
|
/// <summary>Fotky a PDF otevře prohlížeč rovnou, ostatní (DOCX, HEIC) se stáhnou.</summary>
|
||||||
public static bool OpensInBrowser(string contentType) => contentType is "image/jpeg" or "image/png" or "application/pdf";
|
public static bool OpensInBrowser(string contentType) => contentType is "image/jpeg" or "image/png";
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class IssueEventTypes
|
public static class IssueEventTypes
|
||||||
@@ -97,7 +97,7 @@ public sealed record TimelineEntry(IssueEventDto Event, string Text, string? Not
|
|||||||
/// <summary>Formuláře akcí na detailu závady. Každý POST použije jen svá pole.</summary>
|
/// <summary>Formuláře akcí na detailu závady. Každý POST použije jen svá pole.</summary>
|
||||||
public sealed class IssueActionForm
|
public sealed class IssueActionForm
|
||||||
{
|
{
|
||||||
public int RowVersion { get; set; }
|
public int? RowVersion { get; set; }
|
||||||
public string? Action { get; set; }
|
public string? Action { get; set; }
|
||||||
|
|
||||||
/// <summary>Důvod (zamítnutí, znovuotevření) nebo poznámka (předání k ověření).</summary>
|
/// <summary>Důvod (zamítnutí, znovuotevření) nebo poznámka (předání k ověření).</summary>
|
||||||
|
|||||||
@@ -85,7 +85,7 @@ public sealed class EditIssueViewModel : IssueFormViewModel
|
|||||||
public int Id { get; set; }
|
public int Id { get; set; }
|
||||||
|
|
||||||
/// <summary>Verze, kterou uživatel upravuje; když se závada mezitím změní, API vrátí 409.</summary>
|
/// <summary>Verze, kterou uživatel upravuje; když se závada mezitím změní, API vrátí 409.</summary>
|
||||||
public int RowVersion { get; set; }
|
public int? RowVersion { get; set; }
|
||||||
|
|
||||||
public static EditIssueViewModel From(IssueDetail issue) => new()
|
public static EditIssueViewModel From(IssueDetail issue) => new()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,27 +1,28 @@
|
|||||||
@model EmailTokenViewModel
|
@model EmailPasswordViewModel
|
||||||
@{
|
@{
|
||||||
ViewData["Title"] = "Ověření e-mailu";
|
ViewData["Title"] = "Ověření e-mailu";
|
||||||
var failed = !ViewData.ModelState.IsValid || string.IsNullOrEmpty(Model.Token);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
<section class="app-auth">
|
<section class="app-auth">
|
||||||
<h1>Ověření e-mailu</h1>
|
<h1>Ověření e-mailu</h1>
|
||||||
<div class="app-card">
|
<div class="app-card">
|
||||||
@if (failed)
|
@if (string.IsNullOrEmpty(Model.Token))
|
||||||
{
|
{
|
||||||
<partial name="_FormErrors" />
|
<p class="mb-0">Odkaz je neúplný. Otevřete ho prosím znovu z e-mailu.</p>
|
||||||
<p class="mb-0">Odkaz je neplatný, už byl použit, nebo vypršel. Pokud jste e-mail už ověřili, stačí se přihlásit.</p>
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
<p>Dokončete registraci potvrzením svého e-mailu.</p>
|
<p>Nastavením hesla ověříte svůj e-mail.</p>
|
||||||
<form method="post" asp-action="ConfirmEmail">
|
<partial name="_FormErrors" />
|
||||||
|
<form method="post" asp-action="ConfirmEmail" novalidate>
|
||||||
<input type="hidden" asp-for="Token" />
|
<input type="hidden" asp-for="Token" />
|
||||||
<button type="submit" class="btn btn-primary w-100">Ověřit e-mail</button>
|
<partial name="_NewPasswordFields" />
|
||||||
|
<button type="submit" class="btn btn-primary w-100">Ověřit e-mail a nastavit heslo</button>
|
||||||
</form>
|
</form>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
<div class="app-auth-links">
|
<div class="app-auth-links">
|
||||||
|
<a asp-action="Register">Poslat nový ověřovací odkaz</a>
|
||||||
<a asp-action="Login">Přejít na přihlášení</a>
|
<a asp-action="Login">Přejít na přihlášení</a>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
@model RegisterViewModel
|
@model RegisterViewModel
|
||||||
@{
|
@{
|
||||||
ViewData["Title"] = "Registrace";
|
ViewData["Title"] = "Registrace";
|
||||||
|
var resend = ViewData["VerificationEmailFailed"] is true;
|
||||||
}
|
}
|
||||||
|
|
||||||
<section class="app-auth">
|
<section class="app-auth">
|
||||||
@@ -27,18 +28,7 @@
|
|||||||
<span asp-validation-for="LastName" class="invalid-feedback d-block"></span>
|
<span asp-validation-for="LastName" class="invalid-feedback d-block"></span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="mb-3">
|
<button type="submit" class="btn btn-primary w-100">@(resend ? "Poslat ověřovací e-mail znovu" : "Poslat ověřovací e-mail")</button>
|
||||||
<label asp-for="Password" class="form-label"></label>
|
|
||||||
<input asp-for="Password" class="form-control" autocomplete="new-password" aria-describedby="passwordHelp" />
|
|
||||||
<div id="passwordHelp" class="form-text">8 až 64 znaků.</div>
|
|
||||||
<span asp-validation-for="Password" class="invalid-feedback d-block"></span>
|
|
||||||
</div>
|
|
||||||
<div class="mb-4">
|
|
||||||
<label asp-for="ConfirmPassword" class="form-label"></label>
|
|
||||||
<input asp-for="ConfirmPassword" class="form-control" autocomplete="new-password" />
|
|
||||||
<span asp-validation-for="ConfirmPassword" class="invalid-feedback d-block"></span>
|
|
||||||
</div>
|
|
||||||
<button type="submit" class="btn btn-primary w-100">Zaregistrovat se</button>
|
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
<h1>Ověřte svůj e-mail</h1>
|
<h1>Ověřte svůj e-mail</h1>
|
||||||
<div class="app-card">
|
<div class="app-card">
|
||||||
<p>Na adresu <strong>@Model</strong> jsme poslali odkaz pro ověření e-mailu. Platí 24 hodin.</p>
|
<p>Na adresu <strong>@Model</strong> jsme poslali odkaz pro ověření e-mailu. Platí 24 hodin.</p>
|
||||||
<p class="mb-0 text-body-secondary">Po ověření se budete moct přihlásit. Pokud e-mail nevidíte, podívejte se i do nevyžádané pošty.</p>
|
<p class="mb-0 text-body-secondary">Po otevření odkazu si nastavíte heslo k účtu. Pokud e-mail nevidíte, podívejte se i do nevyžádané pošty.</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="app-auth-links">
|
<div class="app-auth-links">
|
||||||
<a asp-action="Login">Zpět na přihlášení</a>
|
<a asp-action="Login">Zpět na přihlášení</a>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
@model ResetPasswordViewModel
|
@model EmailPasswordViewModel
|
||||||
@{
|
@{
|
||||||
ViewData["Title"] = "Nové heslo";
|
ViewData["Title"] = "Nové heslo";
|
||||||
}
|
}
|
||||||
@@ -16,17 +16,8 @@
|
|||||||
<partial name="_FormErrors" />
|
<partial name="_FormErrors" />
|
||||||
<form method="post" asp-action="ResetPassword" novalidate>
|
<form method="post" asp-action="ResetPassword" novalidate>
|
||||||
<input type="hidden" asp-for="Token" />
|
<input type="hidden" asp-for="Token" />
|
||||||
<div class="mb-3">
|
<partial name="_NewPasswordFields" />
|
||||||
<label asp-for="NewPassword" class="form-label"></label>
|
<p class="form-text">Po změně hesla budete odhlášeni na všech zařízeních.</p>
|
||||||
<input asp-for="NewPassword" class="form-control" autocomplete="new-password" autofocus aria-describedby="passwordHelp" />
|
|
||||||
<div id="passwordHelp" class="form-text">8 až 64 znaků. Po změně budete odhlášeni na všech zařízeních.</div>
|
|
||||||
<span asp-validation-for="NewPassword" class="invalid-feedback d-block"></span>
|
|
||||||
</div>
|
|
||||||
<div class="mb-4">
|
|
||||||
<label asp-for="ConfirmPassword" class="form-label"></label>
|
|
||||||
<input asp-for="ConfirmPassword" class="form-control" autocomplete="new-password" />
|
|
||||||
<span asp-validation-for="ConfirmPassword" class="invalid-feedback d-block"></span>
|
|
||||||
</div>
|
|
||||||
<button type="submit" class="btn btn-primary w-100">Nastavit heslo</button>
|
<button type="submit" class="btn btn-primary w-100">Nastavit heslo</button>
|
||||||
</form>
|
</form>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
@model EmailPasswordViewModel
|
||||||
|
|
||||||
|
<div class="mb-3">
|
||||||
|
<label asp-for="NewPassword" class="form-label"></label>
|
||||||
|
<input asp-for="NewPassword" class="form-control" autocomplete="new-password" autofocus aria-describedby="passwordHelp" />
|
||||||
|
<div id="passwordHelp" class="form-text">8 až 64 znaků.</div>
|
||||||
|
<span asp-validation-for="NewPassword" class="invalid-feedback d-block"></span>
|
||||||
|
</div>
|
||||||
|
<div class="mb-4">
|
||||||
|
<label asp-for="ConfirmPassword" class="form-label"></label>
|
||||||
|
<input asp-for="ConfirmPassword" class="form-control" autocomplete="new-password" />
|
||||||
|
<span asp-validation-for="ConfirmPassword" class="invalid-feedback d-block"></span>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
@model AdminUserForm
|
||||||
|
@{
|
||||||
|
var isNew = Model.Id is null;
|
||||||
|
ViewData["Title"] = isNew ? "Založit účet" : "Upravit účet";
|
||||||
|
var query = Model.Query;
|
||||||
|
}
|
||||||
|
|
||||||
|
<section class="app-page-head">
|
||||||
|
<a class="app-back-link" asp-action="Index" asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@query.Page">Správa uživatelů</a>
|
||||||
|
<h1 class="mt-2 mb-0">@ViewData["Title"]</h1>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="row g-4">
|
||||||
|
<div class="col-lg-8">
|
||||||
|
<div class="app-card">
|
||||||
|
<partial name="_FormErrors" />
|
||||||
|
<form method="post" asp-action="@(isNew ? "New" : "Edit")" asp-route-id="@Model.Id"
|
||||||
|
asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@query.Page" novalidate>
|
||||||
|
@if (!isNew)
|
||||||
|
{
|
||||||
|
<input asp-for="RowVersion" type="hidden" />
|
||||||
|
}
|
||||||
|
<div class="row g-3 mb-4">
|
||||||
|
<div class="col-sm-6">
|
||||||
|
<label asp-for="FirstName" class="form-label"></label>
|
||||||
|
<input asp-for="FirstName" class="form-control" />
|
||||||
|
<span asp-validation-for="FirstName" class="invalid-feedback d-block"></span>
|
||||||
|
</div>
|
||||||
|
<div class="col-sm-6">
|
||||||
|
<label asp-for="LastName" class="form-label"></label>
|
||||||
|
<input asp-for="LastName" class="form-control" />
|
||||||
|
<span asp-validation-for="LastName" class="invalid-feedback d-block"></span>
|
||||||
|
</div>
|
||||||
|
<div class="col-sm-6">
|
||||||
|
<label asp-for="Email" class="form-label"></label>
|
||||||
|
<input asp-for="Email" class="form-control" data-admin-email="@(!isNew ? "" : null)" />
|
||||||
|
<span asp-validation-for="Email" class="invalid-feedback d-block"></span>
|
||||||
|
</div>
|
||||||
|
<div class="col-sm-6">
|
||||||
|
<label asp-for="Phone" class="form-label"></label>
|
||||||
|
<input asp-for="Phone" class="form-control" type="tel" />
|
||||||
|
<span asp-validation-for="Phone" class="invalid-feedback d-block"></span>
|
||||||
|
</div>
|
||||||
|
<div class="col-sm-6">
|
||||||
|
<label asp-for="Role" class="form-label"></label>
|
||||||
|
<select asp-for="Role" class="form-select">
|
||||||
|
@foreach (var role in UserRoles.All)
|
||||||
|
{
|
||||||
|
<option value="@role">@UserRoles.DisplayName(role)</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
<span asp-validation-for="Role" class="invalid-feedback d-block"></span>
|
||||||
|
</div>
|
||||||
|
<div class="col-sm-6">
|
||||||
|
<label asp-for="Password" class="form-label">@(isNew ? "Počáteční heslo" : "Nové heslo")</label>
|
||||||
|
<input asp-for="Password" class="form-control" autocomplete="new-password" />
|
||||||
|
@if (isNew)
|
||||||
|
{
|
||||||
|
<div class="form-text">Heslo vyplňte při ručním ověření e-mailu.</div>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="form-text">Prázdné pole ponechá stávající heslo.</div>
|
||||||
|
}
|
||||||
|
<span asp-validation-for="Password" class="invalid-feedback d-block"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-check">
|
||||||
|
<input asp-for="IsActive" class="form-check-input" />
|
||||||
|
<label asp-for="IsActive" class="form-check-label"></label>
|
||||||
|
</div>
|
||||||
|
@if (isNew)
|
||||||
|
{
|
||||||
|
<fieldset class="mt-3 mb-3">
|
||||||
|
<legend class="form-label fs-6">Jak ověřit e-mail</legend>
|
||||||
|
<div class="form-check">
|
||||||
|
<input asp-for="EmailConfirmed" type="radio" value="false" id="verification-email" class="form-check-input" />
|
||||||
|
<label for="verification-email" class="form-check-label">Poslat ověřovací e-mail</label>
|
||||||
|
</div>
|
||||||
|
<div class="form-check">
|
||||||
|
<input asp-for="EmailConfirmed" type="radio" value="true" id="verification-direct" class="form-check-input" />
|
||||||
|
<label for="verification-direct" class="form-check-label">Ověřit e-mail ručně</label>
|
||||||
|
</div>
|
||||||
|
<p class="form-text mb-0">Aktivnímu účtu pošleme odkaz pro nastavení hesla. Při ručním ověření se aktivní uživatel může přihlásit hned.</p>
|
||||||
|
</fieldset>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="form-check">
|
||||||
|
<input asp-for="EmailConfirmed" class="form-check-input" />
|
||||||
|
<label asp-for="EmailConfirmed" class="form-check-label"></label>
|
||||||
|
<p class="form-text mb-2">Při změně adresy se ověření obnoví. Aktivnímu účtu pošleme odkaz na novou adresu.</p>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
<div class="form-check mb-4">
|
||||||
|
<input asp-for="EmailNotificationsEnabled" class="form-check-input" />
|
||||||
|
<label asp-for="EmailNotificationsEnabled" class="form-check-label"></label>
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="btn btn-primary">@(isNew ? "Založit účet" : "Uložit změny")</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@if (!isNew)
|
||||||
|
{
|
||||||
|
<div class="col-lg-4">
|
||||||
|
@if (Model.IsActive && !Model.EmailConfirmed)
|
||||||
|
{
|
||||||
|
<section class="app-card mb-4">
|
||||||
|
<h2 class="h6 fw-bold">Ověření e-mailu</h2>
|
||||||
|
<form method="post" asp-action="SendEmailConfirmation" asp-route-id="@Model.Id"
|
||||||
|
asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@query.Page">
|
||||||
|
<button type="submit" class="btn btn-outline-primary">Poslat ověřovací e-mail</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
<section class="app-card">
|
||||||
|
<h2 class="h6 fw-bold">Smazat účet</h2>
|
||||||
|
<p class="text-body-secondary">Účet ztratí přístup a jeho profil se nevratně anonymizuje. Historie hlášení a návrhů zůstane.</p>
|
||||||
|
<form method="post" asp-action="Delete" asp-route-id="@Model.Id"
|
||||||
|
asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@query.Page">
|
||||||
|
<div class="form-check mb-3">
|
||||||
|
<input id="confirm-delete" name="confirmDelete" type="checkbox" value="true" class="form-check-input" required />
|
||||||
|
<label for="confirm-delete" class="form-check-label">Potvrzuji smazání účtu</label>
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="btn btn-outline-danger">Smazat účet</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
@model AdminUsersViewModel
|
||||||
|
@{
|
||||||
|
ViewData["Title"] = "Správa uživatelů";
|
||||||
|
var result = Model.Users;
|
||||||
|
var query = Model.Query;
|
||||||
|
}
|
||||||
|
|
||||||
|
<section class="app-page-head d-flex flex-wrap justify-content-between align-items-center gap-2">
|
||||||
|
<h1 class="mb-0">Správa uživatelů</h1>
|
||||||
|
<a asp-action="New" asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@query.Page"
|
||||||
|
class="btn btn-primary">Založit účet</a>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<form method="get" asp-action="Index" class="app-card mb-4" role="search" aria-label="Vyhledávání uživatelů">
|
||||||
|
<div class="row g-3 align-items-end">
|
||||||
|
<div class="col-12 col-md-5">
|
||||||
|
<label for="q" class="form-label">Jméno nebo e-mail</label>
|
||||||
|
<input id="q" name="q" type="search" value="@query.Q" class="form-control" />
|
||||||
|
</div>
|
||||||
|
<div class="col-12 col-sm-6 col-md-3">
|
||||||
|
<label for="role" class="form-label">Role</label>
|
||||||
|
<select id="role" name="role" class="form-select">
|
||||||
|
<option value="">Všechny role</option>
|
||||||
|
@foreach (var role in UserRoles.All)
|
||||||
|
{
|
||||||
|
<option value="@role" selected="@(role == query.Role)">@UserRoles.DisplayName(role)</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="col-12 col-sm-auto d-flex flex-wrap gap-2">
|
||||||
|
<button type="submit" class="btn btn-primary">Vyhledat</button>
|
||||||
|
@if (query.Q is not null || query.Role is not null)
|
||||||
|
{
|
||||||
|
<a asp-action="Index" class="btn btn-outline-secondary">Zrušit filtry</a>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
@if (result.Items.Count == 0)
|
||||||
|
{
|
||||||
|
<div class="app-card app-empty-card">
|
||||||
|
<p class="mb-0">Žádní uživatelé k zobrazení.</p>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
@if (result.Items.Any(user => user.Id != Model.CurrentUserId))
|
||||||
|
{
|
||||||
|
<form id="user-bulk" method="post" asp-action="Bulk"
|
||||||
|
asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@query.Page"
|
||||||
|
class="app-card mb-3 py-3" data-user-bulk>
|
||||||
|
<div class="d-flex flex-wrap gap-3 align-items-end">
|
||||||
|
<div class="form-check">
|
||||||
|
<input type="checkbox" class="form-check-input" id="select-page" data-user-select-page />
|
||||||
|
<label class="form-check-label" for="select-page">Vybrat vše na stránce</label>
|
||||||
|
<span class="d-block small text-body-secondary" data-user-count aria-live="polite"></span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="form-label" for="bulk-action">Hromadná akce</label>
|
||||||
|
<select class="form-select" id="bulk-action" name="action" required data-user-action>
|
||||||
|
<option value="">Vyberte akci</option>
|
||||||
|
<option value="activate">Aktivovat</option>
|
||||||
|
<option value="deactivate">Deaktivovat</option>
|
||||||
|
<option value="role">Změnit roli</option>
|
||||||
|
<option value="delete">Smazat</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div data-user-bulk-role>
|
||||||
|
<label class="form-label" for="bulk-role">Nová role při změně role</label>
|
||||||
|
<select class="form-select" id="bulk-role" name="newRole">
|
||||||
|
<option value="">Vyberte roli</option>
|
||||||
|
@foreach (var role in UserRoles.All)
|
||||||
|
{
|
||||||
|
<option value="@role">@UserRoles.DisplayName(role)</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="btn btn-outline-primary">Provést akci</button>
|
||||||
|
</div>
|
||||||
|
<div class="mt-3" data-user-bulk-delete>
|
||||||
|
<div class="form-check">
|
||||||
|
<input name="confirmDelete" value="true" type="checkbox" class="form-check-input" id="confirm-bulk-delete" />
|
||||||
|
<label class="form-check-label" for="confirm-bulk-delete">Potvrzuji smazání vybraných účtů</label>
|
||||||
|
</div>
|
||||||
|
<p class="form-text mb-0">Účty ztratí přístup a jejich profily se anonymizují. Historie hlášení a návrhů zůstane.</p>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
|
||||||
|
<ul class="list-unstyled d-grid gap-2 mb-0">
|
||||||
|
@foreach (var user in result.Items)
|
||||||
|
{
|
||||||
|
<li class="app-card px-3 px-sm-4 py-3">
|
||||||
|
<div class="row g-3 align-items-center">
|
||||||
|
<div class="col-12 col-lg-4">
|
||||||
|
<div class="d-flex align-items-center gap-2">
|
||||||
|
@if (user.Id != Model.CurrentUserId)
|
||||||
|
{
|
||||||
|
<input name="userIds" value="@user.Id" type="checkbox" class="form-check-input mt-0"
|
||||||
|
form="user-bulk" aria-label="Označit účet @user.Email" />
|
||||||
|
}
|
||||||
|
<h2 class="h6 fw-bold text-break mb-1">@user.FullName</h2>
|
||||||
|
</div>
|
||||||
|
<div class="small text-body-secondary text-break">@user.Email</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-12 col-sm-5 col-lg-3">
|
||||||
|
<span class="status-badge @(user.IsActive ? "status-user-active" : "")">@(user.IsActive ? "Aktivní" : "Deaktivovaný")</span>
|
||||||
|
<div class="small text-body-secondary mt-1">@(user.EmailConfirmed ? "E-mail ověřený" : "E-mail neověřený")</div>
|
||||||
|
<div class="small text-body-secondary">
|
||||||
|
Založen <time datetime="@user.CreatedAt.ToString("O")">@DisplayTime.Format(user.CreatedAt)</time>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-12 col-sm-7 col-lg-5 d-flex flex-wrap align-items-center gap-2">
|
||||||
|
@if (user.Id == Model.CurrentUserId)
|
||||||
|
{
|
||||||
|
<span class="badge app-role-badge">@UserRoles.DisplayName(user.Role)</span>
|
||||||
|
<span class="small text-body-secondary">Váš účet</span>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<a asp-action="Edit" asp-route-id="@user.Id" asp-route-q="@query.Q" asp-route-role="@query.Role"
|
||||||
|
asp-route-page="@query.Page" class="btn btn-sm btn-outline-primary"
|
||||||
|
aria-label="Upravit účet @user.Email">Upravit</a>
|
||||||
|
<form method="post" asp-action="ChangeRole" asp-route-id="@user.Id"
|
||||||
|
asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@query.Page"
|
||||||
|
class="d-flex flex-wrap align-items-center gap-2">
|
||||||
|
<label for="[email protected]" class="visually-hidden">Role účtu @user.Email</label>
|
||||||
|
<select id="[email protected]" name="newRole" class="form-select form-select-sm w-auto">
|
||||||
|
@foreach (var role in UserRoles.All)
|
||||||
|
{
|
||||||
|
<option value="@role" selected="@(role == user.Role)">@UserRoles.DisplayName(role)</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
<button type="submit" class="btn btn-sm btn-outline-primary" aria-label="Uložit roli účtu @user.Email">Uložit roli</button>
|
||||||
|
</form>
|
||||||
|
<form method="post" asp-action="SetActive" asp-route-id="@user.Id"
|
||||||
|
asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@query.Page">
|
||||||
|
<input type="hidden" name="isActive" value="@(user.IsActive ? "false" : "true")" />
|
||||||
|
@if (user.IsActive)
|
||||||
|
{
|
||||||
|
<button type="submit" class="btn btn-sm btn-outline-danger" aria-label="Deaktivovat účet @user.Email">Deaktivovat</button>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<button type="submit" class="btn btn-sm btn-outline-primary" aria-label="Aktivovat účet @user.Email">Aktivovat</button>
|
||||||
|
}
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
@if (result.PageCount > 1)
|
||||||
|
{
|
||||||
|
<nav aria-label="Stránkování uživatelů" class="mt-4">
|
||||||
|
<ul class="pagination flex-wrap justify-content-center">
|
||||||
|
@if (result.Page > 1)
|
||||||
|
{
|
||||||
|
<li class="page-item"><a class="page-link" asp-action="Index" asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@(result.Page - 1)">Předchozí</a></li>
|
||||||
|
}
|
||||||
|
<li class="page-item disabled"><span class="page-link" aria-current="page">Strana @result.Page z @result.PageCount</span></li>
|
||||||
|
@if (result.Page < result.PageCount)
|
||||||
|
{
|
||||||
|
<li class="page-item"><a class="page-link" asp-action="Index" asp-route-q="@query.Q" asp-route-role="@query.Role" asp-route-page="@(result.Page + 1)">Další</a></li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
</nav>
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@
|
|||||||
<li><a class="dropdown-item" asp-controller="Profile" asp-action="Index">Můj profil</a></li>
|
<li><a class="dropdown-item" asp-controller="Profile" asp-action="Index">Můj profil</a></li>
|
||||||
@if (User.IsInRole(UserRoles.Admin))
|
@if (User.IsInRole(UserRoles.Admin))
|
||||||
{
|
{
|
||||||
|
<li><a class="dropdown-item" asp-controller="AdminUsers" asp-action="Index">Správa uživatelů</a></li>
|
||||||
<li><a class="dropdown-item" href="~/swagger">Swagger API</a></li>
|
<li><a class="dropdown-item" href="~/swagger">Swagger API</a></li>
|
||||||
}
|
}
|
||||||
<li><hr class="dropdown-divider" /></li>
|
<li><hr class="dropdown-divider" /></li>
|
||||||
|
|||||||
@@ -165,7 +165,7 @@ body { min-height: 100vh; display: flex; flex-direction: column; }
|
|||||||
.status-ASSIGNED { --status-color: var(--status-assigned); }
|
.status-ASSIGNED { --status-color: var(--status-assigned); }
|
||||||
.status-IN_PROGRESS { --status-color: var(--status-in-progress); }
|
.status-IN_PROGRESS { --status-color: var(--status-in-progress); }
|
||||||
.status-PENDING_VERIFICATION, .status-UNDER_REVIEW { --status-color: var(--status-review); }
|
.status-PENDING_VERIFICATION, .status-UNDER_REVIEW { --status-color: var(--status-review); }
|
||||||
.status-RESOLVED, .status-ACCEPTED, .status-IMPLEMENTED { --status-color: var(--status-done); }
|
.status-RESOLVED, .status-ACCEPTED, .status-IMPLEMENTED, .status-user-active { --status-color: var(--status-done); }
|
||||||
.status-REJECTED { --status-color: var(--status-rejected); }
|
.status-REJECTED { --status-color: var(--status-rejected); }
|
||||||
|
|
||||||
@media (prefers-reduced-motion: reduce) {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
|||||||
@@ -4,3 +4,47 @@
|
|||||||
document.querySelectorAll("[data-autosubmit]").forEach((element) => {
|
document.querySelectorAll("[data-autosubmit]").forEach((element) => {
|
||||||
element.addEventListener("change", () => element.form?.requestSubmit());
|
element.addEventListener("change", () => element.form?.requestSubmit());
|
||||||
});
|
});
|
||||||
|
|
||||||
|
document.querySelectorAll("[data-user-bulk]").forEach((form) => {
|
||||||
|
const accounts = Array.from(form.elements).filter((element) => element.name === "userIds");
|
||||||
|
const selectPage = form.querySelector("[data-user-select-page]");
|
||||||
|
const count = form.querySelector("[data-user-count]");
|
||||||
|
const action = form.querySelector("[data-user-action]");
|
||||||
|
const role = form.querySelector("[data-user-bulk-role]");
|
||||||
|
const deletion = form.querySelector("[data-user-bulk-delete]");
|
||||||
|
const confirmDeletion = deletion.querySelector("input");
|
||||||
|
|
||||||
|
function updateSelection() {
|
||||||
|
const selected = accounts.filter((account) => account.checked).length;
|
||||||
|
selectPage.checked = selected === accounts.length;
|
||||||
|
selectPage.indeterminate = selected > 0 && selected < accounts.length;
|
||||||
|
count.textContent = `Vybráno ${selected} z ${accounts.length}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateAction() {
|
||||||
|
role.hidden = action.value !== "role";
|
||||||
|
deletion.hidden = action.value !== "delete";
|
||||||
|
confirmDeletion.required = !deletion.hidden;
|
||||||
|
if (deletion.hidden) confirmDeletion.checked = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
selectPage.addEventListener("change", () => {
|
||||||
|
accounts.forEach((account) => { account.checked = selectPage.checked; });
|
||||||
|
updateSelection();
|
||||||
|
});
|
||||||
|
accounts.forEach((account) => account.addEventListener("change", updateSelection));
|
||||||
|
action.addEventListener("change", updateAction);
|
||||||
|
updateSelection();
|
||||||
|
updateAction();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelectorAll("[data-admin-email]").forEach((email) => {
|
||||||
|
const confirmed = email.form?.querySelector("#EmailConfirmed");
|
||||||
|
if (!confirmed) return;
|
||||||
|
|
||||||
|
email.addEventListener("change", () => {
|
||||||
|
if (email.value.trim().toLowerCase() !== email.defaultValue.trim().toLowerCase()) {
|
||||||
|
confirmed.checked = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user