Files
NTBug/backend/src/Helpdesk.Application/Users/UserService.cs
T
PatTheEvil a51d386278 Základní backend: migrace, autentizace JWT, role, Swagger
- Helpdesk.Migrator (DbUp) aplikuje db/migrations, evidence v schema_version
- Domain/Application/Infrastructure/Api podle Clean Architecture
- registrace, ověření e-mailu, login, refresh s rotací, logout, reset hesla
- JWT podle RFC 7519 evidované jen podle jti v auth_token
- správa uživatelů a rolí, číselníky, ProblemDetails, Swagger UI
- Docker Compose (db, migrator, api), oddělené DB účty
- notifikace mají cizí klíče na issue a proposal
- unit testy domény a zabezpečení

Closes #1, closes #2, closes #3, closes #4, closes #5, closes #9
2026-10-28 21:43:17 +01:00

100 lines
4.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using FluentValidation;
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Auth;
using Helpdesk.Application.Common;
using Helpdesk.Domain;
using Helpdesk.Domain.Auth;
using Helpdesk.Domain.Users;
using Microsoft.EntityFrameworkCore;
namespace Helpdesk.Application.Users;
/// <summary>Vlastní profil (FR-05) a správa uživatelů administrátorem (FR-04).</summary>
public sealed class UserService(
IAppDbContext db,
TokenRevocationService revocation,
IValidator<UpdateProfileRequest> profileValidator)
{
public async Task<UserDto> GetMeAsync(ICurrentUser currentUser, CancellationToken ct) =>
UserDto.From(await GetAsync(currentUser.Id, ct));
public async Task<UserDto> UpdateMeAsync(ICurrentUser currentUser, UpdateProfileRequest request, CancellationToken ct)
{
await profileValidator.ValidateAndThrowAsync(request, ct);
var user = await GetAsync(currentUser.Id, ct);
user.UpdateProfile(request.FirstName, request.LastName, request.Phone, request.EmailNotificationsEnabled);
await db.SaveChangesAsync(ct);
return UserDto.From(user);
}
public async Task<PagedResult<AdminUserDto>> SearchAsync(string? q, string? role, int page, int pageSize, CancellationToken ct)
{
page = Math.Max(page, 1);
pageSize = Math.Clamp(pageSize, 1, 100);
var query = db.Users.AsNoTracking();
if (!string.IsNullOrWhiteSpace(q))
{
var term = q.Trim();
query = query.Where(u => u.Email.Contains(term) || u.FirstName.Contains(term) || u.LastName.Contains(term));
}
if (!string.IsNullOrWhiteSpace(role))
{
var parsed = ParseRole(role);
query = query.Where(u => u.Role == parsed);
}
var total = await query.CountAsync(ct);
var users = await query
.OrderBy(u => u.LastName).ThenBy(u => u.FirstName).ThenBy(u => u.Id)
.Skip((page - 1) * pageSize).Take(pageSize)
.ToListAsync(ct);
var items = users
.Select(u => new AdminUserDto(u.Id, u.Email, u.FirstName, u.LastName, u.Role.ToCode(), u.IsActive, u.EmailConfirmed, u.CreatedAt))
.ToList();
return new PagedResult<AdminUserDto>(items, total, page, pageSize);
}
/// <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)
{
var role = ParseRole(request.Role);
if (userId == admin.Id)
throw new ConflictException("Administrátor nemůže změnit roli sám sobě.");
var user = await GetAsync(userId, ct);
if (user.Role == role)
return;
await revocation.RevokeAllAsync(user.Id, RevokeReason.RoleChanged, ct);
user.ChangeRole(role);
await db.SaveChangesAsync(ct);
}
public async Task SetActiveAsync(ICurrentUser admin, int userId, SetActiveRequest request, CancellationToken ct)
{
if (userId == admin.Id && !request.IsActive)
throw new ConflictException("Administrátor nemůže deaktivovat sám sebe.");
var user = await GetAsync(userId, ct);
if (user.IsActive == request.IsActive)
return;
if (!request.IsActive)
await revocation.RevokeAllAsync(user.Id, RevokeReason.AccountDeactivated, ct);
user.SetActive(request.IsActive);
await db.SaveChangesAsync(ct);
}
private async Task<User> GetAsync(int id, CancellationToken ct) =>
await db.Users.SingleOrDefaultAsync(u => u.Id == id, ct)
?? throw new NotFoundException($"Uživatel {id} neexistuje.");
private static UserRole ParseRole(string code) =>
EnumCode.TryParse<UserRole>(code, out var role)
? role
: throw new BadRequestException($"Neznámá role '{code}'. Povolené: {string.Join(", ", Enum.GetValues<UserRole>().Select(r => r.ToCode()))}.");
}