Skip to content
Open
Show file tree
Hide file tree
Changes from 68 commits
Commits
Show all changes
72 commits
Select commit Hold shift + click to select a range
5941bc5
Merge branch 'develop' into main-resolve-conflict
shubham-y Feb 26, 2022
5aad16d
Merge branch 'develop' of https://github.com/Real-Dev-Squad/website-b…
shubham-y Mar 26, 2022
7358662
Merge branch 'develop' of https://github.com/Real-Dev-Squad/website-b…
shubham-y Apr 20, 2022
0c2e8ce
Merge branch 'develop' of https://github.com/Real-Dev-Squad/website-b…
shubham-y May 18, 2022
0ee25fd
Merge branch 'develop' of https://github.com/Real-Dev-Squad/website-b…
shubham-y Jul 13, 2022
d54f16a
Merge branch 'develop' of https://github.com/Real-Dev-Squad/website-b…
shubham-y Aug 15, 2022
4e5aff3
Merge branch 'develop' of https://github.com/Real-Dev-Squad/website-b…
shubham-y Sep 15, 2022
9afcbd0
Merge branch 'develop' of https://github.com/Real-Dev-Squad/website-b…
shubham-y Oct 26, 2022
0fbfc9a
Merge branch 'develop' of https://github.com/Real-Dev-Squad/website-b…
shubham-y Oct 29, 2022
cc487d9
Merge branch 'develop' of https://github.com/Real-Dev-Squad/website-b…
shubham-y Nov 23, 2022
a5ca925
Merge branch 'develop' of https://github.com/Real-Dev-Squad/website-b…
shubham-y Nov 30, 2022
f01f146
Merge branch 'develop' of https://github.com/Real-Dev-Squad/website-b…
shubham-y Apr 5, 2023
558dd2d
Merge branch 'develop' of https://github.com/Real-Dev-Squad/website-b…
shubham-y Apr 15, 2023
adaf3cb
fixingdoc_duplication
iamYashSinha Apr 24, 2023
8d8232c
fixed linting error
iamYashSinha Apr 24, 2023
e88520b
tests added for github_user_id
iamYashSinha Apr 26, 2023
2e0838b
tests added for github_user_id
iamYashSinha Apr 25, 2023
65f4545
Merge branch 'develop' of https://github.com/Real-Dev-Squad/website-b…
shubham-y Apr 28, 2023
fcac418
added migration route
iamYashSinha Apr 29, 2023
a45e5c8
updated the add or update function
iamYashSinha Apr 29, 2023
63cf7d0
Delete firestore-private-key.json
iamYashSinha Apr 29, 2023
45b2f3b
changed to post method
iamYashSinha Apr 29, 2023
9ee96fc
resolved errors in 15 testcases
iamYashSinha May 1, 2023
0fb5eca
fixed contribution tests error
iamYashSinha May 1, 2023
0d60558
protection on migration route
iamYashSinha May 1, 2023
7c6d7aa
required changes done
iamYashSinha May 2, 2023
e1e57a9
typecast github_user_id field
iamYashSinha May 2, 2023
a481fb6
added batch api calls and fixed test cases
iamYashSinha May 4, 2023
66b6e07
Merge branch 'develop' of https://github.com/Real-Dev-Squad/website-b…
shubham-y May 4, 2023
b25554d
added dynamic batchCount for migration
iamYashSinha May 5, 2023
75d682f
fixed tests and batchWrites call
iamYashSinha May 6, 2023
aa0f615
deleted migration fixtures
iamYashSinha May 7, 2023
fa249fc
Delete migration.js
iamYashSinha May 7, 2023
241df6a
fixed tests and added migration fixture
iamYashSinha May 7, 2023
88aaabd
Merge branch 'bugfix/issue957' of https://github.com/iamYashSinha/web…
iamYashSinha May 7, 2023
7353c58
fixed tests and added migration fixtures
iamYashSinha May 7, 2023
e56cd15
removed github_user_id field in migration fixture
iamYashSinha May 7, 2023
2bdff72
Merge branch 'Real-Dev-Squad:develop' into bugfix/issue957
iamYashSinha May 8, 2023
d59ae9e
removed unwanted spaces
iamYashSinha May 8, 2023
d1b213c
fixed desc of model test
iamYashSinha May 8, 2023
eccbbd5
replaced res.send and removed validation on github_id
iamYashSinha May 14, 2023
9c0fa42
Merge branch 'develop' into bugfix/issue957
iamYashSinha May 15, 2023
f61ff70
changed the variable name in usersModel
iamYashSinha May 15, 2023
7bcdb26
updated tests and replaced res.send
iamYashSinha May 17, 2023
348ce2b
fixed failing test cases and status code
iamYashSinha May 17, 2023
5247952
removed beforeEach and afterEach block in migration test
iamYashSinha May 17, 2023
468b057
made the GitHub API call authenticated
iamYashSinha May 17, 2023
1f04c76
fixed the variable name and spacing
iamYashSinha May 17, 2023
8e9414e
removed unwanted tests
iamYashSinha May 17, 2023
421c736
added a method to find where github_id is not valid
iamYashSinha May 17, 2023
3d11b0b
added users data in response, fixed test cases
iamYashSinha May 19, 2023
20f0b3e
updated variable name
iamYashSinha May 20, 2023
34f235c
fixed sinon test
iamYashSinha May 20, 2023
ae3bfd8
fixed integration test
iamYashSinha May 20, 2023
9569688
fixed sinon.stub and resolves method
iamYashSinha May 20, 2023
5484294
fixed sinon.stub timeout
iamYashSinha May 20, 2023
d20932d
fixed test cases
iamYashSinha Jun 11, 2023
6d309e3
auth token yet to be generated
iamYashSinha Jun 11, 2023
240ccb9
Merge branch 'develop' into bugfix/issue957
iamYashSinha Jun 11, 2023
d0ed63c
add missing closing bracket
shubham-y Jun 26, 2023
c3bd1db
fix conflict in users integration test file
shubham-y Jul 1, 2023
2dc68a5
Merge branch 'develop' of https://github.com/shubham-y/website-backen…
shubham-y Jul 1, 2023
e9a0819
Merge branch 'develop' of https://github.com/Real-Dev-Squad/website-b…
shubham-y Jul 1, 2023
ed2dfc3
add github_user_id in user fixtures
shubham-y Jul 1, 2023
7b57924
update response data for migrate function
shubham-y Jul 3, 2023
97f0959
update tests for migrate route
shubham-y Jul 3, 2023
0dfda95
update tests for migrate route
shubham-y Jul 5, 2023
b2c933e
update response data for migrate function
shubham-y Jul 5, 2023
8158773
Merge branch 'develop' of https://github.com/Real-Dev-Squad/website-b…
shubham-y Jul 26, 2023
31ad08a
update controller function
shubham-y Jul 26, 2023
708d57e
refactor tests
shubham-y Jul 26, 2023
7f79193
update integration test
shubham-y Jul 26, 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
1 change: 1 addition & 0 deletions controllers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const githubAuth = (req, res, next) => {
tokens: {
githubAccessToken: accessToken,
},
github_user_id: user.id,
};

