feat(auth): implement Google OAuth authentication system #95

Closed
forgejo_admin wants to merge 0 commits from feature/auth-google-oauth into feature/database-schema

Summary

This PR implements a complete, production-ready Google OAuth 2.0 authentication system for the AI Bulk Image Renamer SaaS, with security-first design and compliance with specification requirements §18-20.

🔐 Authentication Features Implemented

Core OAuth Flow

  • Google OAuth 2.0: Email scope only, secure callback handling
  • User Creation: Automatic account setup on first login (Basic plan, 50 quota)
  • JWT Sessions: Secure token-based authentication with httpOnly cookies
  • Privacy Protection: SHA-256 email hashing, no raw OAuth token storage

Security Architecture

// Secure OAuth flow with privacy protection
class AuthService {
  async validateOAuthUser(profile: GoogleProfile) {
    const emailHash = createHash('sha256').update(profile.email).digest('hex');
    return await this.createOrFindUser({
      googleId: profile.id,
      displayName: profile.displayName,
      emailHash,
      plan: Plan.BASIC,
      quotaRemaining: 50
    });
  }
}

Route Protection

  • JWT Guards: Automatic route protection with public/optional decorators
  • Rate Limiting: 10 requests/minute for auth endpoints
  • CSRF Protection: Token-based protection for state changes
  • Security Headers: CSP, HSTS, XSS protection, and CORS configuration

📡 API Endpoints

Authentication Flow

GET  /api/auth/google           # Initiate OAuth (§18)
GET  /api/auth/google/callback  # OAuth callback (§19)
POST /api/auth/logout           # Secure sign out
GET  /api/auth/profile          # Current user session
GET  /api/auth/status           # Authentication status

User Management

GET  /api/users/me              # User profile and quota
PUT  /api/users/me              # Update profile  
GET  /api/users/me/stats        # Usage statistics
GET  /api/users/me/quota/check  # Quota availability
DELETE /api/users/me            # Account deactivation

🛡️ Security Standards

Specification Compliance

  • §18: Sign-in button initiates Google OAuth 2.0 with email scope only
  • §19: Create new User record on first successful OAuth callback
  • §20: Store only Google user ID, display name, and email hash (never raw OAuth token)

Additional Security Features

  • Email Privacy: SHA-256 hashing prevents data leaks
  • Token Security: Signed JWT with expiration and validation
  • Session Management: Secure httpOnly cookies with CSRF protection
  • Rate Limiting: Prevents authentication abuse
  • CORS Protection: Configured for frontend integration
  • Security Headers: Comprehensive protection against common attacks

🏗️ Architecture Components

Authentication Module Structure

packages/api/src/auth/
├── auth.module.ts          # Main auth module
├── auth.controller.ts      # OAuth endpoints
├── auth.service.ts         # Business logic
├── google.strategy.ts      # Passport Google OAuth
├── jwt.strategy.ts         # JWT validation
├── auth.guard.ts           # Route protection
└── dto/auth.dto.ts         # Type-safe DTOs

Security Middleware

  • Rate Limiting: IP-based request throttling
  • Security Headers: Helmet.js integration
  • CSRF Protection: Token validation for state changes
  • Input Validation: Class-validator for all DTOs

🔄 OAuth Integration Flow

  1. Frontend Initiation: User clicks "Sign in with Google"
  2. OAuth Redirect: /api/auth/google → Google consent screen
  3. Google Callback: User consents → /api/auth/google/callback
  4. User Processing:
    • Extract profile (ID, name, email)
    • Hash email with SHA-256
    • Create/find User record
    • Generate JWT session
  5. Frontend Return: Redirect with secure session cookie
  6. API Protection: All routes validate JWT automatically

🎯 User Account Management

Account Creation Process

  • Google Profile: Extracted ID, display name, verified email
  • Privacy First: Email immediately hashed with SHA-256
  • Default Setup: Basic plan with 50 images/month quota
  • Audit Trail: Creation timestamp and activity logging
  • No Token Storage: Raw OAuth tokens never persisted

