separating donor and org login controller functions

This commit is contained in:
Arjun Patel
2019-03-14 17:28:09 -07:00
parent c3f6184cc6
commit a7619fcad9
2 changed files with 48 additions and 18 deletions
+45 -14
View File
@@ -1,23 +1,18 @@
const db = require('../config/db.config.js'),
bcrypt = require('bcrypt-nodejs'),
jwt = require('jsonwebtoken'),
errorMaker = require('../helpers/error.maker');
errorMaker = require('../helpers/error.maker'),
roles = require('../helpers/roles');
const { Donor, Organization } = db;
// Find a Donor/Org by email + login with JWT
exports.login = (type, role) => (req, res, next) => {
const curr_types = {
donor: Donor,
org: Organization
};
curr_types[type]
.findAll({
where: {
email: req.body.email
}
})
exports.donorLogin = (req, res, next) => {
Donor.findAll({
where: {
email: req.body.email
}
})
.then(users => {
if (users.length < 1) {
return next(errorMaker(401, 'Invalid or nonexistent email'));
@@ -31,7 +26,43 @@ exports.login = (type, role) => (req, res, next) => {
{
email: users[0].email,
id: users[0].id,
role: role
role: roles.DONOR
},
process.env.JWT_KEY
);
return res.status(200).json({
message: 'Auth successful',
user: users[0],
token
});
}
return next(errorMaker(401, 'Invalid donor'));
});
})
.catch(error => next(error));
};
// Logging in Organization
exports.orgLogin = (req, res, next) => {
Organization.findAll({
where: {
primary_contact_email: req.body.email
}
})
.then(users => {
if (users.length < 1) {
return next(errorMaker(401, 'Invalid or nonexistent email'));
}
bcrypt.compare(req.body.password, users[0].password, (error, result) => {
if (error) {
return next(error);
}
if (result) {
const token = jwt.sign(
{
email: users[0].email,
id: users[0].id,
role: roles.ORGANIZATION
},
process.env.JWT_KEY
);
+3 -4
View File
@@ -1,14 +1,13 @@
const express = require('express'),
router = express.Router(),
checkAuth = require('../middleware/check-auth'),
roles = require('../helpers/roles');
checkAuth = require('../middleware/check-auth');
const auth = require('../controllers/auth.controller.js');
// Check database for donor and get token with donor role
router.post('/donor/login', auth.login('donor', roles.DONOR));
router.post('/donor/login', auth.donorLogin);
// Check database for org and get token with org role
router.post('/org/login', auth.login('org', roles.ORGANIZATION));
router.post('/org/login', auth.orgLogin);
module.exports = router;