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>
155 lines
5.8 KiB
TypeScript
155 lines
5.8 KiB
TypeScript
export const dynamic = 'force-dynamic'
|
|
|
|
import { NextRequest, NextResponse } from 'next/server'
|
|
import { createClient } from '@/lib/supabase/server'
|
|
import { isValidRole } from '@/lib/auth/roles'
|
|
import { requireAdmin } from '@/lib/auth/require-admin'
|
|
import { hashPassword } from '@/lib/auth/password'
|
|
import { asAdmin } from '@/lib/db/with-user'
|
|
import { users } from '@/lib/db/schema'
|
|
import { eq } from 'drizzle-orm'
|
|
|
|
export async function GET() {
|
|
const { session } = await requireAdmin()
|
|
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
|
|
|
const supabase = await createClient()
|
|
const { data, error } = await supabase
|
|
.from('users')
|
|
.select('id, name, email, phone, role, department, site_id, active, created_at')
|
|
.order('created_at', { ascending: false })
|
|
|
|
if (error) return NextResponse.json({ error: 'Fetch failed' }, { status: 500 })
|
|
return NextResponse.json(data ?? [])
|
|
}
|
|
|
|
export async function POST(request: NextRequest) {
|
|
const { session } = await requireAdmin()
|
|
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
|
|
|
const body: { email?: string; name?: string; phone?: string; role?: string; site_id?: string; department?: string; password?: string } =
|
|
await request.json().catch(() => ({}))
|
|
const email = (body.email ?? '').trim().toLowerCase()
|
|
if (!email || !email.includes('@'))
|
|
return NextResponse.json({ error: 'Valid email required' }, { status: 422 })
|
|
if (body.role && !isValidRole(body.role))
|
|
return NextResponse.json({ error: 'Invalid role' }, { status: 422 })
|
|
const password = (body.password ?? '').trim()
|
|
if (!password)
|
|
return NextResponse.json({ error: 'Password required' }, { status: 422 })
|
|
if (password.length < 8)
|
|
return NextResponse.json({ error: 'Password must be at least 8 characters' }, { status: 422 })
|
|
|
|
const passwordHash = await hashPassword(password)
|
|
|
|
const [created] = await asAdmin(db => db.insert(users).values({
|
|
name: body.name ?? '',
|
|
email,
|
|
phone: (body.phone ?? '').trim() || null,
|
|
role: (body.role as typeof users.$inferInsert['role']) ?? 'reporter',
|
|
siteId: body.site_id ?? null,
|
|
department: body.department ?? null,
|
|
passwordHash,
|
|
emailVerifiedAt: new Date(),
|
|
}).returning({ id: users.id }))
|
|
|
|
if (!created) {
|
|
return NextResponse.json({ error: 'User creation failed' }, { status: 500 })
|
|
}
|
|
|
|
const supabase = await createClient()
|
|
await supabase.rpc('write_audit_log', {
|
|
p_table_name: 'users',
|
|
p_record_id: created.id,
|
|
p_action: 'created',
|
|
p_new_value: { email, role: body.role ?? 'reporter', site_id: body.site_id ?? null },
|
|
})
|
|
|
|
return NextResponse.json({ id: created.id }, { status: 201 })
|
|
}
|
|
|
|
export async function PATCH(request: NextRequest) {
|
|
const { session } = await requireAdmin()
|
|
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
|
|
|
const supabase = await createClient()
|
|
|
|
const body: {
|
|
id?: string
|
|
role?: string
|
|
site_id?: string | null
|
|
active?: boolean
|
|
department?: string | null
|
|
} = await request.json().catch(() => ({}))
|
|
|
|
if (!body.id) return NextResponse.json({ error: 'id required' }, { status: 422 })
|
|
if (body.role !== undefined && !isValidRole(body.role))
|
|
return NextResponse.json({ error: 'Invalid role' }, { status: 422 })
|
|
if (body.id === session.sub && body.active === false)
|
|
return NextResponse.json({ error: 'Cannot deactivate your own account' }, { status: 422 })
|
|
if (body.id === session.sub && body.role !== undefined && body.role !== 'admin')
|
|
return NextResponse.json({ error: 'Cannot demote your own account' }, { status: 422 })
|
|
|
|
const update: Record<string, unknown> = {}
|
|
if (body.role !== undefined) update.role = body.role
|
|
if (body.site_id !== undefined) update.site_id = body.site_id
|
|
if (body.active !== undefined) update.active = body.active
|
|
if (body.department !== undefined) update.department = body.department
|
|
if (Object.keys(update).length === 0)
|
|
return NextResponse.json({ error: 'Nothing to update' }, { status: 422 })
|
|
|
|
const { data: before } = await supabase
|
|
.from('users').select('role, site_id, active, department').eq('id', body.id).single()
|
|
if (!before) return NextResponse.json({ error: 'User not found' }, { status: 404 })
|
|
|
|
const { error } = await supabase.from('users').update(update).eq('id', body.id)
|
|
if (error) return NextResponse.json({ error: 'Update failed' }, { status: 500 })
|
|
|
|
await supabase.rpc('write_audit_log', {
|
|
p_table_name: 'users',
|
|
p_record_id: body.id,
|
|
p_action: 'admin_update',
|
|
p_old_value: before ?? null,
|
|
p_new_value: update,
|
|
})
|
|
|
|
return NextResponse.json({ ok: true })
|
|
}
|
|
|
|
export async function DELETE(request: NextRequest) {
|
|
const { session } = await requireAdmin()
|
|
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
|
|
|
const { searchParams } = new URL(request.url)
|
|
const id = searchParams.get('id')
|
|
if (!id) return NextResponse.json({ error: 'id required' }, { status: 422 })
|
|
if (id === session.sub)
|
|
return NextResponse.json({ error: 'Cannot delete your own account' }, { status: 422 })
|
|
|
|
const supabase = await createClient()
|
|
|
|
// fetch user info for audit before deletion
|
|
const { data: target } = await supabase
|
|
.from('users').select('email, name, role').eq('id', id).single()
|
|
|
|
// Delete user directly from DB
|
|
const [deleted] = await asAdmin(db =>
|
|
db.delete(users).where(eq(users.id, id)).returning({ id: users.id })
|
|
)
|
|
|
|
if (!deleted) {
|
|
return NextResponse.json({ error: 'User not found or deletion failed' }, { status: 500 })
|
|
}
|
|
|
|
if (target) {
|
|
await supabase.rpc('write_audit_log', {
|
|
p_table_name: 'users',
|
|
p_record_id: id,
|
|
p_action: 'deleted',
|
|
p_new_value: { email: target.email, name: target.name, role: target.role },
|
|
})
|
|
}
|
|
|
|
return NextResponse.json({ ok: true })
|
|
}
|