-
Notifications
You must be signed in to change notification settings - Fork 0
/
authenticate.js
53 lines (43 loc) · 1.6 KB
/
authenticate.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
const passport = require('passport');
const localStrategy = require('passport-local').Strategy;
const User = require('./models/user');
const jwtStrategy = require('passport-jwt').Strategy;
const jwt = require('jsonwebtoken');
const config = require('./config');
const ExtractToken = require('passport-jwt').ExtractJwt;
exports.local = passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser()); // this will fulfile support for session in user
passport.deserializeUser(User.deserializeUser()); // this will add user in req obj req.user
module.exports.getToken = function(user){
return jwt.sign(user,config.secretKey,{expiresIn:3600});
}
var options = {}
options.jwtFromRequest = ExtractToken.fromAuthHeaderAsBearerToken();
options.secretOrKey = config.secretKey;
module.exports.jwtPassport = passport.use(new jwtStrategy(options,(jwt_payload,done) => {
console.log('Jwt Payload is : ',jwt_payload);
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);
}
});
}));
module.exports.verifyUser = passport.authenticate('jwt',{session:false});
module.exports.verifyAdmin = (req,res,next) => {
if(req.user.admin === true){
res.statusCode = 200;
res.setHeader("Content_Type","application/json");
next();
}
else{
err = new Error("You are Unauthorize to Perform This Operation ")
err.status = 403
return next(err);
}
}