WorkshopTasker/server/middleware/auth.ts

46 lines
1.1 KiB
TypeScript
Raw Normal View History

2023-05-11 06:03:22 +02:00
/* global defineEventHandler, createError, getCookie */
import { database, data } from "~/server/utils/database";
const endpointsWithoutAuth: string[] = [
"/dbtest",
"/echo",
"/hi",
"/login",
"/logout",
"/firstRun",
2023-05-11 06:03:22 +02:00
];
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<boolean> {
if (!token) return false;
try {
const [[session]] = await database.query(
"SELECT EXISTS(SELECT `id` FROM `sessions` WHERE `id` = ? AND `expiry_date` >= NOW()) as `logged_in`",
[token],
) as unknown as data<{logged_in: number}>;
return session.logged_in === 1;
} catch {
return false;
}
2023-05-11 06:03:22 +02:00
}