TofuStack/src/lib/server/api/middlewares/auth.middleware.ts

56 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-06-25 02:45:00 +00:00
import type { MiddlewareHandler } from 'hono';
import { createMiddleware } from 'hono/factory';
import { verifyRequestOrigin } from 'lucia';
2024-06-25 16:14:45 +00:00
import type { Session, User } from 'lucia';
2024-08-07 15:13:36 +00:00
import { Unauthorized } from '../common/exceptions';
2024-09-02 04:36:41 +00:00
import type { HonoTypes } from '../common/types/hono';
import { container } from 'tsyringe';
import { LuciaService } from '../services/lucia.service';
2024-06-25 02:45:00 +00:00
2024-09-02 04:36:41 +00:00
// resolve dependencies from the container
const { lucia } = container.resolve(LuciaService)
// Middleware to verify the origin of the request
2024-06-25 02:45:00 +00:00
export const verifyOrigin: MiddlewareHandler<HonoTypes> = createMiddleware(async (c, next) => {
if (c.req.method === "GET") {
return next();
}
const originHeader = c.req.header("Origin") ?? null;
const hostHeader = c.req.header("Host") ?? null;
if (!originHeader || !hostHeader || !verifyRequestOrigin(originHeader, [hostHeader])) {
return c.body(null, 403);
}
return next();
})
export const validateAuthSession: MiddlewareHandler<HonoTypes> = createMiddleware(async (c, next) => {
const sessionId = lucia.readSessionCookie(c.req.header("Cookie") ?? "");
if (!sessionId) {
c.set("user", null);
c.set("session", null);
return next();
}
const { session, user } = await lucia.validateSession(sessionId);
if (session && session.fresh) {
c.header("Set-Cookie", lucia.createSessionCookie(session.id).serialize(), { append: true });
}
if (!session) {
c.header("Set-Cookie", lucia.createBlankSessionCookie().serialize(), { append: true });
}
c.set("session", session);
c.set("user", user);
return next();
})
2024-06-25 16:14:45 +00:00
export const requireAuth: MiddlewareHandler<{
Variables: {
session: Session;
user: User;
};
}> = createMiddleware(async (c, next) => {
const user = c.var.user;
if (!user) throw Unauthorized('You must be logged in to access this resource');
return next();
});