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​
| Field | Type | Description | Constraints |
|---|---|---|---|
user_id | UUID | Unique identifier for the user | Primary key, auto-generated |
tenant_id | UUID | Associated tenant identifier | Foreign key to Tenant |
email | String | User's email address | Required, unique within tenant |
first_name | String | User's first name | Required in v2, optional in v1 |
last_name | String | User's last name | Required in v2, optional in v1 |
name | String | Display name (v1 compatibility) | Used when first/last not available |
company | String (Optional) | User's company affiliation | Max 255 chars |
role | UserRole (Enum) | User's system role | Required |
is_active | Boolean | Whether user can log in | Default: true |
created_at | DateTime | Account creation timestamp | Auto-set |
updated_at | DateTime | Last modification timestamp | Auto-updated |
last_login | DateTime | Last successful login | Updated on auth |
metadata | JSON (Optional) | Custom attributes | Flexible storage |
password_hash | String (Optional) | Argon2id hashed password | Hidden 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>
Related Code​
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​
-
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
-
Authentication
- Email + password validated against hash
- Failed attempts tracked in audit log
- JWT issued on successful login
- Tokens include user and tenant context
-
Authorization
- Role determines base permissions
- Additional permissions via metadata
- Tenant features affect capabilities
- Admin role has full tenant access
-
Deactivation
- Soft delete (is_active = false)
- Immediate session termination
- Audit log entry created
- Can be reactivated by admin
Security Considerations​
-
Password Management
- Never stored in plain text
- Argon2id with secure parameters
- Password history not maintained
- Reset tokens time-limited
-
Multi-tenancy
- User IDs scoped to tenant
- Email uniqueness per tenant
- Cross-tenant access blocked
- Tenant context in all queries
-
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​
-
Indexes
- Primary: (tenant_id, user_id)
- Secondary: (tenant_id, email)
- Covering index for auth queries
-
Caching
- User objects cached after auth
- Email-to-ID mapping cached
- Permission sets pre-computed
Migration Notes​
V1 to V2 Migration​
- Split
nameintofirst_nameandlast_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