-
Notifications
You must be signed in to change notification settings - Fork 0
/
authenticate.js
88 lines (76 loc) · 2.72 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require('./models/user');
//used with JWT
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const jwt = require('jsonwebtoken');
const FacebookTokenStrategy = require('passport-facebook-token');
const config = require('./config.js');
//If were not using passport-local-mongoose, we would have to pass in another argument
exports.local = passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
exports.getToken = user => {
return jwt.sign(user, config.secretKey, {expiresIn: 3600});
};
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = config.secretKey;
exports.jwtPassport = passport.use(
new JwtStrategy(
opts,
(jwt_payload, done) => {
console.log('JWT payload:', 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);
}
});
}
)
);
exports.verifyUser = passport.authenticate('jwt', {session: false});
exports.verifyAdmin = (req, res, next) => {
if (!req.user.admin) {
return next();
} else {
err = new Error("You are not authorized to perform this operation!");
err.status = 403;
return next(err);
}
}
exports.facebookPassport = passport.use(
new FacebookTokenStrategy(
{
clientID: config.facebook.clientId,
clientSecret: config.facebook.clientSecret
},
(accessToken, refreshToken, profile, done) => {
User.findOne({facebookId: profile.id}, (err, user) => {
if (err) {
return done(err, false);
}
if (!err && user) {
return done(null, user);
} else {
user = new User({ username: profile.displayName });
user.facebookId = profile.id;
user.firstname = profile.name.givenName;
user.lastname = profile.name.familyName;
user.save((err, user) => {
if (err) {
return done(err, false);
} else {
return done(null, user);
}
});
}
});
}
)
);