# Authentication System Setup & Testing Guide ## Current Status ✅ **Frontend Complete**: Next.js 16 application with full authentication UI and services ✅ **Backend Complete**: Django REST Framework with JWT authentication ❌ **Not Tested**: System integration has not been manually tested ❌ **Backend Not Running**: Missing `.env` configuration ## Prerequisites Setup Required ### 1. Django Backend Environment Configuration The Django backend requires a `.env` file in `django-backend/` directory. **Create `django-backend/.env`:** ```bash # Django Settings DEBUG=True SECRET_KEY=django-insecure-development-key-change-in-production-12345 ALLOWED_HOSTS=localhost,127.0.0.1 # Database (PostgreSQL with PostGIS) DATABASE_URL=postgresql://postgres:postgres@localhost:5432/thrillwiki # Redis (for Celery and caching) REDIS_URL=redis://localhost:6379/0 # Celery CELERY_BROKER_URL=redis://localhost:6379/0 CELERY_RESULT_BACKEND=redis://localhost:6379/1 # CloudFlare Images (optional for testing auth) CLOUDFLARE_ACCOUNT_ID=test-account-id CLOUDFLARE_IMAGE_TOKEN=test-token CLOUDFLARE_IMAGE_HASH=test-hash CLOUDFLARE_IMAGE_BASE_URL=https://cdn.thrillwiki.com # Novu (optional for testing auth) NOVU_API_KEY=test-novu-key NOVU_API_URL=https://api.novu.co # Sentry (optional for testing auth) SENTRY_DSN= # CORS - Allow Next.js frontend CORS_ALLOWED_ORIGINS=http://localhost:5173,http://localhost:3000 # OAuth (Optional - needed only for OAuth testing) GOOGLE_CLIENT_ID= GOOGLE_CLIENT_SECRET= DISCORD_CLIENT_ID= DISCORD_CLIENT_SECRET= # MFA Settings (for WebAuthn/Passkeys) MFA_WEBAUTHN_RP_ID=localhost MFA_WEBAUTHN_ALLOW_INSECURE_ORIGIN=true ``` ### 2. Database Setup **PostgreSQL with PostGIS Extension:** ```bash # Install PostgreSQL and PostGIS (if not already installed) brew install postgresql postgis # macOS # or appropriate package manager for your OS # Start PostgreSQL brew services start postgresql # Create database createdb thrillwiki # Connect and enable PostGIS psql thrillwiki CREATE EXTENSION postgis; \q # Run Django migrations cd django-backend python manage.py migrate # Create superuser for testing python manage.py createsuperuser ``` ### 3. Redis Setup (Optional for Full Features) ```bash # Install Redis brew install redis # macOS # Start Redis brew services start redis ``` ### 4. Python Dependencies ```bash cd django-backend pip install -r requirements/local.txt ``` ## Starting the Servers ### Terminal 1: Django Backend ```bash cd django-backend python manage.py runserver # Should start on http://localhost:8000 ``` **Verify it's running:** - Visit http://localhost:8000/admin (Django admin) - Visit http://localhost:8000/api/v1/ (API documentation) ### Terminal 2: Next.js Frontend ```bash # From project root npm run dev # or bun dev # Should start on http://localhost:3000 ``` **Verify it's running:** - Visit http://localhost:3000 (home page) - Should see UserNav component in header ## Manual Testing Checklist ### Test 1: User Registration ✅ Expected **Steps:** 1. Visit http://localhost:3000 2. Click "Sign Up" in UserNav 3. Fill in registration form: - Username: testuser - Email: test@example.com - Password: TestPass123! - Confirm Password: TestPass123! 4. Submit form **Expected Results:** - ✅ Success message displayed - ✅ User automatically logged in - ✅ Redirected to home/dashboard - ✅ UserNav shows user avatar and username - ✅ Tokens stored in localStorage **Check:** ```javascript // Browser console localStorage.getItem('thrillwiki_access_token') localStorage.getItem('thrillwiki_refresh_token') ``` ### Test 2: User Login ✅ Expected **Steps:** 1. If logged in, logout first 2. Click "Login" in UserNav 3. Enter credentials from Test 1 4. Submit form **Expected Results:** - ✅ Success message - ✅ User logged in - ✅ UserNav updates with user info - ✅ Tokens stored in localStorage ### Test 3: Logout ✅ Expected **Steps:** 1. While logged in, click user avatar 2. Click "Logout" from dropdown **Expected Results:** - ✅ Success message - ✅ Tokens cleared from localStorage - ✅ UserNav shows "Login" and "Sign Up" buttons - ✅ Redirected to home page ### Test 4: Protected Route (Dashboard) ✅ Expected **Steps:** 1. Logout if logged in 2. Navigate directly to http://localhost:3000/dashboard **Expected Results:** - ✅ Redirected to home page (not authenticated) **Steps (Logged In):** 1. Login with credentials 2. Navigate to http://localhost:3000/dashboard **Expected Results:** - ✅ Dashboard page loads - ✅ User profile info displayed - ✅ Quick actions visible ### Test 5: Token Refresh ✅ Expected **Setup:** This requires waiting or manually manipulating token expiry. For quick testing: 1. Login 2. Open browser console 3. Wait 60 seconds (auto-refresh checks every 60s) 4. Check console for token refresh logs **Expected Results:** - ✅ Token refresh happens automatically when <5min to expiry - ✅ No interruption to user experience - ✅ New tokens stored in localStorage ### Test 6: Invalid Credentials ✅ Expected **Steps:** 1. Try to login with wrong password **Expected Results:** - ✅ Error message displayed - ✅ "Invalid credentials" or similar message - ✅ User not logged in ### Test 7: Session Persistence ✅ Expected **Steps:** 1. Login successfully 2. Refresh the page (F5) **Expected Results:** - ✅ User remains logged in - ✅ UserNav still shows user info - ✅ No need to login again **Steps:** 1. Login successfully 2. Close browser tab 3. Open new tab to http://localhost:3000 **Expected Results:** - ✅ User still logged in (tokens persist) ### Test 8: Password Reset (If Implemented) ⚠️ UI Not Yet Implemented **Steps:** 1. Click "Forgot Password" in login form 2. Enter email address 3. Check email for reset link **Expected Results:** - ✅ Email sent confirmation - ✅ Reset email received (check Django console for email) - ✅ Reset link works ### Test 9: OAuth Login (If Configured) ⚠️ Requires OAuth Credentials **Steps:** 1. Click "Login with Google" or "Login with Discord" 2. Complete OAuth flow **Expected Results:** - ✅ Redirected to OAuth provider - ✅ Redirected back to app - ✅ User logged in automatically - ✅ User profile created/updated ### Test 10: MFA Challenge (If User Has MFA) ⚠️ Requires MFA Setup **Steps:** 1. Setup MFA for test user (via Django admin) 2. Login with MFA-enabled user 3. Enter TOTP code when prompted **Expected Results:** - ✅ MFA challenge appears - ✅ Correct code allows login - ✅ Incorrect code shows error ## Testing Results Documentation ### Test Results Template ``` Date: [Date] Tester: [Name] Environment: [Dev/Local] | Test # | Test Name | Status | Notes | |--------|-----------|--------|-------| | 1 | User Registration | ⏳ | Not tested yet | | 2 | User Login | ⏳ | Not tested yet | | 3 | Logout | ⏳ | Not tested yet | | 4 | Protected Route | ⏳ | Not tested yet | | 5 | Token Refresh | ⏳ | Not tested yet | | 6 | Invalid Credentials | ⏳ | Not tested yet | | 7 | Session Persistence | ⏳ | Not tested yet | | 8 | Password Reset | ⏳ | Not tested yet | | 9 | OAuth Login | ⏳ | Not tested yet | | 10 | MFA Challenge | ⏳ | Not tested yet | ### Issues Found: - [List any bugs or issues discovered] ### Recommended Fixes: - [Priority fixes needed] ``` ## Known Limitations & Future Work ### Current Limitations 1. **Client-side protection only** - Protected routes use client-side checks 2. **localStorage tokens** - Tokens stored in localStorage (not httpOnly cookies) 3. **No email verification UI** - Backend supports it, frontend doesn't 4. **No profile management** - Can't edit user profile yet 5. **No WebAuthn UI** - Backend supports passkeys, no frontend UI 6. **No session management UI** - Can't view/revoke active sessions ### Recommended Next Steps (Priority Order) #### Phase 1: Testing & Bug Fixes (CRITICAL) - [ ] Complete manual testing of all auth flows - [ ] Document and fix any bugs found - [ ] Verify error handling works correctly - [ ] Test with various browser/network conditions #### Phase 2: Server-Side Security (HIGH PRIORITY) - [ ] Implement Next.js middleware for route protection - [ ] Move tokens to httpOnly cookies - [ ] Add server-side authentication checks - [ ] Implement CSRF protection #### Phase 3: User Profile Management (HIGH VALUE) - [ ] Create `/profile` page to view/edit user info - [ ] Create `/settings` page for account settings - [ ] Add change password functionality - [ ] Add change email functionality - [ ] Display email verification status #### Phase 4: Email Verification (MEDIUM PRIORITY) - [ ] Create email verification page - [ ] Add "Resend verification" button - [ ] Handle verification callback - [ ] Update user state after verification - [ ] Add verification reminder in dashboard #### Phase 5: Enhanced Features (MEDIUM PRIORITY) - [ ] Add "Remember Me" option - [ ] Create active sessions view - [ ] Add "Logout all devices" button - [ ] Add security event log - [ ] Add login notifications #### Phase 6: WebAuthn/Passkeys (LOW PRIORITY) - [ ] Create passkey registration UI - [ ] Create passkey authentication UI - [ ] Add passkey management in settings - [ ] Test with hardware keys #### Phase 7: Content & Features (ONGOING) - [ ] Create parks browse page - [ ] Create rides browse page - [ ] Add search functionality - [ ] Create detail pages - [ ] Implement reviews system - [ ] Add social features ## Troubleshooting ### Django Server Won't Start **Error:** `ImportError` or module not found - **Fix:** Install dependencies: `pip install -r django-backend/requirements/local.txt` **Error:** Database connection failed - **Fix:** 1. Ensure PostgreSQL is running: `brew services start postgresql` 2. Create database: `createdb thrillwiki` 3. Update DATABASE_URL in `.env` **Error:** SECRET_KEY not set - **Fix:** Create `django-backend/.env` file with SECRET_KEY ### Next.js Server Won't Start **Error:** Port 3000 already in use - **Fix:** Kill existing process or use different port: `PORT=3001 npm run dev` **Error:** Environment variables not found - **Fix:** Ensure `.env.local` exists with `NEXT_PUBLIC_DJANGO_API_URL=http://localhost:8000` ### Authentication Not Working **Symptom:** Login button does nothing - **Check:** Browser console for errors - **Check:** Django server is running and accessible - **Check:** CORS configured correctly in Django `.env` **Symptom:** Tokens not stored - **Check:** Browser localStorage is enabled - **Check:** No browser extensions blocking storage **Symptom:** 401 errors - **Check:** Token hasn't expired - **Check:** Token format is correct - **Check:** Django authentication backend is configured ## Quick Reference ### API Endpoints ``` POST /api/v1/auth/registration/ - Register new user POST /api/v1/auth/login/ - Login POST /api/v1/auth/logout/ - Logout POST /api/v1/auth/token/refresh/ - Refresh access token POST /api/v1/auth/password/reset/ - Request password reset POST /api/v1/auth/password/reset/confirm/ - Confirm password reset GET /api/v1/auth/user/ - Get current user PATCH /api/v1/auth/user/ - Update user profile # OAuth GET /api/v1/auth/google/ - Google OAuth GET /api/v1/auth/discord/ - Discord OAuth GET /api/v1/auth/google/callback/ - Google callback GET /api/v1/auth/discord/callback/ - Discord callback # MFA POST /api/v1/auth/mfa/totp/activate/ - Activate TOTP POST /api/v1/auth/mfa/totp/confirm/ - Confirm TOTP POST /api/v1/auth/mfa/totp/deactivate/ - Deactivate TOTP ``` ### Frontend Services ```typescript // lib/services/auth/authService.ts login(credentials) - Login user register(data) - Register user logout() - Logout user getCurrentUser() - Get current user refreshAccessToken() - Refresh token // lib/contexts/AuthContext.tsx useAuth() - Hook to access auth state user - Current user object isAuthenticated - Boolean auth status ``` ### Useful Commands ```bash # Django python manage.py runserver # Start server python manage.py migrate # Run migrations python manage.py createsuperuser # Create admin user python manage.py shell # Django shell # Database psql thrillwiki # Connect to database python manage.py dbshell # Django database shell # Next.js npm run dev # Start dev server npm run build # Build for production npm run lint # Run linter # Monitoring tail -f django-backend/logs/*.log # View Django logs # Browser DevTools > Console # View frontend logs ``` ## Support & Resources - **Django Docs**: https://docs.djangoproject.com/ - **Django REST Framework**: https://www.django-rest-framework.org/ - **django-allauth**: https://docs.allauth.org/ - **Next.js Docs**: https://nextjs.org/docs - **JWT.io**: https://jwt.io/ (decode tokens for debugging) ## Summary The authentication system is **functionally complete** but **not yet tested**. The primary blocker is: 1. ⚠️ **Django backend needs `.env` configuration** 2. ⚠️ **PostgreSQL database needs to be set up** 3. ⚠️ **Manual testing has not been performed** Once these setup steps are completed, the system should be ready for comprehensive testing and further development.