gristlabs_grist-core/app/server/lib/MinimalLogin.ts
Paul Fitzpatrick f9630b3aa4 (core) clean up a collection of small problems affecting grist-core
Summary:
 * Remove adjustSession hack, interfering with loading docs under saml.
 * Allow the anonymous user to receive an empty list of workspaces for
   the merged org.
 * Behave better on first page load when org is in path - this used to
   fail because of lack of cookie.  This is very visible in grist-core,
   as a failure to load localhost:8484 on first visit.
 * Mark cookie explicitly as SameSite=Lax to remove a warning in firefox.
 * Make errorPages available in grist-core.

This changes the default behavior of grist-core to now start off in
anonymous mode, with an explicit sign-in step available.  If SAML is not configured,
the sign-in operation will unconditionally sign the user in as a default
user, without any password check or other security.  The user email is
taken from GRIST_DEFAULT_EMAIL if set.  This is a significant change, but
makes anonymous mode available in grist-core (which is convenient
for testing) and makes behavior with and without SAML much more consistent.

Test Plan: updated test; manual (time to start adding grist-core tests though!)

Reviewers: dsagal

Reviewed By: dsagal

Differential Revision: https://phab.getgrist.com/D2980
2021-08-17 21:44:50 -04:00

54 lines
1.7 KiB
TypeScript

import { UserProfile } from 'app/common/UserAPI';
import { GristLoginMiddleware, GristServer } from 'app/server/lib/GristServer';
import { Request } from 'express';
/**
* Return a login system that supports a single hard-coded user.
*/
export async function getMinimalLoginMiddleware(gristServer: GristServer): Promise<GristLoginMiddleware> {
// Login and logout, redirecting immediately back. Signup is treated as login,
// no nuance here.
return {
async getLoginRedirectUrl(req: Request, url: URL) {
await setSingleUser(req, gristServer);
return url.href;
},
async getLogoutRedirectUrl(req: Request, url: URL) {
return url.href;
},
async getSignUpRedirectUrl(req: Request, url: URL) {
await setSingleUser(req, gristServer);
return url.href;
},
async addEndpoints() {
// If working without a login system, make sure default user exists.
const dbManager = gristServer.getHomeDBManager();
const profile = getDefaultProfile();
const user = await dbManager.getUserByLoginWithRetry(profile.email, profile);
if (user) {
// No need to survey this user!
user.isFirstTimeUser = false;
await user.save();
}
return "no-logins";
}
};
}
/**
* Set the user in the current session to the single hard-coded user.
*/
async function setSingleUser(req: Request, gristServer: GristServer) {
const scopedSession = gristServer.getSessions().getOrCreateSessionFromRequest(req);
await scopedSession.operateOnScopedSession(async (user) => Object.assign(user, {
profile: getDefaultProfile()
}));
}
function getDefaultProfile(): UserProfile {
return {
email: process.env.GRIST_DEFAULT_EMAIL || 'you@example.com',
name: 'You',
};
}