Files
ims/app/api/settings/route.ts
T
adminandClaude Sonnet 4.6 d18d29168a feat(auth): phase 3 — replace Supabase GoTrue with bcryptjs+jose
Custom auth stack: bcryptjs password hashing (cost 10, GoTrue-compatible),
jose JWT session cookies (edge-safe, 8hr TTL), new API routes for
login/logout/reset/change-password, middleware rewritten to JWT-only
verification with no DB access. All 38 protected pages and API routes
migrated from supabase.auth.getUser() to getSession(). Supabase .from()
queries retained for Phase 4. lib/db/index.ts refactored to lazy Proxy
singleton to avoid module-level throw during Next.js build.

tsc: clean, build: clean, tests: 4/4 passed

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-23 16:20:04 +08:00

66 lines
2.1 KiB
TypeScript

export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { getSession } from '@/lib/auth/get-session'
const ALLOWED_KEYS = [
'DEEPSEEK_API_KEY',
'GOOGLE_AI_API_KEY',
'META_WHATSAPP_PHONE_NUMBER_ID',
'META_WHATSAPP_ACCESS_TOKEN',
] as const
type SettingKey = typeof ALLOWED_KEYS[number]
export async function GET() {
const session = await getSession()
if (!session || session.role !== 'admin') return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const { data } = await supabase.from('app_settings').select('key, value, updated_at')
const masked = (data ?? []).map(row => ({
key: row.key,
set: Boolean(row.value),
masked_value: row.value ? `${row.value.slice(0, 8)}${'•'.repeat(12)}` : '',
updated_at: row.updated_at,
}))
return NextResponse.json(masked)
}
export async function POST(request: NextRequest) {
const session = await getSession()
if (!session || session.role !== 'admin') return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
let body: { key?: string; value?: string }
try { body = await request.json() } catch {
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
}
if (!body.key || !ALLOWED_KEYS.includes(body.key as SettingKey)) {
return NextResponse.json({ error: 'Invalid key' }, { status: 422 })
}
if (typeof body.value !== 'string' || body.value.trim() === '') {
return NextResponse.json({ error: 'value must be a non-empty string' }, { status: 422 })
}
const { error } = await supabase.from('app_settings').upsert({
key: body.key,
value: body.value,
updated_at: new Date().toISOString(),
updated_by: session.sub,
})
if (error) return NextResponse.json({ error: 'Save failed' }, { status: 500 })
await supabase.rpc('write_audit_log', {
p_table_name: 'app_settings',
p_record_id: session.sub,
p_action: 'UPDATE',
p_new_value: { key: body.key, set: Boolean(body.value) } as never,
})
return NextResponse.json({ ok: true })
}