mirror of
https://github.com/outline/outline.git
synced 2026-11-25 23:24:06 +03:00
* chore: Rename APIContext to Context and flatten its fields Auth and transaction now live directly on the context instead of in ctx.state and a nested ctx.context, and model helpers read them directly. APIContext remains as a deprecated alias. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf * chore: Remove deprecated APIContext alias Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf * fix: Read auth from context in OAuth provider callbacks Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf * chore: Add withUser and withTransaction context helpers Replaces manual createContext rebuilds that copy fields from an existing context. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf * chore: Remove arbitrary property access from Koa context types AppContext and Context no longer inherit the any index signature from Koa's DefaultContext, custom fields are declared explicitly, and importing Koa's loose Context type is disallowed by lint. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf --------- Co-authored-by: Claude <noreply@anthropic.com>
193 lines
5.8 KiB
TypeScript
193 lines
5.8 KiB
TypeScript
import querystring from "node:querystring";
|
|
import { addMonths } from "date-fns";
|
|
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 { Context, AuthenticationResult, AppContext } 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: AppContext,
|
|
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: AppContext | Context,
|
|
service: string,
|
|
{ user, team, client, isNewTeam }: AuthenticationResult
|
|
) {
|
|
const { transaction } = ctx;
|
|
|
|
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`
|
|
);
|
|
}
|
|
}
|