Reputation: 1395
I've been trying this for quite a while, but I just can't seem to get a hang of how this works.
I have a passport.ts
file which roughly is defined as:
passport.serializeUser<any, any>((user, done) => {
done(undefined, 1);
});
passport.deserializeUser((id, done) => {
done(null, 1);
});
// Strategy config
const GoogleStrategy = passportGoogle.Strategy
passport.use(new GoogleStrategy({
clientID: config.get('googleAuth.clientID'),
clientSecret: config.get('googleAuth.clientSecret'),
callbackURL: config.get('googleAuth.callbackURL'),
passReqToCallback: true
}, async (accessToken, refreshToken, profile, done)=> {
return done
}))
In the root directory of the project, I have an index.ts
which does the standard passport initialization:
app.use(passport.initialize());
app.use(passport.session());
I'm defining controllers via express's Router function in different files, one of which is authenticate.ts
which is roughly along these lines:
import {Router} from 'express';
import passport from 'passport';
import config from 'config';
import * as passportConfig from '../utils/passport' //this is passport.ts which was pasted above
const router = Router();
router.get('/google', passport.authenticate('google', {scope: config.get('googleAuth.scope')}));
I understand that I am missing the callback route, but I had issues making this work as I am unsure as to how the passport object defined in passport.ts with the strategy can be used in different files.
Any help would be great!
Upvotes: 0
Views: 1805
Reputation: 1261
as far as I understood, you want to define your passport strategy in a separate file and use them. For that you can do something like this
Create a file to define your strategy google-strategy.ts
const googleStrategy = new GoogleStrategy({
clientID: config.get('googleAuth.clientID'),
clientSecret: config.get('googleAuth.clientSecret'),
callbackURL: config.get('googleAuth.callbackURL'),
passReqToCallback: true
}, async (accessToken, refreshToken, profile, done)=> {
return done
})
module.exports = googleStrategy;
and in your passport.ts
file
const googleStrategy = require('./google-strategy');
// giving a name to a strategy so we can refer it in routes
passport.use('MyGoogleStrategy', googleStrategy);
and in your authenticate.ts
file
router.get('/google', passport.authenticate('MyGoogleStrategy', {scope: config.get('googleAuth.scope')}));
hope this helps!
Upvotes: 1