Skip to main content

User Model Documentation

Overview​

The User model represents individual users within a tenant, supporting authentication, authorization, and profile management in CODITECT's multi-tenant architecture.

Model Structure​

Core Fields​

FieldTypeDescriptionConstraints
user_idUUIDUnique identifier for the userPrimary key, auto-generated
tenant_idUUIDAssociated tenant identifierForeign key to Tenant
emailStringUser's email addressRequired, unique within tenant
first_nameStringUser's first nameRequired in v2, optional in v1
last_nameStringUser's last nameRequired in v2, optional in v1
nameStringDisplay name (v1 compatibility)Used when first/last not available
companyString (Optional)User's company affiliationMax 255 chars
roleUserRole (Enum)User's system roleRequired
is_activeBooleanWhether user can log inDefault: true
created_atDateTimeAccount creation timestampAuto-set
updated_atDateTimeLast modification timestampAuto-updated
last_loginDateTime (Optional)Last successful loginUpdated on auth
metadataJSON (Optional)Custom attributesFlexible storage
password_hashString (Optional)Argon2id hashed passwordHidden in responses

UserRole Enum​

enum UserRole {
Admin, // Full tenant management
Developer, // Create and manage resources
Manager, // Team and project oversight
Viewer // Read-only access
}

Database Schema​

Primary Storage Pattern​

Key: /{tenant_id}/users/{user_id}
Value: JSON serialized User object

Secondary Indexes​

Email lookup: /{tenant_id}/user_by_email/{email} -> user_id

Example Data​

{
"user_id": "ec6d3130-6de2-4cc6-9c7a-90d25b2b1f09",
"tenant_id": "8eba182c-2ad7-44c5-b0ab-5a1915b6b98a",
"email": "complete1754630330@test.com",
"name": "Complete Test",
"role": "admin",
"is_active": true,
"created_at": "2025-08-08T05:18:51.987101338Z",
"updated_at": "2025-08-08T05:18:51.987101338Z",
"last_login": null,
"metadata": null,
"password_hash": "$argon2id$v=19$m=19456,t=2,p=1$vpmaycUZWacojCCViFvQ+g$tH6Xb0a3kTOC3iyaF1AVZJ4Cowucgmmc+UWCK+DmaTg"
}

Password Security​

Hashing Algorithm​

  • Algorithm: Argon2id (winner of Password Hashing Competition)
  • Parameters:
    • Memory: 19456 KB
    • Iterations: 2
    • Parallelism: 1
  • Salt: Randomly generated per password

Example Hash Format​

$argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>

Source Files​

  • Model Definition: /src/models/user.rs
  • Repository: /src/db/repositories/user_repository.rs
  • API Handler: /src/api/handlers/user_handlers.rs
  • DTO: /src/api/dto/user.rs
  • Auth Service: /src/services/auth_service.rs
  • Tests: /src/db/repositories/tests/user_repository_tests.rs

Key Methods​

impl User {
fn new(tenant_id: Uuid, email: String, ...) -> Self
fn full_name(&self) -> String
fn with_password_hash(self, password_hash: String) -> Self
fn update_last_login(&mut self)
fn deactivate(&mut self)
}

Repository Operations​

trait UserRepository {
async fn create(&self, user: &User) -> Result<()>
async fn get_by_id(&self, tenant_id: &Uuid, user_id: &Uuid) -> Result<Option<User>>
async fn get_by_email(&self, tenant_id: &Uuid, email: &str) -> Result<Option<User>>
async fn update(&self, user: &User) -> Result<()>
async fn list_by_tenant(&self, tenant_id: &Uuid) -> Result<Vec<User>>
async fn delete(&self, tenant_id: &Uuid, user_id: &Uuid) -> Result<()>
}

API Endpoints​

Authentication​

  • POST /api/auth/login
  • Body: { email, password }
  • Response: { token, user }

User Registration​

  • POST /api/auth/register
  • Body: CreateUserRequest
  • Response: { token, user }

Get Current User​

  • GET /api/users/me
  • Response: User
  • Auth: Required

Update User​

  • PUT /api/users/{user_id}
  • Body: UpdateUserRequest
  • Response: User
  • Auth: Self or Admin

List Tenant Users​

  • GET /api/users
  • Response: Vec<User>
  • Auth: Tenant member

Relationships​

Many-to-One​

  • Tenant: Each user belongs to one tenant

One-to-Many​

  • Projects: User can own/participate in many projects
  • Tasks: User can be assigned many tasks
  • Audit Logs: User actions generate audit entries

Many-to-Many​

  • Project Members: Through project_members association
  • Entity Access: Through role-based permissions

Business Rules​

  1. User Creation

    • Email must be unique within tenant
    • Password must meet complexity requirements
    • Tenant must have capacity (max_users check)
    • Default role based on invitation type
  2. Authentication

    • Email + password validated against hash
    • Failed attempts tracked in audit log
    • JWT issued on successful login
    • Tokens include user and tenant context
  3. Authorization

    • Role determines base permissions
    • Additional permissions via metadata
    • Tenant features affect capabilities
    • Admin role has full tenant access
  4. Deactivation

    • Soft delete (is_active = false)
    • Immediate session termination
    • Audit log entry created
    • Can be reactivated by admin

Security Considerations​

  1. Password Management

    • Never stored in plain text
    • Argon2id with secure parameters
    • Password history not maintained
    • Reset tokens time-limited
  2. Multi-tenancy

    • User IDs scoped to tenant
    • Email uniqueness per tenant
    • Cross-tenant access blocked
    • Tenant context in all queries
  3. Session Security

    • JWT with expiration
    • Refresh token rotation
    • Device tracking optional
    • Concurrent session limits

Personal workspace​

For personal tenants (free tier), special handling:

  • Tenant name: "{first_name}'s workspace"
  • Single user limit enforced
  • Auto-created on registration
  • Cannot invite other users

Performance Optimizations​

  1. Indexes

    • Primary: (tenant_id, user_id)
    • Secondary: (tenant_id, email)
    • Covering index for auth queries
  2. Caching

    • User objects cached after auth
    • Email-to-ID mapping cached
    • Permission sets pre-computed

Migration Notes​

V1 to V2 Migration​

  • Split name into first_name and last_name
  • Maintain backwards compatibility
  • Gradual migration via updates

Field Evolution​

V1: { name, email, role }
V2: { first_name, last_name, email, role, company }

Audit Integration​

All user operations generate audit logs:

  • CREATE: User registration/invitation
  • UPDATE: Profile changes
  • DELETE: Account deactivation
  • AUTH: Login/logout events

Last Updated: 2025-08-29 Version: 1.0