Last active
March 11, 2021 03:06
-
-
Save ArVan/a8eb2bff9e453a1850d17dd3af1d0bea to your computer and use it in GitHub Desktop.
JWT Authentication with Passport
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var path = require('path'); | |
var favicon = require('serve-favicon'); | |
var logger = require('morgan'); | |
var cookieParser = require('cookie-parser'); | |
var bodyParser = require('body-parser'); | |
var index = require('./routes/index'); | |
var user = require('./routes/user'); | |
var auth = require('./routes/auth'); | |
const passport = require('passport'); | |
require('./passport'); | |
var app = express(); | |
// view engine setup | |
app.set('views', path.join(__dirname, 'views')); | |
app.set('view engine', 'pug'); | |
// uncomment after placing your favicon in /public | |
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); | |
app.use(logger('dev')); | |
app.use(bodyParser.json()); | |
app.use(bodyParser.urlencoded({ extended: false })); | |
app.use(cookieParser()); | |
app.use(express.static(path.join(__dirname, 'public'))); | |
app.use('/', index); | |
app.use('/user', passport.authenticate('jwt', {session: false}), user); | |
app.use('/auth', auth); | |
// catch 404 and forward to error handler | |
app.use(function(req, res, next) { | |
var err = new Error('Not Found'); | |
err.status = 404; | |
next(err); | |
}); | |
// error handler | |
app.use(function(err, req, res, next) { | |
// set locals, only providing error in development | |
res.locals.message = err.message; | |
res.locals.error = req.app.get('env') === 'development' ? err : {}; | |
// render the error page | |
res.status(err.status || 500); | |
res.render('error'); | |
}); | |
module.exports = app; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const router = express.Router(); | |
const jwt = require('jsonwebtoken'); | |
const passport = require('passport'); | |
/* POST login. */ | |
router.post('/login', function (req, res, next) { | |
passport.authenticate('local', {session: false}, (err, user, info) => { | |
console.log(err); | |
if (err || !user) { | |
return res.status(400).json({ | |
message: info ? info.message : 'Login failed', | |
user : user | |
}); | |
} | |
req.login(user, {session: false}, (err) => { | |
if (err) { | |
res.send(err); | |
} | |
const token = jwt.sign(user 'your_jwt_secret'); | |
return res.json({user, token}); | |
}); | |
}) | |
(req, res); | |
}); | |
module.exports = router; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const passport = require('passport'); | |
const passportJWT = require("passport-jwt"); | |
const ExtractJWT = passportJWT.ExtractJwt; | |
const LocalStrategy = require('passport-local').Strategy; | |
const JWTStrategy = passportJWT.Strategy; | |
passport.use(new LocalStrategy({ | |
usernameField: 'email', | |
passwordField: 'password' | |
}, | |
function (email, password, cb) { | |
//Assume there is a DB module pproviding a global UserModel | |
return UserModel.findOne({email, password}) | |
.then(user => { | |
if (!user) { | |
return cb(null, false, {message: 'Incorrect email or password.'}); | |
} | |
return cb(null, user, { | |
message: 'Logged In Successfully' | |
}); | |
}) | |
.catch(err => { | |
return cb(err); | |
}); | |
} | |
)); | |
passport.use(new JWTStrategy({ | |
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(), | |
secretOrKey : 'your_jwt_secret' | |
}, | |
function (jwtPayload, cb) { | |
//find the user in db if needed | |
return UserModel.findOneById(jwtPayload.id) | |
.then(user => { | |
return cb(null, user); | |
}) | |
.catch(err => { | |
return cb(err); | |
}); | |
} | |
)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var router = express.Router(); | |
/* GET users listing. */ | |
router.get('/', function(req, res, next) { | |
res.send('respond with a resource'); | |
}); | |
/* GET user profile. */ | |
router.get('/profile', function(req, res, next) { | |
res.send(req.user); | |
}); | |
module.exports = router; |
user.js:
var express = require('express');
var router = express.Router();
Should become const
for consistency with the introduction, right?
which port for app run ???
https://gist.github.com/ArVan/a8eb2bff9e453a1850d17dd3af1d0bea#file-auth-js-L25 do you miss a comma here?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
are these the only files that should be there?
index.js, /public, /views
above listed files and folders arent available