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 da88ef1
Show file tree
Hide file tree
Showing 11 changed files with 26 additions and 65 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ This is the backend for E-Commerce-Ninjas, written in Node.js with TypeScript.
- Resend verification Endpoint
- Login Endpoint
- Admin change status Endpoint
- Admin should update user roles Endpoint

## TABLE OF API ENDPOINTS SPECIFICATION AND DESCRIPTION

Expand All @@ -42,9 +43,9 @@ This is the backend for E-Commerce-Ninjas, written in Node.js with TypeScript.
| 3 | GET | /api/auth/verify-email/:token | 200 OK | public | Verifying email |
| 4 | POST | /api/auth/send-verify-email | 200 OK | public | Resend verification email |
| 5 | POST | /api/auth/login | 200 OK | public | Login with Email and Password |
| 5 | PUT | /api/users/admin-update-role/:id | 200 OK | public | Update the user role by admin|
| 5 | PUT | /api/users/admin-update-role/:id | 200 OK | private | Update the user role by admin|
| 6 | PUT | /api/users/admin-update-user-status/:id | 200 OK | private | Admin change status |
| 7 | PUT | /api/users/admin-update-role/:id | 200 OK | public | Update the user role by admin |
| 7 | PUT | /api/users/admin-update-role/:id | 200 OK | private | Update the user role by admin |

## INSTALLATION

Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
"start": "ts-node-dev src/index.ts",
"dev": "ts-node-dev src/index.ts",
"test": "cross-env NODE_ENV=test npm run deleteAllTables && cross-env NODE_ENV=test npm run createAllTables && cross-env NODE_ENV=test npm run createAllSeeders && nyc cross-env NODE_ENV=test mocha --require ts-node/register 'src/**/*.spec.ts' --timeout 600000 --exit",
"test-dev": "cross-env NODE_ENV=development npm run deleteAllTables && cross-env NODE_ENV=development npm run createAllTables && cross-env NODE_ENV=development npm run createAllSeeders && nyc mocha --require ts-node/register './src/**/*.spec.ts' --timeout 300000 --exit",
"coveralls": "nyc --reporter=lcov --reporter=text-lcov npm test | coveralls",
"coverage": "cross-env NODE_ENV=test nyc mocha --require ts-node/register 'src/**/*.spec.ts' --timeout 600000 --exit",
"lint": "eslint . --ext .ts",
Expand Down
11 changes: 0 additions & 11 deletions public/BUILD.txt

This file was deleted.

Binary file removed public/ProjectManagement.jpg
Binary file not shown.
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 da88ef1

Please sign in to comment.