Skip to content

Commit

Permalink
Don't use cache in sign in flow
Browse files Browse the repository at this point in the history
  • Loading branch information
renatodellosso committed Feb 24, 2025
1 parent aa1de31 commit b84dba8
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
13 changes: 6 additions & 7 deletions lib/Auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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;
Expand All @@ -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<User>;
if (!typedUser.slug || typedUser._id?.toString() != typedUser.id) {
Expand All @@ -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);
}
Expand All @@ -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());
};
Expand Down
14 changes: 9 additions & 5 deletions lib/MongoDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,17 @@ clientPromise = global.clientPromise;

export { clientPromise };

export async function getDatabase(): Promise<DbInterface> {
export async function getDatabase(
useCache: boolean = true,
): Promise<DbInterface> {
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;

Expand Down

0 comments on commit b84dba8

Please sign in to comment.