env variables through different file and optimizing error handling with middleware

This commit is contained in:
Arjun Patel
2019-01-13 22:38:44 -08:00
parent 43bf237942
commit 23f40dc73b
13 changed files with 111 additions and 119 deletions
+7 -18
View File
@@ -1,11 +1,12 @@
const db = require('../config/db.config.js'),
bcrypt = require('bcrypt-nodejs'),
jwt = require('jsonwebtoken');
jwt = require('jsonwebtoken'),
errorMaker = require('../helpers/error.maker');
const Donors = db.donors;
// Find a Donor by email + login with JWT
exports.login = (req, res) => {
exports.login = (req, res, next) => {
Donors.findAll({
where: {
email: req.body.email
@@ -13,15 +14,11 @@ exports.login = (req, res) => {
})
.then(donors => {
if (donors.length < 1) {
return res.status(401).json({
message: 'Auth failed'
});
return next(errorMaker(401, 'Invalid or nonexistent email'));
}
bcrypt.compare(req.body.password, donors[0].password, (error, result) => {
if (error) {
return res.status(401).json({
message: 'Auth failed'
});
return next(error);
}
if (result) {
const token = jwt.sign(
@@ -40,16 +37,8 @@ exports.login = (req, res) => {
token
});
}
return res.status(401).json({
message: 'Auth failed'
});
return next(errorMaker(401, 'Invalid user'));
});
})
.catch(error => {
console.log(error);
return res.status(500).json({
error
});
});
.catch(error => next(error));
};
+4 -16
View File
@@ -13,17 +13,13 @@ exports.create = (req, res) => {
})
.then(donors => {
if (donors.length >= 1) {
return res.status(409).json({
message: 'Email exists'
});
return next(errorMaker(409, `Email Exists: ${req.body.email}`));
} else {
// hash and store
bcrypt.hash(req.body.password, null, null, function(error, hash) {
// Store hash in your password DB.
if (error) {
return res.status(500).json({
error
});
return next(error);
} else {
Donors.create({
first_name: req.body.first_name,
@@ -45,20 +41,12 @@ exports.create = (req, res) => {
donor
});
})
.catch(error => {
return res.status(500).json({
error
});
});
.catch(error => next(error));
}
});
}
})
.catch(error => {
return res.status(500).json({
error
});
});
.catch(error => next(error));
};
// FETCH all Donors