Files
guanwang/server/utils/auth.ts

35 lines
946 B
TypeScript

import type { H3Event } from 'h3'
export interface SessionUser {
id: number
username: string
displayName: string
}
export async function getAdminSession(event: H3Event) {
const config = useRuntimeConfig()
const password = config.sessionPassword || (import.meta.dev ? 'dev-session-password-change-before-production-2026' : '')
if (password.length < 32) {
throw new Error('NUXT_SESSION_PASSWORD must contain at least 32 characters')
}
return useSession<{ user?: SessionUser }>(event, {
name: 'huiyu_admin_session',
password,
maxAge: 60 * 60 * 8,
cookie: {
httpOnly: true,
secure: config.sessionCookieSecure,
sameSite: 'lax',
path: '/',
},
})
}
export async function requireAdmin(event: H3Event) {
const session = await getAdminSession(event)
if (!session.data.user) {
throw createError({ statusCode: 401, statusMessage: '请先登录' })
}
return session.data.user
}