2023-11-06 02:57:00 +01:00
|
|
|
import { defineEventHandler, getCookie } from "h3";
|
2023-11-09 18:28:09 +01:00
|
|
|
import SessionToken from "../utils/SessionToken";
|
2023-05-11 06:03:22 +02:00
|
|
|
|
2023-11-08 05:35:48 +01:00
|
|
|
import { database } from "~/server/utils/database";
|
|
|
|
import getRequestingUser from "~/server/utils/getRequestingUser";
|
2023-05-11 06:03:22 +02:00
|
|
|
|
2023-11-09 18:28:09 +01:00
|
|
|
import { createError } from "#imports";
|
|
|
|
|
2023-05-11 06:03:22 +02:00
|
|
|
const endpointsWithoutAuth: string[] = [
|
|
|
|
"/dbtest",
|
|
|
|
"/echo",
|
|
|
|
"/hi",
|
|
|
|
"/login",
|
|
|
|
"/logout",
|
2023-06-14 12:37:57 +02:00
|
|
|
"/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;
|
2023-06-14 12:37:57 +02:00
|
|
|
try {
|
2023-11-08 05:35:48 +01:00
|
|
|
await database.session.findUniqueOrThrow({
|
|
|
|
where: {
|
2023-11-09 18:28:09 +01:00
|
|
|
...SessionToken.fromString(token).toPrisma(),
|
|
|
|
expiry_date: {
|
|
|
|
gte: new Date(),
|
|
|
|
},
|
2023-11-08 05:35:48 +01:00
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
return true;
|
|
|
|
} catch (e) {
|
2023-06-14 12:37:57 +02:00
|
|
|
return false;
|
|
|
|
}
|
2023-05-11 06:03:22 +02:00
|
|
|
}
|