Skip to content

Conversation

@taiphanvan2k3
Copy link
Member

@taiphanvan2k3 taiphanvan2k3 commented Oct 27, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Added user registration functionality with email verification and password requirements
    • Enhanced conversation management with titles, privacy settings, tags, and starred marking
    • Added conversation ownership tracking
  • Bug Fixes

    • Updated authentication service to improve security
  • Refactor

    • Simplified API endpoint routes for cleaner URLs

@taiphanvan2k3 taiphanvan2k3 self-assigned this Oct 27, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 27, 2025

Walkthrough

This pull request refactors user authentication and registration by introducing ASP.NET Core Identity integration. It replaces the UserAggregate domain model with separated identity and domain user entities, adds a new registration feature, updates the login handler to use an external auth service, adjusts database schema to support dual user representations, and configures database seeding for initial roles and admin user.

Changes

Cohort / File(s) Summary
Authentication Service & Identity Infrastructure
src/Application/Interfaces/IAuthService.cs, src/Infrastructure/Identity/ApplicationUser.cs, src/Infrastructure/Identity/ApplicationRole.cs, src/Infrastructure/Identity/IdentityService.cs, src/Infrastructure/Identity/UserMapper.cs
New IAuthService interface defines async operations for user creation, password management, and sign-in/out. ApplicationUser and ApplicationRole extend Identity framework with audit fields. IdentityService implements IAuthService using UserManager and SignInManager. UserMapper provides bidirectional conversions between domain and identity user models.
User Registration Feature
src/Application/Features/Auth/Register/RegisterCommand.cs, src/Application/Features/Auth/Register/RegisterCommandHandler.cs, src/Application/Features/Auth/Register/RegisterCommandValidator.cs, src/Application/Features/Auth/Register/RegisterResponse.cs
New registration pipeline: RegisterCommand encapsulates email, password, and name. Handler verifies email uniqueness, creates domain and identity users, generates tokens. Validator enforces email format, password strength (8+ chars, mixed case, digit), and full name requirements. Response returns user ID, email, name, and optional access/refresh tokens.
Login Handler Update
src/Application/Features/Auth/Login/LoginCommandHandler.cs
Constructor now accepts IAuthService instead of IPasswordHasher. Password validation delegated to authService.CheckPasswordAsync(). Returns Unauthorized on invalid credentials. Token generation and expiration logic unchanged.
Domain Event Behavior Fix
src/Application/Common/Behaviors/DomainEventBehavior.cs
Generic command detection updated to check for ICommand<T> implementations via interface inspection instead of direct ICommand type-check, accommodating generic command interfaces.
User Aggregate Removal
src/Domain/Aggregates/User/UserAggregate.cs
Entire aggregate root deleted, including static Create factory, Deactivate, UpdateInfo, role management (AddRole, RemoveRole), and permission checks (CanPerformAction). User lifecycle now managed through Identity and domain User entity separately.
Domain Entity Updates
src/Domain/Entities/User.cs, src/Domain/Entities/Conversation.cs, src/Domain/Entities/Message.cs
User entity: PasswordHash property removed; Roles assignment changed to list reconstruction in AddRole. Conversation entity: Added Title (required), IsPrivate, Tags array, IsStarred, Owner properties. Message entity: Documentation comment removed.
User Configuration & Repository
src/Infrastructure/Data/Configurations/UserConfiguration.cs, src/Infrastructure/Repositories/UserRepository.cs
UserConfiguration no longer maps PasswordHash column. UserRepository updated to use DomainUsers DbSet instead of Set<User>() for all queries and operations.
Database Context Refactor
src/Infrastructure/Data/Contexts/DataContext.cs, src/Infrastructure/Data/Contexts/Schemas.cs
DataContext now extends IdentityDbContext<ApplicationUser, ApplicationRole, Guid, ...> instead of DbContext. DbSet renamed from Users to DomainUsers. New ConfigureIdentityTables method configures identity schema. Schemas class gains new Identity constant.
Database Migrations
src/Infrastructure/Data/Migrations/20251027111716_AddIdentityToDataContext.cs, src/Infrastructure/Data/Migrations/20251027111716_AddIdentityToDataContext.Designer.cs, src/Infrastructure/Data/Migrations/20251027145835_RemovePasswordHashInDomainUserTable.cs, src/Infrastructure/Data/Migrations/20251027145835_RemovePasswordHashInDomainUserTable.Designer.cs, src/Infrastructure/Data/Migrations/DataContextModelSnapshot.cs
First migration adds identity schema with Roles, Users, Claims, Logins, Tokens, RoleClaims tables; removes UserId from Messages; adds IsStarred to Conversations. Second migration removes PasswordHash from domain Users table. Snapshot reflects final model with both identity and domain entities.
Database Seeding
src/Infrastructure/Data/Seeders/DatabaseSeeder.cs
New seeder runs migrations, ensures Admin/User/Moderator roles exist, and creates default admin user with matching domain and identity records using hardcoded credentials.
Infrastructure Configuration
src/Infrastructure/Extensions/IdentityServiceExtensions.cs, src/Infrastructure/Extensions/ServiceCollectionExtensions.cs, src/Infrastructure/Infrastructure.csproj
IdentityServiceExtensions configures ASP.NET Core Identity with password, lockout, user, and sign-in policies. ServiceCollectionExtensions registers IdentityService and IAuthService, IUserRepository, and calls AddIdentityServices. Project file updates EF Core packages to 8.0.x and adds Microsoft.AspNetCore.Identity.EntityFrameworkCore.
Authentication & API Controllers
src/Web.Api/Extensions/AuthenticationExtensions.cs, src/Web.Api/Controllers/V1/AuthController.cs, src/Web.Api/Controllers/V1/HealthController.cs, src/Web.Api/Controllers/V1/UsersController.cs, src/Web.Api/Program.cs
AuthenticationExtensions provides AddJwtAuthentication to configure JWT Bearer with TokenValidationParameters. AuthController adds Register endpoint, updates Login to return raw response (not wrapped). Health and Users controllers update route attributes to explicit paths. Program.cs replaces explicit JWT setup with extension, introduces SeedDatabaseAsync for startup seeding, adds Identity-related using directives.
Configuration
.gitignore
Adds ignore rule for .containers/.vscode/settings.json.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant AuthController
    participant Mediator
    participant RegisterHandler
    participant UserRepository
    participant AuthService
    participant TokenService

    Client->>AuthController: POST /register (email, password, fullName)
    AuthController->>Mediator: Send RegisterCommand
    Mediator->>RegisterHandler: Handle
    
    RegisterHandler->>UserRepository: GetByEmailAsync(email)
    alt Email exists
        RegisterHandler-->>Mediator: Result.Failure("EmailExists")
        Mediator-->>AuthController: Failure result
        AuthController-->>Client: 409 Conflict
    else Email unique
        RegisterHandler->>UserRepository: CreateAsync(domainUser)
        RegisterHandler->>AuthService: CreateIdentityUserAsync(userId, email, fullName, password, roles)
        alt Identity creation fails
            RegisterHandler-->>Mediator: Result.Failure("IdentityFailed")
            Mediator-->>AuthController: Failure result
            AuthController-->>Client: 400 Bad Request
        else Identity created
            RegisterHandler->>TokenService: GenerateAccessToken
            RegisterHandler->>TokenService: GenerateRefreshToken
            RegisterHandler-->>Mediator: Result.Success(RegisterResponse with tokens)
            Mediator-->>AuthController: Success result
            AuthController-->>Client: 200 OK (userId, email, fullName, accessToken, refreshToken)
        end
    end
