-
Notifications
You must be signed in to change notification settings - Fork 0
/
passport.js
125 lines (109 loc) · 3.03 KB
/
passport.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
const passport = require('passport');
const JwtStrategy = require('passport-jwt').Strategy;
const { ExtractJwt } = require('passport-jwt');
const LocalStrategy = require('passport-local').Strategy;
const FacebookTokenStrategy = require('passport-facebook-token');
const User = require('./models/User');
const {
facebookClientId,
facebookClientSecret,
jwtSecret,
adminEmails
} = require('./config');
// JSON WEB TOKEN STRATEGY
passport.use(
'jwt',
new JwtStrategy(
{
jwtFromRequest: ExtractJwt.fromHeader('authorization'),
secretOrKey: jwtSecret
},
async (payload, done) => {
try {
// Find user specified in token
const user = await User.findById(payload.user.id);
// If user not exists, handle it
if (!user) {
return done(null, false);
}
// Otherwise, return the user
done(null, user);
} catch (err) {
done(err, false);
}
}
)
);
// LOCAL STRATEGY
passport.use(
'local',
new LocalStrategy(
{
usernameField: 'email'
// session: false,
},
async (email, password, done) => {
try {
// Find the user with given email
const user = await User.findOne({ 'local.email': email });
if (!user) {
return done(null, false); // return Unautorized to the client
}
// Check if the password is correct
const isMatch = await user.isValidPassword(password);
if (!isMatch) {
return done(null, false); // return Unautorized to the client
}
// Otherwise return the user
done(null, user);
} catch (err) {
done(err, false);
}
}
)
);
passport.use(
'facebooktoken',
new FacebookTokenStrategy(
{
clientID: facebookClientId,
clientSecret: facebookClientSecret
},
async (accessToken, refreshToken, profile, done) => {
try {
const email = profile.emails[0].value;
let existingUser = await User.findOne({ 'facebook.id': profile.id });
if (existingUser) {
return done(null, existingUser);
}
// Check if we have someone with same email
existingUser = await User.findOne({
$or: [{ 'local.email': email }, { 'facebook.email': email }]
});
if (existingUser) {
// merge facebook's data with local auth
existingUser.methods = [...existingUser.methods, 'facebook'];
existingUser.facebook = {
id: profile.id,
email: email
};
await existingUser.save();
return done(null, existingUser);
}
const newUser = new User({
methods: 'facebook',
isAdmin: adminEmails.indexOf(profile.emails[0].value) !== -1,
name: profile._json.name,
facebook: {
id: profile.id,
email: profile.emails[0].value
}
});
await newUser.save();
return done(null, newUser);
} catch (err) {
done(err, false, err.message);
}
}
)
);