Skip to content

Commit

Permalink
Merge pull request #143 from holabayor/main
Browse files Browse the repository at this point in the history
Code refactoring and lint fixes
  • Loading branch information
holabayor authored Sep 23, 2023
2 parents 466d057 + 7fc4116 commit 97194c7
Show file tree
Hide file tree
Showing 16 changed files with 119 additions and 153 deletions.
3 changes: 2 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,6 @@
"class-methods-use-this": "off",
"prefer-destructuring": ["error", { "object": true, "array": false }],
"no-unused-vars": ["error", { "argsIgnorePattern": "req|res|next|val" }]
}
},
"ignorePatterns": ["tests/"]
}
108 changes: 99 additions & 9 deletions controllers/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,29 @@ const User = require('../models/user.model');
const { createCustomError } = require('../errors/custom-errors');
const Organization = require('../models/organization.model');
const OrgLunchWallet = require('../models/org_lunch_wallet.model');
const {sendEmail} = require('./mailController')
const { sendEmail } = require('./mailController');
const transporter = require('../middlewares/emailConfig');

const secretKey = process.env.JWT_SECRET_KEY;

async function validateEmail(req, res, next) {
try {
const email = req.body.email;
const { email } = req.body;
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

if (!emailRegex.test(email)) {
throw createCustomError('Invalid email format', 400);
}

await sendEmail(email);

next();
} catch (error) {
console.error(`Error sending email: ${error.message}`);
next(createCustomError('Invalid email', 400));
}
}



