backend + web: Add admin account lifecycle management
This commit is contained in:
1 parent
fcf7cd0596
commit
91d0c06c83
25 files changed
+1148
-97
No files matched your search
@@ -22,6 +22,50 @@ 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)]
|
||||||
|
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)]
|
||||||
|
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)]
|
||||||
|
|||||||
@@ -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);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,29 +44,40 @@ public sealed class AuthService(
|
|||||||
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal Task<bool> SendEmailConfirmationAsync(User user, CancellationToken ct) =>
|
||||||
|
SendEmailTokenAsync(user, TokenType.EmailConfirm, ct);
|
||||||
|
|
||||||
public async Task ConfirmEmailAsync(EmailTokenRequest request, CancellationToken ct)
|
public async Task ConfirmEmailAsync(EmailTokenRequest request, CancellationToken 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);
|
||||||
user.ConfirmEmail();
|
user.ConfirmEmail();
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
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)
|
||||||
|
.Select(u => new { u.Id, u.EmailNormalized }).SingleOrDefaultAsync(ct);
|
||||||
|
|
||||||
// Neexistující účet a špatné heslo vracejí stejnou chybu – nelze tak zjišťovat registrované e-maily.
|
// 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)
|
if (account is null)
|
||||||
throw new UnauthorizedException(invalidCredentials);
|
throw new UnauthorizedException(invalidCredentials);
|
||||||
|
|
||||||
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
|
var user = await db.LockUserAsync(account.Id, ct);
|
||||||
|
if (user is null || user.IsDeleted || user.EmailNormalized != account.EmailNormalized)
|
||||||
|
throw new UnauthorizedException(invalidCredentials);
|
||||||
|
var now = clock.GetUtcNow().UtcDateTime;
|
||||||
if (user.IsLockedOut(now))
|
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.");
|
throw new UnauthorizedException("Účet je po opakovaných neúspěšných pokusech dočasně zamčen. Zkuste to později.");
|
||||||
|
|
||||||
@@ -74,16 +85,19 @@ public sealed class AuthService(
|
|||||||
{
|
{
|
||||||
user.RegisterFailedLogin(now);
|
user.RegisterFailedLogin(now);
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
throw new UnauthorizedException(invalidCredentials);
|
throw new UnauthorizedException(invalidCredentials);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!user.IsActive)
|
if (!user.IsActive)
|
||||||
throw new ForbiddenException("Účet je deaktivován.");
|
throw new ForbiddenException("Účet je deaktivován.");
|
||||||
if (!user.EmailConfirmed)
|
if (!user.EmailConfirmed)
|
||||||
throw new ForbiddenException("E-mail ještě nebyl ověřen. Použijte odkaz z registračního e-mailu.");
|
throw new ForbiddenException("E-mail ještě nebyl ověřen. Použijte odkaz z ověřovacího e-mailu.");
|
||||||
|
|
||||||
user.RegisterSuccessfulLogin();
|
user.RegisterSuccessfulLogin();
|
||||||
return await IssueTokenPairAsync(user, ct);
|
var response = await IssueTokenPairAsync(user, ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -95,22 +109,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 (await revocation.TryConsumeAsync(token.Jti, TokenType.Refresh, ct))
|
if (user is null || !user.IsActive || !user.EmailConfirmed)
|
||||||
{
|
throw new UnauthorizedException("Účet neexistuje, je deaktivován nebo nemá ověřený e-mail.");
|
||||||
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);
|
if (await revocation.TryConsumeAsync(token.Jti, TokenType.Refresh, ct))
|
||||||
await transaction.CommitAsync(ct);
|
{
|
||||||
return response;
|
var response = await IssueTokenPairAsync(user, ct);
|
||||||
}
|
await transaction.CommitAsync(ct);
|
||||||
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
await revocation.RevokeAllAsync(token.UserId, RevokeReason.ReuseDetected, ct);
|
var revoked = await revocation.StageRevokeAllAsync([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.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -151,12 +165,13 @@ 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 revocation.StageRevokeAllAsync([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);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<AuthResponse> IssueTokenPairAsync(User user, CancellationToken ct)
|
private async Task<AuthResponse> IssueTokenPairAsync(User user, CancellationToken ct)
|
||||||
@@ -172,21 +187,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;
|
||||||
db.AuthTokens.Add(issued.Record);
|
await using (var transaction = await db.BeginWriteAsync(ct))
|
||||||
await db.SaveChangesAsync(ct);
|
{
|
||||||
|
await db.LockUserAsync(user.Id, ct);
|
||||||
|
var current = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == user.Id, ct);
|
||||||
|
if (current is null || !current.IsActive || current.EmailNormalized != user.EmailNormalized ||
|
||||||
|
(type == TokenType.EmailConfirm && current.EmailConfirmed))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
issued = tokens.Issue(current, type);
|
||||||
|
db.AuthTokens.Add(issued.Record);
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
|
}
|
||||||
|
|
||||||
var baseUrl = _registration.WebBaseUrl.TrimEnd('/');
|
var baseUrl = _registration.WebBaseUrl.TrimEnd('/');
|
||||||
var (subject, path, text) = type switch
|
var (subject, path, text) = type switch
|
||||||
{
|
{
|
||||||
TokenType.EmailConfirm => ("Ověření e-mailu", "confirm-email", "Pro dokončení registrace ověřte svůj e-mail"),
|
TokenType.EmailConfirm => ("Ověření e-mailu", "confirm-email", "Ověřte svůj e-mail"),
|
||||||
TokenType.PasswordReset => ("Obnova hesla", "reset-password", "Nové heslo nastavíte"),
|
TokenType.PasswordReset => ("Obnova hesla", "reset-password", "Nové heslo nastavíte"),
|
||||||
_ => throw new ArgumentOutOfRangeException(nameof(type)),
|
_ => throw new ArgumentOutOfRangeException(nameof(type)),
|
||||||
};
|
};
|
||||||
var link = $"{baseUrl}/{path}?token={Uri.EscapeDataString(issued.Token)}";
|
var link = $"{baseUrl}/{path}?token={Uri.EscapeDataString(issued.Token)}";
|
||||||
await emailSender.SendAsync(user.Email, subject, $"{text} na adrese:\n{link}", ct);
|
await emailSender.SendAsync(user.Email, subject, $"{text} na adrese:\n{link}", ct);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<User> ConsumeEmailTokenAsync(string token, TokenType type, CancellationToken ct)
|
private async Task<User> ConsumeEmailTokenAsync(string token, TokenType type, CancellationToken ct)
|
||||||
@@ -194,10 +221,10 @@ public sealed class AuthService(
|
|||||||
const string invalid = "Odkaz je neplatný, už byl použit nebo vypršel.";
|
const string invalid = "Odkaz je neplatný, už byl použit nebo vypršel.";
|
||||||
|
|
||||||
var validated = await tokens.ValidateAsync(token ?? "", type) ?? throw new BadRequestException(invalid);
|
var validated = await tokens.ValidateAsync(token ?? "", type) ?? throw new BadRequestException(invalid);
|
||||||
if (!await revocation.TryConsumeAsync(validated.Jti, type, ct))
|
var user = await db.LockUserAsync(validated.UserId, ct);
|
||||||
|
if (user is null || !user.IsActive || !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,41 @@ 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>
|
/// <summary>Zneplatní všechny platné tokeny uživatele – jeden UPDATE (kap. 10.1).</summary>
|
||||||
public async Task RevokeAllAsync(int userId, RevokeReason reason, CancellationToken ct)
|
public async Task RevokeAllAsync(int userId, RevokeReason reason, CancellationToken ct) =>
|
||||||
|
Publish(await StageRevokeAllAsync([userId], reason, ct));
|
||||||
|
|
||||||
|
internal async Task<List<RevokedAccessToken>> StageRevokeAllAsync(int[] userIds, 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()
|
||||||
|
|||||||
@@ -6,10 +6,16 @@ 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í.");
|
||||||
|
|
||||||
|
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,6 @@
|
|||||||
|
using System.Text;
|
||||||
using FluentValidation;
|
using FluentValidation;
|
||||||
|
using Helpdesk.Application.Auth;
|
||||||
using Helpdesk.Domain;
|
using Helpdesk.Domain;
|
||||||
using Helpdesk.Domain.Users;
|
using Helpdesk.Domain.Users;
|
||||||
|
|
||||||
@@ -45,3 +47,29 @@ 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 record AdminUserDetailsDto(int Id, string Email, string FirstName, string LastName, string? Phone,
|
||||||
|
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record SaveAdminUserRequest(string Email, string FirstName, string LastName, string? Phone,
|
||||||
|
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, string? Password);
|
||||||
|
|
||||||
|
public sealed class SaveAdminUserRequestValidator : AbstractValidator<SaveAdminUserRequest>
|
||||||
|
{
|
||||||
|
public SaveAdminUserRequestValidator()
|
||||||
|
{
|
||||||
|
RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(254);
|
||||||
|
RuleFor(x => x.Role).NotEmpty();
|
||||||
|
RuleFor(x => x.Password)
|
||||||
|
.NotEmpty().MinimumLength(PasswordRules.MinLength).MaximumLength(PasswordRules.MaxLength)
|
||||||
|
.Must(password => password is null || Encoding.UTF8.GetByteCount(password) <= 72)
|
||||||
|
.WithMessage("Heslo může mít nejvýše 72 bajtů v UTF-8.")
|
||||||
|
.When(x => x.Password is not null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record BulkAdminUsersRequest(int[] UserIds, string Action, string? Role);
|
||||||
@@ -13,7 +13,10 @@ 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,
|
||||||
|
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 +25,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);
|
||||||
|
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);
|
user.UpdateProfile(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled);
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
return UserDto.From(user);
|
return UserDto.From(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,7 +40,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 +53,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 +69,197 @@ 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 Task SetActiveAsync(ICurrentUser admin, int userId, SetActiveRequest request, CancellationToken ct) =>
|
||||||
|
userId == admin.Id && request.IsActive
|
||||||
|
? Task.CompletedTask
|
||||||
|
: UpdateAccountsAsync(admin, [userId], user => SetActive(user, request.IsActive), ct);
|
||||||
|
|
||||||
|
public async Task<AdminUserDetailsDto> GetAdminAsync(int id, CancellationToken ct) =>
|
||||||
|
AdminUserDetailsDto.From(await GetAsync(id, ct));
|
||||||
|
|
||||||
|
public async Task<AdminUserDetailsDto> CreateAsync(ICurrentUser admin, SaveAdminUserRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
if (userId == admin.Id && !request.IsActive)
|
await ValidateAsync(request, ct);
|
||||||
throw new ConflictException("Administrátor nemůže deaktivovat sám sebe.");
|
if (string.IsNullOrWhiteSpace(request.Password))
|
||||||
|
throw new BadRequestException("Zadejte počáteční heslo.");
|
||||||
var user = await GetAsync(userId, ct);
|
var role = ParseRole(request.Role);
|
||||||
if (user.IsActive == request.IsActive)
|
var user = User.Create(request.Email, passwordHasher.Hash(request.Password), request.FirstName, request.LastName, role);
|
||||||
return;
|
ApplyProfile(user, request);
|
||||||
|
|
||||||
if (!request.IsActive)
|
|
||||||
await revocation.RevokeAllAsync(user.Id, RevokeReason.AccountDeactivated, ct);
|
|
||||||
user.SetActive(request.IsActive);
|
user.SetActive(request.IsActive);
|
||||||
|
|
||||||
|
await using (var transaction = await db.BeginWriteAsync(ct))
|
||||||
|
{
|
||||||
|
RequireAdministrator(await db.LockUserAsync(admin.Id, ct));
|
||||||
|
db.Users.Add(user);
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
|
}
|
||||||
|
return await AccountSavedAsync(user, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<AdminUserDetailsDto?> UpdateAsync(ICurrentUser admin, int userId, SaveAdminUserRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await ValidateAsync(request, ct);
|
||||||
|
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 =>
|
||||||
|
{
|
||||||
|
var emailChanged = user.EmailNormalized != User.NormalizeEmail(request.Email);
|
||||||
|
var confirmed = !emailChanged && request.EmailConfirmed;
|
||||||
|
var confirmationChanged = user.EmailConfirmed != confirmed;
|
||||||
|
var roleChanged = ChangeRole(user, role);
|
||||||
|
var activeChanged = SetActive(user, request.IsActive);
|
||||||
|
ApplyProfile(user, request with { EmailConfirmed = confirmed });
|
||||||
|
sendLink = emailChanged && user.IsActive;
|
||||||
|
if (passwordHash is not null)
|
||||||
|
user.ChangePasswordHash(passwordHash);
|
||||||
|
|
||||||
|
if (emailChanged || confirmationChanged)
|
||||||
|
return RevokeReason.LogoutAll;
|
||||||
|
if (passwordHash is not null)
|
||||||
|
return RevokeReason.PasswordChanged;
|
||||||
|
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 deletedIds = users.Where(user => user.IsDeleted).Select(user => user.Id).ToArray();
|
||||||
|
if (deletedIds.Length > 0)
|
||||||
|
await db.PushDevices.Where(device => deletedIds.Contains(device.UserId)).ExecuteDeleteAsync(ct);
|
||||||
|
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
|
revocation.Publish(revoked);
|
||||||
|
return users;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<AdminUserDetailsDto> AccountSavedAsync(User user, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var result = AdminUserDetailsDto.From(user);
|
||||||
|
if (!user.IsActive || user.EmailConfirmed)
|
||||||
|
return result;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return result with { VerificationEmailSent = await auth.SendEmailConfirmationAsync(user, ct) };
|
||||||
|
}
|
||||||
|
catch (EmailDeliveryException)
|
||||||
|
{
|
||||||
|
// Účet je již uložený a ověřovací e-mail lze poslat znovu.
|
||||||
|
return result with { VerificationEmailSent = false };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ValidateAsync(SaveAdminUserRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await adminUserValidator.ValidateAndThrowAsync(request, ct);
|
||||||
|
await profileValidator.ValidateAndThrowAsync(
|
||||||
|
new UpdateProfileRequest(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled), ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ApplyProfile(User user, SaveAdminUserRequest request)
|
||||||
|
{
|
||||||
|
user.UpdateProfile(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled);
|
||||||
|
user.ChangeEmail(request.Email);
|
||||||
|
user.SetEmailConfirmed(request.EmailConfirmed);
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ 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 FailedLoginCount { get; private set; }
|
||||||
@@ -62,6 +63,14 @@ public sealed class User : IHasCreatedAt
|
|||||||
|
|
||||||
public void ConfirmEmail() => EmailConfirmed = true;
|
public void ConfirmEmail() => EmailConfirmed = true;
|
||||||
|
|
||||||
|
public void SetEmailConfirmed(bool confirmed) => EmailConfirmed = confirmed;
|
||||||
|
|
||||||
|
public void ChangeEmail(string email)
|
||||||
|
{
|
||||||
|
Email = email.Trim();
|
||||||
|
EmailNormalized = NormalizeEmail(email);
|
||||||
|
}
|
||||||
|
|
||||||
public void ChangePasswordHash(string passwordHash)
|
public void ChangePasswordHash(string passwordHash)
|
||||||
{
|
{
|
||||||
PasswordHash = passwordHash;
|
PasswordHash = passwordHash;
|
||||||
@@ -79,4 +88,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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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);
|
||||||
|
|||||||
@@ -52,11 +52,23 @@ 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.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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ů.
|
||||||
|
|||||||
@@ -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,153 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using Helpdesk.Application.Auth;
|
||||||
|
using Helpdesk.Application.Catalogs;
|
||||||
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Application.Issues;
|
||||||
|
using Helpdesk.Application.Users;
|
||||||
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||||
|
{
|
||||||
|
private const string Users = "/api/v1/admin/users";
|
||||||
|
|
||||||
|
[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" };
|
||||||
|
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.Forbidden);
|
||||||
|
await ConfirmEmailAsync(anonymous, await fixture.TakeConfirmationTokenAsync(edit.Email));
|
||||||
|
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, Password);
|
||||||
|
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 };
|
||||||
|
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 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) =>
|
||||||
|
ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/confirm-email", new EmailTokenRequest(token), Cancellation), expected);
|
||||||
|
}
|
||||||
@@ -77,7 +77,7 @@ public sealed class BackendFixture : IAsyncLifetime
|
|||||||
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, Password, "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 EmailTokenRequest(await TakeConfirmationTokenAsync(address)), Cancellation), HttpStatusCode.NoContent);
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,6 +89,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) =>
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE app_user
|
||||||
|
ADD COLUMN is_deleted BOOLEAN NOT NULL DEFAULT FALSE;
|
||||||
@@ -116,7 +116,7 @@ Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkr
|
|||||||
| FR-01 | Registrace e-mailem a heslem; po registraci ověření e-mailu odkazem. |
|
| FR-01 | Registrace e-mailem a heslem; po registraci ověření e-mailu odkazem. |
|
||||||
| FR-02 | Přihlášení e-mailem a heslem, vydání JWT access tokenu a refresh tokenu; odhlášení zablokuje oba tokeny (podle `jti`); „odhlásit ze všech zařízení“. |
|
| FR-02 | Přihlášení e-mailem a heslem, vydání JWT access tokenu a refresh tokenu; odhlášení zablokuje oba tokeny (podle `jti`); „odhlásit ze všech zařízení“. |
|
||||||
| FR-03 | Obnova zapomenutého hesla přes e-mail. |
|
| FR-03 | Obnova zapomenutého hesla přes e-mail. |
|
||||||
| FR-04 | Administrátor vyhledává 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
|
||||||
@@ -724,6 +724,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 počátečním heslem a ručním nebo e-mailovým ověřením |
|
||||||
|
| GET / PUT | `/admin/users/{id}` | admin | Detail a úprava účtu, nové heslo je volitelné. Změna adresy aktivního účtu spustí nové ověření. |
|
||||||
|
| 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 |
|
||||||
@@ -981,7 +986,7 @@ V první verzi byla tabulka uživatelů „chobotnice“: vedlo na ni 17 cizích
|
|||||||
- **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` (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`).
|
||||||
|
|||||||
@@ -28,12 +28,15 @@ public sealed class AdminUsersTests
|
|||||||
SignIn(application.Services, client, role);
|
SignIn(application.Services, client, role);
|
||||||
var ct = TestContext.Current.CancellationToken;
|
var ct = TestContext.Current.CancellationToken;
|
||||||
|
|
||||||
using var list = await client.GetAsync(UsersPath, ct);
|
foreach (var path in new[] { UsersPath, UsersPath + "/new", UsersPath + "/7/edit" })
|
||||||
Assert.Equal(HttpStatusCode.Redirect, list.StatusCode);
|
|
||||||
Assert.Equal(redirect, list.Headers.Location?.AbsolutePath);
|
|
||||||
foreach (var action in new[] { "role", "active" })
|
|
||||||
{
|
{
|
||||||
using var update = await client.PostAsync($"{UsersPath}/7/{action}", null, ct);
|
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(HttpStatusCode.Redirect, update.StatusCode);
|
||||||
Assert.Equal(redirect, update.Headers.Location?.AbsolutePath);
|
Assert.Equal(redirect, update.Headers.Location?.AbsolutePath);
|
||||||
}
|
}
|
||||||
@@ -63,8 +66,7 @@ public sealed class AdminUsersTests
|
|||||||
Assert.DoesNotContain($"{UsersPath}/1/active", html);
|
Assert.DoesNotContain($"{UsersPath}/1/active", html);
|
||||||
Assert.Contains($"{UsersPath}/7/role{query}", html);
|
Assert.Contains($"{UsersPath}/7/role{query}", html);
|
||||||
Assert.Contains($"{UsersPath}/7/active{query}", html);
|
Assert.Contains($"{UsersPath}/7/active{query}", html);
|
||||||
var token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value;
|
var token = AntiforgeryToken(html);
|
||||||
Assert.NotEmpty(token);
|
|
||||||
|
|
||||||
var search = Assert.Single(backend.Requests);
|
var search = Assert.Single(backend.Requests);
|
||||||
Assert.Equal(HttpMethod.Get, search.Method);
|
Assert.Equal(HttpMethod.Get, search.Method);
|
||||||
@@ -111,6 +113,133 @@ public sealed class AdminUsersTests
|
|||||||
Assert.Empty(backend.Requests);
|
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);
|
||||||
|
Assert.Contains("[email protected]", await editPage.Content.ReadAsStringAsync(ct));
|
||||||
|
fields.Remove("Password");
|
||||||
|
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);
|
||||||
|
|
||||||
|
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,
|
||||||
|
["Password"] = "Initial-password",
|
||||||
|
["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));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string AntiforgeryToken(string html)
|
||||||
|
{
|
||||||
|
var token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value;
|
||||||
|
Assert.NotEmpty(token);
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
private static WebApplicationFactory<Program> CreateApplication(AdminUsersBackend backend) =>
|
private static WebApplicationFactory<Program> CreateApplication(AdminUsersBackend backend) =>
|
||||||
new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||||
builder.ConfigureTestServices(services => services.AddHttpClient(nameof(HelpdeskApiClient))
|
builder.ConfigureTestServices(services => services.AddHttpClient(nameof(HelpdeskApiClient))
|
||||||
@@ -123,7 +252,7 @@ public sealed class AdminUsersTests
|
|||||||
BaseAddress = new Uri("https://localhost"),
|
BaseAddress = new Uri("https://localhost"),
|
||||||
});
|
});
|
||||||
|
|
||||||
private sealed class AdminUsersBackend : HttpMessageHandler
|
private sealed class AdminUsersBackend(bool failVerification = false) : HttpMessageHandler
|
||||||
{
|
{
|
||||||
public List<(HttpMethod Method, Uri Uri, string? Body)> Requests { get; } = [];
|
public List<(HttpMethod Method, Uri Uri, string? Body)> Requests { get; } = [];
|
||||||
|
|
||||||
@@ -132,9 +261,24 @@ public sealed class AdminUsersTests
|
|||||||
Assert.Equal("test-access", request.Headers.Authorization?.Parameter);
|
Assert.Equal("test-access", request.Headers.Authorization?.Parameter);
|
||||||
var uri = Assert.IsType<Uri>(request.RequestUri);
|
var uri = Assert.IsType<Uri>(request.RequestUri);
|
||||||
Requests.Add((request.Method, uri, request.Content is null ? null : await request.Content.ReadAsStringAsync(ct)));
|
Requests.Add((request.Method, uri, request.Content is null ? null : await request.Content.ReadAsStringAsync(ct)));
|
||||||
if (request.Method == HttpMethod.Put)
|
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.Get)
|
||||||
return new HttpResponseMessage(HttpStatusCode.NoContent);
|
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}
|
||||||
|
""", Encoding.UTF8, "application/json"),
|
||||||
|
};
|
||||||
|
|
||||||
Assert.Equal("/api/v1" + UsersPath, uri.AbsolutePath);
|
Assert.Equal("/api/v1" + UsersPath, uri.AbsolutePath);
|
||||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -52,6 +52,12 @@ public sealed record AdminUserDto(
|
|||||||
public string FullName => $"{FirstName} {LastName}";
|
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, 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);
|
||||||
|
|
||||||
/// <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)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -42,16 +43,52 @@ public sealed class HelpdeskApiClient(HttpClient http)
|
|||||||
|
|
||||||
public async Task ChangeUserRoleAsync(int id, string role, CancellationToken ct)
|
public async Task ChangeUserRoleAsync(int id, string role, CancellationToken ct)
|
||||||
{
|
{
|
||||||
using var response = await http.PutAsJsonAsync($"admin/users/{id.ToString(CultureInfo.InvariantCulture)}/role", new { role }, ct);
|
using var response = await http.PutAsJsonAsync(AdminUserPath(id) + "/role", new { role }, ct);
|
||||||
await ApiResponse.EnsureSuccessAsync(response, ct);
|
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task SetUserActiveAsync(int id, bool isActive, CancellationToken ct)
|
public async Task SetUserActiveAsync(int id, bool isActive, CancellationToken ct)
|
||||||
{
|
{
|
||||||
using var response = await http.PutAsJsonAsync($"admin/users/{id.ToString(CultureInfo.InvariantCulture)}/active", new { isActive }, ct);
|
using var response = await http.PutAsJsonAsync(AdminUserPath(id) + "/active", new { isActive }, ct);
|
||||||
await ApiResponse.EnsureSuccessAsync(response, 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?>
|
||||||
|
|||||||
@@ -24,9 +24,95 @@ public sealed class AdminUsersController(HelpdeskApiClient api) : Controller
|
|||||||
if (users.Items.Count == 0 && users.Page > 1)
|
if (users.Items.Count == 0 && users.Page > 1)
|
||||||
return BackToList(new AdminUsersQuery(q, role, Math.Max(1, users.PageCount)));
|
return BackToList(new AdminUsersQuery(q, role, Math.Max(1, users.PageCount)));
|
||||||
|
|
||||||
int? currentUserId = int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier), CultureInfo.InvariantCulture, out var id)
|
return View(new AdminUsersViewModel(users, new AdminUsersQuery(q, role, users.Page), CurrentUserId));
|
||||||
? id : null;
|
}
|
||||||
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,
|
||||||
|
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")]
|
[HttpPost("{id:int}/role")]
|
||||||
@@ -63,7 +149,7 @@ public sealed class AdminUsersController(HelpdeskApiClient api) : Controller
|
|||||||
await update();
|
await update();
|
||||||
TempData.SetSuccess(success);
|
TempData.SetSuccess(success);
|
||||||
}
|
}
|
||||||
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict)
|
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Conflict or HttpStatusCode.NotFound)
|
||||||
{
|
{
|
||||||
TempData.SetError(ex.AllMessages);
|
TempData.SetError(ex.AllMessages);
|
||||||
}
|
}
|
||||||
@@ -71,6 +157,44 @@ public sealed class AdminUsersController(HelpdeskApiClient api) : Controller
|
|||||||
return BackToList(query);
|
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");
|
||||||
|
|
||||||
|
model.Id = id;
|
||||||
|
model.Query = query;
|
||||||
|
if (id is null && string.IsNullOrWhiteSpace(model.Password))
|
||||||
|
ModelState.AddModelError(nameof(model.Password), "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 (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) =>
|
private RedirectToActionResult BackToList(AdminUsersQuery query) =>
|
||||||
RedirectToAction(nameof(Index), new { q = query.Q, role = query.Role, page = query.Page });
|
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 });
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using Helpdesk.Web.Auth;
|
|
||||||
|
|
||||||
namespace Helpdesk.Web.Infrastructure;
|
namespace Helpdesk.Web.Infrastructure;
|
||||||
|
|
||||||
@@ -21,7 +20,6 @@ public static class Navigation
|
|||||||
new("Nástěnka", "Home", "Index"),
|
new("Nástěnka", "Home", "Index"),
|
||||||
new("Nahlásit závadu", "Issues", "New"),
|
new("Nahlásit závadu", "Issues", "New"),
|
||||||
new("Moje hlášení", "Issues", "Index"),
|
new("Moje hlášení", "Issues", "Index"),
|
||||||
new("Správa uživatelů", "AdminUsers", "Index", UserRoles.Admin),
|
|
||||||
];
|
];
|
||||||
|
|
||||||
public static IEnumerable<NavItem> For(ClaimsPrincipal user) => Items.Where(i => i.IsVisibleTo(user));
|
public static IEnumerable<NavItem> For(ClaimsPrincipal user) => Items.Where(i => i.IsVisibleTo(user));
|
||||||
|
|||||||
@@ -1,7 +1,50 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
using Helpdesk.Web.Api;
|
using Helpdesk.Web.Api;
|
||||||
|
using Helpdesk.Web.Auth;
|
||||||
|
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||||
|
|
||||||
namespace Helpdesk.Web.Models;
|
namespace Helpdesk.Web.Models;
|
||||||
|
|
||||||
public sealed record AdminUsersViewModel(PagedResult<AdminUserDto> Users, AdminUsersQuery Query, int? CurrentUserId);
|
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 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();
|
||||||
|
|
||||||
|
[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);
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
@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>
|
||||||
|
<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">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">Ověřovací odkaz se odešle, pokud je účet aktivní. 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>
|
||||||
@@ -5,8 +5,10 @@
|
|||||||
var query = Model.Query;
|
var query = Model.Query;
|
||||||
}
|
}
|
||||||
|
|
||||||
<section class="app-page-head">
|
<section class="app-page-head d-flex flex-wrap justify-content-between align-items-center gap-2">
|
||||||
<h1>Správa uživatelů</h1>
|
<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>
|
</section>
|
||||||
|
|
||||||
<form method="get" asp-action="Index" class="app-card mb-4" role="search" aria-label="Vyhledávání uživatelů">
|
<form method="get" asp-action="Index" class="app-card mb-4" role="search" aria-label="Vyhledávání uživatelů">
|
||||||
@@ -43,13 +45,63 @@
|
|||||||
}
|
}
|
||||||
else
|
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">
|
<ul class="list-unstyled d-grid gap-2 mb-0">
|
||||||
@foreach (var user in result.Items)
|
@foreach (var user in result.Items)
|
||||||
{
|
{
|
||||||
<li class="app-card px-3 px-sm-4 py-3">
|
<li class="app-card px-3 px-sm-4 py-3">
|
||||||
<div class="row g-3 align-items-center">
|
<div class="row g-3 align-items-center">
|
||||||
<div class="col-12 col-lg-4">
|
<div class="col-12 col-lg-4">
|
||||||
<h2 class="h6 fw-bold text-break mb-1">@user.FullName</h2>
|
<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 class="small text-body-secondary text-break">@user.Email</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-12 col-sm-5 col-lg-3">
|
<div class="col-12 col-sm-5 col-lg-3">
|
||||||
@@ -67,6 +119,9 @@ else
|
|||||||
}
|
}
|
||||||
else
|
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"
|
<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"
|
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">
|
class="d-flex flex-wrap align-items-center gap-2">
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -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