Skip to content

capy-school/auth

Repository files navigation

πŸ” Login Gateway - Comprehensive Authentication System

A modern, passwordless authentication gateway built with Astro, Turso, and Better Auth with support for multiple authentication methods and providers.

✨ Features

Authentication Methods

  • πŸ”‘ Passwordless Authentication
    • Passkey (WebAuthn)
    • Magic Link
    • Email OTP
  • πŸ” Two-Factor Authentication (2FA)
  • πŸ”’ Session Management

OAuth Providers

  • Google
  • Facebook
  • Apple
  • GitHub
  • Kakao
  • Naver
  • Line
  • Yandex
  • VK
  • WeChat

Advanced Features

  • πŸ‘₯ Organization Management - Multi-tenant support
  • πŸ”‘ API Key Management - Generate and manage API keys
  • πŸ‘‘ Admin Panel - Administrative controls
  • πŸ”„ OAuth Proxy - Custom OAuth provider support
  • ⏱️ One-Time Tokens - Secure temporary access
  • πŸ“– OpenAPI Documentation - Auto-generated API docs

πŸš€ Quick Start

Prerequisites

  • Node.js 18+ or Bun
  • Turso account (free at turso.tech)

1. Install Dependencies

bun install
# or
npm install

2. Set Up Turso Database

# Install Turso CLI
curl -sSfL https://get.tur.so/install.sh | bash

# Create a database
turso db create auth-gateway

# Get database URL
turso db show auth-gateway --url

# Create auth token
turso db tokens create auth-gateway

3. Configure Environment Variables

Copy .env.example to .env and fill in your credentials:

cp .env.example .env

Required variables:

TURSO_DATABASE_URL=libsql://your-database.turso.io
TURSO_AUTH_TOKEN=your-auth-token
BETTER_AUTH_SECRET=your-secret-key-here-min-32-chars
BETTER_AUTH_URL=http://localhost:4321

4. Run Database Migration

bun run db:migrate
# or
npm run db:migrate

5. Configure OAuth Providers (Optional)

Add your OAuth credentials to .env:

# Google
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret

# GitHub
GITHUB_CLIENT_ID=your-client-id
GITHUB_CLIENT_SECRET=your-client-secret

# Add more providers as needed...

Setting Up OAuth Providers

Google: Google Cloud Console

  • Callback URL: http://localhost:4321/api/auth/callback/google

GitHub: GitHub Developer Settings

  • Callback URL: http://localhost:4321/api/auth/callback/github

Facebook: Facebook Developers

  • Callback URL: http://localhost:4321/api/auth/callback/facebook

Apple: Apple Developer

  • Callback URL: http://localhost:4321/api/auth/callback/apple

6. Start Development Server

bun dev
# or
npm run dev

Visit http://localhost:4321 to see the login gateway.

πŸ“ Project Structure

/
β”œβ”€β”€ public/              # Static assets
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ components/      # React components
β”‚   β”‚   β”œβ”€β”€ AuthButton.tsx
β”‚   β”‚   └── LoginGateway.tsx
β”‚   β”œβ”€β”€ db/             # Database configuration
β”‚   β”‚   β”œβ”€β”€ client.ts   # Kysely client
β”‚   β”‚   β”œβ”€β”€ schema.ts   # TypeScript types
β”‚   β”‚   └── migrate.ts  # Migration script
β”‚   β”œβ”€β”€ lib/            # Utilities and configs
β”‚   β”‚   β”œβ”€β”€ auth.ts     # Better Auth config
β”‚   β”‚   β”œβ”€β”€ auth-client.ts  # Client-side auth
β”‚   β”‚   └── utils.ts    # Helper functions
β”‚   └── pages/          # Astro pages
β”‚       β”œβ”€β”€ index.astro # Login page
β”‚       β”œβ”€β”€ dashboard.astro # User dashboard
β”‚       └── api/auth/[...all].ts # Auth API routes
β”œβ”€β”€ .env.example        # Environment template
β”œβ”€β”€ astro.config.mjs    # Astro configuration
β”œβ”€β”€ tailwind.config.mjs # Tailwind CSS config
└── package.json

πŸ”§ Commands

Command Action
bun install Install dependencies
bun dev Start dev server at localhost:4321
bun build Build production site to ./dist/
bun preview Preview production build
bun run db:migrate Run database migrations

🎯 Usage Examples

Client-Side Authentication

import { authClient } from './lib/auth-client';

// Magic Link
await authClient.magicLink.sendMagicLink({ 
  email: 'user@example.com' 
});

// Email OTP
await authClient.emailOTP.sendOTP({ 
  email: 'user@example.com' 
});

// Passkey Registration
await authClient.passkey.register();

// Passkey Sign In
await authClient.passkey.signIn();

// Enable 2FA
const { qrCode, secret } = await authClient.twoFactor.enable();

// Create API Key
const apiKey = await authClient.apiKey.create({
  name: 'My API Key',
  expiresIn: 90 // days
});

// Create Organization
const org = await authClient.organization.create({
  name: 'My Company',
  slug: 'my-company'
});

Server-Side Session Check

// In Astro page
---
import { auth } from '../lib/auth';

const session = await auth.api.getSession({
  headers: Astro.request.headers,
});

if (!session) {
  return Astro.redirect('/');
}
---

πŸ” Security Features

  • Passwordless: No passwords to leak or forget
  • Passkey Support: WebAuthn/FIDO2 hardware security
  • 2FA: Time-based one-time passwords
  • Session Management: Secure token-based sessions
  • API Key Management: Scoped and expirable keys
  • Rate Limiting: Built-in protection
  • CSRF Protection: Automatic token validation

πŸ“– API Documentation

Once running, visit /api/auth/reference for the auto-generated OpenAPI documentation.

πŸš€ Deployment

Deploy to Vercel/Netlify/Cloudflare

  1. Build the project:
bun run build
  1. Set environment variables in your hosting platform

  2. Deploy the dist/ directory

Production Checklist

  • βœ… Set secure BETTER_AUTH_SECRET (min 32 chars)
  • βœ… Update BETTER_AUTH_URL to production URL
  • βœ… Configure OAuth callback URLs
  • βœ… Set up email service for Magic Link/OTP
  • βœ… Enable rate limiting
  • βœ… Configure CORS if needed

πŸ› οΈ Customization

Adding Custom OAuth Providers

Edit src/lib/auth.ts and add to the oAuthProxy plugin:

{
  id: 'custom-provider',
  name: 'Custom Provider',
  authorizationUrl: 'https://...',
  tokenUrl: 'https://...',
  userInfoUrl: 'https://...',
  clientId: process.env.CUSTOM_CLIENT_ID || '',
  clientSecret: process.env.CUSTOM_CLIENT_SECRET || '',
  scopes: ['profile', 'email'],
}

Styling

The project uses Tailwind CSS. Customize colors and styles in tailwind.config.mjs or modify component classes directly.

πŸ“š Documentation

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

πŸ“ License

MIT License - feel free to use this in your projects!

πŸ™ Credits

Built with:

Releases

Packages

Contributors

Languages