async function createUser(req, res, next) {
try {
const {
Expand Down Expand Up @@ -63,7 +63,7 @@ async function createUser(req, res, next) {
is_admin: is_admin || false,
profile_pic: 'https://cdn-icons-png.flaticon.com/512/147/147142.png',
org_id: req.org_id || org_id,
lunch_credit_balance: lunch_credit_balance || 1000,
lunch_credit_balance: lunch_credit_balance || 5000,
bank_code,
bank_name,
bank_number,
Expand Down Expand Up @@ -178,7 +178,7 @@ async function createOrgAndUser(req, res, next) {
const organization = await Organization.create({
name: org_name,
lunch_price,
currency_code,
currency_code: currency_code || 'NGN',
});

const lunchWallet = await OrgLunchWallet.create({
Expand Down Expand Up @@ -231,4 +231,94 @@ async function createOrgAndUser(req, res, next) {
}
}

module.exports = { validateEmail, createUser, loginUser, logoutUser, createOrgAndUser };
async function forgotPassword(req, res, next) {
const { email } = req.body;
try {
if (!email) {
return res.status(400).json({
success: false,
message: 'Enter your email address',
});
}

const user = await User.findOne({ where: { email } });

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

const verificationCode = Math.floor(
100000 + Math.random() * 900000,
).toString();

// Send an email with the verification code
const mailOptions = {
from: process.env.MAIL_USER, // Your email address
to: email, // User's email address
subject: 'Password Reset',
text: `Your password reset code is: ${verificationCode}`,
};

// Send the email
await transporter.sendMail(mailOptions);
await user.update({ refresh_token: verificationCode });
// Assuming sendUserOtp returns the expected response object
console.log(user);
res.status(202).json({
success: true,
message: 'Password reset code sent successfully',
data: {
id: user.id,
email: user.email,
},
});
} catch (error) {
next(createCustomError('Invalid email', 401));
}
}

async function resetPassword(req, res, next) {
const { token, password } = req.body;

if (!token || !password) {
return res.status(400).json({
success: false,
message: 'Missing required fields',
data: null,
});
}
try {
const user = await User.findOne({ where: { refresh_token: token } });

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

const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);
// Update the user's password
await user.update({ password_hash: hashedPassword });

await user.update({ refresh_token: null });

await user.save();

res.status(200).json({
success: true,
message: 'Password reset successfully',
data: user,
});
} catch (error) {
next(createCustomError('Invalid reset code', 400));
}
}

module.exports = {
validateEmail,
createUser,
loginUser,
logoutUser,
createOrgAndUser,
forgotPassword,
resetPassword,
};
15 changes: 0 additions & 15 deletions controllers/lunch.controller.js

This file was deleted.

1 change: 1 addition & 0 deletions controllers/organizationController.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const transporter = require('../middlewares/emailConfig');

// Create a new organization and user (Admin user only)
const createOrganization = async (req, res, next) => {
console.log('Hello');
try {
const { name, lunch_price, currency_code } = req.body;

Expand Down
54 changes: 0 additions & 54 deletions controllers/userController.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/* eslint-disable camelcase */
const User = require('../models/user.model'); //import user model
const { createCustomError } = require('../errors/custom-errors');
const { sendUserOtp } = require('./mailController');

async function getMe(req, res, next) {
try {
Expand Down Expand Up @@ -147,63 +146,10 @@ async function updateUser(req, res, next) {
}
}

async function forgotPassword(req, res, next) {
const { email } = req.body;
if (!email) {
return res.status(404).json({
success: false,
message: 'User not found',
});
}

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

const response = await sendUserOtp(user.id, email);

let status = 500;
if (response.status === true) {
status = 202;
}

res.status(status).json(response);
}

async function resetPassword(req, res) {
const { email, otp, password } = req.body;
if (!(email && otp && password)) {
return res.status(404).json({
success: false,
message: 'User not found',
});
}

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

// const response = await verifyOtp(user.id, otp)

// update password
user.password = password;
await user.save();

res.status(200).json({
success: true,
message: 'Password reset successfully',
data: null,
});
}

module.exports = {
getMe,
getUserById,
getAllUsers,
updateUser,
deleteUser,
forgotPassword,
resetPassword,
};
4 changes: 0 additions & 4 deletions controllers/withdraw.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ async function withdrawCashController(req, res, next) {
// eslint-disable-next-line camelcase
userWithdrawing.update({ bank_number, bank_name, bank_code });

console.log(userWithdrawing.lunch_credit_balance);

if (
!userWithdrawing.lunch_credit_balance ||
userWithdrawing.lunch_credit_balance === 0 ||
Expand All @@ -43,13 +41,11 @@ async function withdrawCashController(req, res, next) {
data: newEntry,
});
} catch (error) {
console.log(error);
next(error);
}
}

async function withdrawalHistory(req, res, next) {
console.log(req.user);
try {
const { id } = req.user;

Expand Down
4 changes: 0 additions & 4 deletions generate-secret-key.js

This file was deleted.

2 changes: 0 additions & 2 deletions middlewares/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,6 @@ async function auth(req, res, next) {
}
}



/**
* checks if the user is an admin user
* @requires auth middleware be added first
Expand Down
Empty file removed middlewares/index.js
Empty file.
50 changes: 0 additions & 50 deletions models/index.js

This file was deleted.

3 changes: 3 additions & 0 deletions models/organisation_invite.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ const orgInvites = sequelize.define(
email: {
type: DataTypes.STRING,
allowNull: false,
validate: {
isEmail: { msg: 'Invalid email' },
},
},
token: {
type: DataTypes.STRING,
Expand Down
3 changes: 3 additions & 0 deletions models/user.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ const User = sequelize.define(
type: DataTypes.STRING,
unique: true,
allowNull: false,
validate: {
isEmail: { msg: 'Invalid email' },
},
},
password_hash: {
type: DataTypes.STRING,
Expand Down
7 changes: 7 additions & 0 deletions routes/auth.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ const {
loginUser,
logoutUser,
createOrgAndUser,
forgotPassword,
resetPassword,
} = require('../controllers/authController');
const { auth } = require('../middlewares/auth');

Expand All @@ -12,6 +14,11 @@ const router = express.Router();
router.post('/signup', createUser);
router.post('/login', loginUser);
router.post('/signup/org-user', createOrgAndUser);

// forgot password
router.post('/forgot-password', forgotPassword);
router.post('/reset-password', resetPassword);

router.use(auth);
router.post('/logout', logoutUser);

Expand Down
Loading

0 comments on commit 97194c7

Please sign in to comment.