Nuxt 3 app with: - SQLite (better-sqlite3) for persistence - Anonymous idea submission and voting - Admin auth with session cookies - AI analysis via Gemini API - Nuxt UI components + Tailwind Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
42 lines
1.3 KiB
TypeScript
42 lines
1.3 KiB
TypeScript
import { randomBytes, timingSafeEqual } from 'crypto'
|
|
import type { H3Event } from 'h3'
|
|
import db from './db'
|
|
|
|
export function createSession(): string {
|
|
const token = randomBytes(32).toString('hex')
|
|
const expires = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
|
|
db.prepare('INSERT INTO sessions (token, expires_at) VALUES (?, ?)').run(token, expires)
|
|
return token
|
|
}
|
|
|
|
export function validateSession(token: string): boolean {
|
|
const row = db.prepare('SELECT expires_at FROM sessions WHERE token = ?').get(token) as any
|
|
if (!row) return false
|
|
if (new Date(row.expires_at) < new Date()) {
|
|
db.prepare('DELETE FROM sessions WHERE token = ?').run(token)
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
export function destroySession(token: string) {
|
|
db.prepare('DELETE FROM sessions WHERE token = ?').run(token)
|
|
}
|
|
|
|
export function checkPassword(input: string): boolean {
|
|
const config = useRuntimeConfig()
|
|
const expected = config.adminPassword as string
|
|
if (input.length !== expected.length) return false
|
|
return timingSafeEqual(Buffer.from(input), Buffer.from(expected))
|
|
}
|
|
|
|
export function isAdmin(event: H3Event): boolean {
|
|
return event.context.isAdmin === true
|
|
}
|
|
|
|
export function requireAdmin(event: H3Event) {
|
|
if (!isAdmin(event)) {
|
|
throw createError({ statusCode: 401, statusMessage: 'Unauthorized' })
|
|
}
|
|
}
|