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

Feature: inDiscord #1060

Merged
merged 11 commits into from
May 19, 2023
1 change: 1 addition & 0 deletions constants/roles.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const ROLES = {
APPOWNER: "app_owner",
MEMBER: "member",
ARCHIVED: "archived",
IN_DISCORD: "inDiscord",
};

module.exports = ROLES;
64 changes: 61 additions & 3 deletions controllers/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ const logsQuery = require("../models/logs");
const imageService = require("../services/imageService");
const { profileDiffStatus } = require("../constants/profileDiff");
const { logType } = require("../constants/logs");
const { fetch } = require("../utils/fetch");

const logger = require("../utils/logger");
const obfuscate = require("../utils/obfuscate");
const { getPaginationLink, getUsernamesFromPRs } = require("../utils/users");
const { getPaginationLink, getUsernamesFromPRs, mapDiscordMembersDataAndSyncRole } = require("../utils/users");
const { getQualifiers } = require("../utils/helper");
const { SOMETHING_WENT_WRONG, INTERNAL_SERVER_ERROR } = require("../constants/errorMessages");
const { getFilteredPRsOrIssues } = require("../utils/pullRequests");
const { IN_DISCORD } = require("../constants/roles");
const jwt = require("jsonwebtoken");

const verifyUser = async (req, res) => {
const userId = req.userData.id;
Expand All @@ -24,7 +26,11 @@ const verifyUser = async (req, res) => {
logger.error(`Error while verifying user: ${error}`);
return res.boom.serverUnavailable(SOMETHING_WENT_WRONG);
}
fetch(process.env.IDENTITY_SERVICE_URL, "POST", null, { userId }, { "Content-Type": "application/json" });
fetch(process.env.IDENTITY_SERVICE_URL, {
method: "POST",
body: { userId },
headers: { "Content-Type": "application/json" },
});
heyrandhir marked this conversation as resolved.
Show resolved Hide resolved
return res.json({
DashDeipayan marked this conversation as resolved.
Show resolved Hide resolved
message: "Your request has been queued successfully",
});
Expand Down Expand Up @@ -461,6 +467,55 @@ const filterUsers = async (req, res) => {
return res.boom.serverUnavailable("Something went wrong please contact admin");
}
};
const DISCORD_BASE_URL = "https://89d4-49-36-233-201.ngrok.io";
const syncInDiscordRole = async (req, res) => {
try {
const authToken = jwt.sign({}, config.get("botToken.botPrivateKey"), {
algorithm: "RS256",
});
// console.log(authToken);
const response = await fetch(`${DISCORD_BASE_URL}/discord-members`, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${authToken}`,
},
});
const discordMembers = await response.json();

const allUsers = await userQuery.getAllUsers();
mapDiscordMembersDataAndSyncRole(allUsers, discordMembers);

return res.json({ message: "Synced with discord members " });
} catch (error) {
logger.error(`Error while fetching all users: ${error}`);
return res.boom.serverUnavailable("Something went wrong please contact admin");
}
};

const fetchVerifiedUsers = async (req, res) => {
try {
const verifiedUsers = await userQuery.fetchUsersWhereFieldNotNull("discordId");
return res.json(verifiedUsers);
} catch (error) {
logger.error(`Error while fetching all users: ${error}`);
return res.boom.serverUnavailable("Something went wrong please contact admin");
}
};

const fetchInDiscordUsers = async (req, res) => {
try {
const usersInDiscord = await userQuery.fetchUsersWithRole(IN_DISCORD);

return res.json({
message: "Users found successfully!",
users: usersInDiscord,
count: usersInDiscord.length,
});
} catch (error) {
logger.error(`Error while fetching all users: ${error}`);
return res.boom.serverUnavailable("Something went wrong please contact admin");
}
};

module.exports = {
verifyUser,
Expand All @@ -481,4 +536,7 @@ module.exports = {
addDefaultArchivedRole,
getUserSkills,
filterUsers,
fetchInDiscordUsers,
syncInDiscordRole,
fetchVerifiedUsers,
};
59 changes: 59 additions & 0 deletions models/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,62 @@ const getUsersBasedOnFilter = async (query) => {
const userDocs = (await firestore.getAll(...userRefs)).map((doc) => ({ id: doc.id, ...doc.data() }));
return userDocs;
};
const getAllUsers = async () => {
try {
const usersRef = await userModel.get();
return usersRef;
} catch (err) {
logger.error("Error retrieving users data with roles of inDiscord", err);
throw err;
}
};
const fetchUsersWithRole = async (role) => {
try {
// console.log(role);
const snapshot = await userModel.where(`roles.${role}`, "==", true).get();
const onlyMembers = [];

if (!snapshot.empty) {
snapshot.forEach((doc) => {
onlyMembers.push({
id: doc.id,
...doc.data(),
phone: undefined,
email: undefined,
tokens: undefined,
});
});
}

return onlyMembers;
} catch (err) {
logger.error("Error retrieving users data with roles of inDiscord", err);
throw err;
}
};
const fetchUsersWhereFieldNotNull = async (field) => {
try {
const snapshot = await userModel.where(field, "!=", null).get();
const users = [];

if (!snapshot.empty) {
snapshot.forEach((doc) => {
users.push({
id: doc.id,
...doc.data(),
phone: undefined,
email: undefined,
tokens: undefined,
});
});
}

return users;
} catch (err) {
logger.error("Error retrieving users data with roles of inDiscord", err);
throw err;
}
};

module.exports = {
addOrUpdate,
Expand All @@ -424,4 +480,7 @@ module.exports = {
getRdsUserInfoByGitHubUsername,
fetchUsers,
getUsersBasedOnFilter,
fetchUsersWithRole,
fetchUsersWhereFieldNotNull,
getAllUsers,
};
3 changes: 3 additions & 0 deletions routes/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ router.get("/self", authenticate, users.getSelfDetails);
router.get("/isUsernameAvailable/:username", authenticate, users.getUsernameAvailabilty);
router.get("/chaincode", authenticate, users.generateChaincode);
router.get("/search", userValidator.validateUserQueryParams, users.filterUsers);
router.get("/inDiscord", authenticate, users.fetchInDiscordUsers);
Fixed Show fixed Hide fixed
router.post("/syncInDiscord", authenticate, users.syncInDiscordRole);
Fixed Show fixed Hide fixed
router.get("/verified", authenticate, users.fetchVerifiedUsers);
Fixed Show fixed Hide fixed
router.get("/:username", users.getUser);
router.get("/:userId/intro", authenticate, authorizeRoles([SUPERUSER]), users.getUserIntro);
router.put("/self/intro", authenticate, userValidator.validateJoinData, users.addUserIntro);
Expand Down
24 changes: 24 additions & 0 deletions utils/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,29 @@ function getUsernamesFromPRs(allPRs) {

return usernames;
}
function mapDiscordMembersDataAndSyncRole(allUsers, discordMembers) {
try {
allUsers.forEach((doc) => {
const user = doc.data();

if (user.roles.archived) {
const roles = user.roles ? { ...user.roles, inDiscord: false } : { inDiscord: false };
doc.ref.update({ roles });
} else if (user.discordId) {
const discordUserData = discordMembers.find((item) => item.user.id === user.discordId);
if (discordUserData) {
const roles = user.roles ? { ...user.roles, inDiscord: true } : { inDiscord: true };
doc.ref.update({ roles, joined_RDS: discordUserData.joined_at });
} else {
const roles = user.roles ? { ...user.roles, inDiscord: false } : { inDiscord: false };
doc.ref.update({ roles });
}
}
});
} catch (err) {
logger.error(err);
}
}

module.exports = {
addUserToDBForTest,
Expand All @@ -152,4 +175,5 @@ module.exports = {
getLowestLevelSkill,
getPaginationLink,
getUsernamesFromPRs,
mapDiscordMembersDataAndSyncRole,
};