const { userId, incompleteUserDetails } = await users.addOrUpdate(userData);
Expand Down
71 changes: 71 additions & 0 deletions controllers/users.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const axios = require("axios");
const firestore = require("../utils/firestore");
const chaincodeQuery = require("../models/chaincodes");
const userQuery = require("../models/users");
const profileDiffsQuery = require("../models/profileDiffs");
Expand Down Expand Up @@ -593,6 +595,74 @@ const filterUsers = async (req, res) => {
}
};

// one time script function to perform the migration - adding github_user_id field to the document
const migrate = async (req, res) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could we use a better name for this please

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated the name to addGtihubId

const usersNotFound = [];
let countUserFound = 0;
let countUserNotFound = 0;
try {
// Fetch user data from GitHub API for each document in the users collection
// divided by 500 because firestore api guarantee that we can process in batch of 500.
const usersSnapshot = await firestore.collection("users").get();
const totalUsers = usersSnapshot.docs.length;
const batchCount = Math.ceil(totalUsers / 500);
// Create batch write operations for each batch of documents
for (let i = 0; i < batchCount; i++) {
const batchDocs = usersSnapshot.docs.slice(i * 500, (i + 1) * 500);
Comment on lines +581 to +584
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rather than doing this why not directly fetch just 500 from db itself? something like paginated ones.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It will lead to extra reads on our database as in firestore it reads all the documents up from the startAt document id and also this is simpler in terms of code readability

const batchWrite = firestore.batch();
const batchWrites = [];
for (const userDoc of batchDocs) {
const githubUsername = userDoc.data().github_id;
const username = userDoc.data().username;
const userId = userDoc.id;
batchWrite.update(userDoc.ref, { github_user_id: null });
batchWrites.push(
axios
.get(`https://api.github.com/users/${githubUsername}`, {
headers: {
"Content-Type": "application/json",
},
auth: {
username: config.get("githubOauth.clientId"),
password: config.get("githubOauth.clientSecret"),
},
})
.then((response) => {
const githubUserId = response.data.id;
batchWrite.update(userDoc.ref, { github_user_id: `${githubUserId}` });
countUserFound++;
})
.catch((error) => {
countUserNotFound++;
const invalidUsers = { userId, username, githubUsername };
usersNotFound.push(invalidUsers);
if (error.response && error.response.status === 404) {
logger.error("GitHub user not found", error);
} else {
logger.error("An error occurred at axios.get:", error);
}
})
);
}
await Promise.all(batchWrites);
await batchWrite.commit();
}

return res.status(200).json({
message: "Result of migration",
data: {
totalUsers: totalUsers,
usersUpdated: countUserFound,
usersNotUpdated: countUserNotFound,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if we are sending this i think we should add the reason as well for not updating.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There can be different reasons. So IMO, in such a case we can check our logs for the reason

invalidUsersDetails: usersNotFound,
},
});
} catch (error) {
logger.error(`Error while Updating all users: ${error}`);
return res.boom.badImplementation(INTERNAL_SERVER_ERROR);
}
};

