Leveraging JWT for Authenticated Access

This commit is contained in:
MuhammadKhalilzadeh committed 2024-07-05 10:19:58 +03:30
1 parent a7adb8c04b
commit 4f8031a944
2 files changed
+20 -5

No files matched your search

+19 -4
View File
@@ -274,17 +274,32 @@ const resetPasswordController = async (req, res, next) => {
*/ */
const deleteUserController = async (req, res, next) => { const deleteUserController = async (req, res, next) => {
try { try {
const token = req.headers.authorization.split(' ')[1];
const decodedToken = jwt.decode(token)
const { _id, email } = decodedToken;
console.log("USERID: ", _id, " Email: ", email)
const decodedTokenCastedAsRequest = {
params: {
userId: _id
},
body: {
email
}
}
// Validate user // Validate user
await deleteUserParamValidation.validateAsync(req.body); await deleteUserParamValidation.validateAsync(decodedTokenCastedAsRequest.body);
// Check if the user exists // Check if the user exists
const user = await req.db.getUserByEmail(req); const user = await req.db.getUserByEmail(decodedTokenCastedAsRequest);
if (!user) { if (!user) {
throw new Error(errorMessages.DB_USER_NOT_FOUND); throw new Error(errorMessages.DB_USER_NOT_FOUND);
} }
// 1. Find all the monitors associated with the user id // 1. Find all the monitors associated with the user id
const monitors = await req.db.getMonitorsByUserId(req); const monitors = await req.db.getMonitorsByUserId(decodedTokenCastedAsRequest);
if (monitors) { if (monitors) {
// 2. Delete jobs associated with each monitor // 2. Delete jobs associated with each monitor
@@ -306,7 +321,7 @@ const deleteUserController = async (req, res, next) => {
await req.db.deleteMonitorsByUserId(user._id); await req.db.deleteMonitorsByUserId(user._id);
// 6. Delete the user by id // 6. Delete the user by id
await req.db.deleteUser(req); await req.db.deleteUser(decodedTokenCastedAsRequest);
return res.status(200).json({ return res.status(200).json({
+1 -1
View File
@@ -26,7 +26,7 @@ router.post(
userEditController userEditController
); );
router.get("/users/admin", checkAdminController); router.get("/users/admin", checkAdminController);
router.delete("/user/:userId", /* verifyJWT, verifyOwnership(User, "userId") ,*/ deleteUserController); router.delete("/user/:userId", verifyJWT, verifyOwnership(User, "userId") , deleteUserController);
//Recovery routes //Recovery routes
router.post("/recovery/request", recoveryRequestController); router.post("/recovery/request", recoveryRequestController);