Skip to content

Instantly share code, notes, and snippets.

@alexanmtz
Created January 13, 2019 20:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alexanmtz/e2e8bb14120f67f47995b9bcbcf26efa to your computer and use it in GitHub Desktop.
Save alexanmtz/e2e8bb14120f67f47995b9bcbcf26efa to your computer and use it in GitHub Desktop.
Authentication with Node.js, Express, Sequelize, JWT and webtokens
const {
github
} = require('./secrets')
const passport = require('passport')
const gitHubStrategy = require('passport-github2').Strategy
const LocalStrategy = require('passport-local').Strategy
const passportJWT = require('passport-jwt')
const ExtractJWT = passportJWT.ExtractJwt
const JWTStrategy = passportJWT.Strategy
const jwt = require('jsonwebtoken')
const userExist = require('../modules/users').userExists
const userBuild = require('../modules/users').userBuilds
const userUpdate = require('../modules/users').userUpdate
passport.serializeUser((user, done) => {
done(null, user)
})
passport.deserializeUser((user, done) => {
userExist(user).then(user => {
done(null, user)
})
})
passport.use(
new gitHubStrategy(
{
clientID: github.id,
clientSecret: github.secret,
callbackURL: oauthCallbacks.githubCallbackUrl,
scope: ['user:email']
},
(accessToken, accessTokenSecret, profile, done) => {
process.nextTick(() => {
const data = {
provider: profile.provider
email: profile.emails[0].value
}
if (!data.email) {
return done(null)
}
userExist(data).then(user => {
const token = jwt.sign(
{ email: data.email },
process.env.SECRET_PHRASE
)
data.token = token
return done(null, data)
})
})
}
)
)
passport.use(
new LocalStrategy(
{
usernameField: 'email',
passwordField: 'password'
},
(email, password, done) => {
process.nextTick(_ => {
const userAttributes = {
email: email
}
userExist(userAttributes)
.then(user => {
if (!user) return done(null, false)
if (user.verifyPassword(password, user.password)) {
const token = jwt.sign(
{ email: user.email },
process.env.SECRET_PHRASE
)
user.token = token
return done(null, user)
}
return done(null, false)
})
.catch(error => {
return done(error)
})
})
}
)
)
passport.use(new JWTStrategy({
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.SECRET_PHRASE
},
(jwtPayload, done) => {
process.nextTick(_ => {
const userAttributes = {
email: jwtPayload.email
}
userExist(userAttributes)
.then(user => {
if (!user) return done(null, false)
return done(null, user)
})
.catch(error => {
return done(error)
})
})
}
))
@slidenerd
Copy link

why did you use process.nextTick?

@alexanmtz
Copy link
Author

@slidenerd I think with nextTick we forward the request so it can be used for other middlewares/routes in other parts of the code which adds logic to this route.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment