-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata-service-auth.js
103 lines (93 loc) · 3.31 KB
/
data-service-auth.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
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
const bcrypt = require('bcryptjs');
var User;
var userSchema = new Schema({
"userName": {
type: String,
unique: true
},
"password": String,
"email": String,
"loginHistory": [{
"dateTime": Date,
"userAgent": String
}]
})
exports.initialize = function(){
return new Promise(function(resolve, reject){
let tempConnection = mongoose.createConnection(`mongodb+srv://liamhutch:fatratcat@btiassignment6.cbrbjgz.mongodb.net/test`);
tempConnection.on('error', function(err){
reject("Error: could not connect to mongodb");
})
tempConnection.once('open', function(){
User = tempConnection.model("users", userSchema);
resolve();
})
});
}
exports.registerUser = function(userData){
console.log("called registerUser");
console.log(userData);
return new Promise(function(resolve, reject){
if(userData.password != userData.password2){
console.log("error1");
reject("Error: Passwords do not match");
}
else if (userData.password == "" || userData.password2 == "" || userData.password.trim() == "" || userData.password2.trim() == ""){
console.log("error2");
reject("Error: user name cannot be empty or only white spaces!");
}
else{
var newUser = new User(userData);
newUser.save().then(()=>{
resolve();
}).catch(err=>{
if(err.code == 11000){
console.log("error3");
reject("User Name already taken");
}
else{
console.log("error4");
console.log(err);
reject("There was an error creating the user: " + err);
}
});
}
});
}
exports.checkUser = function(userData){
return new Promise(function(resolve, reject){
User.findOne({ userName: userData.userName })
.exec()
.then((foundUser) => {
if(!foundUser){
console.log("error 6");
reject("Unable to find user: " + userData.userName);
}
else{
if(foundUser.password != userData.password){
console.log("error 7");
reject("Incorrect Password for user: " + userData.userName);
}
else{
foundUser.loginHistory.push({dateTime: (new Date()).toString(), userAgent: userData.userAgent});
User.updateOne(
{ userName: foundUser.userName},
{ $set: { loginHistory: foundUser.loginHistory } }
).exec()
.then(()=>{
resolve(foundUser);
})
.catch(err=>{
reject("There was an error verifying the user: " + err);
})
}
}
})
.catch(err=>{
console.log("error 8");
reject("Unable to find user: " + userData.userName);
})
});
}