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

Upgrade the packages, libraries to the latest. #2050

Merged
merged 18 commits into from
Jun 20, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
fix:eslint and prettier plugin packages and migration tests
  • Loading branch information
Abhay5855 committed Jun 18, 2024
commit c13c8fa5eaf6cb76c6d9e7e498b08e62a3d257c3
17 changes: 1 addition & 16 deletions controllers/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const { getPaginationLink, getUsernamesFromPRs, getRoleToUpdate } = require("../
const { setInDiscordFalseScript, setUserDiscordNickname } = require("../services/discordService");
const { generateDiscordProfileImageUrl } = require("../utils/discord-actions");
const { addRoleToUser, getDiscordMembers } = require("../services/discordService");
const { fetchAllUsers, addGithubUserId } = require("../models/users");
const { fetchAllUsers } = require("../models/users");
const { getOverdueTasks } = require("../models/tasks");
const { getQualifiers } = require("../utils/helper");
const { parseSearchQuery } = require("../utils/users");
Expand Down Expand Up @@ -918,20 +918,6 @@ async function usersPatchHandler(req, res) {
return res.boom.badImplementation(INTERNAL_SERVER_ERROR);
}
}
const migrations = async (req, res) => {
const { page = 0, size } = req.query;

try {
const result = await addGithubUserId(parseInt(page), parseInt(size));
return res.status(200).json({
message: "Result of migration",
data: result,
});
} catch (error) {
logger.error(`Internal Server Error: ${error}`);
return res.boom.badImplementation(INTERNAL_SERVER_ERROR);
}
};

module.exports = {
verifyUser,
Expand Down Expand Up @@ -962,6 +948,5 @@ module.exports = {
updateDiscordUserNickname,
archiveUserIfNotInDiscord,
usersPatchHandler,
migrations,
isDeveloper,
};
61 changes: 0 additions & 61 deletions models/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -900,66 +900,6 @@ const getNonNickNameSyncedUsers = async () => {
throw err;
}
};
const addGithubUserId = async (page, size) => {
try {
const usersNotFound = [];
let countUserFound = 0;
let countUserNotFound = 0;

const requestOptions = {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization:
"Basic " + btoa(`${config.get("githubOauth.clientId")}:${config.get("githubOauth.clientSecret")}`),
},
};
const usersSnapshot = await firestore
.collection("users")
.limit(size)
.offset(page * size)
.get();
// Create batch write operations for each batch of documents
const batchWrite = firestore.batch();
const batchWrites = [];
for (const userDoc of usersSnapshot.docs) {
if (userDoc.data().github_user_id) continue;
const githubUsername = userDoc.data().github_id;
const username = userDoc.data().username;
const userId = userDoc.id;
const getUserDetails = fetch(`https://api.github.com/users/${githubUsername}`, requestOptions)
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then((data) => {
const githubUserId = data.id;
batchWrite.update(userDoc.ref, { github_user_id: `${githubUserId}`, updated_at: Date.now() });
countUserFound++;
})
.catch((error) => {
countUserNotFound++;
const invalidUsers = { userId, username, githubUsername };
usersNotFound.push(invalidUsers);
logger.error("An error occurred at fetch:", error);
});
batchWrites.push(getUserDetails);
}
await Promise.all(batchWrites);
await batchWrite.commit();
return {
totalUsers: usersSnapshot.docs.length,
usersUpdated: countUserFound,
usersNotUpdated: countUserNotFound,
invalidUsersDetails: usersNotFound,
};
} catch (error) {
logger.error(`Error while Updating all users: ${error}`);
throw Error(error);
}
};

