add cache to auth
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { getUserByEmail, updateUser } from "../user/user.service";
|
||||
import { createSession, getSession } from "./auth.service";
|
||||
import { createSession, deleteSession, getSession } from "./auth.service";
|
||||
|
||||
export async function authRoutes(fastify: FastifyInstance) {
|
||||
fastify.get(
|
||||
@@ -55,10 +55,7 @@ export async function authRoutes(fastify: FastifyInstance) {
|
||||
if (!req.headers.authorization) return res.code(200).send();
|
||||
|
||||
const auth = req.headers.authorization.split(" ")[1];
|
||||
const sessionInDb = await getSession(auth);
|
||||
if (sessionInDb === null) return res.code(200).send();
|
||||
|
||||
await sessionInDb.deleteOne();
|
||||
await deleteSession(auth);
|
||||
return res.code(200).send();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { AuthenticatedUser } from "../auth";
|
||||
import { userModel } from "../user/user.schema";
|
||||
import { generateToken } from "../utils/id";
|
||||
import { rules } from "../utils/roles";
|
||||
import { sessionModel } from "./auth.schema";
|
||||
|
||||
export async function createSession(userId: string, ip?: string, ua?: string) {
|
||||
@@ -19,6 +22,28 @@ export async function createSession(userId: string, ip?: string, ua?: string) {
|
||||
return newSession;
|
||||
}
|
||||
|
||||
export async function getSession(sessionId: string) {
|
||||
return await sessionModel.findOne({ sid: sessionId }).populate("user");
|
||||
export async function getSession(
|
||||
sessionId: string
|
||||
): Promise<AuthenticatedUser | null> {
|
||||
console.log("DB HIT");
|
||||
const session = await sessionModel.findOne({ sid: sessionId });
|
||||
if (session === null) return null;
|
||||
|
||||
const user = await userModel.findById(session.user);
|
||||
if (user === null) return null;
|
||||
|
||||
return {
|
||||
sid: session.id,
|
||||
type: "user",
|
||||
userId: user.id,
|
||||
orgId: user.orgId ? user.orgId.toString() : null,
|
||||
role: user.role,
|
||||
tenantId: user.tenantId,
|
||||
claims: rules[user.role].claims ?? [],
|
||||
expiry: new Date(session.expiresAt).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
export async function deleteSession(sessionId: string) {
|
||||
return await sessionModel.deleteOne({ sid: sessionId });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user