From e358f7fc976a7eff3f3521fed32baf5fce72eaf9 Mon Sep 17 00:00:00 2001 From: "Navy.gif" Date: Wed, 9 Nov 2022 21:04:52 +0200 Subject: [PATCH] getters for bound functions --- src/server/middleware/Authenticator.js | 39 ++++++++++++-------------- 1 file changed, 18 insertions(+), 21 deletions(-) diff --git a/src/server/middleware/Authenticator.js b/src/server/middleware/Authenticator.js index 26b0c5f..cdea9bd 100644 --- a/src/server/middleware/Authenticator.js +++ b/src/server/middleware/Authenticator.js @@ -49,23 +49,22 @@ class Authenticator { saveUninitialized: true })); - server.app.use(Passport.initialize()); - server.app.use(Passport.session()); + this.passport = Passport; + server.app.use(this.passport.initialize()); + server.app.use(this.passport.session()); - Passport.serializeUser((user, callback) => { - this.logger.debug(`Serialising ${user.name} (${user.id})`); + this.passport.serializeUser((user, callback) => { callback(null, user.id); }); - Passport.deserializeUser(async (id, callback) => { - this.logger.debug(`Deserialising ${id}`); + this.passport.deserializeUser(async (id, callback) => { const user = await this.userdb.fetchUser(id); callback(null, user); }); // TODO: Should probably allow injection of strategies instead of hardcoding this this through a function - Passport.use('discord', new Strategy({ - clientID: discordID, clientSecret: discordSecret, callbackURL, scope: discordScope, version: discordVersion + this.passport.use('discord', new Strategy({ + clientID: discordID, clientSecret: discordSecret, callbackURL: callbackURL + '/discord', scope: discordScope, version: discordVersion }, async (accessToken, refreshToken, profile, callback) => { this.logger.info(`${profile.username} (${profile.id}) is logging in.`); const user = await this.userdb.userFromDiscord(profile); @@ -74,29 +73,27 @@ class Authenticator { } - // For API requests, does not redirect to a login page - async _auth (req, res, next) { - - this.logger.debug('Non-redirect auth'); - if (await this._authenticate(req, res)) return next(); - - } - + // Getters for bound functions to avoid having to bind them elsewhere get authenticate () { return this._auth.bind(this); } + get authenticateRedirect () { + return this._authenticateRedirect.bind(this); + } + + // For API requests, does not redirect to a login page + async _auth (req, res, next) { + if (await this._authenticate(req, res)) return next(); + } + // Meant for non-api paths _authenticateRedirect (req, res, next) { this.logger.debug('Redirected auth'); if (!req.isAuthenticated()) return res.redirect('/login'); next(); } - - get authenticateRedirect () { - return this._authenticateRedirect.bind(this); - } - + async _authenticate (req, res) { if (req.isAuthenticated()) return true;