const nonVerifiedDiscordUsers = async (req, res) => {
const data = await userQuery.getDiscordUsers();
return res.json(data);
Expand Down Expand Up @@ -626,6 +696,7 @@ module.exports = {
addDefaultArchivedRole,
getUserSkills,
filterUsers,
migrate,
verifyUserImage,
getUserImageForVerification,
nonVerifiedDiscordUsers,
Expand Down
2 changes: 1 addition & 1 deletion models/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const addOrUpdate = async (userData, userId = null) => {
}

// userId is null, Add or Update user
const user = await userModel.where("github_id", "==", userData.github_id).limit(1).get();
const user = await userModel.where("github_user_id", "==", userData.github_user_id).limit(1).get();
if (!user.empty) {
await userModel.doc(user.docs[0].id).set(userData, { merge: true });

Expand Down
3 changes: 3 additions & 0 deletions routes/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,7 @@ router.patch("/rejectDiff", authenticate, authorizeRoles([SUPERUSER]), users.rej
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("/migrate", authenticate, authorizeRoles([SUPERUSER]), users.migrate);

module.exports = router;
38 changes: 38 additions & 0 deletions test/fixtures/user/migration.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const githubUserInfo = require("../auth/githubUserInfo")();

/**
* User info for GitHub auth response
* Multiple responses can be added to the array if required
*
* @return {Object}
*/
module.exports = () => {
return [
{
username: "ankur",
first_name: "Ankur",
last_name: "Narkhede",
yoe: 0,
img: "./img.png",
linkedin_id: "ankurnarkhede",
github_id: githubUserInfo[0].username,
github_display_name: githubUserInfo[0].displayName,
isMember: true,
phone: "1234567890",
email: "[email protected]",
roles: {
member: true,
},
tokens: {
githubAccessToken: "githubAccessToken",
},
status: "active",
profileURL: "https://abcde.com",
picture: {
publicId: "profile/mtS4DhUvNYsKqI7oCWVB/aenklfhtjldc5ytei3ar",
url: "https://res.cloudinary.com/realdevsquad/image/upload/v1667685133/profile/mtS4DhUvNYsKqI7oCWVB/aenklfhtjldc5ytei3ar.jpg",
},
incompleteUserDetails: false,
},
];
};
11 changes: 11 additions & 0 deletions test/fixtures/user/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ module.exports = () => {
yoe: 0,
img: "./img.png",
linkedin_id: "ankurnarkhede",
github_user_id: githubUserInfo[0].id,
github_id: githubUserInfo[0].username,
github_display_name: githubUserInfo[0].displayName,
isMember: true,
Expand Down Expand Up @@ -44,6 +45,7 @@ module.exports = () => {
last_name: "Bhandarkar",
yoe: 0,
img: "./img.png",
github_user_id: "23654780",
github_id: "whydonti",
linkedin_id: "nikhil-bhandarkar",
twitter_id: "whatifi",
Expand All @@ -60,6 +62,7 @@ module.exports = () => {
last_name: "Gajjewar",
yoe: 0,
img: "./img.png",
github_user_id: "23654788",
github_id: "cartmanishere",
linkedin_id: "pranav-gajjewar",
twitter_id: "PGajjewar",
Expand All @@ -80,6 +83,7 @@ module.exports = () => {
yoe: 3,
img: "./img.png",
linkedin_id: "sagarbajpai",
github_user_id: "23654790",
github_id: "sagarbajpai",
github_display_name: "Sagar Bajpai",
phone: "1234567890",
Expand All @@ -105,6 +109,7 @@ module.exports = () => {
yoe: 10,
img: "./img.png",
linkedin_id: "ankushdharkar",
github_user_id: "23654700",
github_id: "ankushdharkar",
github_display_name: "Ankush Dharkar",
phone: "1234567890",
Expand All @@ -131,6 +136,7 @@ module.exports = () => {
yoe: 0,
img: "./img.png",
linkedin_id: "ankitabannore",
github_user_id: "23654725",
github_id: "Ankita2002-Fr",
github_display_name: "Ankita Bannore",
isMember: true,
Expand All @@ -155,6 +161,7 @@ module.exports = () => {
last_name: "Chaudhari",
yoe: 0,
img: "./img.png",
github_user_id: "23654583",
github_id: "mehulkchaudhari",
linkedin_id: "mehulkchaudhari",
twitter_id: "mehulkchaudhari",
Expand All @@ -180,6 +187,7 @@ module.exports = () => {
yoe: 0,
img: "./img.png",
linkedin_id: "ankurnarkhede",
github_user_id: "23654236",
github_id: "ankur1234",
github_display_name: "ankur-xyz",
phone: "1234567890",
Expand All @@ -188,6 +196,7 @@ module.exports = () => {
{
username: "ritvik",
github_id: "RitvikJamwal75",
github_user_id: "23654123",
first_name: "Ritvik",
yoe: 1,
picture: {
Expand Down Expand Up @@ -218,6 +227,7 @@ module.exports = () => {
linkedin_id: "tanishqsingla",
github_id: "tanishqsingla",
github_display_name: "Tanishq Singla",
github_user_id: "26207583",
phone: "1234567890",
email: "[email protected]",
tokens: {
Expand All @@ -240,6 +250,7 @@ module.exports = () => {
linkedin_id: "darthvader",
github_id: "darthvader",
github_display_name: "Darth Vader",
github_user_id: "3188964",
phone: "1234567890",
email: "[email protected]",
tokens: {
Expand Down
3 changes: 3 additions & 0 deletions test/integration/contributions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,20 @@ describe("Contributions", function () {
yoe: 0,
img: "./img.png",
github_id: "prakashchoudhary07",
github_user_id: "12345678",
username: "prakash",
};
// Adding user
await userModel.addOrUpdate(user);
// Creating second user
user.username = "userWithNoPrs";
user.github_id = "userWithNoPrs";
user.github_user_id = "userWithNoPrs";
await userModel.addOrUpdate(user);
// Creating second user
user.username = "userNoTask";
user.github_id = "userNoTask";
user.github_user_id = "userNoTask";
await userModel.addOrUpdate(user);
// Creating task for user
const task = {
Expand Down
1 change: 1 addition & 0 deletions test/integration/tasks.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,7 @@ describe("Tasks", function () {
const { userId: assignedUser } = await userModel.addOrUpdate({
github_id: "prakashchoudhary07",
username: "user1",
github_user_id: "12345678",
});
const assignedTask = [
{
Expand Down
78 changes: 78 additions & 0 deletions test/integration/users.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const chai = require("chai");
const axios = require("axios");
const { expect } = chai;
const chaiHttp = require("chai-http");

Expand Down Expand Up @@ -26,6 +27,7 @@ const userStatusModel = require("../../models/userStatus");

const cookieName = config.get("userToken.cookieName");
const { userPhotoVerificationData } = require("../fixtures/user/photo-verification");
const githubUserInfo = require("../fixtures/auth/githubUserInfo")();
const Sinon = require("sinon");
const { INTERNAL_SERVER_ERROR } = require("../../constants/errorMessages");
const photoVerificationModel = firestore.collection("photo-verification");
Expand Down Expand Up @@ -1229,4 +1231,80 @@ describe("Users", function () {
});
});
});

describe("POST /users/migrate", function () {
let fetchStub;

beforeEach(async function () {
fetchStub = Sinon.stub(axios, "get");
});

afterEach(async function () {
Sinon.restore();
});

it("Should update the user", async function () {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think the title must be should add github_id to the user

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated the title

fetchStub.resolves({
data: githubUserInfo[0]._json,
});
const usersMigrateResponse = await chai
.request(app)
.post(`/users/migrate`)
.set("Cookie", `${cookieName}=${superUserAuthToken}`);
expect(usersMigrateResponse).to.have.status(200);
expect(usersMigrateResponse.body).to.eql({
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please use to deep equal or strict equal

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated the code

message: "Result of migration",
data: {
totalUsers: 2,
usersUpdated: 2,
usersNotUpdated: 0,
invalidUsersDetails: [],
},
});
const usersResponse = await chai.request(app).get(`/users`).set("cookie", `${cookieName}=${superUserAuthToken}`);
expect(usersResponse).to.have.status(200);
usersResponse.body.users.forEach((document) => {
expect(document).to.have.property(`github_user_id`);
});
});
it("Should return details of users with invalid github username", async function () {
fetchStub.rejects({ response: { status: 404 } });
const usersMigrateResponse = await chai
.request(app)
.post(`/users/migrate`)
.set("Cookie", `${cookieName}=${superUserAuthToken}`);
expect(usersMigrateResponse).to.have.status(200);
expect(usersMigrateResponse.body.message).to.be.equal("Result of migration");
expect(usersMigrateResponse.body).to.have.property("data");
expect(usersMigrateResponse.body.data).to.have.property("totalUsers");
expect(usersMigrateResponse.body.data.totalUsers).to.be.equal(2);
expect(usersMigrateResponse.body.data).to.have.property("usersUpdated");
expect(usersMigrateResponse.body.data.usersUpdated).to.be.equal(0);
expect(usersMigrateResponse.body.data).to.have.property("usersNotUpdated");
expect(usersMigrateResponse.body.data.usersNotUpdated).to.be.equal(2);
expect(usersMigrateResponse.body.data).to.have.property("invalidUsersDetails");
usersMigrateResponse.body.data.invalidUsersDetails.forEach((document) => {
expect(document).to.have.property("userId");
expect(document).to.have.property("username");
expect(document).to.have.property("githubUsername");
});
});
it("Should return unauthorized error when not logged in", function (done) {
chai
.request(app)
.post(`/users/migrate`)
.end((err, res) => {
if (err) {
return done(err);
}
expect(res).to.have.status(401);
expect(res.body).to.eql({
statusCode: 401,
error: "Unauthorized",
message: "Unauthenticated User",
});
return done();
});
});
});
});
Loading