-
Notifications
You must be signed in to change notification settings - Fork 0
/
passport.js
111 lines (103 loc) · 3.42 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
//Import Passport
const passport = require("passport");
//Import LocalStrategy module
const LocalStrategy = require("passport-local").Strategy;
const bcrypt = require('bcryptjs');
const models = require('./models/mongo');
//Serialize user
passport.serializeUser(function (userKey, done) {
done(null, userKey);
});
//De-Serialize User
passport.deserializeUser(function (userKey, done) {
switch (userKey.type) {
case 'company':
models.company.findOne({
_id: userKey.userId
}).then((company) => {
done(null, company);
}).catch((Err) => {
console.log(Err);
}); break;
case 'manager':
models.manager.findOne({
_id: userKey.userId
}).then((manager) => {
done(null, manager);
}).catch((Err) => {
console.log(Err);
}); break;
case 'employee':
models.employee.findOne({
_id: userKey.userId
}).then((employee) => {
done(null, employee);
}).catch((Err) => {
console.log(Err);
}); break;
default: console.log("default");
}
});
//User "localstrategy" at "local"
passport.use('local-company',new LocalStrategy( function (username, password, done) {
models.company.findOne({username:username})
.then((company)=>{
if(!company) console.log(" company does not exists");
else {
bcrypt.compare(password,company.password).then((res)=>{
if(res){
let userKey={
type:'company',
userId:company._id
};
return done(null,userKey);
}else
{
console.log("password incorrect");
}
})
}
})
}));
passport.use('local-manager',new LocalStrategy( function (username, password, done) {
models.manager.findOne({username:username})
.then((manager)=>{
if(!manager) console.log(" manager does not exists");
else {
bcrypt.compare(password,manager.password).then((res)=>{
if(res){
let userKey={
type:'manager',
userId:manager._id
};
return done(null,userKey);
}else
{
console.log("password incorrect");
}
})
}
})
}));
passport.use('local-employee',new LocalStrategy( function (username, password, done) {
models.employee.findOne({username:username})
.then((employee)=>{
if(!employee) console.log(" employee does not exists");
else {
bcrypt.compare(password,employee.password).then((res)=>{
if(res){
let userKey={
type:'employee',
userId:employee._id
};
return done(null,userKey);
}else
{
console.log("password incorrect");
}
})
}
})
}));
//Expose passport to be used in server.js
module.exports = passport;