forked from soo-utem/benr2423-week07
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.js
115 lines (105 loc) · 2.76 KB
/
user.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
const bcrypt = require("bcrypt");
const { mongoConnection } = require("./connection");
users = await conn.db("my-database-name").collection("users")
/**
* @addUser
*/
function register(userData) {
return new Promise(async (resolve, reject) => {
try {
// check if user does not exists
let checkUserData = await checkIfUserExists({ email: userData.email });
if (checkUserData.data && checkUserData.data.length > 0) {
// user already exists, send response
return resolve({
error: true,
message: "User already exists with this credentials. Please login",
data: [],
});
}
// generate password hash
let passwordHash = await bcrypt.hash(userData.password, 15);
userData.password = passwordHash;
// add new user
mongoConnection
.collection("users")
.insertOne(userData, async (err, results) => {
if (err) {
console.log(err);
throw new Error(err);
}
//return data
resolve({
error: false,
data: results.ops[0],
});
});
} catch (e) {
reject(e);
}
});
}
/**
* @verifyUser
* @param {*} userData
*/
function login(userData) {
return new Promise(async (resolve, reject) => {
try {
let userDatafromDb = await checkIfUserExists({ email: userData.email });
if (userDatafromDb.data && userDatafromDb.data.length > 0) {
// user already exists, verify the password
let passwordVerification = await bcrypt.compare(
userData.password,
userDatafromDb.data[0].password
);
if (!passwordVerification) {
// password mismatch
return resolve({
error: true,
message: "Invalid email or password",
data: [],
});
}
// password verified
return resolve({ error: false, data: userDatafromDb.data[0] });
} else {
return resolve({
error: true,
message:
"There is no user exists with this credentials. Please create a new account.",
data: [],
});
}
} catch (e) {
console.log(e);
reject(e);
}
});
}
/**
* @checkIfUserExists
*/
function checkIfUserExists(userData) {
return new Promise((resolve, reject) => {
try {
// check if user exists
mongoConnection
.collection("users")
.find({ email: userData.email })
.toArray((err, results) => {
if (err) {
console.log(err);
throw new Error(err);
}
resolve({ error: false, data: results });
});
} catch (e) {
reject(e);
}
});
}
module.exports = {
register: register,
login: login,
};