2020-07-21 13:20:51 +00:00
|
|
|
import {ApiError} from 'app/common/ApiError';
|
|
|
|
import {OpenDocMode} from 'app/common/DocListAPI';
|
|
|
|
import {ErrorWithCode} from 'app/common/ErrorWithCode';
|
2022-05-11 19:05:35 +00:00
|
|
|
import {ActivationState} from 'app/common/gristUrls';
|
2020-10-19 14:25:21 +00:00
|
|
|
import {FullUser, UserProfile} from 'app/common/LoginSessionAPI';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {canEdit, canView, getWeakestRole, Role} from 'app/common/roles';
|
2022-04-11 18:08:44 +00:00
|
|
|
import {UserOptions} from 'app/common/UserAPI';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {Document} from 'app/gen-server/entity/Document';
|
|
|
|
import {User} from 'app/gen-server/entity/User';
|
|
|
|
import {DocAuthKey, DocAuthResult, HomeDBManager} from 'app/gen-server/lib/HomeDBManager';
|
2021-11-24 14:50:44 +00:00
|
|
|
import {forceSessionChange, getSessionProfiles, getSessionUser, getSignInStatus, linkOrgWithEmail, SessionObj,
|
2021-10-01 14:24:23 +00:00
|
|
|
SessionUserObj, SignInStatus} from 'app/server/lib/BrowserSession';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {RequestWithOrg} from 'app/server/lib/extractOrg';
|
2022-07-19 15:39:49 +00:00
|
|
|
import {GristServer} from 'app/server/lib/GristServer';
|
2021-10-01 14:24:23 +00:00
|
|
|
import {COOKIE_MAX_AGE, getAllowedOrgForSessionID, getCookieDomain,
|
|
|
|
cookieName as sessionCookieName} from 'app/server/lib/gristSessions';
|
(core) add a `user.SessionID` value for trigger formulas and granular access rules
Summary:
This makes a `user.SessionID` value available in information about the user, for use with trigger formulas and granular access rules. The ID should be constant within a browser session for anonymous user. For logged in users it simply reflects their user id.
This ID makes it possible to write access rules and trigger formulas that allow different anonymous users to create, view, and edit their own records in a document.
For example, you could have a brain-storming document for puns, and allow anyone to add to it (without logging in), letting people edit their own records, but not showing the records to others until they are approved by a moderator. Without something like this, we could only let anonymous people add one field of a record, and not have a secure way to let them edit that field or others in the same record.
Also adds a `user.IsLoggedIn` flag in passing.
Test Plan: Added a test, updated tests. The test added is a mini-moderation doc, don't use it for real because it allows users to edit their entries after a moderator has approved them.
Reviewers: georgegevoian
Reviewed By: georgegevoian
Subscribers: dsagal
Differential Revision: https://phab.getgrist.com/D3273
2022-02-22 15:42:06 +00:00
|
|
|
import {makeId} from 'app/server/lib/idUtils';
|
2022-07-04 14:14:55 +00:00
|
|
|
import log from 'app/server/lib/log';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {IPermitStore, Permit} from 'app/server/lib/Permit';
|
2022-07-19 15:39:49 +00:00
|
|
|
import {AccessTokenInfo} from 'app/server/lib/AccessTokens';
|
2024-03-15 13:40:56 +00:00
|
|
|
import {allowHost, getOriginUrl, optStringParam} from 'app/server/lib/requestUtils';
|
2021-10-01 14:24:23 +00:00
|
|
|
import * as cookie from 'cookie';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {NextFunction, Request, RequestHandler, Response} from 'express';
|
2022-03-24 17:11:26 +00:00
|
|
|
import {IncomingMessage} from 'http';
|
2022-07-04 14:14:55 +00:00
|
|
|
import onHeaders from 'on-headers';
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
export interface RequestWithLogin extends Request {
|
|
|
|
sessionID: string;
|
|
|
|
session: SessionObj;
|
|
|
|
org?: string;
|
|
|
|
isCustomHost?: boolean; // when set, the request's domain is a recognized custom host linked
|
|
|
|
// with the specified org.
|
|
|
|
users?: UserProfile[];
|
|
|
|
userId?: number;
|
|
|
|
user?: User;
|
|
|
|
userIsAuthorized?: boolean; // If userId is for "anonymous", this will be false.
|
|
|
|
docAuth?: DocAuthResult; // For doc requests, the docId and the user's access level.
|
|
|
|
specialPermit?: Permit;
|
2022-07-19 15:39:49 +00:00
|
|
|
accessToken?: AccessTokenInfo;
|
(core) add a `user.SessionID` value for trigger formulas and granular access rules
Summary:
This makes a `user.SessionID` value available in information about the user, for use with trigger formulas and granular access rules. The ID should be constant within a browser session for anonymous user. For logged in users it simply reflects their user id.
This ID makes it possible to write access rules and trigger formulas that allow different anonymous users to create, view, and edit their own records in a document.
For example, you could have a brain-storming document for puns, and allow anyone to add to it (without logging in), letting people edit their own records, but not showing the records to others until they are approved by a moderator. Without something like this, we could only let anonymous people add one field of a record, and not have a secure way to let them edit that field or others in the same record.
Also adds a `user.IsLoggedIn` flag in passing.
Test Plan: Added a test, updated tests. The test added is a mini-moderation doc, don't use it for real because it allows users to edit their entries after a moderator has approved them.
Reviewers: georgegevoian
Reviewed By: georgegevoian
Subscribers: dsagal
Differential Revision: https://phab.getgrist.com/D3273
2022-02-22 15:42:06 +00:00
|
|
|
altSessionId?: string; // a session id for use in trigger formulas and granular access rules
|
2022-05-11 19:05:35 +00:00
|
|
|
activation?: ActivationState;
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Extract the user id from a request, assuming we've added it via appropriate middleware.
|
|
|
|
* Throws ApiError with code 401 (unauthorized) if the user id is missing.
|
|
|
|
*/
|
|
|
|
export function getUserId(req: Request): number {
|
|
|
|
const userId = (req as RequestWithLogin).userId;
|
|
|
|
if (!userId) {
|
|
|
|
throw new ApiError("user not known", 401);
|
|
|
|
}
|
|
|
|
return userId;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Extract the user object from a request, assuming we've added it via appropriate middleware.
|
|
|
|
* Throws ApiError with code 401 (unauthorized) if the user is missing.
|
|
|
|
*/
|
|
|
|
export function getUser(req: Request): User {
|
|
|
|
const user = (req as RequestWithLogin).user;
|
|
|
|
if (!user) {
|
|
|
|
throw new ApiError("user not known", 401);
|
|
|
|
}
|
|
|
|
return user;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Extract the user profiles from a request, assuming we've added them via appropriate middleware.
|
|
|
|
* Throws ApiError with code 401 (unauthorized) if the profiles are missing.
|
|
|
|
*/
|
|
|
|
export function getUserProfiles(req: Request): UserProfile[] {
|
|
|
|
const users = (req as RequestWithLogin).users;
|
|
|
|
if (!users) {
|
|
|
|
throw new ApiError("user profile not found", 401);
|
|
|
|
}
|
|
|
|
return users;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Extract the user id from a request, requiring it to be authorized (not an anonymous session).
|
|
|
|
export function getAuthorizedUserId(req: Request) {
|
|
|
|
const userId = getUserId(req);
|
|
|
|
if (isAnonymousUser(req)) {
|
|
|
|
throw new ApiError("user not authorized", 401);
|
|
|
|
}
|
|
|
|
return userId;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function isAnonymousUser(req: Request) {
|
|
|
|
return !(req as RequestWithLogin).userIsAuthorized;
|
|
|
|
}
|
|
|
|
|
|
|
|
// True if Grist is configured for a single user without specific authorization
|
|
|
|
// (classic standalone/electron mode).
|
|
|
|
export function isSingleUserMode(): boolean {
|
|
|
|
return process.env.GRIST_SINGLE_USER === '1';
|
|
|
|
}
|
|
|
|
|
2022-03-12 19:01:03 +00:00
|
|
|
/**
|
|
|
|
* Returns a profile if it can be deduced from the request. This requires a
|
2023-11-07 20:04:23 +00:00
|
|
|
* header to specify the users' email address.
|
2022-06-15 14:29:29 +00:00
|
|
|
* A result of null means that the user should be considered known to be anonymous.
|
|
|
|
* A result of undefined means we should go on to consider other authentication
|
|
|
|
* methods (such as cookies).
|
2022-03-12 19:01:03 +00:00
|
|
|
*/
|
2022-04-04 21:50:40 +00:00
|
|
|
export function getRequestProfile(req: Request|IncomingMessage,
|
2023-11-07 20:04:23 +00:00
|
|
|
header: string): UserProfile|null|undefined {
|
2022-06-15 14:29:29 +00:00
|
|
|
let profile: UserProfile|null|undefined;
|
2022-03-12 19:01:03 +00:00
|
|
|
|
2023-11-07 20:04:23 +00:00
|
|
|
// Careful reading headers. If we have an IncomingMessage, there is no
|
|
|
|
// get() function, and header names are lowercased.
|
|
|
|
const headerContent = ('get' in req) ? req.get(header) : req.headers[header.toLowerCase()];
|
|
|
|
if (headerContent) {
|
|
|
|
const userEmail = headerContent.toString();
|
|
|
|
const [userName] = userEmail.split("@", 1);
|
|
|
|
if (userEmail && userName) {
|
|
|
|
profile = {
|
|
|
|
"email": userEmail,
|
|
|
|
"name": userName
|
|
|
|
};
|
2022-06-15 14:29:29 +00:00
|
|
|
}
|
2022-03-12 19:01:03 +00:00
|
|
|
}
|
2023-11-07 20:04:23 +00:00
|
|
|
// If no profile at this point, and header was present,
|
|
|
|
// treat as anonymous user, represented by null value.
|
|
|
|
// Don't go on to look at session.
|
|
|
|
if (!profile && headerContent !== undefined) {
|
|
|
|
profile = null;
|
|
|
|
}
|
2022-03-12 19:01:03 +00:00
|
|
|
return profile;
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
/**
|
|
|
|
* Returns the express request object with user information added, if it can be
|
|
|
|
* found based on passed in headers or the session. Specifically, sets:
|
|
|
|
* - req.userId: the id of the user in the database users table
|
|
|
|
* - req.userIsAuthorized: set if user has presented credentials that were accepted
|
|
|
|
* (the anonymous user has a userId but does not have userIsAuthorized set if,
|
|
|
|
* as would typically be the case, credentials were not presented)
|
|
|
|
* - req.users: set for org-and-session-based logins, with list of profiles in session
|
|
|
|
*/
|
2023-11-07 20:04:23 +00:00
|
|
|
export async function addRequestUser(
|
|
|
|
dbManager: HomeDBManager, permitStore: IPermitStore,
|
|
|
|
options: {
|
|
|
|
gristServer: GristServer,
|
|
|
|
skipSession?: boolean,
|
|
|
|
overrideProfile?(req: Request|IncomingMessage): Promise<UserProfile|null|undefined>,
|
|
|
|
},
|
|
|
|
req: Request, res: Response, next: NextFunction
|
|
|
|
) {
|
2020-07-21 13:20:51 +00:00
|
|
|
const mreq = req as RequestWithLogin;
|
|
|
|
let profile: UserProfile|undefined;
|
|
|
|
|
2022-07-19 15:39:49 +00:00
|
|
|
// We support multiple method of authentication. This flag gets set once
|
|
|
|
// we need not try any more. Specifically, it is used to avoid processing
|
|
|
|
// anything else after setting an access token, for simplicity in reasoning
|
|
|
|
// about this case.
|
|
|
|
let authDone: boolean = false;
|
|
|
|
|
2023-04-06 15:10:29 +00:00
|
|
|
let hasApiKey: boolean = false;
|
|
|
|
|
2022-07-19 15:39:49 +00:00
|
|
|
// Support providing an access token via an `auth` query parameter.
|
|
|
|
// This is useful for letting the browser load assets like image
|
|
|
|
// attachments.
|
2023-09-05 18:27:35 +00:00
|
|
|
const auth = optStringParam(mreq.query.auth, 'auth');
|
2022-07-19 15:39:49 +00:00
|
|
|
if (auth) {
|
|
|
|
const tokens = options.gristServer.getAccessTokens();
|
|
|
|
const token = await tokens.verify(auth);
|
|
|
|
mreq.accessToken = token;
|
|
|
|
// Once an accessToken is supplied, we don't consider anything else.
|
|
|
|
// User is treated as anonymous apart from having an accessToken.
|
|
|
|
authDone = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now, check for an apiKey
|
|
|
|
if (!authDone && mreq.headers && mreq.headers.authorization) {
|
2020-07-21 13:20:51 +00:00
|
|
|
// header needs to be of form "Bearer XXXXXXXXX" to apply
|
|
|
|
const parts = String(mreq.headers.authorization).split(' ');
|
|
|
|
if (parts[0] === "Bearer") {
|
|
|
|
const user = parts[1] ? await dbManager.getUserByKey(parts[1]) : undefined;
|
|
|
|
if (!user) {
|
|
|
|
return res.status(401).send('Bad request: invalid API key');
|
|
|
|
}
|
|
|
|
if (user.id === dbManager.getAnonymousUserId()) {
|
|
|
|
// We forbid the anonymous user to present an api key. That saves us
|
|
|
|
// having to think through the consequences of authorized access to the
|
|
|
|
// anonymous user's profile via the api (e.g. how should the api key be managed).
|
|
|
|
return res.status(401).send('Credentials cannot be presented for the anonymous user account via API key');
|
|
|
|
}
|
|
|
|
mreq.user = user;
|
|
|
|
mreq.userId = user.id;
|
|
|
|
mreq.userIsAuthorized = true;
|
2023-04-06 15:10:29 +00:00
|
|
|
hasApiKey = true;
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Special permission header for internal housekeeping tasks
|
2022-07-19 15:39:49 +00:00
|
|
|
if (!authDone && mreq.headers && mreq.headers.permit) {
|
2020-07-21 13:20:51 +00:00
|
|
|
const permitKey = String(mreq.headers.permit);
|
|
|
|
try {
|
|
|
|
const permit = await permitStore.getPermit(permitKey);
|
|
|
|
if (!permit) { return res.status(401).send('Bad request: unknown permit'); }
|
|
|
|
mreq.user = dbManager.getAnonymousUser();
|
|
|
|
mreq.userId = mreq.user.id;
|
|
|
|
mreq.specialPermit = permit;
|
|
|
|
} catch (err) {
|
|
|
|
log.error(`problem reading permit: ${err}`);
|
|
|
|
return res.status(401).send('Bad request: permit could not be read');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-08 13:28:39 +00:00
|
|
|
// If we haven't already been authenticated, and this is not a GET/HEAD/OPTIONS, then
|
2022-11-03 10:15:42 +00:00
|
|
|
// require a header that would trigger a CORS pre-flight request, either:
|
|
|
|
// - X-Requested-With: XMLHttpRequest
|
|
|
|
// - https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#use-of-custom-request-headers
|
|
|
|
// - https://markitzeroday.com/x-requested-with/cors/2017/06/29/csrf-mitigation-for-ajax-requests.html
|
|
|
|
// - Content-Type: application/json
|
|
|
|
// - https://www.directdefense.com/csrf-in-the-age-of-json/
|
2020-10-08 13:28:39 +00:00
|
|
|
// This is trivial for legitimate web clients to do, and an obstacle to
|
|
|
|
// nefarious ones.
|
2022-11-03 10:15:42 +00:00
|
|
|
if (
|
|
|
|
!mreq.userId &&
|
|
|
|
!(mreq.xhr || mreq.get("content-type") === "application/json") &&
|
|
|
|
!['GET', 'HEAD', 'OPTIONS'].includes(mreq.method)
|
|
|
|
) {
|
|
|
|
return res.status(401).json({
|
|
|
|
error: "Unauthenticated requests require one of the headers" +
|
|
|
|
"'Content-Type: application/json' or 'X-Requested-With: XMLHttpRequest'"
|
|
|
|
});
|
2020-10-08 13:28:39 +00:00
|
|
|
}
|
|
|
|
|
2022-06-15 14:29:29 +00:00
|
|
|
// For some configurations, the user profile can be determined from the request.
|
|
|
|
// If this is the case, we won't use session information.
|
2022-07-19 15:39:49 +00:00
|
|
|
let skipSession: boolean = options.skipSession || authDone;
|
|
|
|
if (!authDone && !mreq.userId) {
|
2023-11-07 20:04:23 +00:00
|
|
|
const candidateProfile = await options.overrideProfile?.(mreq);
|
|
|
|
if (candidateProfile !== undefined) {
|
|
|
|
// Either a valid or a null profile tells us that another login system determined the user,
|
|
|
|
// and that we should skip sessions.
|
2022-06-15 14:29:29 +00:00
|
|
|
skipSession = true;
|
2023-11-07 20:04:23 +00:00
|
|
|
if (candidateProfile) {
|
|
|
|
profile = candidateProfile;
|
|
|
|
const user = await dbManager.getUserByLoginWithRetry(profile.email, {profile});
|
|
|
|
if (user) {
|
|
|
|
mreq.user = user;
|
|
|
|
mreq.users = [profile];
|
|
|
|
mreq.userId = user.id;
|
|
|
|
mreq.userIsAuthorized = true;
|
|
|
|
}
|
2022-06-15 14:29:29 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
// A bit of extra info we'll add to the "Auth" log message when this request passes the check
|
|
|
|
// for custom-host-specific sessionID.
|
|
|
|
let customHostSession = '';
|
|
|
|
|
2022-07-19 15:39:49 +00:00
|
|
|
if (!authDone && !skipSession) {
|
2022-06-15 14:29:29 +00:00
|
|
|
// If we haven't selected a user by other means, and have profiles available in the
|
|
|
|
// session, then select a user based on those profiles.
|
|
|
|
const session = mreq.session;
|
|
|
|
if (session && !session.altSessionId) {
|
|
|
|
// Create a default alternative session id for use in documents.
|
|
|
|
session.altSessionId = makeId();
|
|
|
|
forceSessionChange(session);
|
|
|
|
}
|
|
|
|
mreq.altSessionId = session?.altSessionId;
|
|
|
|
if (!mreq.userId && session && session.users && session.users.length > 0 &&
|
|
|
|
mreq.org !== undefined) {
|
2020-07-21 13:20:51 +00:00
|
|
|
|
2022-06-15 14:29:29 +00:00
|
|
|
// Prevent using custom-domain sessionID to authorize to a different domain, since
|
|
|
|
// custom-domain owner could hijack such sessions.
|
|
|
|
const allowedOrg = getAllowedOrgForSessionID(mreq.sessionID);
|
|
|
|
if (allowedOrg) {
|
2024-03-15 13:40:56 +00:00
|
|
|
if (allowHost(req, allowedOrg.host)) {
|
2022-06-15 14:29:29 +00:00
|
|
|
customHostSession = ` custom-host-match ${allowedOrg.host}`;
|
2020-07-21 13:20:51 +00:00
|
|
|
} else {
|
2022-06-15 14:29:29 +00:00
|
|
|
// We need an exception for internal forwarding from home server to doc-workers. These use
|
|
|
|
// internal hostnames, so we can't expect a custom domain. These requests do include an
|
|
|
|
// Organization header, which we'll use to grant the exception, but security issues remain.
|
|
|
|
// TODO Issue 1: an attacker can use a custom-domain request to get an API key, which is an
|
|
|
|
// open door to all orgs accessible by this user.
|
|
|
|
// TODO Issue 2: Organization header is easy for an attacker (who has stolen a session
|
|
|
|
// cookie) to include too; it does nothing to prove that the request is internal.
|
|
|
|
const org = req.header('organization');
|
|
|
|
if (org && org === allowedOrg.org) {
|
|
|
|
customHostSession = ` custom-host-fwd ${org}`;
|
|
|
|
} else {
|
|
|
|
// Log error and fail.
|
|
|
|
log.warn("Auth[%s]: sessionID for host %s org %s; wrong for host %s org %s", mreq.method,
|
|
|
|
allowedOrg.host, allowedOrg.org, mreq.get('host'), mreq.org);
|
|
|
|
return res.status(403).send('Bad request: invalid session ID');
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-15 14:29:29 +00:00
|
|
|
mreq.users = getSessionProfiles(session);
|
2020-07-21 13:20:51 +00:00
|
|
|
|
2022-06-15 14:29:29 +00:00
|
|
|
// If we haven't set a maxAge yet, set it now.
|
|
|
|
if (session && session.cookie && !session.cookie.maxAge) {
|
|
|
|
if (COOKIE_MAX_AGE !== null) {
|
|
|
|
session.cookie.maxAge = COOKIE_MAX_AGE;
|
|
|
|
forceSessionChange(session);
|
|
|
|
}
|
2022-05-18 10:25:14 +00:00
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
|
2022-06-15 14:29:29 +00:00
|
|
|
// See if we have a profile linked with the active organization already.
|
|
|
|
// TODO: implement userSelector for rest API, to allow "sticky" user selection on pages.
|
2023-09-05 18:27:35 +00:00
|
|
|
let sessionUser: SessionUserObj|null = getSessionUser(session, mreq.org,
|
|
|
|
optStringParam(mreq.query.user, 'user') || '');
|
2020-07-21 13:20:51 +00:00
|
|
|
|
2022-06-15 14:29:29 +00:00
|
|
|
if (!sessionUser) {
|
|
|
|
// No profile linked yet, so let's elect one.
|
|
|
|
// Choose a profile that is no worse than the others available.
|
|
|
|
const option = await dbManager.getBestUserForOrg(mreq.users, mreq.org);
|
|
|
|
if (option) {
|
|
|
|
// Modify request session object to link the current org with our choice of
|
|
|
|
// profile. Express-session will save this change.
|
|
|
|
sessionUser = linkOrgWithEmail(session, option.email, mreq.org);
|
|
|
|
const userOptions: UserOptions = {};
|
|
|
|
if (sessionUser?.profile?.loginMethod === 'Email + Password') {
|
|
|
|
// Link the session authSubject, if present, to the user. This has no effect
|
|
|
|
// if the user already has an authSubject set in the db.
|
|
|
|
userOptions.authSubject = sessionUser.authSubject;
|
|
|
|
}
|
|
|
|
// In this special case of initially linking a profile, we need to look up the user's info.
|
|
|
|
mreq.user = await dbManager.getUserByLogin(option.email, {userOptions});
|
|
|
|
mreq.userId = option.id;
|
|
|
|
mreq.userIsAuthorized = true;
|
|
|
|
} else {
|
|
|
|
// No profile has access to this org. We could choose to
|
|
|
|
// link no profile, in which case user will end up
|
|
|
|
// immediately presented with a sign-in page, or choose to
|
|
|
|
// link an arbitrary profile (say, the first one the user
|
|
|
|
// logged in as), in which case user will end up with a
|
|
|
|
// friendlier page explaining the situation and offering to
|
|
|
|
// add an account to resolve it. We go ahead and pick an
|
|
|
|
// arbitrary profile.
|
|
|
|
sessionUser = session.users[0];
|
|
|
|
if (!session.orgToUser) { throw new Error("Session misconfigured"); }
|
|
|
|
// Express-session will save this change.
|
|
|
|
session.orgToUser[mreq.org] = 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
profile = sessionUser?.profile ?? undefined;
|
|
|
|
|
|
|
|
// If we haven't computed a userId yet, check for one using an email address in the profile.
|
|
|
|
// A user record will be created automatically for emails we've never seen before.
|
|
|
|
if (profile && !mreq.userId) {
|
2022-04-11 18:08:44 +00:00
|
|
|
const userOptions: UserOptions = {};
|
2022-06-15 14:29:29 +00:00
|
|
|
if (profile?.loginMethod === 'Email + Password') {
|
2022-04-11 18:08:44 +00:00
|
|
|
// Link the session authSubject, if present, to the user. This has no effect
|
|
|
|
// if the user already has an authSubject set in the db.
|
|
|
|
userOptions.authSubject = sessionUser.authSubject;
|
|
|
|
}
|
2022-06-15 14:29:29 +00:00
|
|
|
const user = await dbManager.getUserByLoginWithRetry(profile.email, {profile, userOptions});
|
|
|
|
if (user) {
|
|
|
|
mreq.user = user;
|
|
|
|
mreq.userId = user.id;
|
|
|
|
mreq.userIsAuthorized = true;
|
|
|
|
}
|
2022-03-08 19:24:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
// If no userId has been found yet, fall back on anonymous.
|
|
|
|
if (!mreq.userId) {
|
|
|
|
const anon = dbManager.getAnonymousUser();
|
|
|
|
mreq.user = anon;
|
|
|
|
mreq.userId = anon.id;
|
|
|
|
mreq.userIsAuthorized = false;
|
|
|
|
mreq.users = [dbManager.makeFullUser(anon)];
|
|
|
|
}
|
|
|
|
|
2023-01-24 13:13:18 +00:00
|
|
|
if (mreq.userId) {
|
|
|
|
if (mreq.user?.options?.locale) {
|
|
|
|
mreq.language = mreq.user.options.locale;
|
|
|
|
// This is a synchronous call (as it was configured with initImmediate: false).
|
|
|
|
mreq.i18n.changeLanguage(mreq.language).catch(() => {});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-08 18:00:43 +00:00
|
|
|
const meta = {
|
|
|
|
customHostSession,
|
|
|
|
method: mreq.method,
|
|
|
|
host: mreq.get('host'),
|
|
|
|
path: mreq.path,
|
|
|
|
org: mreq.org,
|
|
|
|
email: mreq.user?.loginEmail,
|
|
|
|
userId: mreq.userId,
|
|
|
|
altSessionId: mreq.altSessionId,
|
|
|
|
};
|
|
|
|
log.rawDebug(`Auth[${meta.method}]: ${meta.host} ${meta.path}`, meta);
|
2023-04-06 15:10:29 +00:00
|
|
|
if (hasApiKey) {
|
2023-11-01 13:54:19 +00:00
|
|
|
options.gristServer.getTelemetry().logEvent(mreq, 'apiUsage', {
|
2023-06-06 17:08:50 +00:00
|
|
|
full: {
|
|
|
|
method: mreq.method,
|
|
|
|
userId: mreq.userId,
|
|
|
|
userAgent: mreq.headers['user-agent'],
|
|
|
|
},
|
2023-11-01 13:54:19 +00:00
|
|
|
});
|
2023-04-06 15:10:29 +00:00
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
return next();
|
|
|
|
}
|
|
|
|
|
2020-08-19 20:25:42 +00:00
|
|
|
/**
|
|
|
|
* Returns a handler that redirects the user to a login or signup page.
|
|
|
|
*/
|
|
|
|
export function redirectToLoginUnconditionally(
|
2021-08-16 15:11:17 +00:00
|
|
|
getLoginRedirectUrl: (req: Request, redirectUrl: URL) => Promise<string>,
|
|
|
|
getSignUpRedirectUrl: (req: Request, redirectUrl: URL) => Promise<string>
|
2020-08-19 20:25:42 +00:00
|
|
|
) {
|
|
|
|
return async (req: Request, resp: Response, next: NextFunction) => {
|
|
|
|
const mreq = req as RequestWithLogin;
|
2021-07-15 21:23:15 +00:00
|
|
|
// Tell express-session to set our cookie: session handling post-login relies on it.
|
2021-11-24 14:50:44 +00:00
|
|
|
forceSessionChange(mreq.session);
|
2021-07-15 21:23:15 +00:00
|
|
|
|
2020-08-19 20:25:42 +00:00
|
|
|
// Redirect to sign up if it doesn't look like the user has ever logged in (on
|
|
|
|
// this browser) After logging in, `users` will be set in the session. Even after
|
|
|
|
// logging out again, `users` will still be set.
|
|
|
|
const signUp: boolean = (mreq.session.users === undefined);
|
|
|
|
log.debug(`Authorizer: redirecting to ${signUp ? 'sign up' : 'log in'}`);
|
2022-04-27 16:07:08 +00:00
|
|
|
const redirectUrl = new URL(getOriginUrl(req) + req.originalUrl);
|
2020-08-19 20:25:42 +00:00
|
|
|
if (signUp) {
|
2021-08-16 15:11:17 +00:00
|
|
|
return resp.redirect(await getSignUpRedirectUrl(req, redirectUrl));
|
2020-08-19 20:25:42 +00:00
|
|
|
} else {
|
2021-08-16 15:11:17 +00:00
|
|
|
return resp.redirect(await getLoginRedirectUrl(req, redirectUrl));
|
2020-08-19 20:25:42 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Middleware to redirects user to a login page when the user is not
|
|
|
|
* logged in. If allowExceptions is set, then we make an exception
|
|
|
|
* for a team site allowing anonymous access, or a personal doc
|
|
|
|
* allowing anonymous access, or the merged org.
|
|
|
|
*/
|
|
|
|
export function redirectToLogin(
|
|
|
|
allowExceptions: boolean,
|
2021-08-16 15:11:17 +00:00
|
|
|
getLoginRedirectUrl: (req: Request, redirectUrl: URL) => Promise<string>,
|
|
|
|
getSignUpRedirectUrl: (req: Request, redirectUrl: URL) => Promise<string>,
|
2020-07-21 13:20:51 +00:00
|
|
|
dbManager: HomeDBManager
|
|
|
|
): RequestHandler {
|
2020-08-19 20:25:42 +00:00
|
|
|
const redirectUnconditionally = redirectToLoginUnconditionally(getLoginRedirectUrl,
|
|
|
|
getSignUpRedirectUrl);
|
2020-07-21 13:20:51 +00:00
|
|
|
return async (req: Request, resp: Response, next: NextFunction) => {
|
|
|
|
const mreq = req as RequestWithLogin;
|
2021-11-24 14:50:44 +00:00
|
|
|
// This will ensure that express-session will set our cookie if it hasn't already -
|
|
|
|
// we'll need it if we redirect.
|
|
|
|
forceSessionChange(mreq.session);
|
2020-07-21 13:20:51 +00:00
|
|
|
if (mreq.userIsAuthorized) { return next(); }
|
|
|
|
|
|
|
|
try {
|
2021-08-17 15:22:30 +00:00
|
|
|
// Otherwise it's an anonymous user. Proceed normally only if the org allows anon access,
|
|
|
|
// or if the org is not set (FlexServer._redirectToOrg will deal with that case).
|
|
|
|
if (mreq.userId && allowExceptions) {
|
2020-07-21 13:20:51 +00:00
|
|
|
// Anonymous user has qualified access to merged org.
|
2021-08-17 15:22:30 +00:00
|
|
|
// If no org is set, leave it to other middleware. One common case where the
|
|
|
|
// org is not set is when it is embedded in the url, and the user visits '/'.
|
|
|
|
// If we immediately require a login, it could fail if no cookie exists yet.
|
|
|
|
// Also, '/o/docs' allows anonymous access.
|
|
|
|
if (!mreq.org || dbManager.isMergedOrg(mreq.org)) { return next(); }
|
|
|
|
const result = await dbManager.getOrg({userId: mreq.userId}, mreq.org);
|
2020-07-21 13:20:51 +00:00
|
|
|
if (result.status === 200) { return next(); }
|
|
|
|
}
|
|
|
|
|
|
|
|
// In all other cases (including unknown org), redirect user to login or sign up.
|
2020-08-19 20:25:42 +00:00
|
|
|
return redirectUnconditionally(req, resp, next);
|
2020-07-21 13:20:51 +00:00
|
|
|
} catch (err) {
|
|
|
|
log.info("Authorizer failed to redirect", err.message);
|
|
|
|
return resp.status(401).send(err.message);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Sets mreq.docAuth if not yet set, and returns it.
|
|
|
|
*/
|
|
|
|
export async function getOrSetDocAuth(
|
2022-07-19 15:39:49 +00:00
|
|
|
mreq: RequestWithLogin, dbManager: HomeDBManager,
|
|
|
|
gristServer: GristServer,
|
|
|
|
urlId: string
|
2020-07-21 13:20:51 +00:00
|
|
|
): Promise<DocAuthResult> {
|
|
|
|
if (!mreq.docAuth) {
|
|
|
|
let effectiveUserId = getUserId(mreq);
|
|
|
|
if (mreq.specialPermit && mreq.userId === dbManager.getAnonymousUserId()) {
|
|
|
|
effectiveUserId = dbManager.getPreviewerUserId();
|
|
|
|
}
|
2022-07-19 15:39:49 +00:00
|
|
|
|
|
|
|
// A permit with a token gives us the userId associated with that token.
|
|
|
|
const tokenObj = mreq.accessToken;
|
|
|
|
if (tokenObj) {
|
|
|
|
effectiveUserId = tokenObj.userId;
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
mreq.docAuth = await dbManager.getDocAuthCached({urlId, userId: effectiveUserId, org: mreq.org});
|
2022-07-19 15:39:49 +00:00
|
|
|
|
|
|
|
if (tokenObj) {
|
|
|
|
// Sanity check: does the current document match the document the token is
|
|
|
|
// for? If not, fail.
|
|
|
|
if (!mreq.docAuth.docId || mreq.docAuth.docId !== tokenObj.docId) {
|
|
|
|
throw new ApiError('token misuse', 401);
|
|
|
|
}
|
|
|
|
// Limit access to read-only if specified.
|
|
|
|
if (tokenObj.readOnly) {
|
|
|
|
mreq.docAuth = {...mreq.docAuth, access: getWeakestRole('viewers', mreq.docAuth.access)};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// A permit with a user set to the anonymous user and linked to this document
|
|
|
|
// gets updated to full access.
|
2020-07-21 13:20:51 +00:00
|
|
|
if (mreq.specialPermit && mreq.userId === dbManager.getAnonymousUserId() &&
|
|
|
|
mreq.specialPermit.docId === mreq.docAuth.docId) {
|
|
|
|
mreq.docAuth = {...mreq.docAuth, access: 'owners'};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return mreq.docAuth;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export interface ResourceSummary {
|
|
|
|
kind: 'doc';
|
|
|
|
id: string|number;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
*
|
2020-09-02 18:17:17 +00:00
|
|
|
* Handle authorization for a single document accessed by a given user.
|
2020-07-21 13:20:51 +00:00
|
|
|
*
|
|
|
|
*/
|
|
|
|
export interface Authorizer {
|
|
|
|
// get the id of user, or null if no authorization in place.
|
|
|
|
getUserId(): number|null;
|
|
|
|
|
2020-10-19 14:25:21 +00:00
|
|
|
// get user profile if available.
|
|
|
|
getUser(): FullUser|null;
|
|
|
|
|
2020-09-02 18:17:17 +00:00
|
|
|
// get the id of the document.
|
|
|
|
getDocId(): string;
|
|
|
|
|
2020-12-09 13:57:35 +00:00
|
|
|
// get any link parameters in place when accessing the resource.
|
|
|
|
getLinkParameters(): Record<string, string>;
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
// Fetch the doc metadata from HomeDBManager.
|
|
|
|
getDoc(): Promise<Document>;
|
|
|
|
|
|
|
|
// Check access, throw error if the requested level of access isn't available.
|
2020-12-18 17:37:16 +00:00
|
|
|
assertAccess(role: 'viewers'|'editors'|'owners'): Promise<void>;
|
2020-09-02 18:17:17 +00:00
|
|
|
|
|
|
|
// Get the lasted access information calculated for the doc. This is useful
|
|
|
|
// for logging - but access control itself should use assertAccess() to
|
|
|
|
// ensure the data is fresh.
|
|
|
|
getCachedAuth(): DocAuthResult;
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
2022-10-03 14:45:44 +00:00
|
|
|
export interface DocAuthorizerOptions {
|
|
|
|
dbManager: HomeDBManager;
|
|
|
|
key: DocAuthKey;
|
|
|
|
openMode: OpenDocMode;
|
|
|
|
linkParameters: Record<string, string>;
|
|
|
|
userRef?: string|null;
|
|
|
|
docAuth?: DocAuthResult;
|
|
|
|
profile?: UserProfile;
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
/**
|
|
|
|
*
|
|
|
|
* Handle authorization for a single document and user.
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
export class DocAuthorizer implements Authorizer {
|
2022-10-03 14:45:44 +00:00
|
|
|
public readonly openMode: OpenDocMode;
|
|
|
|
public readonly linkParameters: Record<string, string>;
|
2020-07-21 13:20:51 +00:00
|
|
|
constructor(
|
2022-10-03 14:45:44 +00:00
|
|
|
private _options: DocAuthorizerOptions
|
2020-07-21 13:20:51 +00:00
|
|
|
) {
|
2022-10-03 14:45:44 +00:00
|
|
|
this.openMode = _options.openMode;
|
|
|
|
this.linkParameters = _options.linkParameters;
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public getUserId(): number {
|
2022-10-03 14:45:44 +00:00
|
|
|
return this._options.key.userId;
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
2020-10-19 14:25:21 +00:00
|
|
|
public getUser(): FullUser|null {
|
2022-10-03 14:45:44 +00:00
|
|
|
return this._options.profile ? {
|
|
|
|
id: this.getUserId(),
|
|
|
|
ref: this._options.userRef,
|
|
|
|
...this._options.profile
|
|
|
|
} : null;
|
2020-10-19 14:25:21 +00:00
|
|
|
}
|
|
|
|
|
2020-09-02 18:17:17 +00:00
|
|
|
public getDocId(): string {
|
|
|
|
// We've been careful to require urlId === docId, see DocManager.
|
2022-10-03 14:45:44 +00:00
|
|
|
return this._options.key.urlId;
|
2020-09-02 18:17:17 +00:00
|
|
|
}
|
|
|
|
|
2020-12-09 13:57:35 +00:00
|
|
|
public getLinkParameters(): Record<string, string> {
|
|
|
|
return this.linkParameters;
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
public async getDoc(): Promise<Document> {
|
2022-10-03 14:45:44 +00:00
|
|
|
return this._options.dbManager.getDoc(this._options.key);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
2020-12-18 17:37:16 +00:00
|
|
|
public async assertAccess(role: 'viewers'|'editors'|'owners'): Promise<void> {
|
2022-10-03 14:45:44 +00:00
|
|
|
const docAuth = await this._options.dbManager.getDocAuthCached(this._options.key);
|
|
|
|
this._options.docAuth = docAuth;
|
2020-07-21 13:20:51 +00:00
|
|
|
assertAccess(role, docAuth, {openMode: this.openMode});
|
|
|
|
}
|
2020-09-02 18:17:17 +00:00
|
|
|
|
|
|
|
public getCachedAuth(): DocAuthResult {
|
2022-10-03 14:45:44 +00:00
|
|
|
if (!this._options.docAuth) { throw Error('no cached authentication'); }
|
|
|
|
return this._options.docAuth;
|
2020-09-02 18:17:17 +00:00
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export class DummyAuthorizer implements Authorizer {
|
2020-09-02 18:17:17 +00:00
|
|
|
constructor(public role: Role|null, public docId: string) {}
|
2020-07-21 13:20:51 +00:00
|
|
|
public getUserId() { return null; }
|
2020-10-19 14:25:21 +00:00
|
|
|
public getUser() { return null; }
|
2020-09-02 18:17:17 +00:00
|
|
|
public getDocId() { return this.docId; }
|
2020-12-09 13:57:35 +00:00
|
|
|
public getLinkParameters() { return {}; }
|
2020-07-21 13:20:51 +00:00
|
|
|
public async getDoc(): Promise<Document> { throw new Error("Not supported in standalone"); }
|
|
|
|
public async assertAccess() { /* noop */ }
|
2020-09-02 18:17:17 +00:00
|
|
|
public getCachedAuth(): DocAuthResult {
|
|
|
|
return {
|
|
|
|
access: this.role,
|
|
|
|
docId: this.docId,
|
|
|
|
removed: false,
|
|
|
|
};
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export function assertAccess(
|
2020-12-18 17:37:16 +00:00
|
|
|
role: 'viewers'|'editors'|'owners', docAuth: DocAuthResult, options: {
|
2020-07-21 13:20:51 +00:00
|
|
|
openMode?: OpenDocMode,
|
|
|
|
allowRemoved?: boolean,
|
|
|
|
} = {}) {
|
|
|
|
const openMode = options.openMode || 'default';
|
|
|
|
const details = {status: 403, accessMode: openMode};
|
|
|
|
if (docAuth.error) {
|
|
|
|
if ([400, 401, 403].includes(docAuth.error.status)) {
|
|
|
|
// For these error codes, we know our access level - forbidden. Make errors more uniform.
|
|
|
|
throw new ErrorWithCode("AUTH_NO_VIEW", "No view access", details);
|
|
|
|
}
|
|
|
|
throw docAuth.error;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (docAuth.removed && !options.allowRemoved) {
|
|
|
|
throw new ErrorWithCode("AUTH_NO_VIEW", "Document is deleted", {status: 404});
|
|
|
|
}
|
|
|
|
|
|
|
|
// If docAuth has no error, the doc is accessible, but we should still check the level (in case
|
|
|
|
// it's possible to access the doc with a level less than "viewer").
|
|
|
|
if (!canView(docAuth.access)) {
|
|
|
|
throw new ErrorWithCode("AUTH_NO_VIEW", "No view access", details);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (role === 'editors') {
|
|
|
|
// If opening in a fork or view mode, treat user as viewer and deny write access.
|
|
|
|
const access = (openMode === 'fork' || openMode === 'view') ?
|
|
|
|
getWeakestRole('viewers', docAuth.access) : docAuth.access;
|
|
|
|
if (!canEdit(access)) {
|
|
|
|
throw new ErrorWithCode("AUTH_NO_EDIT", "No write access", details);
|
|
|
|
}
|
|
|
|
}
|
2022-11-30 12:04:27 +00:00
|
|
|
|
|
|
|
if (role === 'owners' && docAuth.access !== 'owners') {
|
|
|
|
throw new ErrorWithCode("AUTH_NO_OWNER", "No owner access", details);
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2022-02-19 09:46:49 +00:00
|
|
|
* Pull out headers to pass along to a proxied service. Focused primarily on
|
2020-07-21 13:20:51 +00:00
|
|
|
* authentication.
|
|
|
|
*/
|
2024-05-14 16:58:41 +00:00
|
|
|
export function getTransitiveHeaders(
|
|
|
|
req: Request,
|
|
|
|
{ includeOrigin }: { includeOrigin: boolean }
|
|
|
|
): {[key: string]: string} {
|
2020-07-21 13:20:51 +00:00
|
|
|
const Authorization = req.get('Authorization');
|
|
|
|
const Cookie = req.get('Cookie');
|
|
|
|
const PermitHeader = req.get('Permit');
|
|
|
|
const Organization = (req as RequestWithOrg).org;
|
2020-10-08 13:28:39 +00:00
|
|
|
const XRequestedWith = req.get('X-Requested-With');
|
2020-12-09 13:57:35 +00:00
|
|
|
const Origin = req.get('Origin'); // Pass along the original Origin since it may
|
|
|
|
// play a role in granular access control.
|
2024-05-14 16:58:41 +00:00
|
|
|
|
2022-03-24 17:11:26 +00:00
|
|
|
const result: Record<string, string> = {
|
2020-07-21 13:20:51 +00:00
|
|
|
...(Authorization ? { Authorization } : undefined),
|
|
|
|
...(Cookie ? { Cookie } : undefined),
|
|
|
|
...(Organization ? { Organization } : undefined),
|
|
|
|
...(PermitHeader ? { Permit: PermitHeader } : undefined),
|
2020-10-08 13:28:39 +00:00
|
|
|
...(XRequestedWith ? { 'X-Requested-With': XRequestedWith } : undefined),
|
2024-05-14 16:58:41 +00:00
|
|
|
...((includeOrigin && Origin) ? { Origin } : undefined),
|
2020-07-21 13:20:51 +00:00
|
|
|
};
|
2023-11-07 20:04:23 +00:00
|
|
|
const extraHeader = process.env.GRIST_FORWARD_AUTH_HEADER;
|
2022-03-24 17:11:26 +00:00
|
|
|
const extraHeaderValue = extraHeader && req.get(extraHeader);
|
|
|
|
if (extraHeader && extraHeaderValue) {
|
|
|
|
result[extraHeader] = extraHeaderValue;
|
|
|
|
}
|
|
|
|
return result;
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
2021-10-01 14:24:23 +00:00
|
|
|
|
|
|
|
export const signInStatusCookieName = sessionCookieName + '_status';
|
|
|
|
|
|
|
|
// We expose a sign-in status in a cookie accessible to all subdomains, to assist in auto-signin.
|
|
|
|
// Its value is SignInStatus ("S", "M" or unset). This middleware keeps this cookie in sync with
|
|
|
|
// the session state.
|
|
|
|
//
|
|
|
|
// Note that this extra cookie isn't strictly necessary today: since it has similar settings to
|
|
|
|
// the session cookie, subdomains can infer status from that one. It is here in anticipation that
|
|
|
|
// we make sessions a host-only cookie, to avoid exposing it to externally-hosted subdomains of
|
|
|
|
// getgrist.com. In that case, the sign-in status cookie would remain a 2nd-level domain cookie.
|
|
|
|
export function signInStatusMiddleware(req: Request, resp: Response, next: NextFunction) {
|
|
|
|
const mreq = req as RequestWithLogin;
|
|
|
|
|
|
|
|
let origSignInStatus: SignInStatus = '';
|
|
|
|
if (req.headers.cookie) {
|
|
|
|
const cookies = cookie.parse(req.headers.cookie);
|
|
|
|
origSignInStatus = cookies[signInStatusCookieName] || '';
|
|
|
|
}
|
|
|
|
|
|
|
|
onHeaders(resp, () => {
|
|
|
|
const newSignInStatus = getSignInStatus(mreq.session);
|
|
|
|
if (newSignInStatus !== origSignInStatus) {
|
|
|
|
// If not signed-in any more, set a past date to delete this cookie.
|
|
|
|
const expires = (newSignInStatus && mreq.session.cookie.expires) || new Date(0);
|
|
|
|
resp.append('Set-Cookie', cookie.serialize(signInStatusCookieName, newSignInStatus, {
|
|
|
|
httpOnly: false, // make available to client-side scripts
|
|
|
|
expires,
|
|
|
|
domain: getCookieDomain(req),
|
2021-10-03 21:27:22 +00:00
|
|
|
path: '/',
|
2021-10-01 14:24:23 +00:00
|
|
|
sameSite: 'lax', // same setting as for grist-sid is fine here.
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
});
|
|
|
|
next();
|
|
|
|
}
|