Initial commit
This commit is contained in:
commit
1e63e008af
48 changed files with 12715 additions and 0 deletions
40
server/middleware/auth.ts
Normal file
40
server/middleware/auth.ts
Normal file
|
@ -0,0 +1,40 @@
|
|||
/* global defineEventHandler, createError, getCookie */
|
||||
|
||||
import { database, data } from "~/server/utils/database";
|
||||
|
||||
const endpointsWithoutAuth: string[] = [
|
||||
"/dbtest",
|
||||
"/echo",
|
||||
"/hi",
|
||||
"/login",
|
||||
"/logout",
|
||||
];
|
||||
|
||||
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;
|
||||
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;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue