Skip to content

Commit 24e30da

Browse files
committed
Fix create, update and login user
1 parent 8221a5c commit 24e30da

File tree

5 files changed

+46
-39
lines changed

5 files changed

+46
-39
lines changed

app.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,10 @@ Object.keys(routes).forEach(routeName => {
2727
})
2828

2929
app.use('*', (req, res) => {
30-
res.send('Its Ok :D')
30+
res.status(404).json({ message: 'Route not found', status: 404 })
3131
})
3232

33+
3334
const listen = () => {
3435
logs(`Database connected at ${connectionURI}`)
3536
app.listen(PORT, () => {

controllers/Auth.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,16 @@ class Auth {
1313
}
1414
try {
1515
let user = await UserModel.findByCredentials(req.body.email, req.body.password)
16-
if (user) {
17-
logs(`Logged user ${user.email}`)
16+
if (user && user._id) {
17+
logs(`Logged user [${user.email}]`)
1818
let token = jwt.sign({
1919
_id: user._id,
2020
expires: moment().add(7, 'days').valueOf()
2121
}, secret)
2222
res.json({ token })
2323
}
2424
} catch (e) {
25-
logs(`Error on login. ${e.message}`)
25+
logs(`Error on login [${e.message}]`)
2626
res.status(httpStatus.UNAUTHORIZED).json({
2727
message: e.message,
2828
status: httpStatus.UNAUTHORIZED

controllers/User.js

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ const mongoose = require('mongoose')
22
const UserModel = mongoose.model('User')
33
const logs = require('../helpers/logs')
44
const httpStatus = require('../helpers/httpStatus')
5-
5+
const bcrypt = require('bcryptjs')
66
class User {
77
create (req, res) {
88
if (!req.body) {
@@ -12,17 +12,17 @@ class User {
1212
try {
1313
UserModel.create(user, (err, created) => {
1414
if (err) {
15-
logs(`Error on create user ${user.email}. Error: ..:: ${err.message} ::..`, 'error')
15+
logs(`Error on create user [${user.email}]. Error: ..:: ${err.message} ::..`, 'error')
1616
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
1717
status: httpStatus.INTERNAL_SERVER_ERROR,
1818
error: err.message
1919
})
2020
}
21-
logs(`Created user ${created}`)
22-
res.status(httpStatus.CREATED).send(created)
21+
logs(`Created user [${created._id}]`)
22+
res.status(httpStatus.CREATED).json(created)
2323
})
2424
} catch (e) {
25-
logs(`Error on create user ${user.email}. Error: ..:: ${e.message} ::..`, 'error')
25+
logs(`Error on create user [${user.email}]. Error: ..:: ${e.message} ::..`, 'error')
2626
res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
2727
status: httpStatus.INTERNAL_SERVER_ERROR,
2828
error: e.message
@@ -38,21 +38,25 @@ class User {
3838
age: newData.age || userData.age,
3939
}
4040
if (newData.password) {
41-
updateObj.password = newData.password
41+
const salt = bcrypt.genSaltSync(10)
42+
const hash = bcrypt.hashSync(newData.password, salt)
43+
updateObj.password = hash
4244
}
43-
UserModel.findByIdAndUpdate(userData._id, updateObj, { lean: true }, function (err, updated) {
45+
updateObj.updated_at = new Date().getTime()
46+
UserModel.findByIdAndUpdate(userData._id, updateObj, function (err, updated) {
4447
if (err) {
45-
logs(`Error on findAndupdate user ${userData.email}. Error: ..:: ${err} ::..`, 'error')
48+
logs(`Error on findAndupdate user [${userData.email}]. Error: ..:: ${err} ::..`, 'error')
4649
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
4750
status: httpStatus.INTERNAL_SERVER_ERROR,
4851
error: err
4952
})
5053
}
51-
logs(`Updated user ${updated.email}`)
52-
return res.json(updated)
54+
UserModel.findById(updated._id, (err, user) => {
55+
return res.json(user)
56+
})
5357
})
5458
} catch (e) {
55-
logs(`Error on update user ${userData.email}. Error: ..:: ${e.message} ::..`, 'error')
59+
logs(`Error on update user [${userData.email}]. Error: ..:: ${e.message} ::..`, 'error')
5660
res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
5761
status: httpStatus.INTERNAL_SERVER_ERROR,
5862
error: e.message

middlewares/auth.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,8 @@ const auth = async (req, res, next) => {
1313
let token = req.headers.authorization
1414
try {
1515
let user = await UserModel.findByToken(token)
16-
logs('User id finded ' + user._id)
1716
if (user) {
18-
req.user = user
17+
req.user = user.toJSON()
1918
next()
2019
} else {
2120
return res.status(httpStatus.NO_CONTENT).json({
@@ -24,7 +23,7 @@ const auth = async (req, res, next) => {
2423
})
2524
}
2625
} catch (e) {
27-
logs('Error :' + e)
26+
logs(`Error [${e}]`)
2827
return res.status(httpStatus.NO_CONTENT).json({
2928
status: httpStatus.NO_CONTENT,
3029
message: e

models/User.js

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -64,12 +64,10 @@ UserSchema.pre('save', function (next) {
6464
user.updated_at = new Date().getTime()
6565

6666
if(user.isModified('password')) {
67-
bcrypt.genSalt(10, (err, salt) => {
68-
bcrypt.hash(user.password, salt, (err, hash) => {
69-
user.password = hash
70-
next()
71-
})
72-
})
67+
const salt = bcrypt.genSaltSync(10)
68+
const hash = bcrypt.hashSync(user.password, salt)
69+
user.password = hash
70+
next()
7371
} else {
7472
next()
7573
}
@@ -84,28 +82,33 @@ UserSchema.pre('update', function (next) {
8482
UserSchema.methods.toJSON = function () {
8583
const user = this
8684
const userObject = user.toObject()
87-
console.log(returnFilter(userObject))
8885
return returnFilter(userObject)
8986
}
9087

9188
UserSchema.statics.returnFilter = returnFilter
9289

9390
UserSchema.statics.findByCredentials = async function (email, password) {
9491
const user = this
95-
const doc = await user.findOne({ email })
96-
return new Promise((resolve, reject) => {
97-
if(!doc) {
98-
return reject({ status: 404, message: 'Invalid credentials'})
92+
return new Promise(async (resolve, reject) => {
93+
try {
94+
user.findOne({ email }, (err, doc) => {
95+
if(err || !doc) {
96+
return reject({ status: 404, message: 'Invalid credentials'})
97+
}
98+
bcrypt.compare(password, doc.password, (err, didMatch) => {
99+
if(err) return reject(err)
100+
if(didMatch) {
101+
resolve(doc)
102+
} else {
103+
reject({ message: 'Not authorized'})
104+
}
105+
})
106+
})
107+
} catch (e) {
108+
reject(e)
99109
}
100-
bcrypt.compare(password, doc.password, (err, didMatch) => {
101-
if(err) return reject(err)
102-
if(didMatch) {
103-
resolve(returnFilter(doc))
104-
} else {
105-
reject({ message: 'Not authorized'})
106-
}
107-
})
108110
})
111+
109112
}
110113

111114
UserSchema.statics.findByToken = function(token) {
@@ -114,9 +117,9 @@ UserSchema.statics.findByToken = function(token) {
114117
let decodedIdAndToken = jwt.verify(token, secret)
115118
User.findById(decodedIdAndToken._id, function (err, user) {
116119
if (err) {
117-
reject()
120+
return reject(err)
118121
}
119-
resolve(returnFilter(user))
122+
resolve(user)
120123
})
121124
})
122125
}

0 commit comments

Comments
 (0)