Session Management

  • JWT Tokens: Signed with secure secret, 24-hour expiration
  • Secure Cookies: httpOnly, sameSite, secure flags
  • Logout Protection: Token invalidation and cookie clearing
  • Concurrent Sessions: Support for multiple device login

🧪 Testing & Development

Environment Configuration

# Google OAuth (§18-20 compliance)
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
GOOGLE_CALLBACK_URL=http://localhost:3001/api/auth/google/callback

# JWT Security
JWT_SECRET=your_secure_jwt_secret
JWT_EXPIRES_IN=24h

# Security Settings
RATE_LIMIT_WINDOW_MS=60000
RATE_LIMIT_MAX_REQUESTS=10

Development Workflow

# Database setup
npm run db:migrate
npm run db:seed

# Start API server
npm run dev:api

# Test OAuth flow
curl http://localhost:3001/api/auth/google

This establishes a production-ready authentication foundation that supports the complete user journey from Google OAuth through quota management and subscription upgrades.

🤖 Generated with Claude Code

## Summary This PR implements a complete, production-ready Google OAuth 2.0 authentication system for the AI Bulk Image Renamer SaaS, with security-first design and compliance with specification requirements §18-20. ## 🔐 Authentication Features Implemented ### **Core OAuth Flow** - **Google OAuth 2.0**: Email scope only, secure callback handling - **User Creation**: Automatic account setup on first login (Basic plan, 50 quota) - **JWT Sessions**: Secure token-based authentication with httpOnly cookies - **Privacy Protection**: SHA-256 email hashing, no raw OAuth token storage ### **Security Architecture** ```typescript // Secure OAuth flow with privacy protection class AuthService { async validateOAuthUser(profile: GoogleProfile) { const emailHash = createHash('sha256').update(profile.email).digest('hex'); return await this.createOrFindUser({ googleId: profile.id, displayName: profile.displayName, emailHash, plan: Plan.BASIC, quotaRemaining: 50 }); } } ``` ### **Route Protection** - **JWT Guards**: Automatic route protection with public/optional decorators - **Rate Limiting**: 10 requests/minute for auth endpoints - **CSRF Protection**: Token-based protection for state changes - **Security Headers**: CSP, HSTS, XSS protection, and CORS configuration ## 📡 API Endpoints ### **Authentication Flow** ``` GET /api/auth/google # Initiate OAuth (§18) GET /api/auth/google/callback # OAuth callback (§19) POST /api/auth/logout # Secure sign out GET /api/auth/profile # Current user session GET /api/auth/status # Authentication status ``` ### **User Management** ``` GET /api/users/me # User profile and quota PUT /api/users/me # Update profile GET /api/users/me/stats # Usage statistics GET /api/users/me/quota/check # Quota availability DELETE /api/users/me # Account deactivation ``` ## 🛡️ Security Standards ### **Specification Compliance** - **§18**: ✅ Sign-in button initiates Google OAuth 2.0 with email scope only - **§19**: ✅ Create new User record on first successful OAuth callback - **§20**: ✅ Store only Google user ID, display name, and email hash (never raw OAuth token) ### **Additional Security Features** - **Email Privacy**: SHA-256 hashing prevents data leaks - **Token Security**: Signed JWT with expiration and validation - **Session Management**: Secure httpOnly cookies with CSRF protection - **Rate Limiting**: Prevents authentication abuse - **CORS Protection**: Configured for frontend integration - **Security Headers**: Comprehensive protection against common attacks ## 🏗️ Architecture Components ### **Authentication Module Structure** ``` packages/api/src/auth/ ├── auth.module.ts # Main auth module ├── auth.controller.ts # OAuth endpoints ├── auth.service.ts # Business logic ├── google.strategy.ts # Passport Google OAuth ├── jwt.strategy.ts # JWT validation ├── auth.guard.ts # Route protection └── dto/auth.dto.ts # Type-safe DTOs ``` ### **Security Middleware** - **Rate Limiting**: IP-based request throttling - **Security Headers**: Helmet.js integration - **CSRF Protection**: Token validation for state changes - **Input Validation**: Class-validator for all DTOs ## 🔄 OAuth Integration Flow 1. **Frontend Initiation**: User clicks "Sign in with Google" 2. **OAuth Redirect**: `/api/auth/google` → Google consent screen 3. **Google Callback**: User consents → `/api/auth/google/callback` 4. **User Processing**: - Extract profile (ID, name, email) - Hash email with SHA-256 - Create/find User record - Generate JWT session 5. **Frontend Return**: Redirect with secure session cookie 6. **API Protection**: All routes validate JWT automatically ## 🎯 User Account Management ### **Account Creation Process** - **Google Profile**: Extracted ID, display name, verified email - **Privacy First**: Email immediately hashed with SHA-256 - **Default Setup**: Basic plan with 50 images/month quota - **Audit Trail**: Creation timestamp and activity logging - **No Token Storage**: Raw OAuth tokens never persisted ### **Session Management** - **JWT Tokens**: Signed with secure secret, 24-hour expiration - **Secure Cookies**: httpOnly, sameSite, secure flags - **Logout Protection**: Token invalidation and cookie clearing - **Concurrent Sessions**: Support for multiple device login ## 🧪 Testing & Development ### **Environment Configuration** ```env # Google OAuth (§18-20 compliance) GOOGLE_CLIENT_ID=your_google_client_id GOOGLE_CLIENT_SECRET=your_google_client_secret GOOGLE_CALLBACK_URL=http://localhost:3001/api/auth/google/callback # JWT Security JWT_SECRET=your_secure_jwt_secret JWT_EXPIRES_IN=24h # Security Settings RATE_LIMIT_WINDOW_MS=60000 RATE_LIMIT_MAX_REQUESTS=10 ``` ### **Development Workflow** ```bash # Database setup npm run db:migrate npm run db:seed # Start API server npm run dev:api # Test OAuth flow curl http://localhost:3001/api/auth/google ``` This establishes a production-ready authentication foundation that supports the complete user journey from Google OAuth through quota management and subscription upgrades. 🤖 Generated with [Claude Code](https://claude.ai/code)
Author
Owner

