generated from nhcarrigan/template
1.8 KiB
1.8 KiB
Authentication Flow
Overview
This API uses Discord OAuth for authentication and JWT tokens for session management. Only the admin user can perform create/update/delete operations, while public read access is available to everyone.
Environment Variables
Set up your prod.env file with 1Password references:
DATABASE_URL- MongoDB connection stringJWT_SECRET- Secret for signing JWT tokensDISCORD_CLIENT_ID- Discord OAuth app client IDDISCORD_CLIENT_SECRET- Discord OAuth app client secretADMIN_DISCORD_ID- Your Discord user ID for admin accessAPI_URL- API base URL (e.g., http://localhost:3000)FRONTEND_URL- Frontend URL to redirect after login
Running the API
# Start with 1Password secrets
op run --env-file=prod.env -- nx serve api
Auth Endpoints
1. Login
GET /api/auth/login - Redirects to Discord OAuth
2. Callback
GET /api/auth/callback - Discord redirects here after auth
- Creates/updates user in database
- Generates JWT token
- Sets httpOnly cookie
auth-token - Redirects to frontend
3. Get Current User
GET /api/auth/me - Returns authenticated user (requires auth)
4. Logout
POST /api/auth/logout - Clears auth cookie
Protected Routes
Example: Games API
GET /api/games- Public (list all games)GET /api/games/:id- Public (get single game)POST /api/games- Admin only (create game)PUT /api/games/:id- Admin only (update game)DELETE /api/games/:id- Admin only (delete game)
Testing
- Set up Discord OAuth app at https://discord.com/developers/applications
- Add redirect URI:
http://localhost:3000/api/auth/callback - Copy client ID and secret to 1Password
- Run the API and visit
http://localhost:3000/api/auth/login - After Discord auth, you'll be redirected to frontend with auth cookie set