Make passport as instance

This commit is contained in:
2026-03-21 21:54:51 +01:00
parent 3b17f9c53c
commit 2772d82d2e
2 changed files with 17 additions and 12 deletions
+14 -10
View File
@@ -1,5 +1,5 @@
import { Router, Request, Response, RequestHandler } from 'express'; import { Router, Request, Response, RequestHandler } from 'express';
import { use, authenticate, AuthenticateOptions } from 'passport'; import * as passport from 'passport';
import { Strategy as LocalStrategy } from 'passport-local'; import { Strategy as LocalStrategy } from 'passport-local';
import { remove } from 'lodash'; import { remove } from 'lodash';
import { MINUTE } from '../../common/constants'; import { MINUTE } from '../../common/constants';
@@ -20,12 +20,16 @@ import { mergeAccounts } from '../api/merge';
import { findOrCreateAuth } from '../authUtils'; import { findOrCreateAuth } from '../authUtils';
import { getOriginFromHTTP, getOrigin, addOrigin } from '../originUtils'; import { getOriginFromHTTP, getOrigin, addOrigin } from '../originUtils';
import { Profile } from '../../common/interfaces'; import { Profile } from '../../common/interfaces';
import { Handler } from 'express';
interface MergeRequest { interface MergeRequest {
accountId: string; accountId: string;
time: number; time: number;
} }
type PassportAuth = passport.Authenticator<Handler, any, any, passport.AuthenticateOptions>
const FRESH_ACCOUNT_TIME = 1 * MINUTE; const FRESH_ACCOUNT_TIME = 1 * MINUTE;
const mergeRequests: MergeRequest[] = []; const mergeRequests: MergeRequest[] = [];
@@ -215,11 +219,11 @@ async function handleAuth(
} }
function createHandler( function createHandler(
server: ServerConfig, live: ServerLiveSettings, id: string, options: AuthenticateOptions, server: ServerConfig, live: ServerLiveSettings, id: string, options: passport.AuthenticateOptions,
removedDocument: RemovedDocument removedDocument: RemovedDocument, passport: PassportAuth
): RequestHandler { ): RequestHandler {
return (req, res, next) => { return (req, res, next) => {
const handler = authenticate(id, options, (error: Error | null, account: IAccount | null) => const handler = passport.authenticate(id, options, (error: Error | null, account: IAccount | null) =>
handleAuth(server, live, removedDocument, req, res, error, account)); handleAuth(server, live, removedDocument, req, res, error, account));
return handler(req, res, next); return handler(req, res, next);
@@ -228,7 +232,7 @@ function createHandler(
export function authRoutes( export function authRoutes(
host: string, server: ServerConfig, settings: Settings, live: ServerLiveSettings, mockLogin: boolean, host: string, server: ServerConfig, settings: Settings, live: ServerLiveSettings, mockLogin: boolean,
removedDocument: RemovedDocument removedDocument: RemovedDocument, passport: PassportAuth
) { ) {
const failureRedirect = `/?error=${encodeURIComponent('Authentication failed')}`; const failureRedirect = `/?error=${encodeURIComponent('Authentication failed')}`;
const app = Router(); const app = Router();
@@ -261,7 +265,7 @@ export function authRoutes(
return account; return account;
} }
use(id, new strategy(options, (req, _accessToken, _refreshToken, oauthProfile, callback) => { passport.use(id, new strategy(options, (req, _accessToken, _refreshToken, oauthProfile, callback) => {
const profile = getProfile(id, oauthProfile); const profile = getProfile(id, oauthProfile);
signInOrSignUp(req, profile) signInOrSignUp(req, profile)
@@ -274,8 +278,8 @@ export function authRoutes(
}); });
})); }));
app.get(`/${id}`, limit(120, 3600), createHandler(server, live, id, { scope, failureRedirect }, removedDocument)); app.get(`/${id}`, limit(120, 3600), createHandler(server, live, id, { scope, failureRedirect }, removedDocument, passport));
app.get(`/${id}/callback`, limit(120, 3600), createHandler(server, live, id, { failureRedirect }, removedDocument)); app.get(`/${id}/callback`, limit(120, 3600), createHandler(server, live, id, { failureRedirect }, removedDocument, passport));
app.get(`/${id}/merge`, limit(120, 3600), authRequest, (req, res) => { app.get(`/${id}/merge`, limit(120, 3600), authRequest, (req, res) => {
const accountId = (req.user as IAccount)._id.toString(); const accountId = (req.user as IAccount)._id.toString();
mergeRequests.push({ accountId, time: Date.now() }); mergeRequests.push({ accountId, time: Date.now() });
@@ -349,8 +353,8 @@ export function authRoutes(
return [account._id.toString(), account.name]; return [account._id.toString(), account.name];
})); }));
use(new LocalStrategy((login, _pass, done) => Account.findById(login, done))); passport.use(new LocalStrategy((login, _pass, done) => Account.findById(login, done)));
app.get('/local', authenticate('local', { successRedirect: '/', failureRedirect: '/failed-login' })); app.get('/local', passport.authenticate('local', { successRedirect: '/', failureRedirect: '/failed-login' }));
} }
return app; return app;
+3 -2
View File
@@ -8,7 +8,7 @@ import * as bodyParser from 'body-parser';
import * as expressSession from 'express-session'; import * as expressSession from 'express-session';
import * as serveFavicon from 'serve-favicon'; import * as serveFavicon from 'serve-favicon';
import * as Rollbar from 'rollbar'; import * as Rollbar from 'rollbar';
import * as passport from 'passport'; import { Passport } from 'passport';
import * as connectMongo from 'connect-mongo'; import * as connectMongo from 'connect-mongo';
import * as express from 'express'; import * as express from 'express';
import { WebSocketServer } from '@encharm/cws'; import { WebSocketServer } from '@encharm/cws';
@@ -83,6 +83,7 @@ const limit = !production || args.tools ? '100mb' : '100kb';
Bluebird.config({ warnings: false, longStackTraces: !production }); Bluebird.config({ warnings: false, longStackTraces: !production });
const passport = new Passport();
const rollbar = config.rollbar && Rollbar.init({ const rollbar = config.rollbar && Rollbar.init({
accessToken: config.rollbar.serverToken, accessToken: config.rollbar.serverToken,
environment: config.rollbar.environment, environment: config.rollbar.environment,
@@ -330,7 +331,7 @@ if (args.login) {
app.use('/assets-admin', ...adminMiddlewares(), express.static(adminAssetsPath, { maxAge, etag })); app.use('/assets-admin', ...adminMiddlewares(), express.static(adminAssetsPath, { maxAge, etag }));
app.use('/auth', ...sessionMiddlewares(), authRoutes( app.use('/auth', ...sessionMiddlewares(), authRoutes(
config.host, server, settings, liveSettings, args.local || DEVELOPMENT, removedDocument)); config.host, server, settings, liveSettings, args.local || DEVELOPMENT, removedDocument, passport));
app.use('/api', ...sessionMiddlewares(), api( app.use('/api', ...sessionMiddlewares(), api(
server, settings, { version, host: config.host, debug: DEVELOPMENT, local: !!args.local }, removedDocument)); server, settings, { version, host: config.host, debug: DEVELOPMENT, local: !!args.local }, removedDocument));
app.use('/api1', ...sessionMiddlewares(), api1(server, settings)); app.use('/api1', ...sessionMiddlewares(), api1(server, settings));