Authentication System
Overview of the HMS authentication architecture and implementation
The HMS (Hosting Management System) implements separate authentication systems for Client and Admin users. This document describes the authentication architecture, security measures, and implementation details.
Architecture
Separation of Concerns
-
Client Authentication:
/api/v1/client/auth/*- Public registration available
- Self-service password management
- Profile: Clients can view and update their profile (name, email) via GET/PUT
/api/v1/client/auth/profile. The client portal provides a Profile/Account page and the sidebar shows the current user’s name and email. - Logout: Clients can end their session via POST
/api/v1/client/auth/logout, which clears auth cookies. The client portal provides a “Log out” control in the user dropdown (sidebar). Logout does not revoke tokens server-side; it only clears cookies in the browser.
-
Admin Authentication:
/api/v1/admin/auth/*- No public registration (admin accounts created by system administrators)
- Role-based access control
- Separate token validation
Authentication Flow
┌─────────┐
│ Client │
│ Browser │
└────┬────┘
│
│ 1. POST /login (email, password)
▼
┌─────────────┐
│ API │
│ Server │
└────┬────────┘
│
│ 2. Verify credentials
│ 3. Generate JWT tokens
│ 4. Set HTTP-only cookies
▼
┌─────────────┐
│ Client │
│ Browser │
└────┬────────┘
│
│ 5. Subsequent requests include cookies
│ 6. Middleware validates token
│ 7. Access granted/denied
▼
┌─────────────┐
│ Protected │
│ Resources │
└─────────────┘Security Implementation
Token Management
Access Tokens
- Lifetime: 15 minutes
- Storage: HTTP-only cookie
- Purpose: Authenticate API requests
- Rotation: Not rotated (short lifetime)
Refresh Tokens
- Lifetime: 7 days
- Storage: HTTP-only cookie
- Purpose: Obtain new access tokens
- Rotation: Should be implemented for enhanced security
Password Security
- Hashing: bcrypt with salt rounds (default: 10)
- Storage: Never stored in plain text
- Reset Tokens:
- Cryptographically secure random tokens
- Expire after 1 hour
- Single-use only
- Stored hashed in database
Cookie Security
{
httpOnly: true, // Prevents JavaScript access
secure: true, // HTTPS only in production
sameSite: 'Lax', // CSRF protection
maxAge: 900 // 15 minutes for access token
}Middleware Protection
All protected routes use authentication middleware:
// Client route
app.get('/protected', authMiddleware('client'), handler)
// Admin route
app.get('/admin-only', authMiddleware('admin'), handler)The middleware:
- Extracts token from HTTP-only cookie
- Verifies token signature and expiration
- Validates user type (client/admin)
- Injects user context into request
Database Schema
Client Model
model Client {
id String @id @default(uuid())
email String @unique
passwordHash String
name String
emailVerified Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
passwordResetTokens PasswordResetToken[]
}Admin Model
model Admin {
id String @id @default(uuid())
email String @unique
passwordHash String
name String
role String @default("admin")
emailVerified Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
passwordResetTokens PasswordResetToken[]
}Password Reset Token Model
model PasswordResetToken {
id String @id @default(uuid())
token String @unique
expiresAt DateTime
used Boolean @default(false)
createdAt DateTime @default(now())
clientId String?
adminId String?
client Client? @relation(...)
admin Admin? @relation(...)
}API Client Integration
Frontend Implementation
The frontend uses type-safe API clients generated from OpenAPI specifications:
// Client portal
import { apiClient } from '../../../lib/api'
// Login
const { client, accessToken, refreshToken } = await apiClient.POST('/api/v1/client/auth/login', {
body: { email, password }
})
// Cookies are automatically handled by the browserToken Refresh Strategy
When an access token expires:
- Frontend detects 401 response
- Automatically attempts refresh using refresh token
- Updates access token cookie
- Retries original request
Security Best Practices
Implemented
✅ HTTP-only cookies for token storage ✅ Secure cookie flags in production ✅ Password hashing with bcrypt ✅ JWT token expiration ✅ Single-use password reset tokens ✅ Email enumeration prevention ✅ CORS configuration ✅ Input validation with Zod
Recommended Additions
⚠️ Rate Limiting: Implement on authentication endpoints ⚠️ Refresh Token Rotation: Rotate refresh tokens on use ⚠️ Account Lockout: Lock accounts after failed login attempts ⚠️ 2FA: Add two-factor authentication for admin accounts ⚠️ Session Management: Track active sessions ⚠️ Audit Logging: Log authentication events
Testing
Unit Tests
- Password hashing and verification
- JWT token generation and validation
- Authentication service logic
- Middleware functionality
Integration Tests
- API endpoint testing
- Request/response validation
- Error handling
- Cookie management
E2E Tests
- Complete authentication flows
- Client registration → login → profile
- Admin login → profile
- Password reset flows
Troubleshooting
Common Issues
401 Unauthorized on protected routes
- Check if access token cookie is present
- Verify token hasn't expired
- Ensure token is valid JWT format
403 Forbidden on admin routes
- Verify user type in token matches route requirement
- Check if token was issued for correct user type
Password reset not working
- Verify token hasn't expired (1 hour limit)
- Check if token was already used
- Ensure email service is configured