Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ft: seller of the product, delete the product #42

Open
wants to merge 7 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3,526 changes: 1,729 additions & 1,797 deletions package-lock.json

Large diffs are not rendered by default.

191 changes: 105 additions & 86 deletions src/controllers/__tests__/authController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,100 +5,119 @@ import app from "../../app";
import USER from "../../models/User";
import { httpRequest, httpResponse } from "../mock/user.mock";
import GoogleController from "../googleAuthController";
import Tokens from "../../models/token"
import Tokens from "../../models/token";
jest.setTimeout(70000);
describe("Login via google", () => {
afterAll(async () => {
USER.destroy({
where: { email: "[email protected]" },
afterAll(async () => {
USER.destroy({
where: { email: "[email protected]" },
});
});
test("redirect to google and authenticate", async () => {
const data = await GoogleController.googleAuth(
httpRequest("[email protected]"),
httpResponse()
);
console.log(data);
expect(data.body).toHaveProperty("user");
});
}, );
test("redirect to google and authenticate", async () => {
const data = await GoogleController.googleAuth(
httpRequest("[email protected]"),
httpResponse()
);
console.log(data);
expect(data.body).toHaveProperty("user");
});

test("testing register", async () => {
const data: any = await GoogleController.googleAuth(
httpRequest("[email protected]"),
httpResponse()
);
console.log(data);
expect(data.body).toHaveProperty("user");
});
test("testing 500", async () => {
const data: any = await GoogleController.googleAuth(
"helll",
httpResponse()
);
expect(data.body.status).toBe(500);
});
test("testing register", async () => {
const data: any = await GoogleController.googleAuth(
httpRequest("[email protected]"),
httpResponse()
);
console.log(data);
expect(data.body).toHaveProperty("user");
});
test("testing 500", async () => {
const data: any = await GoogleController.googleAuth(
"helll",
httpResponse()
);
expect(data.body.status).toBe(500);
});
});

/* eslint-disable @typescript-eslint/no-explicit-any */
describe("Math functions", () => {
it("should multiply 5 by 3", () => {
const result = multiply(5, 3);
expect(result).toEqual(15);
});
it("should multiply 5 by 3", () => {
const result = multiply(5, 3);
expect(result).toEqual(15);
});

it("should add 5 by 3", () => {
const result = add(5, 3);
expect(result).toEqual(8);
});
it("should add 5 by 3", () => {
const result = add(5, 3);
expect(result).toEqual(8);
});
});
// reset password coontroller tests
describe('reset password', () => {
describe('send link to email', () => {
test('incase of unregistered email', async () => {
const response = await supertest(app)
.post('/resetpassword/link')
.send({ email: '[email protected]' })
expect(response.status).toBe(400)
}, 30000) // timeout 30 seconds
})
test('incase of a registered email', async () => {
const response = await supertest(app)
.post('/resetpassword/link')
.send({ email: '[email protected]' })
expect(response.status).toBe(200)
}, 20000)
test('incase invalid email input', async () => {
const response = await supertest(app)
.post('/resetpassword/link')
.send({ email: 'rukundjoseph' })
expect(response.status).toBe(400)
}, 20000)
describe('add token and change password', () => {
test('incase incorrect token', async () => {
const response = await supertest(app)
.patch('/changepassword/[email protected]/65328dba23')
.send({ newpassword: 'newpassword', confirmpass: 'newpassword' })
expect(response.status).toBe(401)
}, 20000)
test('incase of a unmatching passwords', async () => {
const user: any = await USER.findOne({
where: { email: '[email protected]' },
})
const token: any = await Tokens.findOne({ where: { userId: `${user.id}` } })
const response = await supertest(app)
.patch(`/changepassword/[email protected]/${token.token}`)
.send({ newpassword: 'newpas', confirmpass: 'newpaa' })
expect(response.status).toBe(400)
})
test('incase of a valid token and email', async () => {
const user: any = await USER.findOne({
where: { email: '[email protected]' },
})
const token: any = await Tokens.findOne({ where: { userId: `${user.id}` } })
const response = await supertest(app)
.patch(`/changepassword/[email protected]/${token.token}`)
.send({ newpassword: 'newpas', confirmpass: 'newpas' })
expect(response.status).toBe(200)
})
})
})
describe("reset password", () => {
describe("send link to email", () => {
test("incase of unregistered email", async () => {
const response = await supertest(app)
.post("/resetpassword/link")
.send({ email: "[email protected]" });
expect(response.status).toBe(400);
}, 30000); // timeout 30 seconds
});
test("incase of a registered email", async () => {
const response = await supertest(app)
.post("/resetpassword/link")
.send({ email: "[email protected]" });
expect(response.status).toBe(200);
}, 20000);
test("incase invalid email input", async () => {
const response = await supertest(app)
.post("/resetpassword/link")
.send({ email: "rukundjoseph" });
expect(response.status).toBe(400);
}, 20000);
describe("add token and change password", () => {
test("incase incorrect token", async () => {
const response = await supertest(app)
.patch("/changepassword/[email protected]/65328dba23")
.send({
newpassword: "newpassword",
confirmpass: "newpassword",
});
expect(response.status).toBe(401);
}, 20000);
test("incase of a unmatching passwords", async () => {
const user: any = await USER.findOne({
where: { email: "[email protected]" },
});
const token: any = await Tokens.findOne({
where: { userId: `${user.id}` },
});
const response = await supertest(app)
.patch(
`/changepassword/[email protected]/${token.token}`
)
.send({ newpassword: "newpas", confirmpass: "newpaa" });
expect(response.status).toBe(400);
});
test("incase of a valid token and email", async () => {
const user: any = await USER.findOne({
where: { email: "[email protected]" },
});
const token: any = await Tokens.findOne({
where: { userId: `${user.id}` },
});
const response = await supertest(app)
.patch(
`/changepassword/[email protected]/${token.token}`
)
.send({ newpassword: "newpas", confirmpass: "newpas" });
expect(response.status).toBe(200);
});
});
});

// logout tests
describe("Logout user", () => {
test("success logout", async () => {
const response = await supertest(app).post("/logout");
expect(response.status).toBe(200);
}, 30000); // timeout 30 seconds
});
29 changes: 29 additions & 0 deletions src/controllers/__tests__/product.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import supertest from "supertest";
import createServer from "../../utils/server";
/* eslint-disable @typescript-eslint/no-explicit-any */
const app = createServer();
let token;
beforeAll(async () => {
const res = await supertest(app).post("/login").send({
email: "[email protected]",
password: "adminpass",
});
token = res.body.token;
}, 40000);

describe("Seller Collection", () => {
describe("Seller update product availability", () => {
test("Seller update non-existing product", async () => {
const response = await supertest(app).patch(
"/products/delete/72753"
);
expect(response.status).toBe(404);
}, 60000);
test("unauthorised access", async () => {
const response = await supertest(app).patch(
"/products/delete/72753"
);
expect(response.status).toBe(404);
}, 60000);
});
});
56 changes: 50 additions & 6 deletions src/controllers/prodController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,12 +120,15 @@ class ProductController {
try {
const ProductID = req.params.product_id;
const available = req.body.isAvailable;
if (typeof available === "boolean") {
console.log(typeof available);
if (typeof available !== "boolean") {
res.status(400).json({
statusCode: 400,
message: "Use true or false for avalilable",
message:
"The 'isAvailable' field must be a boolean value (true or false)",
});
}

const bToken = req.headers.authorization
? req.headers.authorization.split(" ")[1]
: "";
Expand All @@ -134,10 +137,7 @@ class ProductController {
where: { ProductID },
});
if (checkProduct && userData) {
console.log(checkProduct);
console.log(userData);
if (checkProduct.ProductOwner == userData.id) {
console.log("YOU OWN THIS PRODUCT");
const updatedProduct = await Product.update(
{ available },
{
Expand Down Expand Up @@ -170,7 +170,51 @@ class ProductController {
message: error,
});
}
}
}
static async deleteOneProduct(req: Request, res: Response) {
try {
const ProductID = req.params.product_id;
const bToken = req.headers.authorization
? req.headers.authorization.split(" ")[1]
: "";
const userData: any = decode(bToken);
const checkProduct: any = await Product.findOne({
where: { ProductID },
});
if (checkProduct && userData) {
if (checkProduct.ProductOwner == userData.id) {
console.log("YOU OWN THIS PRODUCT");
// const deletedProduct = await checkProduct.desctroy();
await Product.destroy({
where: {
ProductID,
},
});
return res.status(201).json({
statusCode: 201,
message: "product deleted successfully",
data: checkProduct,
});
} else {
return res.status(403).json({
statusCode: 403,
message:
"you can not authorised to delete this product",
});
}
} else {
return res.status(404).json({
statusCode: 404,
message: `product with id ${ProductID} does not exist`,
});
}
} catch (error) {
return res.json({
statusCode: 400,
message: error,
});
}
}
}

export default ProductController;
25 changes: 25 additions & 0 deletions src/controllers/rolesPermissionControllers/__tests__/roles.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import supertest from "supertest";
import createServer from "../../../utils/server";
/* eslint-disable @typescript-eslint/no-explicit-any */
const app = createServer();
let token;
beforeAll(async () => {
const res = await supertest(app).post("/login").send({
email: "[email protected]",
password: "adminpass",
});
token = res.body.token;
}, 40000);

describe("Admin Manage roles", () => {
describe("Authorised Access", () => {
test("View All Roles", async () => {
const response = await supertest(app).get("/role");
expect(response.status).toBe(404);
}, 60000);
test("Get role by name", async () => {
const response = await supertest(app).get("/role/admin");
expect(response.status).toBe(404);
}, 60000);
});
});
27 changes: 27 additions & 0 deletions src/routes/docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,33 @@
* description: The specified product ID does not exist
*/

/**
* @swagger
* /products/delete/{productId}:
* delete:
* tags:
* - Products
* summary: Seller delete the product in their collection
* security:
* - authsecurity: []
* parameters:
* - in: path
* name: productId
* required: true
* schema:
* type: string
* description: The ID of the product to delete
* responses:
* '200':
* description: Product deleted successfuly
* '400':
* description: The request was malformed or missing required data
* '403':
* description: The user does not have permission to update the product
* '404':
* description: The specified product ID does not exist
*/

/**
* @swagger
* /signup:
Expand Down
10 changes: 8 additions & 2 deletions src/routes/productRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,18 @@ import { roleAuthorization } from "../middlewares/role.middleware";

const prod = Router();
prod.post("/add", ProductController.saveProduct);
// seller manage their product availbility
prod.patch(
"/available/:product_id",
roleAuthorization(["admin", "seller"]),
ProductController.updateProductAvailability
);

// seller delete their product
prod.delete(
"/delete/:product_id",
roleAuthorization(["seller"]),
ProductController.deleteOneProduct
);


export default prod
export default prod;