PronounsPage/server/utils/useAuthentication.ts

34 lines
1.4 KiB
TypeScript

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