WorkshopTasker/server/middleware/auth.ts
Wroclaw ebf5690519 [BREAKING] Auth: replace current auth tokens with more secure ones
previously tokens were only like IDs, time based and incrementing counter.
An attacker could easily bruteforce them.
This patch changes tokens to be completely random.

fixes #2
2023-11-09 18:28:09 +01:00

53 lines
1.2 KiB
TypeScript

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<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;
}
}