diff --git a/server/models/Team.ts b/server/models/Team.ts index 162982b3a8..2bf5d4c738 100644 --- a/server/models/Team.ts +++ b/server/models/Team.ts @@ -416,6 +416,24 @@ class Team extends ParanoidModel< } }; + /** + * Find a team by its current or previous subdomain. + * + * @param subdomain - The subdomain to search for. + * @returns The team with the given or previous subdomain, or null if not found. + */ + static async findBySubdomain(subdomain: string) { + // Preference is always given to the team with the subdomain currently + // otherwise we can try and find a team that previously used the subdomain. + return ( + (await this.findOne({ + where: { + subdomain, + }, + })) || (await this.findByPreviousSubdomain(subdomain)) + ); + } + /** * Find a team by its previous subdomain. * diff --git a/server/routes/index.ts b/server/routes/index.ts index 1e4a4b60e9..986a11bc19 100644 --- a/server/routes/index.ts +++ b/server/routes/index.ts @@ -139,22 +139,28 @@ router.get("*", shareDomains(), async (ctx, next) => { } const team = await getTeamFromContext(ctx); + let redirectUrl; // Redirect all requests to custom domain if one is set if (team?.domain && team.domain !== ctx.hostname) { - ctx.redirect(ctx.href.replace(ctx.hostname, team.domain)); - return; - } + redirectUrl = ctx.href.replace(ctx.hostname, team.domain); - // Redirect if subdomain is not the current team's subdomain - if (team?.subdomain) { + // Redirect if subdomain is not the current team's subdomain + } else if (team?.subdomain) { const { teamSubdomain } = parseDomain(ctx.href); if (team?.subdomain !== teamSubdomain) { - ctx.redirect(ctx.href.replace(teamSubdomain, team.subdomain)); - return; + redirectUrl = ctx.href.replace( + `//${teamSubdomain}.`, + `//${team.subdomain}.` + ); } } + if (redirectUrl) { + ctx.redirect(redirectUrl); + return; + } + const analytics = team ? await Integration.findAll({ where: { diff --git a/server/utils/passport.ts b/server/utils/passport.ts index 37ff145762..503b5f5fb4 100644 --- a/server/utils/passport.ts +++ b/server/utils/passport.ts @@ -127,12 +127,7 @@ export async function getTeamFromContext(ctx: Context) { } else if (domain.custom) { team = await Team.findOne({ where: { domain: domain.host } }); } else if (domain.teamSubdomain) { - // Preference is always given to the team with the subdomain currently - // otherwise we can try and find a team that previously used the subdomain. - team = - (await Team.findOne({ - where: { subdomain: domain.teamSubdomain }, - })) || (await Team.findByPreviousSubdomain(domain.teamSubdomain)); + team = await Team.findBySubdomain(domain.teamSubdomain); } return team;