Skip to content

Commit

Permalink
reset and forgot password
Browse files Browse the repository at this point in the history
  • Loading branch information
holabayor committed Sep 23, 2023
1 parent 7d78d36 commit 7fc4116
Show file tree
Hide file tree
Showing 11 changed files with 96 additions and 135 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/"]
}
85 changes: 85 additions & 0 deletions controllers/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ 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 transporter = require('../middlewares/emailConfig');

const secretKey = process.env.JWT_SECRET_KEY;

Expand Down Expand Up @@ -230,10 +231,94 @@ async function createOrgAndUser(req, res, next) {
}
}

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.

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 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.

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
6 changes: 0 additions & 6 deletions routes/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,10 @@ const {
getUserById,
getAllUsers,
updateUser,
forgotPassword,
resetPassword,
deleteUser,
} = require('../controllers/userController');
const { auth, adminUser } = require('../middlewares/auth');

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

router.use(auth);

router.get('/me', getMe);
Expand Down
5 changes: 2 additions & 3 deletions tests/userController.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,15 +83,14 @@ describe('Users COntroller Endpoints', () => {
});
});


describe('Users Endpoints', () => {
describe('Users Endpoints', () => {
it('should fetch all users', async () => {
const res = await request(app).get(`/api/users`);
expect(res.status).toEqual(500);
});
});

describe('Users Endpoints', () => {
describe('Users Endpoints', () => {
it('should fetch all users', async () => {
const res = await request(app).post(`/api/auth/logout`);
expect(res.status).toEqual(200);
Expand Down

0 comments on commit 7fc4116

Please sign in to comment.