import querystring from "node:querystring"; import { addMonths } from "date-fns"; import type { Context } from "koa"; import { pick } from "es-toolkit/compat"; import { toError } from "@shared/utils/error"; import { Client } from "@shared/types"; import { getCookieDomain } from "@shared/utils/domains"; import { getActiveSessions } from "@shared/utils/sessions"; import env from "@server/env"; import Logger from "@server/logging/Logger"; import { Event, Collection, View } from "@server/models"; import type { Team } from "@server/models"; import type { APIContext, AuthenticationResult } from "@server/types"; import { AuthenticationType } from "@server/types"; import { SessionsCookieHelper } from "./SessionsCookieHelper"; import { clearCSRFCookie } from "./csrf"; /** * Finds the workspace to send a request for the app root domain to, when the * "sessions" cookie has exactly one usable workspace. Entries that are * malformed, expired, deleted, suspended, or already the current host are * ignored. * * @param ctx the Koa context. * @param teams the reconciled workspaces in cookie order. * @returns the workspace url for the requested path, if there is one. */ export function getSessionRedirectUrl( ctx: Context, teams: Team[] ): string | undefined { const activeSessions = getActiveSessions(SessionsCookieHelper.read(ctx)); const candidates = teams.filter( (team) => activeSessions[team.id] && !team.isTeamUrl(ctx.href) ); // With several usable workspaces the client shows a workspace chooser. if (candidates.length !== 1) { return; } const url = new URL(candidates[0].url); url.pathname = ctx.path; url.search = ctx.search; return url.toString(); } /** * Signs in a user by setting authentication cookies and recording the sign-in * event, then redirects to the appropriate destination. * * @param ctx the Koa context. * @param service the name of the authentication service used to sign in. * @param result the authentication result containing user and team details. */ export async function signIn( ctx: Context | APIContext, service: string, { user, team, client, isNewTeam }: AuthenticationResult ) { const { transaction } = ctx.state; if (team.isSuspended) { return ctx.redirect("/?notice=team-suspended"); } if (user.isSuspended) { return ctx.redirect("/?notice=user-suspended"); } if (isNewTeam) { // see: scenes/Login/index.js for where this cookie is written when // viewing the /login or /create pages. It is a URI encoded JSON string. const cookie = ctx.cookies.get("signupQueryParams"); if (cookie) { try { const signupQueryParams = pick( JSON.parse(querystring.unescape(cookie)), ["ref", "utm_content", "utm_medium", "utm_source", "utm_campaign"] ); await team.update( { signupQueryParams, }, { transaction, } ); } catch (error) { Logger.error(`Error persisting signup query params`, toError(error)); } } } // update the database when the user last signed in await user.updateSignedIn(ctx); await Event.createFromContext( ctx, { name: "users.signin", userId: user.id, authType: AuthenticationType.APP, data: { name: user.name, service, }, }, { actorId: user.id, teamId: team.id, } ); const domain = getCookieDomain(ctx.request.hostname, env.isCloudHosted); const expires = addMonths(new Date(), 3); // set a cookie for which service we last signed in with. This is // only used to display a UI hint for the user for next time ctx.cookies.set("lastSignedIn", service, { httpOnly: false, sameSite: true, expires: new Date("2100"), domain, }); // On cloud hosted multi-team deployments, record the signed-in team in the // sessions cookie so the web team switcher stays in sync. This applies to // both web and desktop clients. if (env.isCloudHosted && team.subdomain) { SessionsCookieHelper.add(ctx, team, expires); } // If the authentication request originally came from the desktop app then we send the user // back to a screen in the web app that will immediately redirect to the desktop. The reason // to do this from the client is that if you redirect from the server then the browser ends up // stuck on the SSO screen. if (client === Client.Desktop) { const token = encodeURIComponent(user.getTransferToken(service)); ctx.redirect(`${team.url}/desktop-redirect?token=${token}`); return; } // Redirect to the team subdomain with a short-lived transfer token that the // /auth/redirect handler exchanges for the actual session cookie. if (env.isCloudHosted && team.subdomain) { const token = encodeURIComponent(user.getTransferToken(service)); ctx.redirect(`${team.url}/auth/redirect?token=${token}`); } else { ctx.cookies.set("accessToken", user.getSessionToken(expires, service), { sameSite: "lax", expires, }); clearCSRFCookie(ctx); const defaultCollectionId = team.defaultCollectionId; if (defaultCollectionId) { const collection = await Collection.findOne({ where: { id: defaultCollectionId, teamId: team.id, ownerId: null, }, transaction, }); if (collection) { ctx.redirect(`${team.url}${collection.path}`); return; } } const [collection, view] = await Promise.all([ Collection.findFirstCollectionForUser(user, { transaction, }), View.findOne({ where: { userId: user.id, }, transaction, }), ]); const hasViewedDocuments = !!view; ctx.redirect( !hasViewedDocuments && collection ? `${team.url}${collection.path}/recent` : `${team.url}/home` ); } }