forked from ayubSubhaniya/ssrs-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
passport.js
73 lines (63 loc) · 2.06 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
const passport = require('passport');
const JwtStrategy = require('passport-jwt').Strategy;
const LocalStrategy = require('passport-local').Strategy;
const { JWT_SECRET, validityErrors, userTypes, adminTypes } = require('./configuration');
const User = require('./models/user');
const UserInfo = require('./models/userInfo');
//JSON WEB TOKEN STRATEGY
passport.use(new JwtStrategy({
jwtFromRequest: req => req.cookies.jwt,
secretOrKey: JWT_SECRET,
passReqToCallback: true
}, async (req, payload, done) => {
try {
//find the user specified in token
const user = await User.findOne({ daiictId: payload.sub })
.populate('userInfo');
if (user.userType!=="superAdmin"){
if (user.userInfo.user_type === "STUDENT"){
user.userType = userTypes.student;
} else{
user.userType = adminTypes.admin;
}
}
//user.userType = userInfo.user_type;
//if user doesn't exist handle it
if (!user) {
return done(null, false, { message: validityErrors.invalidToken });
}
//token expired
if (payload.exp < Date.now()) {
return done(null, false, { message: validityErrors.sessionExpired });
}
req['user'] = user;
//Otherwise, return the user
done(null, user);
} catch (error) {
done(error, false);
}
}));
//LOCAL STRATEGY
passport.use(new LocalStrategy({
usernameField: 'daiictId',
}, async (daiictId, password, done) => {
try {
//find the user with given email
const user = await User.findOne({ daiictId })
.populate('userInfo');
//if not handle it
if (!user) {
return done(null, false);
}
//check if the password is correct
const isMatch = await user.isValid(password);
//if not handle it
if (!isMatch) {
return done(null, false);
}
//otherwise return user
done(null, user);
} catch (error) {
done(error, false);
}
}));