Loading
sequenceDiagram
    participant Client
    participant AuthController
    participant Mediator
    participant LoginHandler
    participant UserRepository
    participant AuthService
    participant TokenService

    Client->>AuthController: POST /login (email, password)
    AuthController->>Mediator: Send LoginCommand
    Mediator->>LoginHandler: Handle
    
    LoginHandler->>AuthService: CheckPasswordAsync(email, password)
    alt Password invalid
        LoginHandler-->>Mediator: Result.Unauthorized
        Mediator-->>AuthController: Unauthorized result
        AuthController-->>Client: 401 Unauthorized
    else Password valid
        LoginHandler->>UserRepository: GetByEmailAsync(email)
        alt User not active
            LoginHandler-->>Mediator: Result.Failure
            Mediator-->>AuthController: Failure result
            AuthController-->>Client: 400 Bad Request
        else User active
            LoginHandler->>TokenService: GenerateAccessToken
            LoginHandler->>TokenService: GenerateRefreshToken
            LoginHandler-->>Mediator: Result.Success(LoginResponse)
            Mediator-->>AuthController: Success result
            AuthController-->>Client: 200 OK (accessToken, refreshToken, expiresAt)
        end
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Areas requiring extra attention:

  • Database migrations and schema changes: The dual-schema design (public for domain, identity for auth) and foreign key relationships between identity and domain users need careful validation. Verify cascade delete behaviors are correct and that the migration reversibility (Down methods) properly restores data integrity.
  • Identity integration in DataContext: Ensure all Identity entity mappings are correctly configured in ConfigureIdentityTables, including constraints, indexes, and relationships to domain entities (e.g., Conversation.Owner).
  • User entity separation: Confirm that removing UserAggregate and splitting into domain User + IdentityUser doesn't break existing business logic or domain constraints. Verify that the domain User still enforces necessary invariants (e.g., role management in AddRole via list reconstruction).
  • Authentication flow changes: LoginCommandHandler now depends on IAuthService instead of IPasswordHasher. Verify that CheckPasswordAsync behavior matches previous password validation logic and handles soft-deleted/inactive users correctly.
  • Seeding logic: DatabaseSeeder creates parallel domain and identity users. Ensure IDs align and that role assignments propagate correctly to both representations.
  • RegisterCommandValidator rules: Password complexity rules (8+ chars, mixed case, digit) are new; confirm they align with organizational security policies.
  • API response changes: Login endpoint response type changed from wrapped ApiResponse to raw value. Verify that clients can adapt and that error handling (409 for register conflicts) is correctly surfaced.

