import passport from 'passport' import { AUTH_CONFIG, StrategyMap, StrategyConfig } from '../utils/auth' import { buildQueryString} from '../utils/qs' export const createAuthPaths = ({ app }) => { Object.keys(StrategyMap).map((strategyName: string) => { const strategyConfig: StrategyConfig = AUTH_CONFIG.strategies[strategyName] passport.use( new StrategyMap[strategyName]( { ...strategyConfig, callbackURL: `/auth-${strategyName}-callback`, passReqToCallback: true, }, async (request, token, refreshToken, params, profile, done) => { const result = { token, refreshToken, profile, tokenType: params.token_type, idToken: params.id_token, expiresIn: params.expires_in, } await AUTH_CONFIG.onSuccess?.({ request, ...result }) return done(null, result) }, ), ) app.get(`/auth-${strategyName}`, (req, res) =>{ const authenticate = passport.authenticate( strategyName, { scope: strategyConfig.scope, state: req.query.state } ) return authenticate(req, res) }) app.get(`/auth-${strategyName}-callback`, (req, res) =>{ const state = req.query.state const authenticate = passport.authenticate( strategyName, {}, (error, result) => { if (error) { res.status(400) res.send(error) } else { res.redirect( `${AUTH_CONFIG.callbackURL}?${buildQueryString({ data: result, state })}`, ) } } ) return authenticate(req, res) }) }) }