Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Oct 31, 2025

Fix Add New User Role Assignment Issue ✅

The issue is that when creating a new user through the "Add User" dialog, the role is not being properly passed to the backend. Users are being created with the default role of "citizen" instead of their selected role (admin, supervisor, or driver).

Root Cause

The signUp action in apps/web/src/features/auth/actions.ts calls /api/auth/sign-up/email, which is the standard better-auth signup endpoint. This endpoint doesn't support role assignment and defaults to "citizen" (as configured in apps/api/src/internal/domains/auth/service.ts).

Additionally, the better-auth organization plugin manages roles via organization membership in the member table, not as a direct user property. Simply passing a role parameter to createUser doesn't create the organization membership.

Changes Made

  1. API Schema (apps/api/src/internal/domains/admin/schemas.ts): Added CreateUserSchema that includes role validation
  2. API Service (apps/api/src/internal/domains/admin/service.ts):
    • Added database access to the service constructor
    • Implemented createUser method with proper transaction-like behavior:
      • Creates user account via better-auth API
      • Inserts organization membership with specified role
      • Critical fix: Added cleanup logic to delete user if membership creation fails (prevents orphaned users)
      • Critical fix: Proper error handling - uses handleDatabaseError for DB errors and handleAuthApiError for auth errors
  3. API Handler (apps/api/src/internal/domains/admin/handler.ts):
    • Added POST /api/admin/users endpoint that validates and creates users with roles
    • Pass organization ID from authenticated session to service
    • Added error handling for missing organization
  4. Container (apps/api/src/internal/container/container.ts): Pass database to AdminService constructor
  5. Frontend API Client (apps/web/src/lib/api.ts): Added createUser method to admin API client
  6. Frontend Action (apps/web/src/features/auth/actions.ts): Updated signUp to use the new admin endpoint instead of the generic signup
  7. Tests (apps/api/tests/admin.test.ts): Added comprehensive test cases for creating users with different roles (admin, supervisor, driver) and validating role rejection

Critical Improvements in Latest Commit

  • Prevent Orphaned Users: If membership creation fails after user creation, the user account is automatically deleted
  • Proper Error Classification: Database errors now use handleDatabaseError, auth errors use handleAuthApiError
  • Better Error Recovery: Nested try-catch blocks ensure proper error handling at each step

Solution Plan

  • Understand the issue and codebase structure
  • Add a new admin API endpoint to create users with specified roles
  • Update the admin service to handle user creation with roles via organization membership
  • Update the frontend signUp action to use the new admin endpoint
  • Add test cases to verify role assignment works correctly
  • Fix organization membership creation to properly assign roles
  • Add cleanup logic for failed user creation (critical fix)
  • Implement proper error handling for different failure scenarios
  • Verify TypeScript compilation passes
  • Run security checks (CodeQL - passed with 0 vulnerabilities)

Security Summary

  • ✅ CodeQL scan completed: 0 vulnerabilities found
  • ✅ All TypeScript compilation checks passed
  • ✅ Proper error handling prevents orphaned users
  • ✅ Cleanup mechanism ensures data consistency

The fix ensures that when an admin/supervisor creates a new user through the UI, the user is properly added to the organization with the selected role (admin, supervisor, or driver) via the member table. If any step fails, appropriate cleanup is performed to maintain data integrity.

Original prompt

This section details on the original issue you should resolve

<issue_title>Add new user not working</issue_title>
<issue_description>Fail when trying to add a new admin
Image</issue_description>

<agent_instructions>@copilot look into this issue. Gather info. Work in apps/web and apps/api. If you manage to find the reason, add a test case in the API to catch future instances before deploying </agent_instructions>

Comments on the Issue (you are @copilot in this section)

@totallynotdavid should be fixed by 1622b97 @PedroRojasF Image Image

tras crear el usuario, se guarda en la base de datos como "citizen"</comment_new>


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

…to use it

Co-authored-by: totallynotdavid <20960328+totallynotdavid@users.noreply.github.com>
@cloudflare-workers-and-pages
Copy link

Deploying limalimpia with  Cloudflare Pages  Cloudflare Pages

Latest commit: 08fbcf4
Status: ✅  Deploy successful!
Preview URL: https://79b01359.limalimpia.pages.dev
Branch Preview URL: https://copilot-fix-add-new-user-iss.limalimpia.pages.dev

View logs

Copilot AI changed the title [WIP] Fix issue with adding new admin user Fix user role assignment in admin user creation flow Oct 31, 2025
Copilot AI requested a review from totallynotdavid October 31, 2025 22:52
Copilot finished work on behalf of totallynotdavid October 31, 2025 22:52
@totallynotdavid
Copy link
Contributor

@copilot fix the tests

Co-authored-by: totallynotdavid <20960328+totallynotdavid@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Oct 31, 2025

@copilot fix the tests

Fixed in commit 3d5676d. The issue was that better-auth's organization plugin manages roles via organization membership, not as a direct user property. The createUser method now properly creates the user account and then adds them to the organization with the specified role in the member table.

Copilot finished work on behalf of totallynotdavid November 1, 2025 00:00
@totallynotdavid
Copy link
Contributor

@copilot Make a final review of your changes! Be critical

Co-authored-by: totallynotdavid <20960328+totallynotdavid@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Nov 1, 2025

@copilot Make a final review of your changes! Be critical

Completed critical review. Found and fixed 2 critical issues in commit d74e0f5:

Critical Issue #1: Orphaned Users

  • Problem: If user creation succeeded but membership insertion failed, users would be left without organization access
  • Fix: Added cleanup logic to delete the user if membership creation fails

Critical Issue #2: Incorrect Error Handling

  • Problem: Database errors were being handled by handleAuthApiError instead of handleDatabaseError
  • Fix: Separated error handling - DB errors use handleDatabaseError, auth errors use handleAuthApiError

Other observations:

  • Implementation is now consistent with better-auth's organization plugin architecture
  • Tests cover all role types (admin, supervisor, driver) and invalid role rejection
  • Frontend properly calls the new admin endpoint with role parameter
  • No security vulnerabilities found (CodeQL clean)

The fix now properly handles all failure scenarios and prevents data inconsistency.

Copilot finished work on behalf of totallynotdavid November 1, 2025 00:06
@totallynotdavid totallynotdavid marked this pull request as ready for review November 1, 2025 05:20
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.

Add new user not working

2 participants