Skip to content

Commit

Permalink
ft<User>:change password API
Browse files Browse the repository at this point in the history
  • Loading branch information
Timothy-py committed Jun 5, 2024
1 parent c80f8f5 commit d0cf2d5
Show file tree
Hide file tree
Showing 5 changed files with 130 additions and 18 deletions.
65 changes: 65 additions & 0 deletions controllers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ const _ = require('lodash');
const joi = require('joi');
const Auth = require('../model/auth');
const User = require('../model/user');
const { validateChangePasswordSchema } = require('../middleware/validators');
const auth = require('../model/auth');

/**
* @author Cyril ogoh <cyrilogoh@gmail.com>
Expand Down Expand Up @@ -242,3 +244,66 @@ const sendTokenResponse = (user, statusCode, res) => {
})
);
};

/**
* @author Timothy <adeyeyetimothy33@gmail.com>
* @description Change Password
* @route `/api/v1/auth/change-password`
* @access Private
* @type PUT
*/
exports.changePassword = async (req, res) => {
try {
// Validate the request body
const { error, value } = validateChangePasswordSchema(req.body);
if (error) return res.status(400).send(error.details);
// retrieve request body
const { currentPassword, newPassword } = value;

const authDoc = await auth.findOne({
_id: req.user.auth_id
});

if (!authDoc) {
return res.status(404).json({
status: 'fail',
message: 'User not found'
});
}

// check if password is match
const isMatch = await authDoc.matchPassword(currentPassword);

// if password no match
if (!isMatch) {
return res.status(401).json({
status: 'fail',
messsage: 'The current password does not match'
});
}

const salt = await bcrypt.genSalt(10);
const hashPassword = await bcrypt.hash(newPassword, salt);

// change password
await auth.findOneAndUpdate(
{
_id: req.user.auth_id
},
{
password: hashPassword
}
);

return res.status(200).json({
status: 'success',
message: 'Password updated successfully'
});
} catch (error) {
return res.status(500).json({
status: 'error',
message: 'Unable to update password',
error: error
});
}
};
4 changes: 3 additions & 1 deletion middleware/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ exports.protect = asyncHandler(async (req, res, next) => {
// set token from cookie
token = req.headers.cookie.split('token=')[1];
}

// Make sure token exists
if (!token) {
console.log('ERROR: Invalid');
return next(new ErrorResponse('Not authorized to access this route', 401));
}

Expand All @@ -36,6 +37,7 @@ exports.protect = asyncHandler(async (req, res, next) => {
return next(new ErrorResponse('User Data Is Not Valid', 400));
}
} catch (err) {
console.log('NOT AUTHORIZED HERE');
return next(new ErrorResponse('Not authorized to access this route', 401));
}
});
Expand Down
16 changes: 15 additions & 1 deletion middleware/validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,17 @@ const applyJobSchema = Joi.object({
resumeURL: Joi.string().required()
});

const changePasswordSchema = Joi.object({
currentPassword: Joi.string().required(),
newPassword: Joi.string()
.required()
.min(8)
.pattern(new RegExp('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])'))
.message(
'Password must contain at least one lowercase letter, one uppercase letter, one digit, and one special character (!@#$%^&*)'
)
});

const validateAdminInvite = validator(inviteAdminSchema);
const validateAdminLogin = validator(loginAdminSchema);
const validateJobStatus = validator(jobStatus);
Expand All @@ -118,6 +129,7 @@ const validateReportSchema = validator(createReportSchema);
const validatePasswordSchema = validator(passwordSchema);
const validateCreateJob = validator(jobSchema);
const validateApplyJobSchema = validator(applyJobSchema);
const validateChangePasswordSchema = validator(changePasswordSchema);

const joiErrorMessage = (error) => {
return error.details.map((detail) => {
Expand All @@ -127,6 +139,7 @@ const joiErrorMessage = (error) => {
};
});
};

module.exports = {
joiErrorMessage,
validateAdminInvite,
Expand All @@ -137,5 +150,6 @@ module.exports = {
validateReportSchema,
validatePasswordSchema,
validateCreateJob,
validateApplyJobSchema
validateApplyJobSchema,
validateChangePasswordSchema
};
33 changes: 17 additions & 16 deletions routes/auth.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
const express = require("express");
const express = require('express');
const router = express.Router();
const { protect } = require("../middleware/auth");
const { protect } = require('../middleware/auth');
const {
register,
login,
logout,
forgotPassword,
resetPassword
} = require("../controllers/auth")
register,
login,
logout,
forgotPassword,
resetPassword,
changePassword
} = require('../controllers/auth');

router.post('/register', register);
router.post('/login', login);
router.post('/google/redirect', login);
router.get('/logout', logout);
router.post('/forgot-password', forgotPassword);
router.put('/reset-password', resetPassword);
router.put('/change-password', protect, changePassword);

router.post("/register", register);
router.post("/login", login);
router.post("/google/redirect", login);
router.get("/logout", logout);
router.post("/forgot-password", forgotPassword);
router.put("/reset-password", resetPassword);

module.exports = router;
module.exports = router;
30 changes: 30 additions & 0 deletions swagger/doc.auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -169,3 +169,33 @@
* type:
* $ref: '#/components/schemas/User'
*/

// *************************CHANGE PASSWORD******************************
/**
* @openapi
* /auth/change-password:
* put:
* tags:
* - Auth
* security:
* - BearerAuth: []
* summary: Change Password
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* currentPassword:
* type: string
* newPassword:
* type: string
* responses:
* 400:
* description: There is no user with that email
* 200:
* description: Password changed successfully
* 500:
* description: Internal server error
*/

0 comments on commit d0cf2d5

Please sign in to comment.