Poem

🐰 Hop, hop, identity takes the stage!
Passwords secured in a brand new cage.
Domain and identity, hand in hand dance,
Registration and login get their romance—
Seeds sprout roles, admins take their place,
Authentication blooms all over the place! 🌿


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Free

📥 Commits

Reviewing files that changed from the base of the PR and between a76fe4c and 5c8ff9c.

📒 Files selected for processing (37)
  • .gitignore (1 hunks)
  • src/Application/Common/Behaviors/DomainEventBehavior.cs (1 hunks)
  • src/Application/Features/Auth/Login/LoginCommandHandler.cs (3 hunks)
  • src/Application/Features/Auth/Register/RegisterCommand.cs (1 hunks)
  • src/Application/Features/Auth/Register/RegisterCommandHandler.cs (1 hunks)
  • src/Application/Features/Auth/Register/RegisterCommandValidator.cs (1 hunks)
  • src/Application/Features/Auth/Register/RegisterResponse.cs (1 hunks)
  • src/Application/Features/User/CreateUser/CreateUserCommand.cs (0 hunks)
  • src/Application/Features/User/CreateUser/CreateUserCommandHandler.cs (0 hunks)
  • src/Application/Features/User/CreateUser/CreateUserCommandValidator.cs (0 hunks)
  • src/Application/Interfaces/IAuthService.cs (1 hunks)
  • src/Domain/Aggregates/User/UserAggregate.cs (0 hunks)
  • src/Domain/Entities/Conversation.cs (1 hunks)
  • src/Domain/Entities/Message.cs (0 hunks)
  • src/Domain/Entities/User.cs (1 hunks)
  • src/Infrastructure/Data/Configurations/UserConfiguration.cs (0 hunks)
  • src/Infrastructure/Data/Contexts/DataContext.cs (2 hunks)
  • src/Infrastructure/Data/Contexts/Schemas.cs (1 hunks)
  • src/Infrastructure/Data/Migrations/20251027111716_AddIdentityToDataContext.Designer.cs (1 hunks)
  • src/Infrastructure/Data/Migrations/20251027111716_AddIdentityToDataContext.cs (1 hunks)
  • src/Infrastructure/Data/Migrations/20251027145835_RemovePasswordHashInDomainUserTable.Designer.cs (1 hunks)
  • src/Infrastructure/Data/Migrations/20251027145835_RemovePasswordHashInDomainUserTable.cs (1 hunks)
  • src/Infrastructure/Data/Migrations/DataContextModelSnapshot.cs (3 hunks)
  • src/Infrastructure/Data/Seeders/DatabaseSeeder.cs (1 hunks)
  • src/Infrastructure/Extensions/IdentityServiceExtensions.cs (1 hunks)
  • src/Infrastructure/Extensions/ServiceCollectionExtensions.cs (3 hunks)
  • src/Infrastructure/Identity/ApplicationRole.cs (1 hunks)
  • src/Infrastructure/Identity/ApplicationUser.cs (1 hunks)
  • src/Infrastructure/Identity/IdentityService.cs (1 hunks)
  • src/Infrastructure/Identity/UserMapper.cs (1 hunks)
  • src/Infrastructure/Infrastructure.csproj (1 hunks)
  • src/Infrastructure/Repositories/UserRepository.cs (2 hunks)
  • src/Web.Api/Controllers/V1/AuthController.cs (4 hunks)
  • src/Web.Api/Controllers/V1/HealthController.cs (1 hunks)
  • src/Web.Api/Controllers/V1/UsersController.cs (1 hunks)
  • src/Web.Api/Extensions/AuthenticationExtensions.cs (1 hunks)
  • src/Web.Api/Program.cs (3 hunks)
💤 Files with no reviewable changes (6)
  • src/Application/Features/User/CreateUser/CreateUserCommandHandler.cs
  • src/Application/Features/User/CreateUser/CreateUserCommand.cs
  • src/Domain/Aggregates/User/UserAggregate.cs
  • src/Application/Features/User/CreateUser/CreateUserCommandValidator.cs
  • src/Domain/Entities/Message.cs
  • src/Infrastructure/Data/Configurations/UserConfiguration.cs

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

Comment @coderabbitai help to get the list of available commands and usage tips.

@taiphanvan2k3 taiphanvan2k3 merged commit d125d83 into main Oct 27, 2025
2 checks passed
@taiphanvan2k3 taiphanvan2k3 deleted the feat/implement-identity branch October 27, 2025 16:50
taiphanvan2k3 added a commit that referenced this pull request Dec 22, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants