Skip to content

history-lab/login-auth

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Auth Login for Cloudflare Workers

A Google OAuth integration for Cloudflare Workers that handles both first-time registration and returning user sign-in with a profile form.

Features

  • Google OAuth authentication
  • User profile collection (name, institution, position, terms agreement)
  • Persistent user sessions with HTTP-only secure cookies
  • Cloudflare Workers KV for data storage
  • Automatic handling of returning vs. new users

Architecture

This project consists of a standalone Cloudflare Worker that handles authentication and user profile management. It can be deployed separately from your main application or integrated directly.

Components

  1. Authentication Flow: Handles Google OAuth 2.0 flow with authorization code grant
  2. Profile Collection: Serves and processes a form for collecting additional user information
  3. Session Management: Uses HTTP-only secure cookies for maintaining user sessions
  4. User Storage: Stores user data in Cloudflare KV with mappings between Google IDs and internal UUIDs

Flow Diagram

Browser                   Auth Worker                 Google                   KV Store
   |                          |                          |                        |
   |------- /login ---------->|                          |                        |
   |                          |------- redirect -------->|                        |
   |                          |                          |                        |
   |------ authenticate ----->|                          |                        |
   |                          |                          |                        |
   |<----- redirect back -----|<--------- token ---------|                        |
   |                          |                          |                        |
   |------ /callback -------->|                          |                        |
   |                          |-------------------------->| check if user exists  |
   |                          |<--------------------------|                       |
   |                          |                          |                        |
   |                          |-------------------------->| store user if new     |
   |                          |                          |                        |
   |<-- redirect + session -->|                          |                        |
   |                          |                          |                        |
   |---- /collect-profile --->| (only for new users)     |                        |
   |<----- profile form ------|                          |                        |
   |                          |                          |                        |
   |------ /profile POST ---->|                          |                        |
   |                          |-------------------------->| update user profile   |
   |                          |                          |                        |
   |<----- redirect to app ---|                          |                        |

Setup

  1. Create Google OAuth Credentials:

    • Go to the Google Cloud Console
    • Create a new project or use an existing one
    • Navigate to "APIs & Services" > "Credentials"
    • Create an OAuth Client ID for a Web Application
    • Add your redirect URI (e.g., https://your-worker.workers.dev/callback)
    • Note your Client ID and Client Secret
  2. Configure Wrangler:

    wrangler kv:namespace create USERS
    wrangler kv:namespace create USERS --preview
    

    Update the KV namespace IDs in wrangler.jsonc.

  3. Set Environment Variables:

    wrangler secret put OAUTH_CLIENT_SECRET
    

    Update OAUTH_CLIENT_ID and OAUTH_REDIRECT in wrangler.jsonc.

    Optional Configuration:

    You can also configure these optional environment variables:

    • ALLOWED_ORIGINS: Comma-separated list of allowed origins for CORS and postMessage
    • DEFAULT_RETURN_URL: Default URL to redirect to after successful authentication

    Example in wrangler.jsonc:

    "vars": {
      "OAUTH_CLIENT_ID": "your-client-id.apps.googleusercontent.com",
      "OAUTH_REDIRECT": "https://auth.yourdomain.com/pkce/callback",
      "ALLOWED_ORIGINS": "https://app.yourdomain.com,https://alt.yourdomain.com",
      "DEFAULT_RETURN_URL": "https://app.yourdomain.com"
    }

    These settings can be adjusted for different environments (development, staging, production) without changing code.

  4. Deploy the Worker:

    npm install
    npm run deploy
    

Integration with Chat Application

To integrate with your chat application, you need to:

  1. Make your chat application check for the existence of the auth cookie
  2. If the cookie exists, verify the user by fetching user data from KV
  3. If the cookie doesn't exist, redirect to the auth login endpoint

Example verification in your chat app worker:

// In your chat application worker
const userUuid = getCookie(request, '__hl_session');
if (!userUuid) {
  return Response.redirect('https://auth-worker.your-domain.workers.dev/login', 302);
}

// Check if the user exists in KV
const userJson = await env.USERS.get(`user:${userUuid}`);
if (!userJson) {
  return Response.redirect('https://auth-worker.your-domain.workers.dev/login', 302);
}

// User is authenticated, continue with chat functionality
const user = JSON.parse(userJson);
// Use user.uuid for logging and tracking

Development

npm install
npm run dev

License

MIT

About

Handles registration/login and form submission

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published