community feature

This commit is contained in:
wass08
2026-02-11 15:23:18 +09:00
parent 4f9c4655e6
commit 2e8b663001
71 changed files with 1917 additions and 126 deletions
+142
View File
@@ -0,0 +1,142 @@
# @pascal-app/auth
Authentication package for Pascal Editor using Better Auth.
## Features
- **Magic Link Authentication** - Passwordless email-based authentication
- **Session Management** - Secure cookie-based sessions
- **Supabase Integration** - Uses Supabase as the database adapter
- **Type-safe** - Full TypeScript support with type inference
## Setup
### 1. Configure environment variables
Add these to `apps/editor/.env.local`:
```bash
# Better Auth
BETTER_AUTH_SECRET=<generate_with_openssl_rand_base64_32>
BETTER_AUTH_URL=http://localhost:3000
```
Generate a secret for `BETTER_AUTH_SECRET`:
```bash
openssl rand -base64 32
```
### 2. Ensure database is running
Make sure you have Supabase running with the auth tables created. See `@pascal-app/db` package for setup.
## Usage
### Server-side (API routes, server actions)
```typescript
import { auth } from '@pascal-app/auth/server'
// Get session in server component or action
const session = await auth.api.getSession({ headers: request.headers })
if (!session) {
return { error: 'Unauthorized' }
}
// Access user data
const userId = session.user.id
const email = session.user.email
```
### Client-side (React components)
```typescript
'use client'
import { authClient } from '@pascal-app/auth/client'
function SignInButton() {
const { signIn } = authClient
const handleSignIn = async (email: string) => {
await signIn.magicLink({
email,
callbackURL: '/dashboard',
})
}
return <button onClick={() => handleSignIn('user@example.com')}>Sign In</button>
}
```
### Using the auth hook
```typescript
'use client'
import { authClient } from '@pascal-app/auth/client'
function Profile() {
const { data: session, isPending } = authClient.useSession()
if (isPending) return <div>Loading...</div>
if (!session) return <div>Not signed in</div>
return <div>Signed in as {session.user.email}</div>
}
```
## API Routes
The auth package requires an API route handler in your Next.js app:
```typescript
// app/api/auth/[...all]/route.ts
import { auth } from '@pascal-app/auth/server'
import { toNextJsHandler } from 'better-auth/next-js'
export const { GET, POST } = toNextJsHandler(auth)
```
This handles all Better Auth endpoints:
- `/api/auth/sign-in/magic-link` - Send magic link
- `/api/auth/sign-in/magic-link/verify` - Verify magic link
- `/api/auth/sign-out` - Sign out
- `/api/auth/session` - Get session
- And more...
## Email Configuration
By default, magic links are logged to the console. To send actual emails, you'll need to configure an email provider in `packages/auth/src/server.ts`:
```typescript
magicLink({
sendMagicLink: async ({ email, url }) => {
// Use Resend, SendGrid, or your preferred email service
await sendEmail({
to: email,
subject: 'Sign in to Pascal Editor',
html: `Click here to sign in: <a href="${url}">${url}</a>`,
})
},
})
```
## Database Schema
The auth package requires these tables (created by `@pascal-app/db` migrations):
- `users` - User accounts
- `sessions` - Active sessions
- `accounts` - OAuth provider accounts (for future use)
- `verification_tokens` - Magic link tokens
## Security
- Session cookies are httpOnly and secure (in production)
- Sessions expire after 7 days
- Session cache is enabled for 5 minutes to reduce database queries
- Magic link tokens expire after 15 minutes
- All sensitive operations require valid session tokens
+24
View File
@@ -0,0 +1,24 @@
{
"name": "@pascal-app/auth",
"version": "0.0.0",
"type": "module",
"exports": {
"./server": {
"types": "./src/server.ts",
"default": "./src/server.ts"
},
"./client": {
"types": "./src/client.ts",
"default": "./src/client.ts"
}
},
"dependencies": {
"@pascal-app/db": "*",
"better-auth": "^1.4.18",
"resend": "^4.0.1"
},
"devDependencies": {
"@repo/typescript-config": "*",
"typescript": "5.9.2"
}
}
+37
View File
@@ -0,0 +1,37 @@
import { magicLinkClient } from 'better-auth/client/plugins'
import { createAuthClient } from 'better-auth/react'
/**
* Get the auth base URL
* In development: use the editor URL (localhost:3000)
* In production: use the same origin
*/
function getAuthURL(): string {
if (typeof window !== 'undefined') {
return window.location.origin
}
// SSR fallback
return process.env.BETTER_AUTH_URL || 'http://localhost:3000'
}
/**
* Auth client instance
* Configured for magic link authentication
*/
export const authClient = createAuthClient({
baseURL: getAuthURL(),
plugins: [magicLinkClient()],
})
/**
* Export types for use in components
*/
export type AuthState = {
user: (typeof authClient)['$Infer']['Session']['user'] | null
session: (typeof authClient)['$Infer']['Session']['session'] | null
isLoading: boolean
}
export type User = NonNullable<AuthState['user']>
export type Session = NonNullable<AuthState['session']>
+91
View File
@@ -0,0 +1,91 @@
import { db, schema } from '@pascal-app/db'
import { betterAuth } from 'better-auth'
import { drizzleAdapter } from 'better-auth/adapters/drizzle'
import { magicLink } from 'better-auth/plugins'
import { Resend } from 'resend'
if (!process.env.BETTER_AUTH_SECRET) {
throw new Error(
'Missing BETTER_AUTH_SECRET environment variable. Generate one with: openssl rand -base64 32',
)
}
if (!process.env.BETTER_AUTH_URL) {
throw new Error(
'Missing BETTER_AUTH_URL environment variable. Set it to your app URL (e.g., http://localhost:3000)',
)
}
// Initialize Resend for email sending
const resend = process.env.RESEND_API_KEY ? new Resend(process.env.RESEND_API_KEY) : null
/**
* Better Auth server instance
* Configured with PostgreSQL database (Supabase) and magic link authentication
*/
export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: 'pg',
usePlural: true,
schema,
}),
advanced: {
database: {
generateId: false, // Use our prefixed nanoid IDs from schema
},
},
secret: process.env.BETTER_AUTH_SECRET,
baseURL: process.env.BETTER_AUTH_URL,
plugins: [
magicLink({
sendMagicLink: async ({ email, url }) => {
if (!resend) {
console.log(`[DEV] Magic link for ${email}: ${url}`)
return
}
try {
await resend.emails.send({
from: 'Pascal <noreply@pascal.app>',
to: email,
subject: 'Sign in to Pascal Editor',
html: `
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
<h2>Sign in to Pascal Editor</h2>
<p>Click the button below to sign in to your account:</p>
<a href="${url}" style="display: inline-block; background-color: #000; color: #fff; padding: 12px 24px; text-decoration: none; border-radius: 6px; margin: 20px 0;">
Sign In
</a>
<p style="color: #666; font-size: 14px;">This link will expire in 5 minutes.</p>
<p style="color: #666; font-size: 14px;">If you didn't request this email, you can safely ignore it.</p>
</div>
`,
})
console.log(`✓ Magic link email sent to ${email}`)
} catch (error) {
console.error('Failed to send magic link email:', error)
throw error
}
},
}),
],
session: {
expiresIn: 60 * 60 * 24 * 7, // 7 days
updateAge: 60 * 60 * 24, // 1 day
cookieCache: {
enabled: true,
maxAge: 5 * 60, // 5 minutes
},
additionalFields: {
activePropertyId: {
type: 'string',
},
},
},
})
/**
* Type helpers for better-auth session
*/
export type Session = typeof auth.$Infer.Session.session
export type User = typeof auth.$Infer.Session.user
+9
View File
@@ -0,0 +1,9 @@
{
"extends": "@repo/typescript-config/base.json",
"compilerOptions": {
"outDir": "dist",
"rootDir": "src"
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}