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

Added New PUT Route for User Intro #2293

Merged
Merged
Show file tree
Hide file tree
Changes from 6 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
25 changes: 25 additions & 0 deletions controllers/stocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,31 @@
try {
const { id: userId } = req.userData;
const userStocks = await stocks.fetchUserStocks(userId);

res.set(
"X-Deprecation-Warning",
"WARNING: This endpoint is being deprecated and will be removed in the future. Please use `/stocks/:userId` route to get the user stocks details."
);
return res.json({
message: userStocks.length > 0 ? "User stocks returned successfully!" : "No stocks found",
userStocks,
});
} catch (err) {
logger.error(`Error while getting user stocks ${err}`);
return res.boom.badImplementation(INTERNAL_SERVER_ERROR);
}
};

/**
* Fetches all the stocks of the authenticated user
*
* @param req {Object} - Express request object
* @param res {Object} - Express response object
*/
const getUserStocks = async (req, res) => {

Check failure on line 72 in controllers/stocks.js

View workflow job for this annotation

GitHub Actions / build (20.11.x)

'getUserStocks' is assigned a value but never used
try {
const userStocks = await stocks.fetchUserStocks(req.params.userId);

return res.json({
message: userStocks.length > 0 ? "User stocks returned successfully!" : "No stocks found",
userStocks,
Expand Down
9 changes: 9 additions & 0 deletions middlewares/userAuthorization.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { NextFunction } from "express";
import { CustomRequest, CustomResponse } from "../types/global";

export const userAuthorization = (req: CustomRequest, res: CustomResponse, next: NextFunction) => {
if (req.params.userId === req.userData.id) {
return next();
}
res.boom.forbidden("Unauthorized access");
};
5 changes: 4 additions & 1 deletion routes/stocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@
const { addNewStock, fetchStocks, getSelfStocks } = require("../controllers/stocks");
const { createStock } = require("../middlewares/validators/stocks");
const { SUPERUSER } = require("../constants/roles");
const { devFlagMiddleware } = require("../middlewares/devFlag");
const { userAuthorization } = require("../middlewares/userAuthorization");

router.get("/", fetchStocks);
router.post("/", authenticate, authorizeRoles([SUPERUSER]), createStock, addNewStock);
router.get("/user/self", authenticate, getSelfStocks);
router.get("/user/self", authenticate, getSelfStocks); // this route will soon be deprecated, please use `/stocks/:userId` route.
router.get("/:userId", devFlagMiddleware, authenticate, userAuthorization, getUserStocks);

Check failure on line 14 in routes/stocks.js

View workflow job for this annotation

GitHub Actions / build (20.11.x)

'getUserStocks' is not defined

module.exports = router;
12 changes: 11 additions & 1 deletion routes/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
const ROLES = require("../constants/roles");
const { Services } = require("../constants/bot");
const authenticateProfile = require("../middlewares/authenticateProfile");
const { devFlagMiddleware } = require("../middlewares/devFlag");
const { userAuthorization } = require("../middlewares/userAuthorization");

router.post("/", authorizeAndAuthenticate([ROLES.SUPERUSER], [Services.CRON_JOB_HANDLER]), users.markUnverified);
router.post("/update-in-discord", authenticate, authorizeRoles([SUPERUSER]), users.setInDiscordScript);
Expand All @@ -35,7 +37,15 @@
);
router.get("/:username", users.getUser);
router.get("/:userId/intro", authenticate, authorizeRoles([SUPERUSER]), users.getUserIntro);
router.put("/self/intro", authenticate, userValidator.validateJoinData, users.addUserIntro);
router.put("/self/intro", authenticate, userValidator.validateJoinData, users.addUserIntro); // This route is being deprecated soon, please use alternate available route `/users/:userId/intro`.
Dismissed Show dismissed Hide dismissed
router.put(
"/:userId/intro",
devFlagMiddleware,
authenticate,
Dismissed Show dismissed Hide dismissed
userValidator.validateJoinData,
userAuthorization,
users.addUserIntro
);
router.get("/:id/skills", users.getUserSkills);
router.get("/:id/badges", getUserBadges);
router.patch(
Expand Down
102 changes: 102 additions & 0 deletions test/integration/users.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1579,6 +1579,108 @@ describe("Users", function () {
});
});

describe("PUT /users/:userId/intro", function () {
let userStatusData;

beforeEach(async function () {
await userStatusModel.updateUserStatus(userId, userStatusDataAfterSignup);
const updateStatus = await userStatusModel.updateUserStatus(userId, userStatusDataAfterFillingJoinSection);
userStatusData = (await firestore.collection("usersStatus").doc(updateStatus.id).get()).data();
});

it("should return 409 if the data already present", function (done) {
addJoinData(joinData(userId)[3]);
chai
.request(app)
.put(`/users/${userId}/intro?dev=true`)
.set("Cookie", `${cookieName}=${jwt}`)
.send(joinData(userId)[3])
.end((err, res) => {
if (err) {
return done(err);
}
expect(res).to.have.status(409);
expect(res.body).to.be.a("object");
expect(res.body.message).to.equal("User data is already present!");
return done();
});
});

it("Should store the info in db", function (done) {
chai
.request(app)
.put(`/users/${userId}/intro?dev=true`)
.set("Cookie", `${cookieName}=${jwt}`)
.send(joinData()[2])
.end((err, res) => {
if (err) {
return done(err);
}
expect(res).to.have.status(201);
expect(res.body).to.be.a("object");
expect(res.body.message).to.equal("User join data and newstatus data added and updated successfully");
expect(userStatusData).to.have.own.property("currentStatus");
expect(userStatusData).to.have.own.property("monthlyHours");
expect(userStatusData.currentStatus.state).to.equal("ONBOARDING");
expect(userStatusData.monthlyHours.committed).to.equal(40);
return done();
});
});

it("Should return 401 for Unauthenticated User Request", function (done) {
chai
.request(app)
.put(`/users/${userId}/intro?dev=true`)
.set("Cookie", `${cookieName}=""`)
.send(joinData()[2])
.end((err, res) => {
if (err) {
return done(err);
}
expect(res).to.have.status(401);
expect(res.body).to.be.a("object");
expect(res.body.message).to.equal("Unauthenticated User");
return done();
});
});

it("Should return 400 for invalid Data", function (done) {
chai
.request(app)
.put(`/users/${userId}/intro?dev=true`)
.set("Cookie", `${cookieName}=${jwt}`)
.send(joinData()[1])
.end((err, res) => {
if (err) {
return done(err);
}
expect(res).to.have.status(400);
expect(res.body).to.be.a("object");
expect(res.body.message).to.be.equal('"firstName" is required');
return done();
});
});

it("Should return 403 for Forbidden access", function (done) {
const userId = "anotherUser123";
addJoinData(joinData(userId)[3]);
chai
.request(app)
.put(`/users/${userId}/intro?dev=true`)
.set("cookie", `${cookieName}=${jwt}`)
.send(joinData(userId)[3])
.end((err, res) => {
if (err) return done(err);

expect(res).to.have.status(403);
expect(res.body).to.be.an("object");
expect(res.body.message).to.equal("Forbidden access");

return done();
});
});
});

describe("PATCH /users/rejectDiff", function () {
let profileDiffsId;

Expand Down
70 changes: 70 additions & 0 deletions test/unit/middlewares/userAuthorization.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import * as sinon from "sinon";
import chai from "chai";
const { expect } = chai;
const { userAuthorization } = require("../../../middlewares/userAuthorization");

describe("userAuthorization Middleware", function () {
let req;
let res;
let next;

beforeEach(function () {
req = {
params: {},
userData: {},
};
res = {
boom: {
forbidden: sinon.spy((message) => {
res.status = 403;
res.message = message;
}),
},
};
next = sinon.spy();
});

it("should call next() if userId matches userData.id", function () {
req.params.userId = "123";
req.userData.id = "123";

userAuthorization(req, res, next);

expect(next.calledOnce).to.be.true;
expect(res.boom.forbidden.notCalled).to.be.true;
});

it("should call res.boom.forbidden() if userId does not match userData.id", function () {
req.params.userId = "123";
req.userData.id = "456";

userAuthorization(req, res, next);

expect(res.boom.forbidden.calledOnce).to.be.true;
expect(res.status).to.equal(403);
expect(res.message).to.equal("Unauthorized access");
expect(next.notCalled).to.be.true;
});

it("should call res.boom.forbidden() if userData.id is missing", function () {
req.params.userId = "123";

userAuthorization(req, res, next);

expect(res.boom.forbidden.calledOnce).to.be.true;
expect(res.status).to.equal(403);
expect(res.message).to.equal("Unauthorized access");
expect(next.notCalled).to.be.true;
});

it("should call res.boom.forbidden() if userId is missing", function () {
req.userData.id = "123";

userAuthorization(req, res, next);

expect(res.boom.forbidden.calledOnce).to.be.true;
expect(res.status).to.equal(403);
expect(res.message).to.equal("Unauthorized access");
expect(next.notCalled).to.be.true;
});
});
Loading