import { defineEventHandler, getCookie } from "h3"; import SessionToken from "../utils/SessionToken"; import { database } from "~/server/utils/database"; import getRequestingUser from "~/server/utils/getRequestingUser"; import { createError } from "#imports"; const endpointsWithoutAuth: string[] = [ "/dbtest", "/echo", "/hi", "/login", "/logout", "/firstRun", ]; export default defineEventHandler(async (e) => { const endpoint = e.path?.match(/^\/api(\/.*)/)?.[1]; // if client does not access api if (!endpoint) return; for (const i of endpointsWithoutAuth) // if accessed endpoint doesn't require auth if (endpoint.startsWith(i)) return; const token = getCookie(e, "token"); if (!await isAuthorised(token)) throw createError({ statusCode: 401, message: "Unauthorized" }); }); /** * Checks if the token is authorised * @param token the token to ckeck */ export async function isAuthorised(token: string | undefined): Promise { if (!token) return false; try { await database.session.findUniqueOrThrow({ where: { ...SessionToken.fromString(token).toPrisma(), expiry_date: { gte: new Date(), }, }, }); return true; } catch (e) { return false; } }