diff --git a/lib/plugins/auth/routes/mod.ts b/lib/plugins/auth/routes/mod.ts index e9ac63cf..611990a0 100644 --- a/lib/plugins/auth/routes/mod.ts +++ b/lib/plugins/auth/routes/mod.ts @@ -41,7 +41,13 @@ export const getRoutesByProvider = ( provider, tokens.accessToken, ); - const userCurrent = await ctx.state.auth.getUser(userProvider.authId); + let userCurrent = await ctx.state.auth.getUser(userProvider.authId); + if (!userCurrent) { + // IMPORTANT: authId can be provisionally hard-coded to the unique email of the user + // when first being invited or when manually creating users in the database therefore + // we also attempt to find the user by email if the above query by authId fails + userCurrent = await ctx.state.auth.getInvitedUser(userProvider.email); + } // IMPORTANT: must explicitly set all properties to prevent "undefined" values const user = { @@ -66,6 +72,8 @@ export const getRoutesByProvider = ( if (user[key] === undefined) delete user[key]; }); + console.log({ userProvider, userCurrent, user }); + if (!userCurrent) { if (allowNewUserRegistration === true) { await ctx.state.auth.createUser(user); diff --git a/lib/plugins/auth/utils/adapter.ts b/lib/plugins/auth/utils/adapter.ts index 10a7f794..2a434304 100644 --- a/lib/plugins/auth/utils/adapter.ts +++ b/lib/plugins/auth/utils/adapter.ts @@ -31,14 +31,13 @@ export const createDatabaseAuth = (db: ReturnType): Auth => { const user = await db.query.$users.findFirst({ where: eq($users.authId, authId), }) as AuthUser; - if (user) return user; - // IMPORTANT: authId can be provisionally hard-coded to the unique email of the user - // when first being invited or when manually creating users in the database therefore - // we also attempt to find the user by email if the above query by authId fails - const userTemporary = await db.query.$users.findFirst({ - where: eq($users.email, authId), + return user ?? null; + }, + getInvitedUser: async (email: string) => { + const user = await db.query.$users.findFirst({ + where: eq($users.authId, email), }) as AuthUser; - return userTemporary ?? null; + return user ?? null; }, getUserBySession: async (sessionId: string) => { const session = await db.query.$sessions.findFirst({ diff --git a/lib/plugins/auth/utils/types.ts b/lib/plugins/auth/utils/types.ts index 4b31c326..bcdc4395 100644 --- a/lib/plugins/auth/utils/types.ts +++ b/lib/plugins/auth/utils/types.ts @@ -44,6 +44,12 @@ export type Auth = { * Gets the user with the given authId from the database. */ getUser: (authId: string) => Promise; + /** + * Gets the user with the given email from the database. This is used when + * the user is invited manually by explicitly setting "$users.authId" to his + * email addres in the database. This authId will be overwritten on first login. + */ + getInvitedUser: (email: string) => Promise; /** * Gets the user with the given session ID from the database. The first attempt * is done with eventual consistency. If that returns `null`, the second