Initial commit: Custom Start Page application with authentication and DynamoDB storage
This commit is contained in:
160
docs/task-2.2-implementation.md
Normal file
160
docs/task-2.2-implementation.md
Normal file
@@ -0,0 +1,160 @@
|
||||
# Task 2.2: OAuth Service Implementation
|
||||
|
||||
## Overview
|
||||
This document describes the implementation of the OAuth service with Google provider support for the Custom Start Page application.
|
||||
|
||||
## Components Implemented
|
||||
|
||||
### 1. OAuth Service (`internal/auth/oauth.go`)
|
||||
- **Purpose**: Manages OAuth authentication flows
|
||||
- **Key Methods**:
|
||||
- `InitiateOAuth(provider string)`: Generates OAuth redirect URL with CSRF protection
|
||||
- `HandleOAuthCallback(ctx, provider, code, state)`: Exchanges authorization code for access token
|
||||
- `GetGoogleConfig()`: Returns OAuth configuration for accessing user info
|
||||
- **Features**:
|
||||
- CSRF protection using state tokens
|
||||
- Support for Google OAuth (extensible for other providers)
|
||||
- Secure state token generation using crypto/rand
|
||||
|
||||
### 2. State Store (`internal/auth/state_store.go`)
|
||||
- **Purpose**: Manages OAuth state tokens for CSRF protection
|
||||
- **Implementation**: In-memory store with automatic cleanup
|
||||
- **Key Methods**:
|
||||
- `Set(state, expiry)`: Stores state token with expiration
|
||||
- `Validate(state)`: Checks if state token is valid and not expired
|
||||
- `Delete(state)`: Removes state token after use
|
||||
- **Features**:
|
||||
- Automatic cleanup of expired tokens every 5 minutes
|
||||
- Thread-safe with mutex protection
|
||||
- 10-minute token expiry for security
|
||||
|
||||
### 3. User Service (`internal/auth/user_service.go`)
|
||||
- **Purpose**: Handles user creation and retrieval from OAuth providers
|
||||
- **Key Methods**:
|
||||
- `GetOrCreateUserFromGoogle(ctx, token, config)`: Fetches user info and creates/updates user
|
||||
- `fetchGoogleUserInfo(ctx, token, config)`: Retrieves user data from Google API
|
||||
- **Features**:
|
||||
- Automatic user creation on first login
|
||||
- Email verification check
|
||||
- Updates last login timestamp
|
||||
|
||||
### 4. Session Store (`internal/auth/session_store.go`)
|
||||
- **Purpose**: Manages user sessions using cookies
|
||||
- **Implementation**: Cookie-based sessions using gorilla/sessions
|
||||
- **Key Methods**:
|
||||
- `CreateSession(w, r, userID)`: Creates authenticated session
|
||||
- `GetUserID(r)`: Retrieves user ID from session
|
||||
- `DestroySession(w, r)`: Logs out user
|
||||
- **Features**:
|
||||
- Secure, HTTP-only cookies
|
||||
- Configurable session expiry (default: 7 days)
|
||||
- SameSite protection
|
||||
|
||||
### 5. User Repository (`internal/storage/user_repository.go`)
|
||||
- **Purpose**: Handles user data persistence in DynamoDB
|
||||
- **Key Methods**:
|
||||
- `Create(ctx, user)`: Creates new user
|
||||
- `GetByID(ctx, userID)`: Retrieves user by ID
|
||||
- `GetByOAuthID(ctx, provider, oauthID)`: Finds user by OAuth credentials
|
||||
- `Update(ctx, user)`: Updates existing user
|
||||
- **Note**: Currently uses Scan for OAuth lookup; consider adding GSI in production
|
||||
|
||||
### 6. Auth Handler (`internal/handlers/auth_handler.go`)
|
||||
- **Purpose**: HTTP handlers for authentication endpoints
|
||||
- **Endpoints**:
|
||||
- `GET /auth/oauth/{provider}`: Initiates OAuth flow
|
||||
- `GET /auth/callback/{provider}`: Handles OAuth callback
|
||||
- `POST /logout`: Logs out user
|
||||
- `GET /login`: Displays login page
|
||||
- **Features**:
|
||||
- Error handling with user-friendly messages
|
||||
- Automatic redirect to dashboard on success
|
||||
- Session management integration
|
||||
|
||||
## HTTP Endpoints
|
||||
|
||||
### OAuth Flow
|
||||
1. **Initiate OAuth**: `GET /auth/oauth/google`
|
||||
- Generates state token
|
||||
- Redirects to Google OAuth consent screen
|
||||
|
||||
2. **OAuth Callback**: `GET /auth/callback/google?code=...&state=...`
|
||||
- Validates state token (CSRF protection)
|
||||
- Exchanges code for access token
|
||||
- Fetches user info from Google
|
||||
- Creates or retrieves user account
|
||||
- Creates session
|
||||
- Redirects to dashboard
|
||||
|
||||
3. **Logout**: `POST /logout`
|
||||
- Destroys session
|
||||
- Redirects to login page
|
||||
|
||||
4. **Login Page**: `GET /login`
|
||||
- Displays OAuth provider buttons
|
||||
- Shows error messages if authentication failed
|
||||
|
||||
## Configuration
|
||||
|
||||
Required environment variables:
|
||||
```bash
|
||||
GOOGLE_CLIENT_ID=your-google-client-id
|
||||
GOOGLE_CLIENT_SECRET=your-google-client-secret
|
||||
GOOGLE_REDIRECT_URL=http://localhost:8080/auth/callback/google
|
||||
SESSION_SECRET=change-me-in-production
|
||||
SESSION_MAX_AGE=604800 # 7 days in seconds
|
||||
```
|
||||
|
||||
## Security Features
|
||||
|
||||
1. **CSRF Protection**: State tokens prevent cross-site request forgery
|
||||
2. **Secure Sessions**: HTTP-only, secure cookies with SameSite protection
|
||||
3. **Email Verification**: Only verified Google emails are accepted
|
||||
4. **Token Expiry**: State tokens expire after 10 minutes
|
||||
5. **Cryptographic Randomness**: State tokens use crypto/rand for security
|
||||
|
||||
## Testing
|
||||
|
||||
Comprehensive test coverage includes:
|
||||
- OAuth service initialization and callback handling
|
||||
- State store operations (set, validate, delete, expiry)
|
||||
- Session store operations (create, retrieve, destroy)
|
||||
- Error handling for invalid states and codes
|
||||
- Concurrent state management
|
||||
|
||||
Run tests:
|
||||
```bash
|
||||
go test ./internal/auth/... -v
|
||||
```
|
||||
|
||||
## Integration with Main Server
|
||||
|
||||
The OAuth service is integrated into `cmd/server/main.go`:
|
||||
- Initializes DynamoDB client and creates Users table
|
||||
- Sets up OAuth service with Google configuration
|
||||
- Creates session store with configured secret
|
||||
- Registers auth handlers for OAuth endpoints
|
||||
- Protects dashboard route with session check
|
||||
|
||||
## Requirements Validated
|
||||
|
||||
This implementation addresses the following requirements:
|
||||
- **1.2**: OAuth provider selection triggers redirect
|
||||
- **1.3**: Successful OAuth creates or retrieves user
|
||||
- **1.5**: Google OAuth support
|
||||
- **1.6**: Additional OAuth providers can be configured (extensible design)
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
1. **Production State Store**: Replace in-memory store with Redis or DynamoDB for multi-server deployments
|
||||
2. **OAuth Provider GSI**: Add Global Secondary Index on oauth_provider + oauth_id for efficient user lookup
|
||||
3. **Additional Providers**: Add GitHub, Microsoft, and other OAuth providers
|
||||
4. **Rate Limiting**: Add rate limiting on OAuth endpoints
|
||||
5. **Audit Logging**: Log authentication events for security monitoring
|
||||
|
||||
## Dependencies Added
|
||||
|
||||
- `golang.org/x/oauth2`: OAuth 2.0 client library
|
||||
- `golang.org/x/oauth2/google`: Google OAuth provider
|
||||
- `github.com/gorilla/sessions`: Session management
|
||||
- `github.com/gorilla/securecookie`: Secure cookie encoding (dependency of sessions)
|
||||
Reference in New Issue
Block a user