|
| 1 | +# Discord OAuth Integration |
| 2 | + |
| 3 | +This document describes the Discord OAuth2 integration implementation for the TeachLink authentication flow. |
| 4 | + |
| 5 | +## Overview |
| 6 | + |
| 7 | +The Discord OAuth integration allows users to authenticate using their Discord account, providing a seamless signup/login experience. |
| 8 | + |
| 9 | +## Features |
| 10 | + |
| 11 | +- **OAuth2 Flow**: Implements the standard Discord OAuth2 authorization code flow |
| 12 | +- **Security**: Uses state parameter to prevent CSRF attacks |
| 13 | +- **Email Verification**: Requires Discord accounts to have verified emails |
| 14 | +- **Avatar Support**: Fetches and displays user avatars from Discord |
| 15 | +- **Edge Runtime**: Optimized for Edge deployment for fast performance |
| 16 | + |
| 17 | +## Architecture |
| 18 | + |
| 19 | +### Components |
| 20 | + |
| 21 | +1. **OAuth Utilities** (`src/lib/discord/oauth.ts`) |
| 22 | + - `getDiscordAuthUrl()`: Generates Discord authorization URL |
| 23 | + - `exchangeCodeForToken()`: Exchanges authorization code for access token |
| 24 | + - `getDiscordUser()`: Fetches user information from Discord |
| 25 | + - `getDiscordAvatarUrl()`: Generates avatar URL with fallback |
| 26 | + - `generateState()`: Generates random state for CSRF protection |
| 27 | + |
| 28 | +2. **API Routes** |
| 29 | + - `GET /api/auth/discord`: Initiates OAuth flow |
| 30 | + - `GET /api/auth/discord/callback`: Handles OAuth callback |
| 31 | + |
| 32 | +3. **UI Components** |
| 33 | + - `DiscordButton`: Reusable button component for Discord auth |
| 34 | + - Updated login/signup pages with Discord button |
| 35 | + |
| 36 | +### Flow Diagram |
| 37 | + |
| 38 | +``` |
| 39 | +User clicks Discord button |
| 40 | + ↓ |
| 41 | +GET /api/auth/discord |
| 42 | + ↓ |
| 43 | +Generate state, set cookie, redirect to Discord |
| 44 | + ↓ |
| 45 | +User authorizes on Discord |
| 46 | + ↓ |
| 47 | +Discord redirects to callback with code |
| 48 | + ↓ |
| 49 | +GET /api/auth/discord/callback |
| 50 | + ↓ |
| 51 | +Validate state, exchange code for token |
| 52 | + ↓ |
| 53 | +Fetch user info from Discord |
| 54 | + ↓ |
| 55 | +Create/update user session |
| 56 | + ↓ |
| 57 | +Return auth response |
| 58 | +``` |
| 59 | + |
| 60 | +## Configuration |
| 61 | + |
| 62 | +Add the following environment variables to your `.env` file: |
| 63 | + |
| 64 | +```env |
| 65 | +DISCORD_CLIENT_ID=your_discord_client_id |
| 66 | +DISCORD_CLIENT_SECRET=your_discord_client_secret |
| 67 | +DISCORD_REDIRECT_URI=http://localhost:3000/api/auth/discord/callback |
| 68 | +``` |
| 69 | + |
| 70 | +### Getting Discord OAuth Credentials |
| 71 | + |
| 72 | +1. Go to [Discord Developer Portal](https://discord.com/developers/applications) |
| 73 | +2. Create a new application |
| 74 | +3. Navigate to "OAuth2" → "General" |
| 75 | +4. Copy the Client ID and generate a Client Secret |
| 76 | +5. Add your redirect URI under "Redirects" |
| 77 | +6. Save the credentials in your environment variables |
| 78 | + |
| 79 | +### Production Redirect URI |
| 80 | + |
| 81 | +For production, use your actual domain: |
| 82 | +```env |
| 83 | +DISCORD_REDIRECT_URI=https://yourdomain.com/api/auth/discord/callback |
| 84 | +``` |
| 85 | + |
| 86 | +## Security Considerations |
| 87 | + |
| 88 | +1. **CSRF Protection**: State parameter is stored in httpOnly cookie and validated on callback |
| 89 | +2. **HTTPS Required**: In production, always use HTTPS for OAuth callbacks |
| 90 | +3. **Secret Management**: Never commit Discord secrets to version control |
| 91 | +4. **Email Verification**: Only accepts Discord accounts with verified emails |
| 92 | +5. **Rate Limiting**: All OAuth endpoints are rate-limited |
| 93 | + |
| 94 | +## API Reference |
| 95 | + |
| 96 | +### GET /api/auth/discord |
| 97 | + |
| 98 | +Initiates Discord OAuth flow. |
| 99 | + |
| 100 | +**Response:** Redirect to Discord authorization page |
| 101 | + |
| 102 | +**Cookie:** Sets `discord_oauth_state` for CSRF protection |
| 103 | + |
| 104 | +### GET /api/auth/discord/callback |
| 105 | + |
| 106 | +Handles Discord OAuth callback. |
| 107 | + |
| 108 | +**Query Parameters:** |
| 109 | +- `code`: Authorization code from Discord |
| 110 | +- `state`: State parameter for CSRF validation |
| 111 | +- `error`: OAuth error (if any) |
| 112 | + |
| 113 | +**Response:** |
| 114 | +```json |
| 115 | +{ |
| 116 | + "message": "Discord authentication successful", |
| 117 | + "user": { |
| 118 | + "id": "user_id", |
| 119 | + "name": "username", |
| 120 | + "email": "user@example.com", |
| 121 | + "avatar": "avatar_url", |
| 122 | + "provider": "discord", |
| 123 | + "providerId": "discord_user_id" |
| 124 | + }, |
| 125 | + "token": "jwt_token" |
| 126 | +} |
| 127 | +``` |
| 128 | + |
| 129 | +**Error Responses:** |
| 130 | +- `400`: Invalid parameters, unverified email, or OAuth error |
| 131 | +- `500`: Internal server error |
| 132 | + |
| 133 | +## Testing |
| 134 | + |
| 135 | +### Unit Tests |
| 136 | + |
| 137 | +Test OAuth utility functions: |
| 138 | +```bash |
| 139 | +pnpm test src/lib/discord/__tests__/oauth.test.ts |
| 140 | +``` |
| 141 | + |
| 142 | +### Integration Tests |
| 143 | + |
| 144 | +Test API routes: |
| 145 | +```bash |
| 146 | +pnpm test src/app/api/auth/discord/__tests__/route.test.ts |
| 147 | +pnpm test src/app/api/auth/discord/callback/__tests__/route.test.ts |
| 148 | +``` |
| 149 | + |
| 150 | +### E2E Tests |
| 151 | + |
| 152 | +Test complete OAuth flow: |
| 153 | +```bash |
| 154 | +pnpm test:e2e e2e/auth/discord.spec.ts |
| 155 | +``` |
| 156 | + |
| 157 | +## Future Enhancements |
| 158 | + |
| 159 | +- [ ] Implement token refresh logic |
| 160 | +- [ ] Add Discord role-based access control |
| 161 | +- [ ] Store Discord tokens for API integrations |
| 162 | +- [ ] Add Discord guild membership verification |
| 163 | +- [ ] Implement account linking (multiple OAuth providers) |
| 164 | + |
| 165 | +## Troubleshooting |
| 166 | + |
| 167 | +### Common Issues |
| 168 | + |
| 169 | +1. **"Discord OAuth configuration is missing"** |
| 170 | + - Ensure all environment variables are set |
| 171 | + - Check that variables are loaded in the Edge runtime |
| 172 | + |
| 173 | +2. **"Invalid state parameter"** |
| 174 | + - Clear cookies and try again |
| 175 | + - Ensure state cookie is being set correctly |
| 176 | + |
| 177 | +3. **"Discord email must be verified"** |
| 178 | + - User must verify their email on Discord first |
| 179 | + - Cannot use Discord accounts without verified email |
| 180 | + |
| 181 | +4. **Callback URL mismatch** |
| 182 | + - Ensure redirect URI matches exactly what's configured in Discord Developer Portal |
| 183 | + - Check for trailing slashes or protocol differences (http vs https) |
| 184 | + |
| 185 | +## Related Documentation |
| 186 | + |
| 187 | +- [Discord OAuth2 Documentation](https://discord.com/developers/docs/topics/oauth2) |
| 188 | +- [Next.js Edge Runtime](https://nextjs.org/docs/pages/building-your-application/rendering/edge-runtime) |
| 189 | +- [Authentication Flow Documentation](./AUTHENTICATION_FLOW.md) |
0 commit comments