add cache to auth
This commit is contained in:
48
src/auth.ts
48
src/auth.ts
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user