added auth middleware

This commit is contained in:
Milo Schwartz 2024-10-02 23:54:14 -04:00
parent 7dbf4307e7
commit 942dbd8e56
No known key found for this signature in database
4 changed files with 44 additions and 0 deletions

View file

@ -0,0 +1,33 @@
import { NextFunction, Response, Request } from "express";
import ErrorResponse from "@server/types/ErrorResponse";
import { unauthorized, verifySession } from "@server/auth";
import { db } from "@server/db";
import { users } from "@server/db/schema";
import { eq } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
export const verifySessionMiddleware = async (
req: any,
res: Response<ErrorResponse>,
next: NextFunction,
) => {
const { session, user } = await verifySession(req);
if (!session || !user) {
return next(unauthorized());
}
const existingUser = await db
.select()
.from(users)
.where(eq(users.id, user.id));
if (!existingUser || !existingUser[0]) {
return next(
createHttpError(HttpCode.BAD_REQUEST, "User does not exist"),
);
}
req.user = existingUser[0];
req.session = session;
};