diff --git a/server/commands/accountProvisioner.js b/server/commands/accountProvisioner.js index f8508623..b0a93b0e 100644 --- a/server/commands/accountProvisioner.js +++ b/server/commands/accountProvisioner.js @@ -8,7 +8,7 @@ import { } from "../errors"; import mailer from "../mailer"; import { Collection, Team, User } from "../models"; -import teamCreator from "./teamCreator"; +import teamCreator, { findExistingTeam } from "./teamCreator"; import userCreator from "./userCreator"; type Props = {| @@ -53,13 +53,15 @@ export default async function accountProvisioner({ }: Props): Promise { let result; try { - result = await teamCreator({ - name: teamParams.name, - domain: teamParams.domain, - subdomain: teamParams.subdomain, - avatarUrl: teamParams.avatarUrl, - authenticationProvider: authenticationProviderParams, - }); + result = + (await findExistingTeam(authenticationProviderParams)) || + (await teamCreator({ + name: teamParams.name, + domain: teamParams.domain, + subdomain: teamParams.subdomain, + avatarUrl: teamParams.avatarUrl, + authenticationProvider: authenticationProviderParams, + })); } catch (err) { throw new AuthenticationError(err.message); } diff --git a/server/commands/teamCreator.js b/server/commands/teamCreator.js index 9a05cc61..94d256e6 100644 --- a/server/commands/teamCreator.js +++ b/server/commands/teamCreator.js @@ -12,6 +12,44 @@ type TeamCreatorResult = {| isNewTeam: boolean, |}; +export async function findExistingTeam(authenticationProvider: {| + name: string, + providerId: string, +|}): Promise { + // Should outline deployed in a multi-tenant environment, skip searching + // for an existing team. + if (process.env.DEPLOYMENT === "hosted") return null; + + // get the first team that exists, ordered by createdAt + const team = await Team.findOne({ limit: 1, order: ["createdAt"] }); + if (team === null) { + return null; + } + + // query if a corresponding authenticationProvider already exists + let authenticationProviders = await team.getAuthenticationProviders({ + where: { + name: authenticationProvider.name, + }, + }); + + // ... if this is not the case, create a new authentication provider + // that we use instead, overwriting the providerId with the domain of the team + let authP = + authenticationProviders.length === 0 + ? await team.createAuthenticationProvider({ + ...authenticationProvider, + providerId: team.domain, + }) + : authenticationProviders[0]; + + return { + authenticationProvider: authP, + team: team, + isNewTeam: false, + }; +} + export default async function teamCreator({ name, domain,