WorkshopTasker/server/middleware/auth.ts

54 lines
1.2 KiB
TypeScript
Raw Normal View History

import { defineEventHandler, getCookie } from "h3";
import SessionToken from "../utils/SessionToken";
2023-05-11 06:03:22 +02:00
import { database } from "~/server/utils/database";
import getRequestingUser from "~/server/utils/getRequestingUser";
2023-05-11 06:03:22 +02:00
import { createError } from "#imports";
2023-05-11 06:03:22 +02:00
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 {
await database.session.findUniqueOrThrow({
where: {
...SessionToken.fromString(token).toPrisma(),
expiry_date: {
gte: new Date(),
},
},
});
return true;
} catch (e) {
return false;
}
2023-05-11 06:03:22 +02:00
}