Overview
JOIP uses a flexible authentication system that adapts to your environment:- Replit OIDC - When deployed on Replit with
REPLIT_DOMAINSconfigured - Local Auth - For development environments with test accounts
Authentication Flow
Login Process
-
Initiate Login
- Navigate to
/api/loginor click the login button - Optionally include a redirect parameter:
/api/login?redirect=/sessions
- Navigate to
-
Authentication
- Replit: Redirects to Replit OIDC provider
- Local: Validates credentials against test accounts
-
Session Creation
- Creates a secure session with 1-week expiration
- Session stored in PostgreSQL (
sessionstable) - HTTP-only cookie prevents XSS attacks
-
User Account Creation
- New users are automatically created in the database
- Initial credit balance granted (default: 50 credits)
- Referral codes processed if provided
Session Management
Sessions use PostgreSQL-backed storage with these characteristics:- Automatic expiration after 1 week of inactivity
- Secure cookies (HTTPS in production)
- Cross-tab synchronization via localStorage events
- Automatic cleanup of expired sessions
User Accounts
User Profile Structure
Each user account contains:Local Development Accounts
For development environments, these test accounts are available:/api/login- Auto-login with [email protected] (GET request)/api/dev-login- Auto-login with [email protected] (GET request)
API Endpoints
Authentication Endpoints
POST /api/login
POST /api/login
Authenticate with email and password (local auth only).Request Body:Response:
- Success: Redirects to homepage or specified redirect path
- Failure: Redirects to
/loginpage
redirect- Path to redirect after successful login (must start with/)
GET /api/auth/user
GET /api/auth/user
Get the current authenticated user’s profile and credit balance.Response:Status Codes:
200- Success401- Not authenticated404- User not found in database500- Server error
PATCH /api/auth/user
PATCH /api/auth/user
Update the current user’s profile information.Request Body:Allowed Fields:
firstName- User’s first namelastName- User’s last nameprofileImageUrl- URL to profile picture
POST /api/auth/verify-age
POST /api/auth/verify-age
Update user’s age verification status.Request Body:Validation:Compliance:
Age verification is logged in activity logs with timestamp and IP address for compliance purposes.
- Birth date must be in
YYYY-MM-DDformat - Date cannot be in the future
- Must be a valid calendar date
GET /api/logout
GET /api/logout
Log out the current user and destroy the session.Response:
Redirects to homepageEffects:
- Destroys server-side session
- Clears session cookie
- Broadcasts logout event to other tabs
Client-Side Auth Context
React Auth Hook
The client provides auseAuth() hook for managing authentication state:
Cross-Tab Synchronization
The auth system automatically synchronizes across browser tabs:- Login in one tab → All tabs update to authenticated state
- Logout in one tab → All tabs update to logged out state
- Uses
localStorageevents for cross-tab communication
Security Features
Session Security
-
HTTP-Only Cookies
- Cookies cannot be accessed via JavaScript
- Prevents XSS attacks from stealing session tokens
-
SameSite Protection
sameSite: 'lax'prevents CSRF attacks- Cookies only sent on same-site requests
-
Secure Cookies in Production
- HTTPS-only cookies when
NODE_ENV=production - Prevents man-in-the-middle attacks
- HTTPS-only cookies when
-
Session Secret
- Required in production (
SESSION_SECRETenv var) - Used to sign session cookies
- Prevents session tampering
- Required in production (
Input Validation
All user inputs are validated using Zod schemas:Activity Logging
All authentication-related actions are logged:- Login attempts (successful and failed)
- Profile updates with field changes
- Age verification updates (with timestamp and IP)
- Session creation and destruction
Onboarding Flow
First-Time Users
New users go through an onboarding process:-
Account Creation
- User record created in database
- Initial credits allocated (50 credits)
- Referral code generated (if applicable)
-
Onboarding Survey (Optional)
- Content role: Creator or Consumer
- Preferred features (max 2)
- Preferred tags (max 5)
-
Age Verification
- Required for certain features
- Birth date stored for compliance
- Logged in activity logs
Onboarding Endpoints
POST /api/auth/onboarding
POST /api/auth/onboarding
Save user onboarding preferences.Request Body:Validation:
contentRole: Must be “creator” or “consumer”preferredFeatures: Maximum 2 feature slugspreferredTags: Maximum 5 tag slugs
onboardingCompleted: trueNote:
Can only be completed once unless explicitly reset by admin/dev.POST /api/auth/onboarding/reset
POST /api/auth/onboarding/reset
Reset user onboarding status (admin or dev environment only).Authorization:
- Admin users (role: admin or super_admin)
- Development environment (
NODE_ENV !== 'production')
onboardingCompleted: falseUse Case:
Testing onboarding flow during development.Referral System Integration
The authentication system integrates with the referral program:New User Referrals
When a new user signs up with a referral code:-
Referral Detection
- Checks for
pending_referralcookie - Cookie set by visiting link like
?r={encodedCode} - Also supports
referral_sourceandreferral_source_idfor tracking
- Checks for
-
Referral Processing
- Validates referral code format and existence
- Prevents self-referral
- Checks rate limiting (max 10 referrals per hour per referrer)
-
Credit Distribution
- Referrer receives 10 credits (default)
- New user receives 25 bonus credits (default)
- Credits added atomically in database transaction
-
Cookie Cleanup
- Clears referral cookies after processing
- Prevents duplicate referral claims
User ID Extraction
The system uses a consistent method for extracting user IDs from requests:Environment Configuration
Required Environment Variables
Production (Replit OIDC):Security Recommendations
-
Generate Strong Session Secret
-
Use HTTPS in Production
- Ensures secure cookie transmission
- Prevents session hijacking
-
Rotate Session Secret Periodically
- Invalidates all existing sessions
- Good security practice every 90 days
-
Monitor Failed Login Attempts
- Check activity logs for suspicious patterns
- Implement rate limiting if needed
Troubleshooting
Common Issues
401 Unauthorized on /api/auth/user
401 Unauthorized on /api/auth/user
Session not persisting
Session not persisting
Cause: Cookie settings or database issuesSolution:
- Verify
SESSION_SECRETis set in production - Check PostgreSQL connection (sessions table)
- Ensure cookies are enabled in browser
- Check for
sameSitecookie issues in development
Referral credits not awarded
Referral credits not awarded
Cause: Referral code validation or timing issuesSolution:
- Check server logs for referral processing errors
- Verify referral code format (8 uppercase alphanumeric)
- Ensure user is truly new (not already referred)
- Check rate limiting (max 10/hour per referrer)
Cross-tab sync not working
Cross-tab sync not working
Cause: localStorage not available or disabledSolution:
- Check if localStorage is enabled in browser
- Verify not in private/incognito mode
- Manual refresh will still work as fallback
Best Practices
Client-Side
-
Always use the
useAuth()hook -
Handle loading states
-
Refresh user data after updates
Server-Side
-
Use
isAuthenticatedmiddleware -
Extract user ID consistently
-
Sanitize user data before sending to client
-
Log important auth events
Related Documentation
- Credits System - Credit balance and tier information
- Referral Program - Earn credits by referring friends
- Profile Management - Update profile and preferences