6.0 KiB
6.0 KiB
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 protectionHandleOAuthCallback(ctx, provider, code, state): Exchanges authorization code for access tokenGetGoogleConfig(): 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 expirationValidate(state): Checks if state token is valid and not expiredDelete(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 userfetchGoogleUserInfo(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 sessionGetUserID(r): Retrieves user ID from sessionDestroySession(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 userGetByID(ctx, userID): Retrieves user by IDGetByOAuthID(ctx, provider, oauthID): Finds user by OAuth credentialsUpdate(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 flowGET /auth/callback/{provider}: Handles OAuth callbackPOST /logout: Logs out userGET /login: Displays login page
- Features:
- Error handling with user-friendly messages
- Automatic redirect to dashboard on success
- Session management integration
HTTP Endpoints
OAuth Flow
-
Initiate OAuth:
GET /auth/oauth/google- Generates state token
- Redirects to Google OAuth consent screen
-
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
-
Logout:
POST /logout- Destroys session
- Redirects to login page
-
Login Page:
GET /login- Displays OAuth provider buttons
- Shows error messages if authentication failed
Configuration
Required environment variables:
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
- CSRF Protection: State tokens prevent cross-site request forgery
- Secure Sessions: HTTP-only, secure cookies with SameSite protection
- Email Verification: Only verified Google emails are accepted
- Token Expiry: State tokens expire after 10 minutes
- 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:
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
- Production State Store: Replace in-memory store with Redis or DynamoDB for multi-server deployments
- OAuth Provider GSI: Add Global Secondary Index on oauth_provider + oauth_id for efficient user lookup
- Additional Providers: Add GitHub, Microsoft, and other OAuth providers
- Rate Limiting: Add rate limiting on OAuth endpoints
- Audit Logging: Log authentication events for security monitoring
Dependencies Added
golang.org/x/oauth2: OAuth 2.0 client librarygolang.org/x/oauth2/google: Google OAuth providergithub.com/gorilla/sessions: Session managementgithub.com/gorilla/securecookie: Secure cookie encoding (dependency of sessions)