forked from Celesta-IITP/Celesta20Backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
passport.js
72 lines (62 loc) · 1.7 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
const passport = require('passport');
const JwtStrategy = require('passport-jwt').Strategy;
const {
ExtractJwt
} = require('passport-jwt');
const LocalStrategy = require('passport-local').Strategy;
const {
JWT_SECRET
} = require('./configs/config');
const { User } = require('./models/user')
//JSON WEB TOKENS STRATEGY
passport.use(new JwtStrategy({
jwtFromRequest: ExtractJwt.fromHeader('authorization'),
secretOrKey: JWT_SECRET
}, async (payload, done) => {
try {
//find the user specified in token
const user = await User.findById(payload.sub)
//if user doesn't exist handle it
if (!user) {
return done({
message: 'Unauthorized user',
status: 401
}, false);
}
//otherwise return the user
done(null, user);
} catch (error) {
done(error, false);
}
}));
//LOCAL STRATEGY
passport.use(new LocalStrategy({
usernameField: 'email'
}, async (email, password, done) => {
try {
//find the user given the email
const user = await User.findOne({
email: email
});
//if not handle it
if (!user) {
return done({
message: 'User not found',
status: 404
}, false, );
}
//check if the password is correct
const isMatch = await user.isValidPassword(password)
//if not, handle it
if (!isMatch) {
return done({
message: 'Wrong Password',
status: 415
}, false);
}
//otherwise return the user
done(null, user);
} catch (error) {
done(error, false);
}
}))