Skip to content

Instantly share code, notes, and snippets.

@FBosler
Last active December 15, 2020 18:00
Show Gist options
  • Save FBosler/30c30b67c59e50fa79f36840cffc1b4b to your computer and use it in GitHub Desktop.
Save FBosler/30c30b67c59e50fa79f36840cffc1b4b to your computer and use it in GitHub Desktop.
Backend redirect
#CANONICAL-URL
FRONT_END_URL=http://localhost:3000
DOMAIN=localhost
...
#OTHER STUFF
const conf = require('../../config/config');
// auth routers
router.get('/:provider', (req, res, next) => {
passport.authenticate(provider, options)(req, res, next);
});
// callbacks
router.get('/:provider/callback', (req, res, next) => {
passport.authenticate(req.params.provider, function (err, user, info) {
// YOUR CODE
req.logIn(user, { session: false }, function (err) {
if (err) {
// DO ERROR
}
const token = signToken(user);
return res
.status(200)
.cookie('jwt', token, { httpOnly: true, domain: conf.DOMAIN })
.redirect(redirectUponLogin(state.referer, flowId));
});
})(req, res, next);
});
const dotenv = require('dotenv');
if (process.env.NODE_ENV === 'production') {
dotenv.config({ path: '../.env' });
} else {
dotenv.config({ path: '../.env.dev' });
}
const generateCallbackURL = (provider) => {
return `${conf.FRONT_END_URL}/api/auth/${provider}/callback`
}
// Google Strategy
passport.use(
new GoogleStrategy(
{
clientID: credentials.GOOGLE.client_id,
clientSecret: credentials.GOOGLE.client_secret,
callbackURL: generateCallbackURL('google'),
passReqToCallback: true,
},
(req, accessToken, refreshToken, profile, done) => {
const email = profile.emails.filter((email) => email.verified)[0].value
findByEmailOrCreate(email, req, profile, done)
}
)
)
// Facebook Strategy
passport.use(
new FacebookStrategy(
{
clientID: credentials.FACEBOOK.client_id,
clientSecret: credentials.FACEBOOK.client_secret,
callbackURL: generateCallbackURL('facebook'),
passReqToCallback: true,
profileFields: [
'id',
'email',
'gender',
'link',
'locale',
'name',
'displayName',
'timezone',
'updated_time',
'verified',
],
},
function (req, accessToken, refreshToken, profile, done) {
const email = profile.emails[0].value
findByEmailOrCreate(email, req, profile, done)
}
)
)
//Other strategies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment