Skip to content

Commit

Permalink
BE #2 user login using JWT
Browse files Browse the repository at this point in the history
  • Loading branch information
tito433 committed May 8, 2020
1 parent 44b5b9c commit 62471a0
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 2 deletions.
42 changes: 42 additions & 0 deletions authenticate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
var passport = require('passport');
var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens

var config = require('./config.js');


var LocalStrategy = require('passport-local').Strategy;
var User = require('./models/user');

exports.local=passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

exports.getToken = function(user) {
return jwt.sign(user, config.secretKey,
{expiresIn: 3600});
};

var opts = {
jwtFromRequest : ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey : config.secretKey
};


exports.jwtPassport = passport.use(new JwtStrategy(opts,
(jwt_payload, done) => {
User.findOne({_id: jwt_payload._id}, (err, user) => {
if (err) {
return done(err, false);
}
else if (user) {
return done(null, user);
}
else {
return done(null, false);
}
});
}));

exports.verifyUser = passport.authenticate('jwt', {session: false});
20 changes: 18 additions & 2 deletions routes/users.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
var express = require('express');
var User =require('../models/user');
var passport = require('passport');
var authenticate = require('../authenticate');

var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
router.get('/',authenticate.verifyUser, function(req, res, next) {
User.find({})
.then((users)=>{
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(users);
}, (err) => next(err))
.catch((err) => next(err));
});

router.post('/signup', (req, res, next) => {
Expand Down Expand Up @@ -39,4 +47,12 @@ router.post('/signup', (req, res, next) => {
});
});

router.post('/login', passport.authenticate('local'), (req, res) => {

var token = authenticate.getToken({_id: req.user._id});
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({success: true, token: token, status: 'You are successfully logged in!'});
});

module.exports = router;

0 comments on commit 62471a0

Please sign in to comment.