Issue Resolved in v1.0.0 Release

This issue has been successfully resolved and implemented in the v1.0.0 release of the AI Bulk Image Renamer SaaS platform.

Implementation Summary:

  • Complete Google OAuth 2.0 authentication system with Passport.js integration
  • JWT-based session management with secure token handling
  • User registration and profile management
  • Email scope-only access for privacy compliance
  • Protected route middleware and authentication guards

Merge Commit: 68ec648 - Merge branch 'feature/auth-google-oauth' into feature/production-complete

Release Tag: v1.0.0

The Google OAuth authentication system has been successfully implemented and is now production-ready with secure user authentication and session management.

## ✅ Issue Resolved in v1.0.0 Release This issue has been successfully resolved and implemented in the **v1.0.0 release** of the AI Bulk Image Renamer SaaS platform. **Implementation Summary:** - Complete Google OAuth 2.0 authentication system with Passport.js integration - JWT-based session management with secure token handling - User registration and profile management - Email scope-only access for privacy compliance - Protected route middleware and authentication guards **Merge Commit:** `68ec648` - Merge branch 'feature/auth-google-oauth' into feature/production-complete **Release Tag:** [v1.0.0](https://vibecodetogether.com/Vibecode-Together/SEO_iamge_renamer_starting_point/releases/tag/v1.0.0) The Google OAuth authentication system has been successfully implemented and is now production-ready with secure user authentication and session management.
forgejo_admin closed this pull request 2025-08-05 19:58:48 +02:00

Pull request closed

Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference: Vibecode-Together/SEO_iamge_renamer_starting_point#95
No description provided.