From bc1586761d4f5173b5e1f80abba64c8b61151ef0 Mon Sep 17 00:00:00 2001 From: Rory Powell Date: Mon, 5 Sep 2022 09:46:54 +0100 Subject: [PATCH] Fix auto user creation for OIDC auth --- packages/worker/src/sdk/users/users.ts | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/packages/worker/src/sdk/users/users.ts b/packages/worker/src/sdk/users/users.ts index 0ea16bf670..a8944b936a 100644 --- a/packages/worker/src/sdk/users/users.ts +++ b/packages/worker/src/sdk/users/users.ts @@ -189,23 +189,34 @@ export const save = async ( const tenantId = tenancy.getTenantId() const db = tenancy.getGlobalDB() let { email, _id } = user + if (!email && !_id) { + throw new Error("_id or email is required") + } let dbUser: User | undefined if (_id) { // try to get existing user from db - dbUser = (await db.get(_id)) as User - if (email && dbUser.email !== email) { - throw "Email address cannot be changed" + try { + dbUser = (await db.get(_id)) as User + if (email && dbUser.email !== email) { + throw "Email address cannot be changed" + } + email = dbUser.email + } catch (e: any) { + if (e.status === 404) { + // do nothing, save this new user with the id specified - required for SSO auth + } else { + throw e + } } - email = dbUser.email - } else if (email) { + } + + if (!dbUser && email) { // no id was specified - load from email instead dbUser = await usersCore.getGlobalUserByEmail(email) if (dbUser && dbUser._id !== _id) { throw `Unavailable` } - } else { - throw new Error("_id or email is required") } await validateUniqueUser(email, tenantId)