Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
2fed9ad
✨feat(addDefaultColor):
isVivek99 Sep 23, 2022
0f505b7
Merge branch 'develop' into feature/one-time-user-colors
vivek-geekyants Oct 4, 2022
cd2c96d
feat(user-colors):added code to add user colors
vivek-geekyants Oct 6, 2022
5bd0f9a
Merge branch 'develop' into feature/one-time-user-colors
vivek-geekyants Oct 6, 2022
5e4f75a
🐞 fix():removed console logs
vivek-geekyants Oct 6, 2022
04c43e7
fixes+chores():fixed PR review changes and changed the filenames plus…
isVivek99 Oct 13, 2022
964dd56
chore(): dele commented code
isVivek99 Oct 13, 2022
0f65a11
chore(one-time-user-color): chores
isVivek99 Oct 17, 2022
146304a
fix(fixtures): changed color property
isVivek99 Oct 17, 2022
01c8138
fix():changed file structure suggested in the PR
isVivek99 Oct 18, 2022
7a75444
fix: helpers.js
isVivek99 Oct 26, 2022
54c94ce
chore():fixed migration filenames
isVivek99 Nov 5, 2022
f4d60d3
fix(userMigrations):
isVivek99 Nov 5, 2022
64f56cc
chore():removed unwanted comment
isVivek99 Nov 5, 2022
b210076
fix(usercolorArray): added constant
isVivek99 Nov 10, 2022
804c64c
code fix
isVivek99 Jun 9, 2023
b2c9c3c
Merge branch 'develop' into feature/one-time-user-colors
isVivek99 Jul 17, 2023
b495022
added firestore batch changes and updated tests
isVivek99 Jul 24, 2023
807df54
Update controllers/userMigrations.js
isVivek99 Aug 5, 2023
2ecedb5
review changes
isVivek99 Aug 5, 2023
4b0df82
change route name to noun
isVivek99 Aug 5, 2023
cc10b82
(#712) change route name to noun
isVivek99 Aug 5, 2023
b8c7521
update response based on review
isVivek99 Aug 6, 2023
231cbef
update test based on review
isVivek99 Aug 6, 2023
48f6ef3
(#712) moved firestore interaction inside controller and updated name…
isVivek99 Aug 8, 2023
f322598
Merge branch 'develop' of https://github.com/Real-Dev-Squad/website-b…
isVivek99 Aug 14, 2023
018f829
(#712) added test for helpers
isVivek99 Aug 14, 2023
62fb581
updated tests for the model
isVivek99 Aug 14, 2023
542d504
updated tests for the model
isVivek99 Aug 14, 2023
7e0d00a
Update users.test.js
isVivek99 Aug 16, 2023
a522f0f
adress PR comments
isVivek99 Aug 16, 2023
c723578
remove unrequired check
isVivek99 Aug 16, 2023
d76b090
Merge branch 'feature/one-time-user-colors' of https://github.com/vic…
isVivek99 Aug 16, 2023
c87fe9c
added dataAccessLayer to fetch users
isVivek99 Aug 17, 2023
6aaafd7
address failing test
isVivek99 Aug 20, 2023
c2151cd
updated helper file
isVivek99 Aug 21, 2023
0852243
update helper
isVivek99 Aug 21, 2023
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
12 changes: 12 additions & 0 deletions constants/cardColorArray.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
module.exports = [
{ color_primary: "#DB1212", color_secondary: "#F88181" },
{ color_primary: "#E9C46A", color_secondary: "#FFE094" },
{ color_primary: "#F4A261", color_secondary: "#FFBF8C" },
{ color_primary: "#2A9D8F", color_secondary: "#42E0CD" },
{ color_primary: "#165692", color_secondary: "#3D8BD3" },
{ color_primary: "#264653", color_secondary: "#387892" },
{ color_primary: "#B93160", color_secondary: "#D75281" },
{ color_primary: "#A5C9CA", color_secondary: "#E7F6F2" },
{ color_primary: "#6E85B7", color_secondary: "#B2C8DF" },
{ color_primary: "#FBA1A1", color_secondary: "#FBC5C5" },
];
27 changes: 27 additions & 0 deletions controllers/migrations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const userQuery = require("../models/users");
const logger = require("../utils/logger");

/**
* Returns the lists of usernames where default colors were added
*
* @param req {Object} - Express request object
* @param res {Object} - Express response object
*/

const addDefaultColors = async (req, res) => {
try {
const addedDefaultColorsData = await userQuery.addDefaultColors();

return res.json({
message: "User colors updated successfully!",
...addedDefaultColorsData,
});
} catch (error) {
logger.error(`Error adding default colors to users: ${error}`);
return res.boom.badImplementation("Something went wrong. Please contact admin");
}
};

module.exports = {
addDefaultColors,
};
37 changes: 36 additions & 1 deletion models/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ const walletConstants = require("../constants/wallets");
const firestore = require("../utils/firestore");
const { fetchWallet, createWallet } = require("../models/wallets");
const userModel = firestore.collection("users");

const cardColorArray = require("../constants/cardColorArray");
const { addColorsProperty } = require("../utils/users");
/**
* Adds or updates the user data
*
Expand Down Expand Up @@ -188,6 +189,39 @@ const fetchUserImage = async (users) => {
return images;
};

/**
* Adds default archived role
* @return {Promise<usersMigrated|Object>}
*/

const addDefaultColors = async () => {
try {
const usersSnapshot = await userModel.get();
const migratedUsers = [];
const updateUserPromises = [];
const usersArr = [];

usersSnapshot.forEach((doc) => usersArr.push({ id: doc.id, ...doc.data() }));

for (const user of usersArr) {
const colors = user.colors ? user.colors : {};
if (user.colors === undefined) {
const userColorIndex = addColorsProperty(cardColorArray);

colors.primary_color = cardColorArray[parseInt(userColorIndex)].color_primary;
colors.secondary_color = cardColorArray[parseInt(userColorIndex)].color_secondary;
updateUserPromises.push(userModel.doc(user.id).set({ ...user, colors }));
migratedUsers.push(user.username);
}
}
await Promise.all(updateUserPromises);
return { count: migratedUsers.length, users: migratedUsers };
} catch (err) {
logger.error("Error adding default colors to users", err);
throw err;
}
};

module.exports = {
addOrUpdate,
fetchUsers,
Expand All @@ -196,4 +230,5 @@ module.exports = {
initializeUser,
updateUserPicture,
fetchUserImage,
addDefaultColors,
};
1 change: 1 addition & 0 deletions routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@ app.use("/trade", require("./trading.js"));
app.use("/users", require("./users.js"));
app.use("/profileDiffs", require("./profileDiffs.js"));
app.use("/wallet", require("./wallets.js"));
app.use("/migrations", require("./migrations.js"));

module.exports = app;
10 changes: 10 additions & 0 deletions routes/migrations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const express = require("express");
const router = express.Router();
const authenticate = require("../middlewares/authenticate");
const authorizeRoles = require("../middlewares/authorizeRoles");
const { SUPERUSER } = require("../constants/roles");
const migrations = require("../controllers/migrations");

router.patch("/addDefaultColorProperty", authenticate, authorizeRoles([SUPERUSER]), migrations.addDefaultColors);

module.exports = router;
4 changes: 4 additions & 0 deletions test/fixtures/user/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,10 @@ module.exports = () => {
app_owner: true,
archived: true,
},
colors: {
primary_color: "#DB1212",
secondary_color: "#F88181",
},
},
{
username: "mehul",
Expand Down
50 changes: 49 additions & 1 deletion test/integration/users.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ const cleanDb = require("../utils/cleanDb");
const userData = require("../fixtures/user/user")();
const profileDiffData = require("../fixtures/profileDiffs/profileDiffs")();
const superUser = userData[4];
const nonSuperUser = userData[0];
const userWithColorProperty = [userData[5].username];
const colorBearingUsernames = [superUser.username, nonSuperUser.username];

const config = require("config");
const cookieName = config.get("userToken.cookieName");
Expand All @@ -22,11 +25,12 @@ describe("Users", function () {
let superUserId;
let superUserAuthToken;
let userId = "";

let nonSuperUserId = "";
beforeEach(async function () {
userId = await addUser();
jwt = authService.generateAuthToken({ userId });
superUserId = await addUser(superUser);
nonSuperUserId = await addUser(nonSuperUser);
superUserAuthToken = authService.generateAuthToken({ userId: superUserId });
});

Expand Down Expand Up @@ -565,4 +569,48 @@ describe("Users", function () {
});
});
});

describe("PATCH /users/addDefaultColorProperty", function () {
it("Should return 401 if user is not a super user", function (done) {
const nonSuperUserJwt = authService.generateAuthToken({ userId: nonSuperUserId });
chai
.request(app)
.patch(`/users/addDefaultColorProperty`)
.set("cookie", `${cookieName}=${nonSuperUserJwt}`)
.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("You are not authorized for this action.");
return done();
});
});
it("Should add default color property to all users,using authorized user (super_user)", function (done) {
chai
.request(app)
.patch(`/users/addDefaultColorProperty`)
.set("cookie", `${cookieName}=${superUserAuthToken}`)
.end((err, res) => {
if (err) {
return done(err);
}
expect(res).to.have.status(200);
expect(res.body.count).to.be.equal(colorBearingUsernames.length);
const migratedUsernames = res.body.users;

expect(migratedUsernames).to.include(
colorBearingUsernames[0],
"Should add default color property to user without color property"
);

expect(migratedUsernames).to.not.include.any.members(
userWithColorProperty,
"Should not modify color property of user with color object"
);
return done();
});
});
});
});
10 changes: 10 additions & 0 deletions utils/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,19 @@ const getParticipantUserIds = async (participantArray) => {
}
};

/**
* Returns a random object from the array of colors to user
* @param cardColorArray {array} : color containing array
* @returns userColorIndex number : index between the range 0 to cardColorArray.length
*/
const addColorsProperty = (cardColorArray) => {
return Math.floor(Math.random() * (cardColorArray.length - 0) + 0);
};

module.exports = {
getUserId,
getUsername,
getParticipantUserIds,
getParticipantUsernames,
addColorsProperty,
};