From b84dba8df1cf51d7a83ede17f3d7ddccfffa5198 Mon Sep 17 00:00:00 2001 From: renatodellosso Date: Mon, 24 Feb 2025 16:49:35 -0500 Subject: [PATCH] Don't use cache in sign in flow --- lib/Auth.ts | 13 ++++++------- lib/MongoDB.ts | 14 +++++++++----- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/lib/Auth.ts b/lib/Auth.ts index 4900d320..d7956ada 100644 --- a/lib/Auth.ts +++ b/lib/Auth.ts @@ -14,8 +14,6 @@ import CollectionId from "./client/CollectionId"; import { AdapterUser } from "next-auth/adapters"; import { wait } from "./client/ClientUtils"; -const db = getDatabase(); - const adapter = MongoDBAdapter(clientPromise, { databaseName: process.env.DB }); export const AuthenticationOptions: AuthOptions = { @@ -92,7 +90,7 @@ export const AuthenticationOptions: AuthOptions = { callbacks: { async session({ session, user }) { session.user = await ( - await db + await getDatabase() ).findObjectById(CollectionId.Users, new ObjectId(user.id)); return session; @@ -107,6 +105,7 @@ export const AuthenticationOptions: AuthOptions = { */ async signIn({ user }) { Analytics.signIn(user.name ?? "Unknown User"); + const db = await getDatabase(false); let typedUser = user as Partial; if (!typedUser.slug || typedUser._id?.toString() != typedUser.id) { @@ -116,9 +115,9 @@ export const AuthenticationOptions: AuthOptions = { ); let foundUser: User | undefined = undefined; while (!foundUser) { - foundUser = await ( - await db - ).findObject(CollectionId.Users, { email: typedUser.email }); + foundUser = await db.findObject(CollectionId.Users, { + email: typedUser.email, + }); if (!foundUser) await wait(50); } @@ -128,7 +127,7 @@ export const AuthenticationOptions: AuthOptions = { typedUser._id = foundUser._id; typedUser.lastSignInDateTime = new Date(); - typedUser = await repairUser(await db, typedUser); + typedUser = await repairUser(db, typedUser); console.log("User updated:", typedUser._id?.toString()); }; diff --git a/lib/MongoDB.ts b/lib/MongoDB.ts index f7343f11..f79f6362 100644 --- a/lib/MongoDB.ts +++ b/lib/MongoDB.ts @@ -30,13 +30,17 @@ clientPromise = global.clientPromise; export { clientPromise }; -export async function getDatabase(): Promise { +export async function getDatabase( + useCache: boolean = true, +): Promise { if (!global.interface) { await clientPromise; - const dbInterface = new CachedDbInterface( - new MongoDBInterface(clientPromise), - cacheOptions, - ); + + const mongo = new MongoDBInterface(clientPromise); + + const dbInterface = useCache + ? new CachedDbInterface(mongo, cacheOptions) + : mongo; await dbInterface.init(); global.interface = dbInterface;