import type { H3Event } from 'h3'; import { getLocale } from '~/server/data.ts'; import jwt from '~/server/jwt.ts'; import { isGrantedForUser } from '~/src/helpers.ts'; import type { PermissionArea } from '~/src/helpers.ts'; import type { User } from '~/src/user.ts'; export type IsGrantedFn = (area?: PermissionArea, locale?: string) => boolean; export default async (event: H3Event) => { let rawUser = undefined; const authorizationHeader = getHeader(event, 'authorization'); if (authorizationHeader && authorizationHeader.startsWith('Bearer ')) { rawUser = await jwt.validate(getLocale(event), authorizationHeader.substring(7)); } else { const tokenCookie = getCookie(event, 'token'); if (tokenCookie && tokenCookie !== 'null') { rawUser = await jwt.validate(getLocale(event), tokenCookie); } } const user = rawUser?.authenticated ? rawUser : null; const requestedLocale = getLocale(event); const isGranted = (area: PermissionArea = '', locale = requestedLocale): boolean => { return !!user && isGrantedForUser(user, locale, area); }; return { rawUser, user, isGranted }; };