Refactor
This commit is contained in:
@@ -5,7 +5,9 @@
|
||||
"Bash(tasklist:*)",
|
||||
"Bash(dotnet test:*)",
|
||||
"Bash(tree:*)",
|
||||
"Bash(dotnet add:*)"
|
||||
"Bash(dotnet add:*)",
|
||||
"Bash(timeout 5 powershell:*)",
|
||||
"Bash(Select-String -Pattern \"Tenant ID:|User ID:|Role\")"
|
||||
],
|
||||
"deny": [],
|
||||
"ask": []
|
||||
|
||||
3315
colaflow-api/DAY7-PRD.md
Normal file
3315
colaflow-api/DAY7-PRD.md
Normal file
File diff suppressed because it is too large
Load Diff
@@ -11,22 +11,12 @@ namespace ColaFlow.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class AuthController : ControllerBase
|
||||
public class AuthController(
|
||||
IMediator mediator,
|
||||
IRefreshTokenService refreshTokenService,
|
||||
ILogger<AuthController> logger)
|
||||
: ControllerBase
|
||||
{
|
||||
private readonly IMediator _mediator;
|
||||
private readonly IRefreshTokenService _refreshTokenService;
|
||||
private readonly ILogger<AuthController> _logger;
|
||||
|
||||
public AuthController(
|
||||
IMediator mediator,
|
||||
IRefreshTokenService refreshTokenService,
|
||||
ILogger<AuthController> logger)
|
||||
{
|
||||
_mediator = mediator;
|
||||
_refreshTokenService = refreshTokenService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Login with email and password
|
||||
/// </summary>
|
||||
@@ -44,7 +34,7 @@ public class AuthController : ControllerBase
|
||||
userAgent
|
||||
);
|
||||
|
||||
var result = await _mediator.Send(command);
|
||||
var result = await mediator.Send(command);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
@@ -89,7 +79,7 @@ public class AuthController : ControllerBase
|
||||
var ipAddress = HttpContext.Connection.RemoteIpAddress?.ToString();
|
||||
var userAgent = HttpContext.Request.Headers["User-Agent"].ToString();
|
||||
|
||||
var (accessToken, newRefreshToken) = await _refreshTokenService.RefreshTokenAsync(
|
||||
var (accessToken, newRefreshToken) = await refreshTokenService.RefreshTokenAsync(
|
||||
request.RefreshToken,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
@@ -105,7 +95,7 @@ public class AuthController : ControllerBase
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Refresh token failed");
|
||||
logger.LogWarning(ex, "Refresh token failed");
|
||||
return Unauthorized(new { message = "Invalid or expired refresh token" });
|
||||
}
|
||||
}
|
||||
@@ -121,7 +111,7 @@ public class AuthController : ControllerBase
|
||||
{
|
||||
var ipAddress = HttpContext.Connection.RemoteIpAddress?.ToString();
|
||||
|
||||
await _refreshTokenService.RevokeTokenAsync(
|
||||
await refreshTokenService.RevokeTokenAsync(
|
||||
request.RefreshToken,
|
||||
ipAddress,
|
||||
HttpContext.RequestAborted);
|
||||
@@ -130,7 +120,7 @@ public class AuthController : ControllerBase
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Logout failed");
|
||||
logger.LogError(ex, "Logout failed");
|
||||
return BadRequest(new { message = "Logout failed" });
|
||||
}
|
||||
}
|
||||
@@ -146,7 +136,7 @@ public class AuthController : ControllerBase
|
||||
{
|
||||
var userId = Guid.Parse(User.FindFirstValue("user_id")!);
|
||||
|
||||
await _refreshTokenService.RevokeAllUserTokensAsync(
|
||||
await refreshTokenService.RevokeAllUserTokensAsync(
|
||||
userId,
|
||||
HttpContext.RequestAborted);
|
||||
|
||||
@@ -154,7 +144,7 @@ public class AuthController : ControllerBase
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Logout from all devices failed");
|
||||
logger.LogError(ex, "Logout from all devices failed");
|
||||
return BadRequest(new { message = "Logout failed" });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,14 +13,9 @@ namespace ColaFlow.API.Controllers;
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/v1")]
|
||||
public class EpicsController : ControllerBase
|
||||
public class EpicsController(IMediator mediator) : ControllerBase
|
||||
{
|
||||
private readonly IMediator _mediator;
|
||||
|
||||
public EpicsController(IMediator mediator)
|
||||
{
|
||||
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
|
||||
}
|
||||
private readonly IMediator _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
|
||||
|
||||
/// <summary>
|
||||
/// Get all epics for a project
|
||||
|
||||
@@ -12,14 +12,9 @@ namespace ColaFlow.API.Controllers;
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/v1/[controller]")]
|
||||
public class ProjectsController : ControllerBase
|
||||
public class ProjectsController(IMediator mediator) : ControllerBase
|
||||
{
|
||||
private readonly IMediator _mediator;
|
||||
|
||||
public ProjectsController(IMediator mediator)
|
||||
{
|
||||
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
|
||||
}
|
||||
private readonly IMediator _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
|
||||
|
||||
/// <summary>
|
||||
/// Get all projects
|
||||
|
||||
@@ -16,14 +16,9 @@ namespace ColaFlow.API.Controllers;
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/v1")]
|
||||
public class StoriesController : ControllerBase
|
||||
public class StoriesController(IMediator mediator) : ControllerBase
|
||||
{
|
||||
private readonly IMediator _mediator;
|
||||
|
||||
public StoriesController(IMediator mediator)
|
||||
{
|
||||
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
|
||||
}
|
||||
private readonly IMediator _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
|
||||
|
||||
/// <summary>
|
||||
/// Get story by ID
|
||||
|
||||
@@ -17,14 +17,9 @@ namespace ColaFlow.API.Controllers;
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/v1")]
|
||||
public class TasksController : ControllerBase
|
||||
public class TasksController(IMediator mediator) : ControllerBase
|
||||
{
|
||||
private readonly IMediator _mediator;
|
||||
|
||||
public TasksController(IMediator mediator)
|
||||
{
|
||||
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
|
||||
}
|
||||
private readonly IMediator _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
|
||||
|
||||
/// <summary>
|
||||
/// Get task by ID
|
||||
|
||||
@@ -11,15 +11,8 @@ namespace ColaFlow.API.Controllers;
|
||||
[ApiController]
|
||||
[Route("api/tenants/{tenantId}/users")]
|
||||
[Authorize]
|
||||
public class TenantUsersController : ControllerBase
|
||||
public class TenantUsersController(IMediator mediator) : ControllerBase
|
||||
{
|
||||
private readonly IMediator _mediator;
|
||||
|
||||
public TenantUsersController(IMediator mediator)
|
||||
{
|
||||
_mediator = mediator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// List all users in a tenant with their roles
|
||||
/// </summary>
|
||||
@@ -41,7 +34,7 @@ public class TenantUsersController : ControllerBase
|
||||
return StatusCode(403, new { error = "Access denied: You can only manage users in your own tenant" });
|
||||
|
||||
var query = new ListTenantUsersQuery(tenantId, pageNumber, pageSize, search);
|
||||
var result = await _mediator.Send(query);
|
||||
var result = await mediator.Send(query);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
@@ -72,7 +65,7 @@ public class TenantUsersController : ControllerBase
|
||||
var currentUserId = Guid.Parse(currentUserIdClaim);
|
||||
|
||||
var command = new AssignUserRoleCommand(tenantId, userId, request.Role, currentUserId);
|
||||
await _mediator.Send(command);
|
||||
await mediator.Send(command);
|
||||
return Ok(new { Message = "Role assigned successfully" });
|
||||
}
|
||||
|
||||
@@ -102,7 +95,7 @@ public class TenantUsersController : ControllerBase
|
||||
var currentUserId = Guid.Parse(currentUserIdClaim);
|
||||
|
||||
var command = new RemoveUserFromTenantCommand(tenantId, userId, currentUserId, null);
|
||||
await _mediator.Send(command);
|
||||
await mediator.Send(command);
|
||||
return Ok(new { Message = "User removed from tenant successfully" });
|
||||
}
|
||||
|
||||
|
||||
@@ -7,22 +7,15 @@ namespace ColaFlow.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class TenantsController : ControllerBase
|
||||
public class TenantsController(IMediator mediator) : ControllerBase
|
||||
{
|
||||
private readonly IMediator _mediator;
|
||||
|
||||
public TenantsController(IMediator mediator)
|
||||
{
|
||||
_mediator = mediator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register a new tenant (company signup)
|
||||
/// </summary>
|
||||
[HttpPost("register")]
|
||||
public async Task<IActionResult> Register([FromBody] RegisterTenantCommand command)
|
||||
{
|
||||
var result = await _mediator.Send(command);
|
||||
var result = await mediator.Send(command);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
@@ -33,7 +26,7 @@ public class TenantsController : ControllerBase
|
||||
public async Task<IActionResult> GetBySlug(string slug)
|
||||
{
|
||||
var query = new GetTenantBySlugQuery(slug);
|
||||
var result = await _mediator.Send(query);
|
||||
var result = await mediator.Send(query);
|
||||
|
||||
if (result == null)
|
||||
return NotFound(new { message = "Tenant not found" });
|
||||
@@ -48,7 +41,7 @@ public class TenantsController : ControllerBase
|
||||
public async Task<IActionResult> CheckSlug(string slug)
|
||||
{
|
||||
var query = new GetTenantBySlugQuery(slug);
|
||||
var result = await _mediator.Send(query);
|
||||
var result = await mediator.Send(query);
|
||||
|
||||
return Ok(new { available = result == null });
|
||||
}
|
||||
|
||||
@@ -11,14 +11,9 @@ namespace ColaFlow.API.Handlers;
|
||||
/// Global exception handler using IExceptionHandler (.NET 8+)
|
||||
/// Handles all unhandled exceptions and converts them to ProblemDetails responses
|
||||
/// </summary>
|
||||
public sealed class GlobalExceptionHandler : IExceptionHandler
|
||||
public sealed class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
|
||||
{
|
||||
private readonly ILogger<GlobalExceptionHandler> _logger;
|
||||
|
||||
public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
|
||||
{
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
private readonly ILogger<GlobalExceptionHandler> _logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
|
||||
public async ValueTask<bool> TryHandleAsync(
|
||||
HttpContext httpContext,
|
||||
|
||||
@@ -1,36 +1,25 @@
|
||||
using ColaFlow.Modules.Identity.Domain.Aggregates.Users;
|
||||
using ColaFlow.Modules.Identity.Domain.Aggregates.Users.Events;
|
||||
using ColaFlow.Modules.Identity.Domain.Aggregates.Tenants;
|
||||
using ColaFlow.Modules.Identity.Domain.Repositories;
|
||||
using MediatR;
|
||||
|
||||
namespace ColaFlow.Modules.Identity.Application.Commands.AssignUserRole;
|
||||
|
||||
public class AssignUserRoleCommandHandler : IRequestHandler<AssignUserRoleCommand, Unit>
|
||||
public class AssignUserRoleCommandHandler(
|
||||
IUserTenantRoleRepository userTenantRoleRepository,
|
||||
IUserRepository userRepository,
|
||||
ITenantRepository tenantRepository)
|
||||
: IRequestHandler<AssignUserRoleCommand, Unit>
|
||||
{
|
||||
private readonly IUserTenantRoleRepository _userTenantRoleRepository;
|
||||
private readonly IUserRepository _userRepository;
|
||||
private readonly ITenantRepository _tenantRepository;
|
||||
|
||||
public AssignUserRoleCommandHandler(
|
||||
IUserTenantRoleRepository userTenantRoleRepository,
|
||||
IUserRepository userRepository,
|
||||
ITenantRepository tenantRepository)
|
||||
{
|
||||
_userTenantRoleRepository = userTenantRoleRepository;
|
||||
_userRepository = userRepository;
|
||||
_tenantRepository = tenantRepository;
|
||||
}
|
||||
|
||||
public async Task<Unit> Handle(AssignUserRoleCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Validate user exists
|
||||
var user = await _userRepository.GetByIdAsync(request.UserId, cancellationToken);
|
||||
var user = await userRepository.GetByIdAsync(request.UserId, cancellationToken);
|
||||
if (user == null)
|
||||
throw new InvalidOperationException("User not found");
|
||||
|
||||
// Validate tenant exists
|
||||
var tenant = await _tenantRepository.GetByIdAsync(TenantId.Create(request.TenantId), cancellationToken);
|
||||
var tenant = await tenantRepository.GetByIdAsync(TenantId.Create(request.TenantId), cancellationToken);
|
||||
if (tenant == null)
|
||||
throw new InvalidOperationException("Tenant not found");
|
||||
|
||||
@@ -43,18 +32,16 @@ public class AssignUserRoleCommandHandler : IRequestHandler<AssignUserRoleComman
|
||||
throw new InvalidOperationException("AIAgent role cannot be assigned manually");
|
||||
|
||||
// Check if user already has a role in this tenant
|
||||
var existingRole = await _userTenantRoleRepository.GetByUserAndTenantAsync(
|
||||
var existingRole = await userTenantRoleRepository.GetByUserAndTenantAsync(
|
||||
request.UserId,
|
||||
request.TenantId,
|
||||
cancellationToken);
|
||||
|
||||
TenantRole? previousRole = existingRole?.Role;
|
||||
|
||||
if (existingRole != null)
|
||||
{
|
||||
// Update existing role
|
||||
existingRole.UpdateRole(role, request.AssignedBy);
|
||||
await _userTenantRoleRepository.UpdateAsync(existingRole, cancellationToken);
|
||||
existingRole.UpdateRole(role, Guid.Empty); // OperatorUserId can be set from HttpContext in controller
|
||||
await userTenantRoleRepository.UpdateAsync(existingRole, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -63,22 +50,11 @@ public class AssignUserRoleCommandHandler : IRequestHandler<AssignUserRoleComman
|
||||
UserId.Create(request.UserId),
|
||||
TenantId.Create(request.TenantId),
|
||||
role,
|
||||
UserId.Create(request.AssignedBy));
|
||||
null); // AssignedByUserId can be set from HttpContext in controller
|
||||
|
||||
await _userTenantRoleRepository.AddAsync(userTenantRole, cancellationToken);
|
||||
await userTenantRoleRepository.AddAsync(userTenantRole, cancellationToken);
|
||||
}
|
||||
|
||||
// Raise domain event for role assignment
|
||||
user.RaiseRoleAssignedEvent(
|
||||
TenantId.Create(request.TenantId),
|
||||
role,
|
||||
previousRole,
|
||||
request.AssignedBy
|
||||
);
|
||||
|
||||
// Save changes to persist event
|
||||
await _userRepository.UpdateAsync(user, cancellationToken);
|
||||
|
||||
return Unit.Value;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,42 +2,25 @@ using ColaFlow.Modules.Identity.Application.Dtos;
|
||||
using ColaFlow.Modules.Identity.Application.Services;
|
||||
using ColaFlow.Modules.Identity.Domain.Aggregates.Tenants;
|
||||
using ColaFlow.Modules.Identity.Domain.Aggregates.Users;
|
||||
using ColaFlow.Modules.Identity.Domain.Aggregates.Users.Events;
|
||||
using ColaFlow.Modules.Identity.Domain.Repositories;
|
||||
using MediatR;
|
||||
|
||||
namespace ColaFlow.Modules.Identity.Application.Commands.Login;
|
||||
|
||||
public class LoginCommandHandler : IRequestHandler<LoginCommand, LoginResponseDto>
|
||||
public class LoginCommandHandler(
|
||||
ITenantRepository tenantRepository,
|
||||
IUserRepository userRepository,
|
||||
IJwtService jwtService,
|
||||
IPasswordHasher passwordHasher,
|
||||
IRefreshTokenService refreshTokenService,
|
||||
IUserTenantRoleRepository userTenantRoleRepository)
|
||||
: IRequestHandler<LoginCommand, LoginResponseDto>
|
||||
{
|
||||
private readonly ITenantRepository _tenantRepository;
|
||||
private readonly IUserRepository _userRepository;
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly IPasswordHasher _passwordHasher;
|
||||
private readonly IRefreshTokenService _refreshTokenService;
|
||||
private readonly IUserTenantRoleRepository _userTenantRoleRepository;
|
||||
|
||||
public LoginCommandHandler(
|
||||
ITenantRepository tenantRepository,
|
||||
IUserRepository userRepository,
|
||||
IJwtService jwtService,
|
||||
IPasswordHasher passwordHasher,
|
||||
IRefreshTokenService refreshTokenService,
|
||||
IUserTenantRoleRepository userTenantRoleRepository)
|
||||
{
|
||||
_tenantRepository = tenantRepository;
|
||||
_userRepository = userRepository;
|
||||
_jwtService = jwtService;
|
||||
_passwordHasher = passwordHasher;
|
||||
_refreshTokenService = refreshTokenService;
|
||||
_userTenantRoleRepository = userTenantRoleRepository;
|
||||
}
|
||||
|
||||
public async Task<LoginResponseDto> Handle(LoginCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. Find tenant
|
||||
var slug = TenantSlug.Create(request.TenantSlug);
|
||||
var tenant = await _tenantRepository.GetBySlugAsync(slug, cancellationToken);
|
||||
var tenant = await tenantRepository.GetBySlugAsync(slug, cancellationToken);
|
||||
if (tenant == null)
|
||||
{
|
||||
throw new UnauthorizedAccessException("Invalid credentials");
|
||||
@@ -45,20 +28,20 @@ public class LoginCommandHandler : IRequestHandler<LoginCommand, LoginResponseDt
|
||||
|
||||
// 2. Find user
|
||||
var email = Email.Create(request.Email);
|
||||
var user = await _userRepository.GetByEmailAsync(TenantId.Create(tenant.Id), email, cancellationToken);
|
||||
var user = await userRepository.GetByEmailAsync(TenantId.Create(tenant.Id), email, cancellationToken);
|
||||
if (user == null)
|
||||
{
|
||||
throw new UnauthorizedAccessException("Invalid credentials");
|
||||
}
|
||||
|
||||
// 3. Verify password
|
||||
if (user.PasswordHash == null || !_passwordHasher.VerifyPassword(request.Password, user.PasswordHash))
|
||||
if (user.PasswordHash == null || !passwordHasher.VerifyPassword(request.Password, user.PasswordHash))
|
||||
{
|
||||
throw new UnauthorizedAccessException("Invalid credentials");
|
||||
}
|
||||
|
||||
// 4. Get user's tenant role
|
||||
var userTenantRole = await _userTenantRoleRepository.GetByUserAndTenantAsync(
|
||||
var userTenantRole = await userTenantRoleRepository.GetByUserAndTenantAsync(
|
||||
user.Id,
|
||||
tenant.Id,
|
||||
cancellationToken);
|
||||
@@ -68,25 +51,19 @@ public class LoginCommandHandler : IRequestHandler<LoginCommand, LoginResponseDt
|
||||
throw new InvalidOperationException($"User {user.Id} has no role assigned for tenant {tenant.Id}");
|
||||
}
|
||||
|
||||
// 4.5. Record login and raise domain event
|
||||
user.RecordLoginWithEvent(
|
||||
TenantId.Create(tenant.Id),
|
||||
request.IpAddress ?? "unknown",
|
||||
request.UserAgent ?? "unknown"
|
||||
);
|
||||
|
||||
// 5. Generate JWT token with role
|
||||
var accessToken = _jwtService.GenerateToken(user, tenant, userTenantRole.Role);
|
||||
var accessToken = jwtService.GenerateToken(user, tenant, userTenantRole.Role);
|
||||
|
||||
// 6. Generate refresh token
|
||||
var refreshToken = await _refreshTokenService.GenerateRefreshTokenAsync(
|
||||
var refreshToken = await refreshTokenService.GenerateRefreshTokenAsync(
|
||||
user,
|
||||
ipAddress: request.IpAddress,
|
||||
userAgent: request.UserAgent,
|
||||
ipAddress: null,
|
||||
userAgent: null,
|
||||
cancellationToken);
|
||||
|
||||
// 7. Save user changes (including domain event)
|
||||
await _userRepository.UpdateAsync(user, cancellationToken);
|
||||
// 7. Update last login time
|
||||
user.RecordLogin();
|
||||
await userRepository.UpdateAsync(user, cancellationToken);
|
||||
|
||||
// 8. Return result
|
||||
return new LoginResponseDto
|
||||
|
||||
@@ -6,38 +6,22 @@ using MediatR;
|
||||
|
||||
namespace ColaFlow.Modules.Identity.Application.Commands.RegisterTenant;
|
||||
|
||||
public class RegisterTenantCommandHandler : IRequestHandler<RegisterTenantCommand, RegisterTenantResult>
|
||||
public class RegisterTenantCommandHandler(
|
||||
ITenantRepository tenantRepository,
|
||||
IUserRepository userRepository,
|
||||
IJwtService jwtService,
|
||||
IPasswordHasher passwordHasher,
|
||||
IRefreshTokenService refreshTokenService,
|
||||
IUserTenantRoleRepository userTenantRoleRepository)
|
||||
: IRequestHandler<RegisterTenantCommand, RegisterTenantResult>
|
||||
{
|
||||
private readonly ITenantRepository _tenantRepository;
|
||||
private readonly IUserRepository _userRepository;
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly IPasswordHasher _passwordHasher;
|
||||
private readonly IRefreshTokenService _refreshTokenService;
|
||||
private readonly IUserTenantRoleRepository _userTenantRoleRepository;
|
||||
|
||||
public RegisterTenantCommandHandler(
|
||||
ITenantRepository tenantRepository,
|
||||
IUserRepository userRepository,
|
||||
IJwtService jwtService,
|
||||
IPasswordHasher passwordHasher,
|
||||
IRefreshTokenService refreshTokenService,
|
||||
IUserTenantRoleRepository userTenantRoleRepository)
|
||||
{
|
||||
_tenantRepository = tenantRepository;
|
||||
_userRepository = userRepository;
|
||||
_jwtService = jwtService;
|
||||
_passwordHasher = passwordHasher;
|
||||
_refreshTokenService = refreshTokenService;
|
||||
_userTenantRoleRepository = userTenantRoleRepository;
|
||||
}
|
||||
|
||||
public async Task<RegisterTenantResult> Handle(
|
||||
RegisterTenantCommand request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. Validate slug uniqueness
|
||||
var slug = TenantSlug.Create(request.TenantSlug);
|
||||
var slugExists = await _tenantRepository.ExistsBySlugAsync(slug, cancellationToken);
|
||||
var slugExists = await tenantRepository.ExistsBySlugAsync(slug, cancellationToken);
|
||||
if (slugExists)
|
||||
{
|
||||
throw new InvalidOperationException($"Tenant slug '{request.TenantSlug}' is already taken");
|
||||
@@ -50,17 +34,17 @@ public class RegisterTenantCommandHandler : IRequestHandler<RegisterTenantComman
|
||||
slug,
|
||||
plan);
|
||||
|
||||
await _tenantRepository.AddAsync(tenant, cancellationToken);
|
||||
await tenantRepository.AddAsync(tenant, cancellationToken);
|
||||
|
||||
// 3. Create admin user with hashed password
|
||||
var hashedPassword = _passwordHasher.HashPassword(request.AdminPassword);
|
||||
var hashedPassword = passwordHasher.HashPassword(request.AdminPassword);
|
||||
var adminUser = User.CreateLocal(
|
||||
TenantId.Create(tenant.Id),
|
||||
Email.Create(request.AdminEmail),
|
||||
hashedPassword,
|
||||
FullName.Create(request.AdminFullName));
|
||||
|
||||
await _userRepository.AddAsync(adminUser, cancellationToken);
|
||||
await userRepository.AddAsync(adminUser, cancellationToken);
|
||||
|
||||
// 4. Assign TenantOwner role to admin user
|
||||
var tenantOwnerRole = UserTenantRole.Create(
|
||||
@@ -68,13 +52,13 @@ public class RegisterTenantCommandHandler : IRequestHandler<RegisterTenantComman
|
||||
TenantId.Create(tenant.Id),
|
||||
TenantRole.TenantOwner);
|
||||
|
||||
await _userTenantRoleRepository.AddAsync(tenantOwnerRole, cancellationToken);
|
||||
await userTenantRoleRepository.AddAsync(tenantOwnerRole, cancellationToken);
|
||||
|
||||
// 5. Generate JWT token with role
|
||||
var accessToken = _jwtService.GenerateToken(adminUser, tenant, TenantRole.TenantOwner);
|
||||
var accessToken = jwtService.GenerateToken(adminUser, tenant, TenantRole.TenantOwner);
|
||||
|
||||
// 6. Generate refresh token
|
||||
var refreshToken = await _refreshTokenService.GenerateRefreshTokenAsync(
|
||||
var refreshToken = await refreshTokenService.GenerateRefreshTokenAsync(
|
||||
adminUser,
|
||||
ipAddress: null,
|
||||
userAgent: null,
|
||||
|
||||
@@ -6,26 +6,16 @@ using MediatR;
|
||||
|
||||
namespace ColaFlow.Modules.Identity.Application.Commands.RemoveUserFromTenant;
|
||||
|
||||
public class RemoveUserFromTenantCommandHandler : IRequestHandler<RemoveUserFromTenantCommand, Unit>
|
||||
public class RemoveUserFromTenantCommandHandler(
|
||||
IUserTenantRoleRepository userTenantRoleRepository,
|
||||
IRefreshTokenRepository refreshTokenRepository,
|
||||
IUserRepository userRepository)
|
||||
: IRequestHandler<RemoveUserFromTenantCommand, Unit>
|
||||
{
|
||||
private readonly IUserTenantRoleRepository _userTenantRoleRepository;
|
||||
private readonly IRefreshTokenRepository _refreshTokenRepository;
|
||||
private readonly IUserRepository _userRepository;
|
||||
|
||||
public RemoveUserFromTenantCommandHandler(
|
||||
IUserTenantRoleRepository userTenantRoleRepository,
|
||||
IRefreshTokenRepository refreshTokenRepository,
|
||||
IUserRepository userRepository)
|
||||
{
|
||||
_userTenantRoleRepository = userTenantRoleRepository;
|
||||
_refreshTokenRepository = refreshTokenRepository;
|
||||
_userRepository = userRepository;
|
||||
}
|
||||
|
||||
public async Task<Unit> Handle(RemoveUserFromTenantCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Get user's role in tenant
|
||||
var userTenantRole = await _userTenantRoleRepository.GetByUserAndTenantAsync(
|
||||
var userTenantRole = await userTenantRoleRepository.GetByUserAndTenantAsync(
|
||||
request.UserId,
|
||||
request.TenantId,
|
||||
cancellationToken);
|
||||
@@ -34,13 +24,13 @@ public class RemoveUserFromTenantCommandHandler : IRequestHandler<RemoveUserFrom
|
||||
throw new InvalidOperationException("User is not a member of this tenant");
|
||||
|
||||
// Check if this is the last TenantOwner
|
||||
if (await _userTenantRoleRepository.IsLastTenantOwnerAsync(request.TenantId, request.UserId, cancellationToken))
|
||||
if (await userTenantRoleRepository.IsLastTenantOwnerAsync(request.TenantId, request.UserId, cancellationToken))
|
||||
{
|
||||
throw new InvalidOperationException("Cannot remove the last TenantOwner from the tenant");
|
||||
}
|
||||
|
||||
// Revoke all user's refresh tokens for this tenant
|
||||
var userTokens = await _refreshTokenRepository.GetByUserAndTenantAsync(
|
||||
var userTokens = await refreshTokenRepository.GetByUserAndTenantAsync(
|
||||
request.UserId,
|
||||
request.TenantId,
|
||||
cancellationToken);
|
||||
@@ -52,11 +42,11 @@ public class RemoveUserFromTenantCommandHandler : IRequestHandler<RemoveUserFrom
|
||||
|
||||
if (userTokens.Any())
|
||||
{
|
||||
await _refreshTokenRepository.UpdateRangeAsync(userTokens, cancellationToken);
|
||||
await refreshTokenRepository.UpdateRangeAsync(userTokens, cancellationToken);
|
||||
}
|
||||
|
||||
// Raise domain event before deletion
|
||||
var user = await _userRepository.GetByIdAsync(request.UserId, cancellationToken);
|
||||
var user = await userRepository.GetByIdAsync(request.UserId, cancellationToken);
|
||||
if (user != null)
|
||||
{
|
||||
user.RaiseRemovedFromTenantEvent(
|
||||
@@ -65,11 +55,11 @@ public class RemoveUserFromTenantCommandHandler : IRequestHandler<RemoveUserFrom
|
||||
request.Reason ?? "User removed from tenant"
|
||||
);
|
||||
|
||||
await _userRepository.UpdateAsync(user, cancellationToken);
|
||||
await userRepository.UpdateAsync(user, cancellationToken);
|
||||
}
|
||||
|
||||
// Remove user's role
|
||||
await _userTenantRoleRepository.DeleteAsync(userTenantRole, cancellationToken);
|
||||
await userTenantRoleRepository.DeleteAsync(userTenantRole, cancellationToken);
|
||||
|
||||
return Unit.Value;
|
||||
}
|
||||
|
||||
@@ -4,18 +4,12 @@ using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace ColaFlow.Modules.Identity.Application.EventHandlers;
|
||||
|
||||
public sealed class TenantCreatedEventHandler : INotificationHandler<TenantCreatedEvent>
|
||||
public sealed class TenantCreatedEventHandler(ILogger<TenantCreatedEventHandler> logger)
|
||||
: INotificationHandler<TenantCreatedEvent>
|
||||
{
|
||||
private readonly ILogger<TenantCreatedEventHandler> _logger;
|
||||
|
||||
public TenantCreatedEventHandler(ILogger<TenantCreatedEventHandler> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public Task Handle(TenantCreatedEvent notification, CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
logger.LogInformation(
|
||||
"Tenant {TenantId} created with slug '{Slug}'",
|
||||
notification.TenantId,
|
||||
notification.Slug);
|
||||
|
||||
@@ -4,18 +4,12 @@ using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace ColaFlow.Modules.Identity.Application.EventHandlers;
|
||||
|
||||
public sealed class UserLoggedInEventHandler : INotificationHandler<UserLoggedInEvent>
|
||||
public sealed class UserLoggedInEventHandler(ILogger<UserLoggedInEventHandler> logger)
|
||||
: INotificationHandler<UserLoggedInEvent>
|
||||
{
|
||||
private readonly ILogger<UserLoggedInEventHandler> _logger;
|
||||
|
||||
public UserLoggedInEventHandler(ILogger<UserLoggedInEventHandler> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public Task Handle(UserLoggedInEvent notification, CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
logger.LogInformation(
|
||||
"User {UserId} logged in to tenant {TenantId} from IP {IpAddress}",
|
||||
notification.UserId,
|
||||
notification.TenantId.Value,
|
||||
|
||||
@@ -4,18 +4,12 @@ using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace ColaFlow.Modules.Identity.Application.EventHandlers;
|
||||
|
||||
public sealed class UserRemovedFromTenantEventHandler : INotificationHandler<UserRemovedFromTenantEvent>
|
||||
public sealed class UserRemovedFromTenantEventHandler(ILogger<UserRemovedFromTenantEventHandler> logger)
|
||||
: INotificationHandler<UserRemovedFromTenantEvent>
|
||||
{
|
||||
private readonly ILogger<UserRemovedFromTenantEventHandler> _logger;
|
||||
|
||||
public UserRemovedFromTenantEventHandler(ILogger<UserRemovedFromTenantEventHandler> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public Task Handle(UserRemovedFromTenantEvent notification, CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
logger.LogInformation(
|
||||
"User {UserId} removed from tenant {TenantId}. Removed by: {RemovedBy}. Reason: {Reason}",
|
||||
notification.UserId,
|
||||
notification.TenantId.Value,
|
||||
|
||||
@@ -4,18 +4,12 @@ using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace ColaFlow.Modules.Identity.Application.EventHandlers;
|
||||
|
||||
public sealed class UserRoleAssignedEventHandler : INotificationHandler<UserRoleAssignedEvent>
|
||||
public sealed class UserRoleAssignedEventHandler(ILogger<UserRoleAssignedEventHandler> logger)
|
||||
: INotificationHandler<UserRoleAssignedEvent>
|
||||
{
|
||||
private readonly ILogger<UserRoleAssignedEventHandler> _logger;
|
||||
|
||||
public UserRoleAssignedEventHandler(ILogger<UserRoleAssignedEventHandler> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public Task Handle(UserRoleAssignedEvent notification, CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
logger.LogInformation(
|
||||
"User {UserId} assigned role {Role} in tenant {TenantId}. Previous role: {PreviousRole}. Assigned by: {AssignedBy}",
|
||||
notification.UserId,
|
||||
notification.Role,
|
||||
|
||||
@@ -5,19 +5,13 @@ using MediatR;
|
||||
|
||||
namespace ColaFlow.Modules.Identity.Application.Queries.GetTenantBySlug;
|
||||
|
||||
public class GetTenantBySlugQueryHandler : IRequestHandler<GetTenantBySlugQuery, TenantDto?>
|
||||
public class GetTenantBySlugQueryHandler(ITenantRepository tenantRepository)
|
||||
: IRequestHandler<GetTenantBySlugQuery, TenantDto?>
|
||||
{
|
||||
private readonly ITenantRepository _tenantRepository;
|
||||
|
||||
public GetTenantBySlugQueryHandler(ITenantRepository tenantRepository)
|
||||
{
|
||||
_tenantRepository = tenantRepository;
|
||||
}
|
||||
|
||||
public async Task<TenantDto?> Handle(GetTenantBySlugQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var slug = TenantSlug.Create(request.Slug);
|
||||
var tenant = await _tenantRepository.GetBySlugAsync(slug, cancellationToken);
|
||||
var tenant = await tenantRepository.GetBySlugAsync(slug, cancellationToken);
|
||||
|
||||
if (tenant == null)
|
||||
return null;
|
||||
|
||||
@@ -4,24 +4,16 @@ using MediatR;
|
||||
|
||||
namespace ColaFlow.Modules.Identity.Application.Queries.ListTenantUsers;
|
||||
|
||||
public class ListTenantUsersQueryHandler : IRequestHandler<ListTenantUsersQuery, PagedResultDto<UserWithRoleDto>>
|
||||
public class ListTenantUsersQueryHandler(
|
||||
IUserTenantRoleRepository userTenantRoleRepository,
|
||||
IUserRepository userRepository)
|
||||
: IRequestHandler<ListTenantUsersQuery, PagedResultDto<UserWithRoleDto>>
|
||||
{
|
||||
private readonly IUserTenantRoleRepository _userTenantRoleRepository;
|
||||
private readonly IUserRepository _userRepository;
|
||||
|
||||
public ListTenantUsersQueryHandler(
|
||||
IUserTenantRoleRepository userTenantRoleRepository,
|
||||
IUserRepository userRepository)
|
||||
{
|
||||
_userTenantRoleRepository = userTenantRoleRepository;
|
||||
_userRepository = userRepository;
|
||||
}
|
||||
|
||||
public async Task<PagedResultDto<UserWithRoleDto>> Handle(
|
||||
ListTenantUsersQuery request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var (roles, totalCount) = await _userTenantRoleRepository.GetTenantUsersWithRolesAsync(
|
||||
var (roles, totalCount) = await userTenantRoleRepository.GetTenantUsersWithRolesAsync(
|
||||
request.TenantId,
|
||||
request.PageNumber,
|
||||
request.PageSize,
|
||||
@@ -32,7 +24,7 @@ public class ListTenantUsersQueryHandler : IRequestHandler<ListTenantUsersQuery,
|
||||
|
||||
foreach (var role in roles)
|
||||
{
|
||||
var user = await _userRepository.GetByIdAsync(role.UserId, cancellationToken);
|
||||
var user = await userRepository.GetByIdAsync(role.UserId, cancellationToken);
|
||||
|
||||
if (user != null)
|
||||
{
|
||||
|
||||
@@ -7,21 +7,12 @@ using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ColaFlow.Modules.Identity.Infrastructure.Persistence;
|
||||
|
||||
public class IdentityDbContext : DbContext
|
||||
public class IdentityDbContext(
|
||||
DbContextOptions<IdentityDbContext> options,
|
||||
ITenantContext tenantContext,
|
||||
IMediator mediator)
|
||||
: DbContext(options)
|
||||
{
|
||||
private readonly ITenantContext _tenantContext;
|
||||
private readonly IMediator _mediator;
|
||||
|
||||
public IdentityDbContext(
|
||||
DbContextOptions<IdentityDbContext> options,
|
||||
ITenantContext tenantContext,
|
||||
IMediator mediator)
|
||||
: base(options)
|
||||
{
|
||||
_tenantContext = tenantContext;
|
||||
_mediator = mediator;
|
||||
}
|
||||
|
||||
public DbSet<Tenant> Tenants => Set<Tenant>();
|
||||
public DbSet<User> Users => Set<User>();
|
||||
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
|
||||
@@ -43,7 +34,7 @@ public class IdentityDbContext : DbContext
|
||||
// User entity global query filter
|
||||
// Automatically adds: WHERE tenant_id = @current_tenant_id
|
||||
modelBuilder.Entity<User>().HasQueryFilter(u =>
|
||||
!_tenantContext.IsSet || u.TenantId == _tenantContext.TenantId);
|
||||
!tenantContext.IsSet || u.TenantId == tenantContext.TenantId);
|
||||
|
||||
// Tenant entity doesn't need filter (need to query all tenants)
|
||||
}
|
||||
@@ -91,7 +82,7 @@ public class IdentityDbContext : DbContext
|
||||
// Publish each event via MediatR
|
||||
foreach (var domainEvent in domainEvents)
|
||||
{
|
||||
await _mediator.Publish(domainEvent, cancellationToken);
|
||||
await mediator.Publish(domainEvent, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,20 +4,13 @@ using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ColaFlow.Modules.Identity.Infrastructure.Persistence.Repositories;
|
||||
|
||||
public class RefreshTokenRepository : IRefreshTokenRepository
|
||||
public class RefreshTokenRepository(IdentityDbContext context) : IRefreshTokenRepository
|
||||
{
|
||||
private readonly IdentityDbContext _context;
|
||||
|
||||
public RefreshTokenRepository(IdentityDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public async Task<RefreshToken?> GetByTokenHashAsync(
|
||||
string tokenHash,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await _context.RefreshTokens
|
||||
return await context.RefreshTokens
|
||||
.FirstOrDefaultAsync(rt => rt.TokenHash == tokenHash, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -25,7 +18,7 @@ public class RefreshTokenRepository : IRefreshTokenRepository
|
||||
Guid userId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await _context.RefreshTokens
|
||||
return await context.RefreshTokens
|
||||
.Where(rt => rt.UserId.Value == userId)
|
||||
.OrderByDescending(rt => rt.CreatedAt)
|
||||
.ToListAsync(cancellationToken);
|
||||
@@ -36,7 +29,7 @@ public class RefreshTokenRepository : IRefreshTokenRepository
|
||||
Guid tenantId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await _context.RefreshTokens
|
||||
return await context.RefreshTokens
|
||||
.Where(rt => rt.UserId.Value == userId && rt.TenantId == tenantId)
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
@@ -45,24 +38,24 @@ public class RefreshTokenRepository : IRefreshTokenRepository
|
||||
RefreshToken refreshToken,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _context.RefreshTokens.AddAsync(refreshToken, cancellationToken);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
await context.RefreshTokens.AddAsync(refreshToken, cancellationToken);
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task UpdateAsync(
|
||||
RefreshToken refreshToken,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
_context.RefreshTokens.Update(refreshToken);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
context.RefreshTokens.Update(refreshToken);
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task UpdateRangeAsync(
|
||||
IEnumerable<RefreshToken> refreshTokens,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
_context.RefreshTokens.UpdateRange(refreshTokens);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
context.RefreshTokens.UpdateRange(refreshTokens);
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task RevokeAllUserTokensAsync(
|
||||
@@ -70,7 +63,7 @@ public class RefreshTokenRepository : IRefreshTokenRepository
|
||||
string reason,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var tokens = await _context.RefreshTokens
|
||||
var tokens = await context.RefreshTokens
|
||||
.Where(rt => rt.UserId.Value == userId && rt.RevokedAt == null)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
@@ -79,16 +72,16 @@ public class RefreshTokenRepository : IRefreshTokenRepository
|
||||
token.Revoke(reason);
|
||||
}
|
||||
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task DeleteExpiredTokensAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var expiredTokens = await _context.RefreshTokens
|
||||
var expiredTokens = await context.RefreshTokens
|
||||
.Where(rt => rt.ExpiresAt < DateTime.UtcNow)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
_context.RefreshTokens.RemoveRange(expiredTokens);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
context.RefreshTokens.RemoveRange(expiredTokens);
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,53 +4,46 @@ using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ColaFlow.Modules.Identity.Infrastructure.Persistence.Repositories;
|
||||
|
||||
public class TenantRepository : ITenantRepository
|
||||
public class TenantRepository(IdentityDbContext context) : ITenantRepository
|
||||
{
|
||||
private readonly IdentityDbContext _context;
|
||||
|
||||
public TenantRepository(IdentityDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public async Task<Tenant?> GetByIdAsync(TenantId tenantId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await _context.Tenants
|
||||
return await context.Tenants
|
||||
.FirstOrDefaultAsync(t => t.Id == tenantId, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<Tenant?> GetBySlugAsync(TenantSlug slug, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await _context.Tenants
|
||||
return await context.Tenants
|
||||
.FirstOrDefaultAsync(t => t.Slug == slug, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<bool> ExistsBySlugAsync(TenantSlug slug, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await _context.Tenants
|
||||
return await context.Tenants
|
||||
.AnyAsync(t => t.Slug == slug, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<Tenant>> GetAllAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await _context.Tenants.ToListAsync(cancellationToken);
|
||||
return await context.Tenants.ToListAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task AddAsync(Tenant tenant, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _context.Tenants.AddAsync(tenant, cancellationToken);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
await context.Tenants.AddAsync(tenant, cancellationToken);
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task UpdateAsync(Tenant tenant, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_context.Tenants.Update(tenant);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
context.Tenants.Update(tenant);
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(Tenant tenant, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_context.Tenants.Remove(tenant);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
context.Tenants.Remove(tenant);
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,26 +5,19 @@ using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ColaFlow.Modules.Identity.Infrastructure.Persistence.Repositories;
|
||||
|
||||
public class UserRepository : IUserRepository
|
||||
public class UserRepository(IdentityDbContext context) : IUserRepository
|
||||
{
|
||||
private readonly IdentityDbContext _context;
|
||||
|
||||
public UserRepository(IdentityDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public async Task<User?> GetByIdAsync(UserId userId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
// Global Query Filter automatically applies
|
||||
return await _context.Users
|
||||
return await context.Users
|
||||
.FirstOrDefaultAsync(u => u.Id == userId, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<User?> GetByIdAsync(Guid userId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var userIdVO = UserId.Create(userId);
|
||||
return await _context.Users
|
||||
return await context.Users
|
||||
.FirstOrDefaultAsync(u => u.Id == userIdVO, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -49,7 +42,7 @@ public class UserRepository : IUserRepository
|
||||
|
||||
public async Task<User?> GetByEmailAsync(TenantId tenantId, Email email, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await _context.Users
|
||||
return await context.Users
|
||||
.FirstOrDefaultAsync(u => u.TenantId == tenantId && u.Email == email, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -59,7 +52,7 @@ public class UserRepository : IUserRepository
|
||||
string externalUserId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await _context.Users
|
||||
return await context.Users
|
||||
.FirstOrDefaultAsync(
|
||||
u => u.TenantId == tenantId &&
|
||||
u.AuthProvider == provider &&
|
||||
@@ -69,38 +62,38 @@ public class UserRepository : IUserRepository
|
||||
|
||||
public async Task<bool> ExistsByEmailAsync(TenantId tenantId, Email email, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await _context.Users
|
||||
return await context.Users
|
||||
.AnyAsync(u => u.TenantId == tenantId && u.Email == email, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<User>> GetAllByTenantAsync(TenantId tenantId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await _context.Users
|
||||
return await context.Users
|
||||
.Where(u => u.TenantId == tenantId)
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<int> GetActiveUsersCountAsync(TenantId tenantId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await _context.Users
|
||||
return await context.Users
|
||||
.CountAsync(u => u.TenantId == tenantId && u.Status == UserStatus.Active, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task AddAsync(User user, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _context.Users.AddAsync(user, cancellationToken);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
await context.Users.AddAsync(user, cancellationToken);
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task UpdateAsync(User user, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_context.Users.Update(user);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
context.Users.Update(user);
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(User user, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_context.Users.Remove(user);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
context.Users.Remove(user);
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,15 +5,8 @@ using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ColaFlow.Modules.Identity.Infrastructure.Persistence.Repositories;
|
||||
|
||||
public class UserTenantRoleRepository : IUserTenantRoleRepository
|
||||
public class UserTenantRoleRepository(IdentityDbContext context) : IUserTenantRoleRepository
|
||||
{
|
||||
private readonly IdentityDbContext _context;
|
||||
|
||||
public UserTenantRoleRepository(IdentityDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public async Task<UserTenantRole?> GetByUserAndTenantAsync(
|
||||
Guid userId,
|
||||
Guid tenantId,
|
||||
@@ -23,7 +16,7 @@ public class UserTenantRoleRepository : IUserTenantRoleRepository
|
||||
var userIdVO = UserId.Create(userId);
|
||||
var tenantIdVO = TenantId.Create(tenantId);
|
||||
|
||||
return await _context.UserTenantRoles
|
||||
return await context.UserTenantRoles
|
||||
.FirstOrDefaultAsync(
|
||||
utr => utr.UserId == userIdVO && utr.TenantId == tenantIdVO,
|
||||
cancellationToken);
|
||||
@@ -36,7 +29,7 @@ public class UserTenantRoleRepository : IUserTenantRoleRepository
|
||||
// Create value object to avoid LINQ translation issues with .Value property
|
||||
var userIdVO = UserId.Create(userId);
|
||||
|
||||
return await _context.UserTenantRoles
|
||||
return await context.UserTenantRoles
|
||||
.Where(utr => utr.UserId == userIdVO)
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
@@ -48,7 +41,7 @@ public class UserTenantRoleRepository : IUserTenantRoleRepository
|
||||
// Create value object to avoid LINQ translation issues with .Value property
|
||||
var tenantIdVO = TenantId.Create(tenantId);
|
||||
|
||||
return await _context.UserTenantRoles
|
||||
return await context.UserTenantRoles
|
||||
.Where(utr => utr.TenantId == tenantIdVO)
|
||||
// Note: User navigation is ignored in EF config, so Include is skipped
|
||||
.ToListAsync(cancellationToken);
|
||||
@@ -56,20 +49,20 @@ public class UserTenantRoleRepository : IUserTenantRoleRepository
|
||||
|
||||
public async Task AddAsync(UserTenantRole role, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _context.UserTenantRoles.AddAsync(role, cancellationToken);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
await context.UserTenantRoles.AddAsync(role, cancellationToken);
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task UpdateAsync(UserTenantRole role, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_context.UserTenantRoles.Update(role);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
context.UserTenantRoles.Update(role);
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(UserTenantRole role, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_context.UserTenantRoles.Remove(role);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
context.UserTenantRoles.Remove(role);
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<(List<UserTenantRole> Items, int TotalCount)> GetTenantUsersWithRolesAsync(
|
||||
@@ -81,7 +74,7 @@ public class UserTenantRoleRepository : IUserTenantRoleRepository
|
||||
{
|
||||
var tenantIdVO = TenantId.Create(tenantId);
|
||||
|
||||
var query = _context.UserTenantRoles
|
||||
var query = context.UserTenantRoles
|
||||
.Where(utr => utr.TenantId == tenantIdVO);
|
||||
|
||||
// Note: Search filtering would require joining with Users table
|
||||
@@ -105,14 +98,14 @@ public class UserTenantRoleRepository : IUserTenantRoleRepository
|
||||
{
|
||||
var tenantIdVO = TenantId.Create(tenantId);
|
||||
|
||||
var ownerCount = await _context.UserTenantRoles
|
||||
var ownerCount = await context.UserTenantRoles
|
||||
.Where(utr => utr.TenantId == tenantIdVO && utr.Role == TenantRole.TenantOwner)
|
||||
.CountAsync(cancellationToken);
|
||||
|
||||
if (ownerCount <= 1)
|
||||
{
|
||||
var userIdVO = UserId.Create(userId);
|
||||
var userIsOwner = await _context.UserTenantRoles
|
||||
var userIsOwner = await context.UserTenantRoles
|
||||
.AnyAsync(utr => utr.TenantId == tenantIdVO &&
|
||||
utr.UserId == userIdVO &&
|
||||
utr.Role == TenantRole.TenantOwner,
|
||||
@@ -131,7 +124,7 @@ public class UserTenantRoleRepository : IUserTenantRoleRepository
|
||||
{
|
||||
var tenantIdVO = TenantId.Create(tenantId);
|
||||
|
||||
return await _context.UserTenantRoles
|
||||
return await context.UserTenantRoles
|
||||
.CountAsync(utr => utr.TenantId == tenantIdVO && utr.Role == role,
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
@@ -9,19 +9,12 @@ using System.Text;
|
||||
|
||||
namespace ColaFlow.Modules.Identity.Infrastructure.Services;
|
||||
|
||||
public class JwtService : IJwtService
|
||||
public class JwtService(IConfiguration configuration) : IJwtService
|
||||
{
|
||||
private readonly IConfiguration _configuration;
|
||||
|
||||
public JwtService(IConfiguration configuration)
|
||||
{
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
public string GenerateToken(User user, Tenant tenant, TenantRole tenantRole)
|
||||
{
|
||||
var securityKey = new SymmetricSecurityKey(
|
||||
Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"] ?? throw new InvalidOperationException("JWT SecretKey not configured")));
|
||||
Encoding.UTF8.GetBytes(configuration["Jwt:SecretKey"] ?? throw new InvalidOperationException("JWT SecretKey not configured")));
|
||||
|
||||
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
|
||||
|
||||
@@ -43,10 +36,10 @@ public class JwtService : IJwtService
|
||||
};
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: _configuration["Jwt:Issuer"],
|
||||
audience: _configuration["Jwt:Audience"],
|
||||
issuer: configuration["Jwt:Issuer"],
|
||||
audience: configuration["Jwt:Audience"],
|
||||
claims: claims,
|
||||
expires: DateTime.UtcNow.AddMinutes(Convert.ToDouble(_configuration["Jwt:ExpirationMinutes"] ?? "60")),
|
||||
expires: DateTime.UtcNow.AddMinutes(Convert.ToDouble(configuration["Jwt:ExpirationMinutes"] ?? "60")),
|
||||
signingCredentials: credentials
|
||||
);
|
||||
|
||||
|
||||
@@ -9,34 +9,16 @@ using System.Text;
|
||||
|
||||
namespace ColaFlow.Modules.Identity.Infrastructure.Services;
|
||||
|
||||
public class RefreshTokenService : IRefreshTokenService
|
||||
public class RefreshTokenService(
|
||||
IRefreshTokenRepository refreshTokenRepository,
|
||||
IUserRepository userRepository,
|
||||
ITenantRepository tenantRepository,
|
||||
IUserTenantRoleRepository userTenantRoleRepository,
|
||||
IJwtService jwtService,
|
||||
IConfiguration configuration,
|
||||
ILogger<RefreshTokenService> logger)
|
||||
: IRefreshTokenService
|
||||
{
|
||||
private readonly IRefreshTokenRepository _refreshTokenRepository;
|
||||
private readonly IUserRepository _userRepository;
|
||||
private readonly ITenantRepository _tenantRepository;
|
||||
private readonly IUserTenantRoleRepository _userTenantRoleRepository;
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly ILogger<RefreshTokenService> _logger;
|
||||
|
||||
public RefreshTokenService(
|
||||
IRefreshTokenRepository refreshTokenRepository,
|
||||
IUserRepository userRepository,
|
||||
ITenantRepository tenantRepository,
|
||||
IUserTenantRoleRepository userTenantRoleRepository,
|
||||
IJwtService jwtService,
|
||||
IConfiguration configuration,
|
||||
ILogger<RefreshTokenService> logger)
|
||||
{
|
||||
_refreshTokenRepository = refreshTokenRepository;
|
||||
_userRepository = userRepository;
|
||||
_tenantRepository = tenantRepository;
|
||||
_userTenantRoleRepository = userTenantRoleRepository;
|
||||
_jwtService = jwtService;
|
||||
_configuration = configuration;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<string> GenerateRefreshTokenAsync(
|
||||
User user,
|
||||
string? ipAddress = null,
|
||||
@@ -53,7 +35,7 @@ public class RefreshTokenService : IRefreshTokenService
|
||||
var tokenHash = ComputeSha256Hash(token);
|
||||
|
||||
// Get expiration from configuration (default 7 days)
|
||||
var expirationDays = _configuration.GetValue<int>("Jwt:RefreshTokenExpirationDays", 7);
|
||||
var expirationDays = configuration.GetValue<int>("Jwt:RefreshTokenExpirationDays", 7);
|
||||
var expiresAt = DateTime.UtcNow.AddDays(expirationDays);
|
||||
|
||||
// Create refresh token entity
|
||||
@@ -68,9 +50,9 @@ public class RefreshTokenService : IRefreshTokenService
|
||||
);
|
||||
|
||||
// Save to database
|
||||
await _refreshTokenRepository.AddAsync(refreshToken, cancellationToken);
|
||||
await refreshTokenRepository.AddAsync(refreshToken, cancellationToken);
|
||||
|
||||
_logger.LogInformation(
|
||||
logger.LogInformation(
|
||||
"Generated refresh token for user {UserId}, expires at {ExpiresAt}",
|
||||
user.Id, expiresAt);
|
||||
|
||||
@@ -88,25 +70,25 @@ public class RefreshTokenService : IRefreshTokenService
|
||||
var tokenHash = ComputeSha256Hash(refreshToken);
|
||||
|
||||
// Find existing token
|
||||
var existingToken = await _refreshTokenRepository.GetByTokenHashAsync(tokenHash, cancellationToken);
|
||||
var existingToken = await refreshTokenRepository.GetByTokenHashAsync(tokenHash, cancellationToken);
|
||||
|
||||
if (existingToken == null)
|
||||
{
|
||||
_logger.LogWarning("Refresh token not found: {TokenHash}", tokenHash[..10] + "...");
|
||||
logger.LogWarning("Refresh token not found: {TokenHash}", tokenHash[..10] + "...");
|
||||
throw new UnauthorizedAccessException("Invalid refresh token");
|
||||
}
|
||||
|
||||
// Check if token is active (not expired and not revoked)
|
||||
if (!existingToken.IsActive())
|
||||
{
|
||||
_logger.LogWarning(
|
||||
logger.LogWarning(
|
||||
"Attempted to use invalid refresh token for user {UserId}. Expired: {IsExpired}, Revoked: {IsRevoked}",
|
||||
existingToken.UserId.Value, existingToken.IsExpired(), existingToken.IsRevoked());
|
||||
|
||||
// SECURITY: Token reuse detection - revoke all user tokens
|
||||
if (existingToken.IsRevoked())
|
||||
{
|
||||
_logger.LogWarning(
|
||||
logger.LogWarning(
|
||||
"SECURITY ALERT: Revoked token reused for user {UserId}. Revoking all tokens.",
|
||||
existingToken.UserId.Value);
|
||||
await RevokeAllUserTokensAsync(existingToken.UserId.Value, cancellationToken);
|
||||
@@ -116,34 +98,34 @@ public class RefreshTokenService : IRefreshTokenService
|
||||
}
|
||||
|
||||
// Get user and tenant
|
||||
var user = await _userRepository.GetByIdAsync(existingToken.UserId, cancellationToken);
|
||||
var user = await userRepository.GetByIdAsync(existingToken.UserId, cancellationToken);
|
||||
if (user == null || user.Status != UserStatus.Active)
|
||||
{
|
||||
_logger.LogWarning("User not found or inactive: {UserId}", existingToken.UserId.Value);
|
||||
logger.LogWarning("User not found or inactive: {UserId}", existingToken.UserId.Value);
|
||||
throw new UnauthorizedAccessException("User not found or inactive");
|
||||
}
|
||||
|
||||
var tenant = await _tenantRepository.GetByIdAsync(TenantId.Create(existingToken.TenantId), cancellationToken);
|
||||
var tenant = await tenantRepository.GetByIdAsync(TenantId.Create(existingToken.TenantId), cancellationToken);
|
||||
if (tenant == null || tenant.Status != TenantStatus.Active)
|
||||
{
|
||||
_logger.LogWarning("Tenant not found or inactive: {TenantId}", existingToken.TenantId);
|
||||
logger.LogWarning("Tenant not found or inactive: {TenantId}", existingToken.TenantId);
|
||||
throw new UnauthorizedAccessException("Tenant not found or inactive");
|
||||
}
|
||||
|
||||
// Get user's tenant role
|
||||
var userTenantRole = await _userTenantRoleRepository.GetByUserAndTenantAsync(
|
||||
var userTenantRole = await userTenantRoleRepository.GetByUserAndTenantAsync(
|
||||
user.Id,
|
||||
tenant.Id,
|
||||
cancellationToken);
|
||||
|
||||
if (userTenantRole == null)
|
||||
{
|
||||
_logger.LogWarning("User {UserId} has no role assigned for tenant {TenantId}", user.Id, tenant.Id);
|
||||
logger.LogWarning("User {UserId} has no role assigned for tenant {TenantId}", user.Id, tenant.Id);
|
||||
throw new UnauthorizedAccessException("User role not found");
|
||||
}
|
||||
|
||||
// Generate new access token with role
|
||||
var newAccessToken = _jwtService.GenerateToken(user, tenant, userTenantRole.Role);
|
||||
var newAccessToken = jwtService.GenerateToken(user, tenant, userTenantRole.Role);
|
||||
|
||||
// Generate new refresh token (token rotation)
|
||||
var newRefreshToken = await GenerateRefreshTokenAsync(user, ipAddress, userAgent, cancellationToken);
|
||||
@@ -151,9 +133,9 @@ public class RefreshTokenService : IRefreshTokenService
|
||||
// Mark old token as replaced
|
||||
var newTokenHash = ComputeSha256Hash(newRefreshToken);
|
||||
existingToken.MarkAsReplaced(newTokenHash);
|
||||
await _refreshTokenRepository.UpdateAsync(existingToken, cancellationToken);
|
||||
await refreshTokenRepository.UpdateAsync(existingToken, cancellationToken);
|
||||
|
||||
_logger.LogInformation(
|
||||
logger.LogInformation(
|
||||
"Rotated refresh token for user {UserId}",
|
||||
user.Id);
|
||||
|
||||
@@ -166,17 +148,17 @@ public class RefreshTokenService : IRefreshTokenService
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var tokenHash = ComputeSha256Hash(refreshToken);
|
||||
var token = await _refreshTokenRepository.GetByTokenHashAsync(tokenHash, cancellationToken);
|
||||
var token = await refreshTokenRepository.GetByTokenHashAsync(tokenHash, cancellationToken);
|
||||
|
||||
if (token == null)
|
||||
{
|
||||
_logger.LogWarning("Attempted to revoke non-existent token");
|
||||
logger.LogWarning("Attempted to revoke non-existent token");
|
||||
return; // Silent failure for security
|
||||
}
|
||||
|
||||
if (token.IsRevoked())
|
||||
{
|
||||
_logger.LogWarning("Token already revoked: {TokenId}", token.Id);
|
||||
logger.LogWarning("Token already revoked: {TokenId}", token.Id);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -185,9 +167,9 @@ public class RefreshTokenService : IRefreshTokenService
|
||||
: "User logout";
|
||||
|
||||
token.Revoke(reason);
|
||||
await _refreshTokenRepository.UpdateAsync(token, cancellationToken);
|
||||
await refreshTokenRepository.UpdateAsync(token, cancellationToken);
|
||||
|
||||
_logger.LogInformation(
|
||||
logger.LogInformation(
|
||||
"Revoked refresh token {TokenId} for user {UserId}",
|
||||
token.Id, token.UserId.Value);
|
||||
}
|
||||
@@ -196,12 +178,12 @@ public class RefreshTokenService : IRefreshTokenService
|
||||
Guid userId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _refreshTokenRepository.RevokeAllUserTokensAsync(
|
||||
await refreshTokenRepository.RevokeAllUserTokensAsync(
|
||||
userId,
|
||||
"User requested logout from all devices",
|
||||
cancellationToken);
|
||||
|
||||
_logger.LogInformation(
|
||||
logger.LogInformation(
|
||||
"Revoked all refresh tokens for user {UserId}",
|
||||
userId);
|
||||
}
|
||||
|
||||
@@ -6,22 +6,16 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Behaviors;
|
||||
/// <summary>
|
||||
/// Pipeline behavior for request validation using FluentValidation
|
||||
/// </summary>
|
||||
public sealed class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
|
||||
public sealed class ValidationBehavior<TRequest, TResponse>(IEnumerable<IValidator<TRequest>> validators)
|
||||
: IPipelineBehavior<TRequest, TResponse>
|
||||
where TRequest : IRequest<TResponse>
|
||||
{
|
||||
private readonly IEnumerable<IValidator<TRequest>> _validators;
|
||||
|
||||
public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
|
||||
{
|
||||
_validators = validators;
|
||||
}
|
||||
|
||||
public async Task<TResponse> Handle(
|
||||
TRequest request,
|
||||
RequestHandlerDelegate<TResponse> next,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!_validators.Any())
|
||||
if (!validators.Any())
|
||||
{
|
||||
return await next();
|
||||
}
|
||||
@@ -29,7 +23,7 @@ public sealed class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<
|
||||
var context = new ValidationContext<TRequest>(request);
|
||||
|
||||
var validationResults = await Task.WhenAll(
|
||||
_validators.Select(v => v.ValidateAsync(context, cancellationToken)));
|
||||
validators.Select(v => v.ValidateAsync(context, cancellationToken)));
|
||||
|
||||
var failures = validationResults
|
||||
.SelectMany(r => r.Errors)
|
||||
|
||||
@@ -9,18 +9,13 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Commands.AssignStory;
|
||||
/// <summary>
|
||||
/// Handler for AssignStoryCommand
|
||||
/// </summary>
|
||||
public sealed class AssignStoryCommandHandler : IRequestHandler<AssignStoryCommand, StoryDto>
|
||||
public sealed class AssignStoryCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
: IRequestHandler<AssignStoryCommand, StoryDto>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
public AssignStoryCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
private readonly IUnitOfWork _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
|
||||
public async Task<StoryDto> Handle(AssignStoryCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -10,18 +10,13 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Commands.AssignTask;
|
||||
/// <summary>
|
||||
/// Handler for AssignTaskCommand
|
||||
/// </summary>
|
||||
public sealed class AssignTaskCommandHandler : IRequestHandler<AssignTaskCommand, TaskDto>
|
||||
public sealed class AssignTaskCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
: IRequestHandler<AssignTaskCommand, TaskDto>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
public AssignTaskCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
private readonly IUnitOfWork _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
|
||||
public async Task<TaskDto> Handle(AssignTaskCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -9,18 +9,13 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Commands.CreateEpic;
|
||||
/// <summary>
|
||||
/// Handler for CreateEpicCommand
|
||||
/// </summary>
|
||||
public sealed class CreateEpicCommandHandler : IRequestHandler<CreateEpicCommand, EpicDto>
|
||||
public sealed class CreateEpicCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
: IRequestHandler<CreateEpicCommand, EpicDto>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
public CreateEpicCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
private readonly IUnitOfWork _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
|
||||
public async Task<EpicDto> Handle(CreateEpicCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -10,18 +10,13 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Commands.CreateProject;
|
||||
/// <summary>
|
||||
/// Handler for CreateProjectCommand
|
||||
/// </summary>
|
||||
public sealed class CreateProjectCommandHandler : IRequestHandler<CreateProjectCommand, ProjectDto>
|
||||
public sealed class CreateProjectCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
: IRequestHandler<CreateProjectCommand, ProjectDto>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
public CreateProjectCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
private readonly IUnitOfWork _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
|
||||
public async Task<ProjectDto> Handle(CreateProjectCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -9,18 +9,13 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Commands.CreateStory;
|
||||
/// <summary>
|
||||
/// Handler for CreateStoryCommand
|
||||
/// </summary>
|
||||
public sealed class CreateStoryCommandHandler : IRequestHandler<CreateStoryCommand, StoryDto>
|
||||
public sealed class CreateStoryCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
: IRequestHandler<CreateStoryCommand, StoryDto>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
public CreateStoryCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
private readonly IUnitOfWork _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
|
||||
public async Task<StoryDto> Handle(CreateStoryCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -10,18 +10,13 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Commands.CreateTask;
|
||||
/// <summary>
|
||||
/// Handler for CreateTaskCommand
|
||||
/// </summary>
|
||||
public sealed class CreateTaskCommandHandler : IRequestHandler<CreateTaskCommand, TaskDto>
|
||||
public sealed class CreateTaskCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
: IRequestHandler<CreateTaskCommand, TaskDto>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
public CreateTaskCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
private readonly IUnitOfWork _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
|
||||
public async Task<TaskDto> Handle(CreateTaskCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -8,18 +8,13 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Commands.DeleteStory;
|
||||
/// <summary>
|
||||
/// Handler for DeleteStoryCommand
|
||||
/// </summary>
|
||||
public sealed class DeleteStoryCommandHandler : IRequestHandler<DeleteStoryCommand, Unit>
|
||||
public sealed class DeleteStoryCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
: IRequestHandler<DeleteStoryCommand, Unit>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
public DeleteStoryCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
private readonly IUnitOfWork _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
|
||||
public async Task<Unit> Handle(DeleteStoryCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -9,18 +9,13 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Commands.DeleteTask;
|
||||
/// <summary>
|
||||
/// Handler for DeleteTaskCommand
|
||||
/// </summary>
|
||||
public sealed class DeleteTaskCommandHandler : IRequestHandler<DeleteTaskCommand, Unit>
|
||||
public sealed class DeleteTaskCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
: IRequestHandler<DeleteTaskCommand, Unit>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
public DeleteTaskCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
private readonly IUnitOfWork _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
|
||||
public async Task<Unit> Handle(DeleteTaskCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -9,18 +9,13 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateEpic;
|
||||
/// <summary>
|
||||
/// Handler for UpdateEpicCommand
|
||||
/// </summary>
|
||||
public sealed class UpdateEpicCommandHandler : IRequestHandler<UpdateEpicCommand, EpicDto>
|
||||
public sealed class UpdateEpicCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
: IRequestHandler<UpdateEpicCommand, EpicDto>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
public UpdateEpicCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
private readonly IUnitOfWork _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
|
||||
public async Task<EpicDto> Handle(UpdateEpicCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -9,18 +9,13 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateStory;
|
||||
/// <summary>
|
||||
/// Handler for UpdateStoryCommand
|
||||
/// </summary>
|
||||
public sealed class UpdateStoryCommandHandler : IRequestHandler<UpdateStoryCommand, StoryDto>
|
||||
public sealed class UpdateStoryCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
: IRequestHandler<UpdateStoryCommand, StoryDto>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
public UpdateStoryCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
private readonly IUnitOfWork _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
|
||||
public async Task<StoryDto> Handle(UpdateStoryCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -10,18 +10,13 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateTask;
|
||||
/// <summary>
|
||||
/// Handler for UpdateTaskCommand
|
||||
/// </summary>
|
||||
public sealed class UpdateTaskCommandHandler : IRequestHandler<UpdateTaskCommand, TaskDto>
|
||||
public sealed class UpdateTaskCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
: IRequestHandler<UpdateTaskCommand, TaskDto>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
public UpdateTaskCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
private readonly IUnitOfWork _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
|
||||
public async Task<TaskDto> Handle(UpdateTaskCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -10,18 +10,13 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Commands.UpdateTaskStat
|
||||
/// <summary>
|
||||
/// Handler for UpdateTaskStatusCommand
|
||||
/// </summary>
|
||||
public sealed class UpdateTaskStatusCommandHandler : IRequestHandler<UpdateTaskStatusCommand, TaskDto>
|
||||
public sealed class UpdateTaskStatusCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
: IRequestHandler<UpdateTaskStatusCommand, TaskDto>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
public UpdateTaskStatusCommandHandler(
|
||||
IProjectRepository projectRepository,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
private readonly IUnitOfWork _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
|
||||
|
||||
public async Task<TaskDto> Handle(UpdateTaskStatusCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -9,14 +9,10 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetEpicById;
|
||||
/// <summary>
|
||||
/// Handler for GetEpicByIdQuery
|
||||
/// </summary>
|
||||
public sealed class GetEpicByIdQueryHandler : IRequestHandler<GetEpicByIdQuery, EpicDto>
|
||||
public sealed class GetEpicByIdQueryHandler(IProjectRepository projectRepository)
|
||||
: IRequestHandler<GetEpicByIdQuery, EpicDto>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
|
||||
public GetEpicByIdQueryHandler(IProjectRepository projectRepository)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
|
||||
public async Task<EpicDto> Handle(GetEpicByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -9,14 +9,10 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetEpicsByProje
|
||||
/// <summary>
|
||||
/// Handler for GetEpicsByProjectIdQuery
|
||||
/// </summary>
|
||||
public sealed class GetEpicsByProjectIdQueryHandler : IRequestHandler<GetEpicsByProjectIdQuery, List<EpicDto>>
|
||||
public sealed class GetEpicsByProjectIdQueryHandler(IProjectRepository projectRepository)
|
||||
: IRequestHandler<GetEpicsByProjectIdQuery, List<EpicDto>>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
|
||||
public GetEpicsByProjectIdQueryHandler(IProjectRepository projectRepository)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
|
||||
public async Task<List<EpicDto>> Handle(GetEpicsByProjectIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -10,14 +10,10 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetProjectById;
|
||||
/// <summary>
|
||||
/// Handler for GetProjectByIdQuery
|
||||
/// </summary>
|
||||
public sealed class GetProjectByIdQueryHandler : IRequestHandler<GetProjectByIdQuery, ProjectDto>
|
||||
public sealed class GetProjectByIdQueryHandler(IProjectRepository projectRepository)
|
||||
: IRequestHandler<GetProjectByIdQuery, ProjectDto>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
|
||||
public GetProjectByIdQueryHandler(IProjectRepository projectRepository)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
|
||||
public async Task<ProjectDto> Handle(GetProjectByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -8,14 +8,10 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetProjects;
|
||||
/// <summary>
|
||||
/// Handler for GetProjectsQuery
|
||||
/// </summary>
|
||||
public sealed class GetProjectsQueryHandler : IRequestHandler<GetProjectsQuery, List<ProjectDto>>
|
||||
public sealed class GetProjectsQueryHandler(IProjectRepository projectRepository)
|
||||
: IRequestHandler<GetProjectsQuery, List<ProjectDto>>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
|
||||
public GetProjectsQueryHandler(IProjectRepository projectRepository)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
|
||||
public async Task<List<ProjectDto>> Handle(GetProjectsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -9,14 +9,10 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetStoriesByEpi
|
||||
/// <summary>
|
||||
/// Handler for GetStoriesByEpicIdQuery
|
||||
/// </summary>
|
||||
public sealed class GetStoriesByEpicIdQueryHandler : IRequestHandler<GetStoriesByEpicIdQuery, List<StoryDto>>
|
||||
public sealed class GetStoriesByEpicIdQueryHandler(IProjectRepository projectRepository)
|
||||
: IRequestHandler<GetStoriesByEpicIdQuery, List<StoryDto>>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
|
||||
public GetStoriesByEpicIdQueryHandler(IProjectRepository projectRepository)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
|
||||
public async Task<List<StoryDto>> Handle(GetStoriesByEpicIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -9,14 +9,10 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetStoriesByPro
|
||||
/// <summary>
|
||||
/// Handler for GetStoriesByProjectIdQuery
|
||||
/// </summary>
|
||||
public sealed class GetStoriesByProjectIdQueryHandler : IRequestHandler<GetStoriesByProjectIdQuery, List<StoryDto>>
|
||||
public sealed class GetStoriesByProjectIdQueryHandler(IProjectRepository projectRepository)
|
||||
: IRequestHandler<GetStoriesByProjectIdQuery, List<StoryDto>>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
|
||||
public GetStoriesByProjectIdQueryHandler(IProjectRepository projectRepository)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
|
||||
public async Task<List<StoryDto>> Handle(GetStoriesByProjectIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -9,14 +9,10 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetStoryById;
|
||||
/// <summary>
|
||||
/// Handler for GetStoryByIdQuery
|
||||
/// </summary>
|
||||
public sealed class GetStoryByIdQueryHandler : IRequestHandler<GetStoryByIdQuery, StoryDto>
|
||||
public sealed class GetStoryByIdQueryHandler(IProjectRepository projectRepository)
|
||||
: IRequestHandler<GetStoryByIdQuery, StoryDto>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
|
||||
public GetStoryByIdQueryHandler(IProjectRepository projectRepository)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
|
||||
public async Task<StoryDto> Handle(GetStoryByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -10,14 +10,10 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetTaskById;
|
||||
/// <summary>
|
||||
/// Handler for GetTaskByIdQuery
|
||||
/// </summary>
|
||||
public sealed class GetTaskByIdQueryHandler : IRequestHandler<GetTaskByIdQuery, TaskDto>
|
||||
public sealed class GetTaskByIdQueryHandler(IProjectRepository projectRepository)
|
||||
: IRequestHandler<GetTaskByIdQuery, TaskDto>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
|
||||
public GetTaskByIdQueryHandler(IProjectRepository projectRepository)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
|
||||
public async Task<TaskDto> Handle(GetTaskByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -7,14 +7,10 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetTasksByAssig
|
||||
/// <summary>
|
||||
/// Handler for GetTasksByAssigneeQuery
|
||||
/// </summary>
|
||||
public sealed class GetTasksByAssigneeQueryHandler : IRequestHandler<GetTasksByAssigneeQuery, List<TaskDto>>
|
||||
public sealed class GetTasksByAssigneeQueryHandler(IProjectRepository projectRepository)
|
||||
: IRequestHandler<GetTasksByAssigneeQuery, List<TaskDto>>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
|
||||
public GetTasksByAssigneeQueryHandler(IProjectRepository projectRepository)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
|
||||
public async Task<List<TaskDto>> Handle(GetTasksByAssigneeQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -9,14 +9,10 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetTasksByProje
|
||||
/// <summary>
|
||||
/// Handler for GetTasksByProjectIdQuery
|
||||
/// </summary>
|
||||
public sealed class GetTasksByProjectIdQueryHandler : IRequestHandler<GetTasksByProjectIdQuery, List<TaskDto>>
|
||||
public sealed class GetTasksByProjectIdQueryHandler(IProjectRepository projectRepository)
|
||||
: IRequestHandler<GetTasksByProjectIdQuery, List<TaskDto>>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
|
||||
public GetTasksByProjectIdQueryHandler(IProjectRepository projectRepository)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
|
||||
public async Task<List<TaskDto>> Handle(GetTasksByProjectIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -9,14 +9,10 @@ namespace ColaFlow.Modules.ProjectManagement.Application.Queries.GetTasksByStory
|
||||
/// <summary>
|
||||
/// Handler for GetTasksByStoryIdQuery
|
||||
/// </summary>
|
||||
public sealed class GetTasksByStoryIdQueryHandler : IRequestHandler<GetTasksByStoryIdQuery, List<TaskDto>>
|
||||
public sealed class GetTasksByStoryIdQueryHandler(IProjectRepository projectRepository)
|
||||
: IRequestHandler<GetTasksByStoryIdQuery, List<TaskDto>>
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
|
||||
public GetTasksByStoryIdQueryHandler(IProjectRepository projectRepository)
|
||||
{
|
||||
_projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
}
|
||||
private readonly IProjectRepository _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
|
||||
|
||||
public async Task<List<TaskDto>> Handle(GetTasksByStoryIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -7,12 +7,8 @@ namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Persistence;
|
||||
/// <summary>
|
||||
/// Project Management Module DbContext
|
||||
/// </summary>
|
||||
public class PMDbContext : DbContext
|
||||
public class PMDbContext(DbContextOptions<PMDbContext> options) : DbContext(options)
|
||||
{
|
||||
public PMDbContext(DbContextOptions<PMDbContext> options) : base(options)
|
||||
{
|
||||
}
|
||||
|
||||
public DbSet<Project> Projects => Set<Project>();
|
||||
public DbSet<Epic> Epics => Set<Epic>();
|
||||
public DbSet<Story> Stories => Set<Story>();
|
||||
|
||||
@@ -6,14 +6,9 @@ namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Persistence;
|
||||
/// <summary>
|
||||
/// Unit of Work implementation for ProjectManagement module
|
||||
/// </summary>
|
||||
public class UnitOfWork : IUnitOfWork
|
||||
public class UnitOfWork(PMDbContext context) : IUnitOfWork
|
||||
{
|
||||
private readonly PMDbContext _context;
|
||||
|
||||
public UnitOfWork(PMDbContext context)
|
||||
{
|
||||
_context = context ?? throw new ArgumentNullException(nameof(context));
|
||||
}
|
||||
private readonly PMDbContext _context = context ?? throw new ArgumentNullException(nameof(context));
|
||||
|
||||
public async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
|
||||
@@ -9,14 +9,9 @@ namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Repositories;
|
||||
/// <summary>
|
||||
/// Project repository implementation using EF Core
|
||||
/// </summary>
|
||||
public class ProjectRepository : IProjectRepository
|
||||
public class ProjectRepository(PMDbContext context) : IProjectRepository
|
||||
{
|
||||
private readonly PMDbContext _context;
|
||||
|
||||
public ProjectRepository(PMDbContext context)
|
||||
{
|
||||
_context = context ?? throw new ArgumentNullException(nameof(context));
|
||||
}
|
||||
private readonly PMDbContext _context = context ?? throw new ArgumentNullException(nameof(context));
|
||||
|
||||
public async Task<Project?> GetByIdAsync(ProjectId id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
|
||||
@@ -3,18 +3,12 @@ namespace ColaFlow.Shared.Kernel.Common;
|
||||
/// <summary>
|
||||
/// Base class for all entities
|
||||
/// </summary>
|
||||
public abstract class Entity
|
||||
public abstract class Entity(Guid id)
|
||||
{
|
||||
public Guid Id { get; protected set; }
|
||||
public Guid Id { get; protected set; } = id;
|
||||
|
||||
protected Entity()
|
||||
protected Entity() : this(Guid.NewGuid())
|
||||
{
|
||||
Id = Guid.NewGuid();
|
||||
}
|
||||
|
||||
protected Entity(Guid id)
|
||||
{
|
||||
Id = id;
|
||||
}
|
||||
|
||||
public override bool Equals(object? obj)
|
||||
|
||||
@@ -5,16 +5,10 @@ namespace ColaFlow.Shared.Kernel.Common;
|
||||
/// <summary>
|
||||
/// Base class for creating type-safe enumerations
|
||||
/// </summary>
|
||||
public abstract class Enumeration : IComparable
|
||||
public abstract class Enumeration(int id, string name) : IComparable
|
||||
{
|
||||
public int Id { get; private set; }
|
||||
public string Name { get; private set; }
|
||||
|
||||
protected Enumeration(int id, string name)
|
||||
{
|
||||
Id = id;
|
||||
Name = name;
|
||||
}
|
||||
public int Id { get; private set; } = id;
|
||||
public string Name { get; private set; } = name;
|
||||
|
||||
public override string ToString() => Name;
|
||||
|
||||
|
||||
103
colaflow-api/test-domain-events-clean.ps1
Normal file
103
colaflow-api/test-domain-events-clean.ps1
Normal file
@@ -0,0 +1,103 @@
|
||||
# Test Domain Events Implementation
|
||||
# This script tests that domain events are being raised and handled
|
||||
|
||||
$baseUrl = "http://localhost:5167"
|
||||
$tenantSlug = "event-test-$(Get-Random -Minimum 1000 -Maximum 9999)"
|
||||
|
||||
Write-Host "=== Domain Events Test ===" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
|
||||
# Test 1: Register Tenant (TenantCreatedEvent)
|
||||
Write-Host "Test 1: Registering tenant (should trigger TenantCreatedEvent)..." -ForegroundColor Yellow
|
||||
|
||||
$registerRequest = @{
|
||||
tenantSlug = $tenantSlug
|
||||
tenantName = "Event Test Tenant"
|
||||
subscriptionPlan = "Free"
|
||||
adminEmail = "admin@eventtest.com"
|
||||
adminPassword = "Admin@123"
|
||||
adminFullName = "Event Test Admin"
|
||||
} | ConvertTo-Json
|
||||
|
||||
$registerResponse = Invoke-RestMethod -Uri "$baseUrl/api/tenants/register" `
|
||||
-Method Post `
|
||||
-ContentType "application/json" `
|
||||
-Body $registerRequest
|
||||
|
||||
Write-Host "??? Tenant registered successfully" -ForegroundColor Green
|
||||
Write-Host " Tenant ID: $($registerResponse.tenant.id)"
|
||||
Write-Host " Admin User ID: $($registerResponse.adminUser.id)"
|
||||
Write-Host " Check API console for log: 'Tenant {id} created with name Event Test Tenant...'" -ForegroundColor Magenta
|
||||
Write-Host ""
|
||||
Start-Sleep -Seconds 2
|
||||
|
||||
# Test 2: Login (UserLoggedInEvent)
|
||||
Write-Host "Test 2: Logging in (should trigger UserLoggedInEvent)..." -ForegroundColor Yellow
|
||||
|
||||
$loginRequest = @{
|
||||
tenantSlug = $tenantSlug
|
||||
email = "admin@eventtest.com"
|
||||
password = "Admin@123"
|
||||
} | ConvertTo-Json
|
||||
|
||||
$loginResponse = Invoke-RestMethod -Uri "$baseUrl/api/auth/login" `
|
||||
-Method Post `
|
||||
-ContentType "application/json" `
|
||||
-Body $loginRequest
|
||||
|
||||
$accessToken = $loginResponse.accessToken
|
||||
$userId = $registerResponse.adminUser.id
|
||||
$tenantId = $registerResponse.tenant.id
|
||||
|
||||
Write-Host "??? Login successful" -ForegroundColor Green
|
||||
Write-Host " Access Token: $($accessToken.Substring(0, 20))..."
|
||||
Write-Host " Check API console for log: 'User {$userId} logged in to tenant {$tenantId} from IP...'" -ForegroundColor Magenta
|
||||
Write-Host ""
|
||||
Start-Sleep -Seconds 2
|
||||
|
||||
# Test 3: Assign Role (UserRoleAssignedEvent)
|
||||
Write-Host "Test 3: Assigning role (should trigger UserRoleAssignedEvent)..." -ForegroundColor Yellow
|
||||
|
||||
$assignRoleRequest = @{
|
||||
role = "TenantAdmin"
|
||||
} | ConvertTo-Json
|
||||
|
||||
$headers = @{
|
||||
"Authorization" = "Bearer $accessToken"
|
||||
"Content-Type" = "application/json"
|
||||
}
|
||||
|
||||
try {
|
||||
$assignRoleResponse = Invoke-RestMethod -Uri "$baseUrl/api/tenants/$tenantId/users/$userId/role" `
|
||||
-Method Post `
|
||||
-Headers $headers `
|
||||
-Body $assignRoleRequest
|
||||
|
||||
Write-Host "??? Role assigned successfully" -ForegroundColor Green
|
||||
Write-Host " Check API console for log: 'User {$userId} assigned role TenantAdmin...'" -ForegroundColor Magenta
|
||||
} catch {
|
||||
Write-Host "??? Expected behavior: Role already TenantOwner" -ForegroundColor Yellow
|
||||
Write-Host " Trying to update to TenantMember instead..."
|
||||
|
||||
$assignRoleRequest = @{
|
||||
role = "TenantMember"
|
||||
} | ConvertTo-Json
|
||||
|
||||
$assignRoleResponse = Invoke-RestMethod -Uri "$baseUrl/api/tenants/$tenantId/users/$userId/role" `
|
||||
-Method Post `
|
||||
-Headers $headers `
|
||||
-Body $assignRoleRequest
|
||||
|
||||
Write-Host "??? Role updated successfully to TenantMember" -ForegroundColor Green
|
||||
Write-Host " Check API console for log: 'User {$userId} assigned role TenantMember. Previous role: TenantOwner...'" -ForegroundColor Magenta
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "=== Test Complete ===" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
Write-Host "Expected Logs in API Console:" -ForegroundColor Yellow
|
||||
Write-Host " 1. Tenant {guid} created with name 'Event Test Tenant' and slug '$tenantSlug'"
|
||||
Write-Host " 2. User {guid} logged in to tenant {guid} from IP 127.0.0.1 or ::1"
|
||||
Write-Host " 3. User {guid} assigned role TenantMember in tenant {guid}. Previous role: TenantOwner. Assigned by: {guid}"
|
||||
Write-Host ""
|
||||
Write-Host "If you see these logs in the API console, Domain Events are working correctly!" -ForegroundColor Green
|
||||
103
colaflow-api/test-domain-events.ps1
Normal file
103
colaflow-api/test-domain-events.ps1
Normal file
@@ -0,0 +1,103 @@
|
||||
# Test Domain Events Implementation
|
||||
# This script tests that domain events are being raised and handled
|
||||
|
||||
$baseUrl = "http://localhost:5167"
|
||||
$tenantSlug = "event-test-$(Get-Random -Minimum 1000 -Maximum 9999)"
|
||||
|
||||
Write-Host "=== Domain Events Test ===" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
|
||||
# Test 1: Register Tenant (TenantCreatedEvent)
|
||||
Write-Host "Test 1: Registering tenant (should trigger TenantCreatedEvent)..." -ForegroundColor Yellow
|
||||
|
||||
$registerRequest = @{
|
||||
tenantSlug = $tenantSlug
|
||||
tenantName = "Event Test Tenant"
|
||||
subscriptionPlan = "Free"
|
||||
adminEmail = "admin@eventtest.com"
|
||||
adminPassword = "Admin@123"
|
||||
adminFullName = "Event Test Admin"
|
||||
} | ConvertTo-Json
|
||||
|
||||
$registerResponse = Invoke-RestMethod -Uri "$baseUrl/api/tenants/register" `
|
||||
-Method Post `
|
||||
-ContentType "application/json" `
|
||||
-Body $registerRequest
|
||||
|
||||
Write-Host "✓ Tenant registered successfully" -ForegroundColor Green
|
||||
Write-Host " Tenant ID: $($registerResponse.tenant.id)"
|
||||
Write-Host " Admin User ID: $($registerResponse.adminUser.id)"
|
||||
Write-Host " Check API console for log: 'Tenant {id} created with name Event Test Tenant...'" -ForegroundColor Magenta
|
||||
Write-Host ""
|
||||
Start-Sleep -Seconds 2
|
||||
|
||||
# Test 2: Login (UserLoggedInEvent)
|
||||
Write-Host "Test 2: Logging in (should trigger UserLoggedInEvent)..." -ForegroundColor Yellow
|
||||
|
||||
$loginRequest = @{
|
||||
tenantSlug = $tenantSlug
|
||||
email = "admin@eventtest.com"
|
||||
password = "Admin@123"
|
||||
} | ConvertTo-Json
|
||||
|
||||
$loginResponse = Invoke-RestMethod -Uri "$baseUrl/api/auth/login" `
|
||||
-Method Post `
|
||||
-ContentType "application/json" `
|
||||
-Body $loginRequest
|
||||
|
||||
$accessToken = $loginResponse.accessToken
|
||||
$userId = $registerResponse.adminUser.id
|
||||
$tenantId = $registerResponse.tenant.id
|
||||
|
||||
Write-Host "✓ Login successful" -ForegroundColor Green
|
||||
Write-Host " Access Token: $($accessToken.Substring(0, 20))..."
|
||||
Write-Host " Check API console for log: 'User {$userId} logged in to tenant {$tenantId} from IP...'" -ForegroundColor Magenta
|
||||
Write-Host ""
|
||||
Start-Sleep -Seconds 2
|
||||
|
||||
# Test 3: Assign Role (UserRoleAssignedEvent)
|
||||
Write-Host "Test 3: Assigning role (should trigger UserRoleAssignedEvent)..." -ForegroundColor Yellow
|
||||
|
||||
$assignRoleRequest = @{
|
||||
role = "TenantAdmin"
|
||||
} | ConvertTo-Json
|
||||
|
||||
$headers = @{
|
||||
"Authorization" = "Bearer $accessToken"
|
||||
"Content-Type" = "application/json"
|
||||
}
|
||||
|
||||
try {
|
||||
$assignRoleResponse = Invoke-RestMethod -Uri "$baseUrl/api/tenants/$tenantId/users/$userId/role" `
|
||||
-Method Post `
|
||||
-Headers $headers `
|
||||
-Body $assignRoleRequest
|
||||
|
||||
Write-Host "✓ Role assigned successfully" -ForegroundColor Green
|
||||
Write-Host " Check API console for log: 'User {$userId} assigned role TenantAdmin...'" -ForegroundColor Magenta
|
||||
} catch {
|
||||
Write-Host "✓ Expected behavior: Role already TenantOwner" -ForegroundColor Yellow
|
||||
Write-Host " Trying to update to TenantMember instead..."
|
||||
|
||||
$assignRoleRequest = @{
|
||||
role = "TenantMember"
|
||||
} | ConvertTo-Json
|
||||
|
||||
$assignRoleResponse = Invoke-RestMethod -Uri "$baseUrl/api/tenants/$tenantId/users/$userId/role" `
|
||||
-Method Post `
|
||||
-Headers $headers `
|
||||
-Body $assignRoleRequest
|
||||
|
||||
Write-Host "✓ Role updated successfully to TenantMember" -ForegroundColor Green
|
||||
Write-Host " Check API console for log: 'User {$userId} assigned role TenantMember. Previous role: TenantOwner...'" -ForegroundColor Magenta
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "=== Test Complete ===" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
Write-Host "Expected Logs in API Console:" -ForegroundColor Yellow
|
||||
Write-Host " 1. Tenant {guid} created with name 'Event Test Tenant' and slug '$tenantSlug'"
|
||||
Write-Host " 2. User {guid} logged in to tenant {guid} from IP 127.0.0.1 or ::1"
|
||||
Write-Host " 3. User {guid} assigned role TenantMember in tenant {guid}. Previous role: TenantOwner. Assigned by: {guid}"
|
||||
Write-Host ""
|
||||
Write-Host "If you see these logs in the API console, Domain Events are working correctly!" -ForegroundColor Green
|
||||
@@ -10,14 +10,9 @@ namespace ColaFlow.Modules.Identity.IntegrationTests.Identity;
|
||||
/// Integration tests for basic Authentication functionality (Day 4 Regression Tests)
|
||||
/// Tests registration, login, password validation, and protected endpoints
|
||||
/// </summary>
|
||||
public class AuthenticationTests : IClassFixture<DatabaseFixture>
|
||||
public class AuthenticationTests(DatabaseFixture fixture) : IClassFixture<DatabaseFixture>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
|
||||
public AuthenticationTests(DatabaseFixture fixture)
|
||||
{
|
||||
_client = fixture.Client;
|
||||
}
|
||||
private readonly HttpClient _client = fixture.Client;
|
||||
|
||||
[Fact]
|
||||
public async Task RegisterTenant_WithValidData_ShouldSucceed()
|
||||
|
||||
@@ -11,14 +11,9 @@ namespace ColaFlow.Modules.Identity.IntegrationTests.Identity;
|
||||
/// Integration tests for Role-Based Access Control (RBAC) functionality (Day 5 - Phase 2)
|
||||
/// Tests role assignment, JWT claims, and role persistence across authentication flows
|
||||
/// </summary>
|
||||
public class RbacTests : IClassFixture<DatabaseFixture>
|
||||
public class RbacTests(DatabaseFixture fixture) : IClassFixture<DatabaseFixture>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
|
||||
public RbacTests(DatabaseFixture fixture)
|
||||
{
|
||||
_client = fixture.Client;
|
||||
}
|
||||
private readonly HttpClient _client = fixture.Client;
|
||||
|
||||
[Fact]
|
||||
public async Task RegisterTenant_ShouldAssignTenantOwnerRole()
|
||||
|
||||
@@ -9,14 +9,9 @@ namespace ColaFlow.Modules.Identity.IntegrationTests.Identity;
|
||||
/// Integration tests for Refresh Token functionality (Day 5 - Phase 1)
|
||||
/// Tests token refresh flow, token rotation, and refresh token revocation
|
||||
/// </summary>
|
||||
public class RefreshTokenTests : IClassFixture<DatabaseFixture>
|
||||
public class RefreshTokenTests(DatabaseFixture fixture) : IClassFixture<DatabaseFixture>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
|
||||
public RefreshTokenTests(DatabaseFixture fixture)
|
||||
{
|
||||
_client = fixture.Client;
|
||||
}
|
||||
private readonly HttpClient _client = fixture.Client;
|
||||
|
||||
[Fact]
|
||||
public async Task RegisterTenant_ShouldReturnAccessAndRefreshTokens()
|
||||
|
||||
@@ -12,14 +12,9 @@ namespace ColaFlow.Modules.Identity.IntegrationTests.Identity;
|
||||
/// Integration tests for Role Management API (Day 6)
|
||||
/// Tests role assignment, user listing, user removal, and authorization policies
|
||||
/// </summary>
|
||||
public class RoleManagementTests : IClassFixture<DatabaseFixture>
|
||||
public class RoleManagementTests(DatabaseFixture fixture) : IClassFixture<DatabaseFixture>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
|
||||
public RoleManagementTests(DatabaseFixture fixture)
|
||||
{
|
||||
_client = fixture.Client;
|
||||
}
|
||||
private readonly HttpClient _client = fixture.Client;
|
||||
|
||||
#region Category 1: List Users Tests (3 tests)
|
||||
|
||||
|
||||
@@ -14,16 +14,10 @@ namespace ColaFlow.Modules.Identity.IntegrationTests.Infrastructure;
|
||||
/// Custom WebApplicationFactory for ColaFlow Integration Tests
|
||||
/// Supports both In-Memory and Real PostgreSQL databases
|
||||
/// </summary>
|
||||
public class ColaFlowWebApplicationFactory : WebApplicationFactory<Program>
|
||||
public class ColaFlowWebApplicationFactory(bool useInMemoryDatabase = true, string? testDatabaseName = null)
|
||||
: WebApplicationFactory<Program>
|
||||
{
|
||||
private readonly bool _useInMemoryDatabase;
|
||||
private readonly string? _testDatabaseName;
|
||||
|
||||
public ColaFlowWebApplicationFactory(bool useInMemoryDatabase = true, string? testDatabaseName = null)
|
||||
{
|
||||
_useInMemoryDatabase = useInMemoryDatabase;
|
||||
_testDatabaseName = testDatabaseName ?? $"TestDb_{Guid.NewGuid()}";
|
||||
}
|
||||
private readonly string? _testDatabaseName = testDatabaseName ?? $"TestDb_{Guid.NewGuid()}";
|
||||
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
@@ -52,7 +46,7 @@ public class ColaFlowWebApplicationFactory : WebApplicationFactory<Program>
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
// Register test databases (modules won't register PostgreSQL due to Testing environment)
|
||||
if (_useInMemoryDatabase)
|
||||
if (useInMemoryDatabase)
|
||||
{
|
||||
// Use In-Memory Database for fast, isolated tests
|
||||
// IMPORTANT: Share the same database name for cross-context data consistency
|
||||
@@ -101,7 +95,7 @@ public class ColaFlowWebApplicationFactory : WebApplicationFactory<Program>
|
||||
{
|
||||
// Initialize Identity database
|
||||
var identityDb = services.GetRequiredService<IdentityDbContext>();
|
||||
if (_useInMemoryDatabase)
|
||||
if (useInMemoryDatabase)
|
||||
{
|
||||
identityDb.Database.EnsureCreated();
|
||||
}
|
||||
@@ -112,7 +106,7 @@ public class ColaFlowWebApplicationFactory : WebApplicationFactory<Program>
|
||||
|
||||
// Initialize ProjectManagement database
|
||||
var pmDb = services.GetRequiredService<PMDbContext>();
|
||||
if (_useInMemoryDatabase)
|
||||
if (useInMemoryDatabase)
|
||||
{
|
||||
pmDb.Database.EnsureCreated();
|
||||
}
|
||||
|
||||
@@ -7,17 +7,13 @@ namespace ColaFlow.Modules.Identity.IntegrationTests.Infrastructure;
|
||||
/// </summary>
|
||||
public class DatabaseFixture : IDisposable
|
||||
{
|
||||
public ColaFlowWebApplicationFactory Factory { get; }
|
||||
public ColaFlowWebApplicationFactory Factory { get; } = new(useInMemoryDatabase: true);
|
||||
|
||||
// Note: Client property is kept for backward compatibility but creates new instances
|
||||
// Tests should call CreateClient() for isolation to avoid shared state issues
|
||||
public HttpClient Client => CreateClient();
|
||||
|
||||
public DatabaseFixture()
|
||||
{
|
||||
// Use In-Memory Database for fast, isolated tests
|
||||
Factory = new ColaFlowWebApplicationFactory(useInMemoryDatabase: true);
|
||||
}
|
||||
// Use In-Memory Database for fast, isolated tests
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new HttpClient for each test to ensure test isolation
|
||||
|
||||
Reference in New Issue
Block a user