Wroclaw
eebf25198d
also I updated packages, and properly typed api input a lot of time was spent, I don't remeber what really I did x3 but everything was related to replacing mysql2 with prisma
48 lines
1.1 KiB
TypeScript
48 lines
1.1 KiB
TypeScript
import { defineEventHandler, getCookie } from "h3";
|
|
import { createError } from "#imports";
|
|
|
|
import { database } from "~/server/utils/database";
|
|
import getRequestingUser from "~/server/utils/getRequestingUser";
|
|
|
|
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<boolean> {
|
|
if (!token) return false;
|
|
try {
|
|
await database.session.findUniqueOrThrow({
|
|
where: {
|
|
id: BigInt(token),
|
|
},
|
|
});
|
|
|
|
return true;
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
}
|