Skip to content

Commit

Permalink
Merge pull request #101 from holabayor/dev-branch
Browse files Browse the repository at this point in the history
refactoring
  • Loading branch information
holabayor authored Sep 21, 2023
2 parents d817a91 + 94e17db commit 20e6b99
Show file tree
Hide file tree
Showing 11 changed files with 160 additions and 179 deletions.
12 changes: 0 additions & 12 deletions Errors/custom-errors.js

This file was deleted.

143 changes: 143 additions & 0 deletions controllers/authController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
/* eslint-disable camelcase */
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const User = require('../models/user.model');
const { createCustomError } = require('../errors/custom-errors');
const Invite = require('../models/organisation_invite.model');

const secretKey = process.env.JWT_SECRET_KEY;

async function createUser(req, res, next) {
try {
const {
first_name,
last_name,
email,
phone,
password,
is_admin,
profile_pic,
org_id,
lunch_credit_balance,
refresh_token,
bank_code,
bank_name,
bank_number,
token,
} = req.body;

// Validate input data

if (!first_name || !last_name || !email || !password || !token) {
// TODO: truly validate data
throw createCustomError('Missing required fields', 400);
}

// Check if the token is valid and retrieve org_id
const invite = await Invite.findOne({ where: { token } });

if (!invite || new Date() > invite.ttl) {
throw createCustomError('Invalid or expired invitation token', 400);
}

const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);

const user = {
first_name,
last_name,
email,
phone,
password_hash: hashedPassword,
is_admin,
profile_pic,
org_id,
lunch_credit_balance,
refresh_token,
bank_code,
bank_name,
bank_number,
};

const newUser = await User.create(user);
delete newUser.password_hash;

const userWithoutPassword = Object.assign(newUser.toJSON);
delete userWithoutPassword.password_hash;
console.log(userWithoutPassword);

return res.status(200).json({
success: true,
message: 'User registered successfully',
data: {
user: userWithoutPassword,
},
});
} catch (error) {
if (error.name === 'SequelizeUniqueConstraintError') {
// Unique constraint violation (duplicate email)
let errorMessage = error.errors[0].message;
errorMessage = errorMessage[0].toUpperCase() + errorMessage.slice(1);
next(createCustomError(errorMessage, 400));
}
next(error.message);
}
}

const loginUser = async (req, res, next) => {
const { email, password } = req.body;

try {
if (!email || !password) {
throw createCustomError('Fill all required fields', 400);
}

console.log(1);
const user = await User.findOne({ where: { email } });
if (!user) {
throw createCustomError('Invalid credentials', 404);
}

const isPasswordValid = await bcrypt.compare(password, user.password_hash);

if (!isPasswordValid) {
throw createCustomError('Invalid credentials', 401);
}

const token = jwt.sign({ id: user.id }, secretKey, {
expiresIn: '1h',
});

// Sending the token in the response

return res.status(200).json({
message: 'User authenticated successfully',
statusCode: 200,
data: {
access_token: token,
email: user.email,
id: user.id,
isAdmin: user.is_admin,
},
});
} catch (error) {
next(error);
}
};

const logoutUser = (req, res) => {
try {
const token = req.header('Authorization').replace('Bearer ', '');

jwt.verify(token, process.env.JWT_SECRET_KEY);
if (!token) {
createCustomError('User is not logged in.', 401);
}

return res.status(200).json({ message: 'User logged out successfully.' });
} catch (error) {
return res.status(200).json({ message: 'User logged out successfully.' });
}
};

module.exports = { createUser, loginUser, logoutUser };
Empty file removed controllers/index.js
Empty file.
File renamed without changes.
4 changes: 2 additions & 2 deletions controllers/organizationController.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ const createOrganization = async (req, res, next) => {
}
};

async function sendInvitation(req, res, next) {
async function sendInvite(req, res, next) {
try {
const { email, organizationId } = req.body;

Expand All @@ -68,4 +68,4 @@ async function sendInvitation(req, res, next) {
}
}

module.exports = { sendInvitation, createOrganization };
module.exports = { sendInvite, createOrganization };
88 changes: 2 additions & 86 deletions controllers/userController.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
/* eslint-disable camelcase */
const bcrypt = require('bcrypt'); // import bcrypt to hash password
const User = require('../models/user.model'); //import user model
const { createCustomError } = require('../errors/custom-errors');
const Invite = require('../models/organisation_invite.model');

async function getMe(req, res, next) {
try {
Expand All @@ -24,14 +22,13 @@ async function getMe(req, res, next) {
}
}


async function getUserById(req, res, next) {
try {
const userId = req.params.id;
const user = await User.findOne({ where: { id: userId } });

if (!user) {
throw createCustomError('User not found', 404)
throw createCustomError('User not found', 404);
}

res.status(200).json({
Expand All @@ -42,91 +39,11 @@ async function getUserById(req, res, next) {
},
});
} catch (error) {
next(error)
next(error);
}
}

// Controllers Function to register new user
async function createUser(req, res, next) {
try {
const {
first_name,
last_name,
email,
phone,
password,
is_admin,
profile_pic,
org_id,
lunch_credit_balance,
refresh_token,
bank_code,
bank_name,
bank_number,
token,
} = req.body;


// Validate input data

if (!first_name || !last_name || !email || !password || !token) {
// TODO: truly validate data
throw createCustomError('Missing required fields', 400);

}

// Check if the token is valid and retrieve org_id
const invite = await Invite.findOne({ where: { token } });

if (!invite || new Date() > invite.ttl) {
throw createCustomError('Invalid or expired invitation token', 400)
}

const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);

const user = {
first_name,
last_name,
email,
phone,
password_hash: hashedPassword,
is_admin,
profile_pic,
org_id,
lunch_credit_balance,
refresh_token,
bank_code,
bank_name,
bank_number,
};

const newUser = await User.create(user);
delete newUser.password_hash;

const userWithoutPassword = Object.assign(newUser.toJSON)
delete userWithoutPassword.password_hash;
console.log(userWithoutPassword);

return res.status(200).json({
success: true,
message: 'User registered successfully',
data: {
user: userWithoutPassword,
},
});
} catch (error) {

if (error.name === 'SequelizeUniqueConstraintError') {
// Unique constraint violation (duplicate email)
let errorMessage = error.errors[0].message;
errorMessage = errorMessage[0].toUpperCase() + errorMessage.slice(1);
next(createCustomError(errorMessage, 400))
}
next(error.message)
}
}

async function getAllUsers(req, res, next) {
try {
const users = await User.findAll({
Expand Down Expand Up @@ -232,7 +149,6 @@ async function updateUser(req, res, next) {
module.exports = {
getMe,
getUserById,
createUser,
getAllUsers,
updateUser,
deleteUser,
Expand Down
49 changes: 0 additions & 49 deletions controllers/userLoginController.js

This file was deleted.

19 changes: 0 additions & 19 deletions controllers/userLogoutController.js

This file was deleted.

12 changes: 8 additions & 4 deletions routes/auth.route.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
const express = require('express');
const userLoginController = require('../controllers/userLoginController');
const { createUser } = require('../controllers/userController');
const {
createUser,
loginUser,
logoutUser,
} = require('../controllers/authController');

const router = express.Router();

router.post('/login', userLoginController);
router.post('/user/signup', createUser);
router.post('/auth/signup', createUser);
router.post('/auth/login', loginUser);
router.post('/auth/logout', logoutUser);

module.exports = router;
Loading

0 comments on commit 20e6b99

Please sign in to comment.