add cache to auth

This commit is contained in:
2025-01-24 19:24:27 +05:30
parent 59ce61d3a6
commit 405338c314
8 changed files with 125 additions and 67 deletions

View File

@@ -3,8 +3,13 @@ import { FastifyReply, FastifyRequest } from "fastify";
import { getToken } from "./tokens/token.service";
import { Claim } from "./utils/claims";
import { OAuth2Namespace } from "@fastify/oauth2";
import { getSession } from "./auth/auth.service";
import { roles, rules } from "./utils/roles";
import { deleteSession, getSession } from "./auth/auth.service";
import { rules } from "./utils/roles";
import {
cacheSession,
getCachedSession,
removeCachedSession,
} from "./utils/cache";
export type AuthenticatedUser = {
sid?: string;
@@ -14,6 +19,7 @@ export type AuthenticatedUser = {
role?: string;
tenantId: string;
claims: Array<Claim>;
expiry?: string;
};
declare module "fastify" {
@@ -56,35 +62,21 @@ export async function authHandler(req: FastifyRequest, res: FastifyReply) {
claims: tokenInDb.claims as Array<Claim>,
};
} else {
const sessionInDb = await getSession(authHeader);
if (sessionInDb === null)
let session = getCachedSession(authHeader);
if (!session) {
session = await getSession(authHeader);
cacheSession(authHeader, session);
}
if (!session) return res.code(401).send({ error: "invalid_token" });
if (new Date() > new Date(session.expiry)) {
removeCachedSession(authHeader);
await deleteSession(authHeader);
return res.code(401).send({ error: "invalid_token" });
if (new Date() > new Date(sessionInDb.expiresAt)) {
await sessionInDb.deleteOne();
return res.code(401).send({ error: "session_expired" });
}
//@ts-ignore
if (!rules[sessionInDb.user.role]) {
return res.code(401).send({ error: "no role" });
}
req.user = {
sid: authHeader,
//@ts-ignore
type: sessionInDb.user.type,
//@ts-ignore
userId: sessionInDb.user.id,
//@ts-ignore
tenantId: sessionInDb.user.tenantId,
//@ts-ignore
orgId: sessionInDb.user.orgId,
//@ts-ignore
role: sessionInDb.user.role,
//@ts-ignore
claims: rules[sessionInDb.user.role].claims,
};
req.user = session;
}
}