Skip to content

Latest commit

Β 

History

History
357 lines (291 loc) Β· 9.98 KB

File metadata and controls

357 lines (291 loc) Β· 9.98 KB

Circle Authentication Implementation Summary

βœ… What Has Been Implemented

Backend (Python FastAPI)

Core Files Created:

  1. backend/main.py - FastAPI application entry point with CORS configuration
  2. backend/config.py - Environment settings and configuration management
  3. backend/models.py - Pydantic data models for requests/responses
  4. backend/requirements.txt - Python dependencies

Services:

  1. backend/services/circle_service.py - Circle Headless API integration

    • get_auth_token() - Generate auth token for user by email
    • verify_member() - Verify Circle member with access token
    • get_member_by_email() - Fetch member details by email
    • refresh_token() - Refresh Circle access token
  2. backend/services/auth_service.py - JWT and Google OAuth management

    • create_access_token() - Create JWT token
    • verify_token() - Verify JWT token
    • verify_google_token() - Verify Google OAuth token

Routers:

  1. backend/routers/auth.py - Authentication endpoints
    • POST /auth/login - Email/password login
    • POST /auth/google - Google OAuth login
    • GET /auth/me - Get current user
    • POST /auth/refresh - Refresh token

Middleware:

  1. backend/middleware/auth_middleware.py - Token verification middleware

Configuration:

  1. backend/.env.example - Environment variables template
  2. backend/.gitignore - Git ignore rules for Python

Frontend (Preact/Astro)

Components:

  1. src/islands/LoginForm.tsx - Login form component with:
    • Email/password login form
    • Google OAuth button integration
    • User session display
    • Auto-login on page load
    • Token management

Pages:

  1. src/pages/login.astro - Login page with complete UI

Utilities:

  1. src/utils/auth.ts - Authentication service utility
    • AuthService.login() - Login with email/password
    • AuthService.loginWithGoogle() - Login with Google
    • AuthService.checkAuth() - Check authentication status
    • AuthService.logout() - Logout user
    • AuthService.refreshToken() - Refresh token
    • Global state management with signals

Types:

  1. src/types/google-signin.d.ts - TypeScript definitions for Google Sign-In

Documentation:

  1. backend/README.md - Backend setup and API documentation
  2. CIRCLE_AUTH_SETUP.md - Complete setup guide
  3. start-auth-servers.sh - Startup script for both servers

Configuration Updates:

  1. .gitignore - Updated to ignore backend files

πŸ”‘ Key Features

Authentication Methods

  • βœ… Email/Password login (verifies Circle membership)
  • βœ… Google OAuth login
  • βœ… JWT token-based authentication
  • βœ… Token refresh mechanism
  • βœ… Auto-login on page load

Security

  • βœ… JWT tokens with configurable expiration (7 days default)
  • βœ… CORS protection
  • βœ… Secure token storage (localStorage)
  • βœ… Circle membership verification
  • βœ… Google OAuth integration

User Management

  • βœ… Fetch user profile from Circle
  • βœ… Display user info (name, email, avatar)
  • βœ… Logout functionality
  • βœ… Session persistence

πŸ“‹ API Endpoints

Authentication

  • POST /auth/login - Login with email/password
  • POST /auth/google - Login with Google OAuth
  • GET /auth/me - Get current authenticated user
  • POST /auth/refresh - Refresh Circle access token

System

  • GET / - API info
  • GET /health - Health check

πŸš€ Quick Start Guide

1. Backend Setup

cd backend
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
cp .env.example .env
# Edit .env with your credentials
python main.py

2. Frontend Setup

# From project root
npm install
npm run dev

3. Or Use Startup Script

chmod +x start-auth-servers.sh
./start-auth-servers.sh

πŸ”§ Configuration Required

Circle API Token

  1. Go to Circle admin β†’ Settings β†’ Developers β†’ Tokens
  2. Create "Headless Auth" token
  3. Add to backend/.env:
    CIRCLE_HEADLESS_TOKEN=your_token_here
    CIRCLE_COMMUNITY_ID=your_community_id

Environment Variables

