Authentication Architecture
This document outlines the authentication and authorization architecture for the BuildAppsWith platform, including system design, authentication flows, and implementation details.Overview
The authentication system for BuildAppsWith uses Clerk as the primary identity provider with standardized middleware patterns for secure, type-safe authentication across the platform. Following comprehensive infrastructure standardization in Session 8 (May 2025), the architecture achieves:✅ Session 8 Achievement: Complete Infrastructure Standardization
- AuthObject Pattern: Unified across all authentication middleware
- Type Safety: 100% TypeScript coverage in authentication layer
- Middleware Infrastructure: Production-ready and fully standardized
- API Route Protection: Consistent patterns across entire platform
Architectural Principles
- Standardized Authentication Patterns - AuthObject consistency across all middleware
- Complete Type Safety - Strong TypeScript typing with zero authentication errors
- Infrastructure-First Design - Proven middleware foundation supporting all components
- Performance Optimization - Efficient authentication flows with minimal overhead
- Security by Design - Industry best practices with comprehensive role-based access control
System Components
The authentication architecture consists of the following components:1. Authentication Provider
Clerk serves as the authentication provider, handling:- User identity management
- OAuth integrations (Google, GitHub, etc.)
- Password management and security
- MFA (Multi-Factor Authentication)
- Session management
2. Express SDK Integration
The Express SDK provides an abstraction layer over Clerk:- Consistent API for auth operations
- Optimized performance and caching
- Type-safe interface for authentication
- Server and client integration
3. Auth API Layer
The auth API layer provides a unified interface for interacting with Clerk through Express SDK:- Client-side authentication functions in
express/client-auth.ts - Server-side authentication checks in
express/server-auth.ts - Role and permission validation in
express/role-hooks.ts - Session management in
express/middleware.ts
4. Auth Hooks Layer
Custom React hooks provide authentication state and functionality to components:useAuth- Core auth state and user detailsuseAuthStatus- Simple authentication status checksuseIsAdmin,useIsBuilder,useIsClient- Role-specific checksuseHasRole,useHasAllRoles,useHasAnyRole- Role validationuseSignOut- Authentication action hooksuseAuthToken- Token management
5. Auth Components Layer
Reusable UI components for authentication flows:ExpressAuthProvider- Auth provider componentProtectedRoute- Component wrapper for protected routesRoleProtected- Component for role-based access control- Form components for auth flows
Authentication Flows
Sign-In Flow
Protected Route Flow
Role-Based Access Control
BuildAppsWith implements a role-based access control (RBAC) system with the following roles:| Role | Description | Capabilities |
|---|---|---|
USER | Standard user | Access personal dashboard, participate in sessions |
BUILDER | Verified builder | Create builder profile, receive job requests |
ADMIN | Platform administrator | Access admin dashboard, manage users, view analytics |
SUPER_ADMIN | Super administrator | Configure platform settings, manage all data |
Permission Model
Permissions are derived from roles and implemented through thehasPermission function:
Authentication for Non-Authenticated Routes
Some routes in BuildAppsWith are designed to work for both authenticated and non-authenticated users. These routes use thegetOptionalServerAuth function to provide a seamless experience:
Implementation Details
Session Storage
Auth sessions are stored using a combination of:- HTTP-only cookies for server authentication
- In-memory state for client-side auth status
- Local storage for non-sensitive session data
Token Management
Authentication tokens are managed with these considerations:- Access tokens have short lifespans (15 minutes)
- Refresh tokens are used for session persistence
- Token rotation is implemented for security
- Tokens are validated on every protected request
Security Measures
The authentication system implements these security measures:- CSRF protection on all auth endpoints
- Rate limiting for authentication attempts
- Password strength requirements
- Session timeout and inactivity detection
- IP-based anomaly detection
Authentication Error Handling
Authentication errors are handled using standardized error codes:| Error Code | Description | User Action |
|---|---|---|
AUTH_REQUIRED | Authentication required | Redirect to login |
INVALID_CREDENTIALS | Invalid username/password | Show error message |
SESSION_EXPIRED | User session expired | Re-authenticate |
PERMISSION_DENIED | User lacks permission | Show access denied |
ACCOUNT_LOCKED | Account temporarily locked | Contact support |
Diagram: Auth System Architecture
Best Practices
When interacting with the auth system, follow these best practices:- Always use typed auth functions - Never create manual auth checks
- Handle loading states - Auth checks may be asynchronous
- Implement proper error handling - Display user-friendly auth errors
- Use the highest-level abstraction available - Prefer hooks over direct API calls
- Test with different user roles - Verify permissions work correctly