Skip to content

Commit

Permalink
mend
Browse files Browse the repository at this point in the history
  • Loading branch information
ndahimana154 committed May 30, 2024
1 parent 77dafc3 commit 8f757e0
Show file tree
Hide file tree
Showing 7 changed files with 23 additions and 51 deletions.
37 changes: 1 addition & 36 deletions src/middlewares/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,42 +99,7 @@ const verifyUserCredentials = async (req: Request, res: Response, next: NextFunc



const updateUserRoleSchema = Joi.object({
role: Joi.string().valid("Admin", "Buyer", "Seller").required().messages({
"any.required": "The 'role' parameter is required.",
"string.base": "The 'role' parameter must be a string.",
"any.only": "The 'role' parameter must be one of ['Admin', 'Buyer', 'Seller']."
})
});



const validateUpdateUserRole = async (req: Request, res: Response, next: NextFunction) => {
const { id } = req.params;
const { error } = updateUserRoleSchema.validate(req.body);

if (error) {
return res.status(httpStatus.BAD_REQUEST).json({
status: httpStatus.BAD_REQUEST,
message: error.details[0].message
});
}

try {
const user = await authRepositories.findUserByAttributes("id", id);
if (!user) {
return res
.status(httpStatus.NOT_FOUND)
.json({ status: httpStatus.NOT_FOUND, message: "User doesn't exist." });
}
next();
} catch (err) {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
status: httpStatus.INTERNAL_SERVER_ERROR,
message: err.message
});
}
};


export { validation, isUserExist, isAccountVerified, validateUpdateUserRole, updateUserRoleSchema,verifyUserCredentials };
export { validation, isUserExist, isAccountVerified,verifyUserCredentials };
2 changes: 1 addition & 1 deletion src/modules/auth/controller/authControllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const sendVerifyEmail = async (req: any, res: Response) => {
const verifyEmail = async (req: any, res: Response) => {
try {
await authRepositories.destroySession(req.user.id, req.session.token)
await authRepositories.UpdateUserByAttributes("isVerified", true, "id", req.user.id);
await authRepositories.updateUserByAttributes("isVerified", true, "id", req.user.id);
res.status(httpStatus.OK).json({ status: httpStatus.OK, message: "Account verified successfully, now login." });
} catch (error) {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ status: httpStatus.INTERNAL_SERVER_ERROR, message: error.message });
Expand Down
4 changes: 2 additions & 2 deletions src/modules/auth/repository/authRepositories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const findUserByAttributes = async (key:string, value:any) =>{
return await Users.findOne({ where: { [key]: value} })
}

const UpdateUserByAttributes = async (updatedKey:string, updatedValue:any, whereKey:string, whereValue:any) =>{
const updateUserByAttributes = async (updatedKey:string, updatedValue:any, whereKey:string, whereValue:any) =>{
await Users.update({ [updatedKey]: updatedValue }, { where: { [whereKey]: whereValue} });
return await findUserByAttributes(whereKey, whereValue)
}
Expand All @@ -28,4 +28,4 @@ const destroySession = async (userId: number, token:string) =>{
return await Session.destroy({ where: {userId, token } });
}

export default { createUser, createSession, findUserByAttributes, destroySession, UpdateUserByAttributes, findSessionByUserId }
export default { createUser, createSession, findUserByAttributes, destroySession, updateUserByAttributes, findSessionByUserId }
10 changes: 4 additions & 6 deletions src/modules/user/controller/userControllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,15 @@ import httpStatus from "http-status";

const updateUserRole = async (req: Request, res: Response) => {
try {
await authRepositories.UpdateUserByAttributes("role", req.body.role, "id", req.params.id)
const updatedUser = await authRepositories.findUserByAttributes("id", req.params.id)
const data = await authRepositories.updateUserByAttributes("role", req.body.role, "id", req.params.id)
return res.status(httpStatus.OK).json({
status: httpStatus.OK,
message: "User role updated successfully",
new: updatedUser
data
});
} catch (error) {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
status: httpStatus.INTERNAL_SERVER_ERROR,
message: error
message: error.message
});
}
};
Expand All @@ -25,7 +23,7 @@ const updateUserRole = async (req: Request, res: Response) => {
const updateUserStatus = async (req: Request, res: Response): Promise<void> => {
try {
const userId: number = Number(req.params.id);
const data = await authRepositories.UpdateUserByAttributes("status", req.body.status, "id", userId);
const data = await authRepositories.updateUserByAttributes("status", req.body.status, "id", userId);
res.status(httpStatus.OK).json({ message: "Status updated successfully.", data });
} catch (error) {
res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ status: httpStatus.INTERNAL_SERVER_ERROR, message: error.message });
Expand Down
6 changes: 3 additions & 3 deletions src/modules/user/test/user.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,15 +113,15 @@ describe("User Repository Functions", () => {
it("should update the user status successfully", async () => {
updateStub.resolves([1]);
const user = { id: 1, status: true };
const result = await authRepositories.UpdateUserByAttributes("status", "enabled", "id", 1);
const result = await authRepositories.updateUserByAttributes("status", "enabled", "id", 1);
expect(updateStub.calledOnce).to.be.true;
expect(updateStub.calledWith({ status: true }, { where: { id: 1 } })).to.be.false;
});

it("should throw an error if there is a database error", async () => {
updateStub.rejects(new Error("Database error"));
try {
await authRepositories.UpdateUserByAttributes("status", "enabled", "id", 1);
await authRepositories.updateUserByAttributes("status", "enabled", "id", 1);
} catch (error) {
expect(updateStub.calledOnce).to.be.true;
expect(error.message).to.equal("Database error");
Expand Down Expand Up @@ -211,7 +211,7 @@ describe("Admin update User roles", () => {
router().put("/api/users/admin-update-role/10001").send({ role: "Admin" }).end((err, res) => {
expect(res).to.have.status(httpStatus.NOT_FOUND);
expect(res.body).to.be.an("object");
expect(res.body).to.have.property("message", "User doesn't exist.")
expect(res.body).to.have.property("message", "User not found")
done(err)
})
})
Expand Down
9 changes: 9 additions & 0 deletions src/modules/user/validation/userValidations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,12 @@ export const statusSchema = Joi.object({
"any.required": "Status is required"
})
});


export const roleSchema = Joi.object({
role: Joi.string().valid("Admin", "Buyer", "Seller").required().messages({
"any.required": "The 'role' parameter is required.",
"string.base": "The 'role' parameter must be a string.",
"any.only": "The 'role' parameter must be one of ['Admin', 'Buyer', 'Seller']."
})
});
6 changes: 3 additions & 3 deletions src/routes/userRouter.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Router } from "express";
import userControllers from "../modules/user/controller/userControllers";
import {isUserExist, validation,validateUpdateUserRole,updateUserRoleSchema} from "../middlewares/validation";
import { statusSchema } from "../modules/user/validation/userValidations";
import {isUserExist, validation} from "../middlewares/validation";
import { statusSchema,roleSchema } from "../modules/user/validation/userValidations";


const router: Router = Router()

router.put("/admin-update-user-status/:id", validation(statusSchema), isUserExist, userControllers.updateUserStatus);
router.put("/admin-update-role/:id",validation(updateUserRoleSchema),validateUpdateUserRole, userControllers.updateUserRole);
router.put("/admin-update-role/:id",validation(roleSchema),isUserExist, userControllers.updateUserRole);

export default router;

0 comments on commit 8f757e0

Please sign in to comment.