-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser-service.js
92 lines (80 loc) · 2.33 KB
/
user-service.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
const mongoose = require('mongoose')
const bcrypt = require('bcryptjs')
let mongoDBConnectionString =
'mongodb+srv://rroldan:[email protected]/?retryWrites=true&w=majority'
let Schema = mongoose.Schema
let userSchema = new Schema({
userName: {
type: String,
unique: true,
},
password: String,
fullName: String,
role: String,
})
let User
module.exports.connect = function () {
return new Promise(function (resolve, reject) {
let db = mongoose.createConnection(mongoDBConnectionString, {
useNewUrlParser: true,
})
db.on('error', (err) => {
reject(err) // reject the promise with the provided error
})
db.once('open', () => {
User = db.model('users', userSchema)
resolve()
})
})
}
module.exports.registerUser = function (userData) {
return new Promise(function (resolve, reject) {
if (userData.password != userData.password2) {
reject('Passwords do not match')
} else {
bcrypt
.hash(userData.password, 10)
.then((hash) => {
// Hash the password using a Salt that was generated using 10 rounds
userData.password = hash
let newUser = new User(userData)
newUser
.save()
.then(() => {
resolve('User ' + userData.userName + ' successfully registered')
})
.catch((err) => {
if (err.code == 11000) {
reject('User Name already taken')
} else {
reject('There was an error creating the user: ' + err)
}
})
})
.catch((err) => reject(err))
}
})
}
module.exports.checkUser = function (userData) {
return new Promise(function (resolve, reject) {
User.find({ userName: userData.userName })
.limit(1)
.exec()
.then((users) => {
if (users.length == 0) {
reject('Unable to find user ' + userData.userName)
} else {
bcrypt.compare(userData.password, users[0].password).then((res) => {
if (res === true) {
resolve(users[0])
} else {
reject('Incorrect password for user ' + userData.userName)
}
})
}
})
.catch((err) => {
reject('Unable to find user ' + userData.userName)
})
})
}