Create backend/.env with:

  • CIRCLE_HEADLESS_TOKEN - Your Circle API token
  • CIRCLE_COMMUNITY_ID - Your Circle community ID
  • GOOGLE_CLIENT_ID - Google OAuth client ID (already provided)
  • GOOGLE_CLIENT_SECRET - Google OAuth secret (already provided)
  • JWT_SECRET - Strong secret key (generate your own!)
  • FRONTEND_URL - Frontend URL (http://localhost:4321)

πŸ“ File Structure

ai_builders_tutorial/
β”œβ”€β”€ backend/                          # Python FastAPI backend
β”‚   β”œβ”€β”€ main.py                      # FastAPI app
β”‚   β”œβ”€β”€ config.py                    # Settings
β”‚   β”œβ”€β”€ models.py                    # Data models
β”‚   β”œβ”€β”€ requirements.txt             # Dependencies
β”‚   β”œβ”€β”€ .env.example                 # Environment template
β”‚   β”œβ”€β”€ .gitignore                   # Git ignore
β”‚   β”œβ”€β”€ README.md                    # Backend docs
β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”œβ”€β”€ circle_service.py       # Circle API
β”‚   β”‚   └── auth_service.py         # JWT & OAuth
β”‚   β”œβ”€β”€ routers/
β”‚   β”‚   └── auth.py                 # Auth endpoints
β”‚   └── middleware/
β”‚       └── auth_middleware.py      # Token verification
β”‚
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ islands/
β”‚   β”‚   └── LoginForm.tsx           # Login component
β”‚   β”œβ”€β”€ pages/
β”‚   β”‚   └── login.astro             # Login page
β”‚   β”œβ”€β”€ types/
β”‚   β”‚   └── google-signin.d.ts      # TypeScript types
β”‚   └── utils/
β”‚       └── auth.ts                 # Auth service
β”‚
β”œβ”€β”€ CIRCLE_AUTH_SETUP.md            # Setup guide
β”œβ”€β”€ start-auth-servers.sh           # Startup script
└── .gitignore                      # Updated git ignore

πŸ§ͺ Testing

Test Backend

# Health check
curl http://localhost:8000/health

# Login
curl -X POST http://localhost:8000/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "user@example.com", "password": "any"}'

# Get user
curl http://localhost:8000/auth/me \
  -H "Authorization: Bearer YOUR_TOKEN"

Test Frontend

  1. Visit: http://localhost:4321/login
  2. Try email login (must be Circle member)
  3. Try Google login (must be Circle member)
  4. Verify user info displays
  5. Test logout

πŸ“ Environment Variables Reference

# Circle API
CIRCLE_HEADLESS_TOKEN=your_headless_auth_token_here
CIRCLE_COMMUNITY_ID=your_community_id
CIRCLE_API_URL=https://app.circle.so/api/v1

# Google OAuth
GOOGLE_CLIENT_ID=695004012662-a3981egieh12pqcbb57sbiug99b48mos.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=GOCSPX-Z57roRadsZ74hWhr0U-Jl3TP_OG

# JWT
JWT_SECRET=your_super_secret_jwt_key_change_this
JWT_ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=10080  # 7 days

# CORS
FRONTEND_URL=http://localhost:4321

🎯 Next Steps

Immediate

  1. βœ… Create backend/.env from .env.example
  2. βœ… Get Circle API token and add to .env
  3. βœ… Generate strong JWT_SECRET
  4. βœ… Start servers and test login

Future Enhancements

  • Email verification
  • Password reset flow
  • Role-based access control
  • User profile management
  • Activity logging
  • Rate limiting
  • Refresh token rotation
  • Remember me functionality
  • Multi-factor authentication

πŸ”’ Security Checklist

  • βœ… Environment variables in .gitignore
  • βœ… CORS protection configured
  • βœ… JWT tokens with expiration
  • βœ… Secure token storage
  • ⚠️ Change JWT_SECRET in production
  • ⚠️ Use HTTPS in production
  • ⚠️ Update FRONTEND_URL for production

πŸ› Common Issues & Solutions

Backend won't start

  • Check Python 3.8+ is installed
  • Activate virtual environment: source venv/bin/activate
  • Install dependencies: pip install -r requirements.txt
  • Verify .env file exists

Circle API errors

  • Verify token has "Headless Auth" permission
  • Check community ID is correct
  • Test token in Circle dashboard

CORS errors

  • Check FRONTEND_URL in .env matches frontend
  • Verify CORS middleware in main.py

Google Sign-In not loading

  • Check Google Client ID
  • Verify script is loaded (browser console)
  • Check for JavaScript errors

πŸ“š Resources

πŸ’‘ Usage Examples

Using AuthService in Components

import { AuthService, currentUser, isAuthenticated } from '../utils/auth';

// Check if user is logged in
const checkAuth = async () => {
  const isAuth = await AuthService.checkAuth();
  if (!isAuth) {
    window.location.href = '/login';
  }
};

// Login
const login = async (email: string, password: string) => {
  const result = await AuthService.login(email, password);
  if (result.success) {
    // User is logged in, currentUser.value is set
    console.log('Welcome', currentUser.value?.name);
  } else {
    console.error(result.error);
  }
};

// Logout
const logout = () => {
  AuthService.logout();
  window.location.href = '/login';
};

Protected Routes in Astro

---
import { AuthService } from '../utils/auth';

// Server-side auth check
const authHeader = Astro.request.headers.get('Authorization');
if (!authHeader) {
  return Astro.redirect('/login');
}
---

πŸŽ‰ Success Criteria

βœ… Backend server starts successfully βœ… Frontend server starts successfully
βœ… Can visit /login page βœ… Can login with Circle member email βœ… Can login with Google (Circle member) βœ… User info displays after login βœ… Logout works correctly βœ… Session persists on page reload βœ… API docs accessible at /docs

πŸ“ž Support

For issues or questions: