44 lines
933 B
TypeScript
44 lines
933 B
TypeScript
import { H3Event } from 'h3'
|
|
|
|
export function setAuthCookie(event: H3Event, username: string) {
|
|
setCookie(event, 'auth', username, {
|
|
httpOnly: true,
|
|
secure: process.env.NODE_ENV === 'production',
|
|
maxAge: 60 * 60 * 24 * 7, // 7 days
|
|
path: '/'
|
|
})
|
|
}
|
|
|
|
export function getAuthCookie(event: H3Event) {
|
|
return getCookie(event, 'auth')
|
|
}
|
|
|
|
export function clearAuthCookie(event: H3Event) {
|
|
deleteCookie(event, 'auth')
|
|
}
|
|
|
|
export function isAuthenticated(event: H3Event): boolean {
|
|
const auth = getAuthCookie(event)
|
|
return !!auth
|
|
}
|
|
|
|
export async function getAuthUser(event: H3Event) {
|
|
const username = getAuthCookie(event)
|
|
if (!username) {
|
|
return null
|
|
}
|
|
|
|
const { getUserByUsername } = await import('./database')
|
|
const user = getUserByUsername(username)
|
|
|
|
if (!user) {
|
|
clearAuthCookie(event)
|
|
return null
|
|
}
|
|
|
|
return {
|
|
username: user.username,
|
|
isAdmin: user.is_admin === 1
|
|
}
|
|
}
|