feat: 初始化慧遇书院官网一期
This commit is contained in:
34
server/utils/auth.ts
Normal file
34
server/utils/auth.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user