module.exports = {
addOrUpdate,
Expand Down Expand Up @@ -990,5 +930,4 @@ module.exports = {
fetchUsersListForMultipleValues,
fetchUserForKeyValue,
getNonNickNameSyncedUsers,
addGithubUserId,
};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@
"nodemon": "3.1.3",
"nyc": "15.1.0",
"pre-commit": "1.2.2",
"prettier": "3.3.2",
"prettier": "^3.2.5",
"sinon": "18.0.0",
"ts-node": "10.9.2",
"ts-node-dev": "2.0.0",
Expand Down
9 changes: 1 addition & 8 deletions routes/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,5 @@ router.patch("/profileURL", authenticate, userValidator.updateProfileURL, users.
router.patch("/rejectDiff", authenticate, authorizeRoles([SUPERUSER]), users.rejectProfileDiff);
router.patch("/:userId", authenticate, authorizeRoles([SUPERUSER]), users.updateUser);
router.get("/suggestedUsers/:skillId", authenticate, authorizeRoles([SUPERUSER]), users.getSuggestedUsers);
// WARNING!! - One time Script/Route to do migration
router.post(
"/migrations",
authenticate,
authorizeRoles([SUPERUSER]),
userValidator.migrationsValidator,
users.migrations,
);

module.exports = router;
99 changes: 0 additions & 99 deletions test/unit/models/users.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,6 @@ const photoVerificationModel = firestore.collection("photo-verification");
const userData = require("../../fixtures/user/user");
const addUser = require("../../utils/addUser");
const { userState } = require("../../../constants/userStatus");
const app = require("../../../server");
const prodUsers = require("../../fixtures/user/prodUsers");
const authService = require("../../../services/authService");
const cookieName = config.get("userToken.cookieName");
/**
* Test the model functions and validate the data stored
*/
Expand Down Expand Up @@ -492,99 +488,4 @@ describe("users", function () {
expect(userListResult[0].discordId).to.be.deep.equal(userDataArray[0].discordId);
});
});

describe("Adding github_user_id for each user document", function () {
let userId, userToken, superUserId, superUserToken;

beforeEach(async function () {
userId = await addUser(prodUsers[1]);
userToken = authService.generateAuthToken({ userId: userId });
superUserId = await addUser(prodUsers[0]);
superUserToken = authService.generateAuthToken({ userId: superUserId });
});

afterEach(async function () {
await cleanDb();
});

it("Migration API should not be accessible by any regular user", function (done) {
chai
.request(app)
.post("/users/migrations?action=adds-github-id&page=0&size=10")
.set("cookie", `${cookieName}=${userToken}`)
.send()
.end((err, res) => {
if (err) {
return done();
}
expect(res).to.have.status(401);
expect(res.body).to.be.an("object");
expect(res.body).to.eql({
statusCode: 401,
error: "Unauthorized",
message: "You are not authorized for this action.",
});
return done();
});
});

it("Migration API should be not be accessible with invalid query params", async function () {
const res = await chai
.request(app)
.post("/users/migrations")
.set("cookie", `${cookieName}=${superUserToken}`)
.send();
expect(res).to.have.status(400);
expect(res.body).to.have.property("message");
expect(res.body).to.have.property("error");
expect(res.body.message).to.equal("Invalid Query Parameters Passed");
expect(res.body.error).to.equal("Bad Request");
});

it("Migration API should be accessible by super user", async function () {
const res = await chai
.request(app)
.post("/users/migrations?action=adds-github-id&page=0&size=10")
.set("cookie", `${cookieName}=${superUserToken}`)
.send();
expect(res).to.have.status(200);
});

it("Migration API to add github_user_id should work", async function () {
for (const user of prodUsers.slice(2)) {
await addUser(user);
}
const allUsers = await chai.request(app).get("/users").set("cookie", `${cookieName}=${superUserToken}`).send();
const usersWithoutGithubId = allUsers.body.users.filter((user) => {
return !user.github_user_id;
});

expect(usersWithoutGithubId).to.not.have.length(0);

const res = await chai
.request(app)
.post("/users/migrations?action=adds-github-id&page=0&size=10")
.set("cookie", `${cookieName}=${superUserToken}`)
.send();

expect(res).to.have.status(200);
expect(res.body).to.have.property("data").that.is.an("object");
expect(res.body.data).to.have.property("totalUsers").that.is.a("number");
expect(res.body.data).to.have.property("usersUpdated").that.is.a("number");
expect(res.body.data).to.have.property("usersNotUpdated").that.is.a("number");
expect(res.body.data).to.have.property("invalidUsersDetails").that.is.an("array");

const updatedUsers = await chai
.request(app)
.get("/users")
.set("cookie", `${cookieName}=${superUserToken}`)
.send();

const updatedUsersWithoutGithubId = updatedUsers.body.users.filter((user) => {
return !user.github_user_id;
});
// For invalid username
expect(updatedUsersWithoutGithubId).to.have.length(1);
});
});
});
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6351,7 +6351,7 @@ prettier-linter-helpers@^1.0.0:
dependencies:
fast-diff "^1.1.2"

prettier@3.3.2:
prettier@^3.2.5:
version "3.3.2"
resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.3.2.tgz#03ff86dc7c835f2d2559ee76876a3914cec4a90a"
integrity sha512-rAVeHYMcv8ATV5d508CFdn+8/pHPpXeIid1DdrPwXnaAdH7cqjVbpJaT5eq4yRAFU/lsbwYwSF/n5iNrdJHPQA==
Expand Down
Loading