Skip to content

Commit da8412e

Browse files
sahsisunnyivinayakgmanish591Pratiyushkumarravikumar1002
authored
Dev to main sync (#1420)
* api created * done suggested changes * added one more check * changes in the update task api * initial commit * test/added integration tests for route /update-archived * test/added tests for function archiveUserIfNotInDiscord * refactor: overdue and extension requests APIs * feat/added route controller and model function * remove redundant code * removed redundant code * FIX: resolved comments * FIX: merge conflicts * FIX: resolved comments * TEST: updated tests * REFACTOR: updated variable names * TEST: assert total users made archived * REFACTOR: updated route * TEST: updated route * FEAT: handles batch updates more that 500 * TEST: updated tests * TEST: assert for failed operation added * FIX: added error handling for failed batch updates * REFACTOR: removed redundant changes * TEST: fetched only users relavant in testing * TEST: updated users integration tests * TEST: added tests for archiver user function * reolved comments * feat: added test cases for tasks validators * REFACTOR: to remove circular dependency * added onBoarding status of user more than 31 days * finally finalized the route of the onboarding state * FEAT: added common route /users * TEST: updated tests * TEST: fix failed tests * REFACTOR: changed param to query * add: github created at key in db for new joiner * refactor: requested changes for overdue tasks API * fix: convert date type into unix timestamp * TEST: added model error test case * REFACTOR: added payload validator middleware * REFACTOR: added error & success states constants * FEAT: added failed users details in response * REFACTOR: resolved comments * REFACTOR: fix lint issues * TEST: updated user service test * changed the variables name * (#1367) added fix for api response * (#1367) updated tests for the code * (#1367) address failing test for validator * (#1367) address failing validator test * refactor: changed the flow for overdue tasks API * removed the filter utility function * fix: Unix Timestamp method * feat: test for github_created_at fields * remove: extra fixtures data * added integration test case * commiting unit testing * unit testing is done * resolved conflicts * TEST: fix failing test * refactor: made the overdue tasks API behind the feature flag * refactor: overdue and extension requests APIs * feat: added test cases for tasks validators * refactor: requested changes for overdue tasks API * refactor: changed the flow for overdue tasks API * refactor: made the overdue tasks API behind the feature flag * (#1367) added dataAccessLayer to fetch user * (#1368) updated model tests * refactor: overdue and extension requests APIs * feat: added test cases for tasks validators * refactor: requested changes for overdue tasks API * refactor: changed the flow for overdue tasks API * refactor: made the overdue tasks API behind the feature flag * api created * done suggested changes * added one more check * refactor: overdue and extension requests APIs * feat: added test cases for tasks validators * refactor: requested changes for overdue tasks API * refactor: changed the flow for overdue tasks API * changed the function working and made the getUsersBasedOnFilter generic * completed validation of verify status * tests for model and middleware * resolved the comments * completed validation of verify status * resolved the comments * sync with develop * resolved the comments and added generateUniqueToken action * fixed failing tests * Validation after authentication * fixing code * Refactor: keeping body optional in archiving details in the archiving process * update error message * added onBoarding condition * fixed prettier error and added logical and * validator test cases added and corrected spelling mistake * fix the staging for archived users (#1421) * removing one time script - remove tokens * forgot to remove tests * API endpoint to update Discord usernames for backend users (#1378) * Add a sample route to test it's working * FEAT:Add functionality to update discord Nickname * CHORE: remove console.log's * TEST: Added for discord-nickname-update controller * TEST: add message object accessible * TEST: Added for setUserDiscordNickname * REFACTOR: added a fixture, removed console.log's * Revert "Revert "Dev to Main Sync"" This reverts commit 3423a5f. * FEATURE: Filter task based assignee and task title (#1392) * FEATURE: add functionality to fetch task base on filter like assignee and task title * FIX : fix assignee filter * FIX : add order by title in status filter * FIX: task size related issue * FIX: order all task at initial state * TEMP * FIX: change variable name * FEATURE: add functionality to fetch task based on filter like assignee and task title * FIX(TEST) : fix failing tests * REFACTOR:change term to title query param * TEST: add test for tasks validator chages * TEST: add test for task utils * TEST: add test for task models changes * TEST: add test for task controller(integration test) * Update test/integration/tasks.test.js --------- Co-authored-by: Pratiyush Kumar <[email protected]> * FIX: Overdue tasks query issue (#1441) * FIX: overdue tasks query issue * FIX: overdue tasks query issue * Add isMember Field to API Response for Group Membership (#1413) * Adding isMember param to show membership of the user * reverting script * populating membership details only when flag is set * Adding tests * fixing PR comments: more specific checks for flags * Handling firebase limitation of 30 comparision * PR comments: semantical fix --------- Co-authored-by: ivinayakg <[email protected]> Co-authored-by: Manish Devrani <[email protected]> Co-authored-by: Manish Devrani <[email protected]> Co-authored-by: Pratiyush Kumar <[email protected]> Co-authored-by: Vinayak Goyal <[email protected]> Co-authored-by: Ravi kumar <[email protected]> Co-authored-by: vivek lokhande <[email protected]> Co-authored-by: Amit Prakash <[email protected]> Co-authored-by: Pratiyush Kumar <[email protected]> Co-authored-by: shreya-mishra <[email protected]> Co-authored-by: Lakshay Manchanda <[email protected]> Co-authored-by: gauravsinhaweb <[email protected]> Co-authored-by: Ritik Jaiswal <[email protected]> Co-authored-by: FMK2312 <[email protected]> Co-authored-by: Ankush Dharkar <[email protected]> Co-authored-by: kotesh_Mudila <[email protected]> Co-authored-by: Prakash <[email protected]> Co-authored-by: Prakash Choudhary <[email protected]> Co-authored-by: Bikash Singh <[email protected]>
1 parent e63f2b9 commit da8412e

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

61 files changed

+2385
-276
lines changed

constants/errorMessages.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,5 @@ module.exports = {
88
BAD_REQUEST: "BAD_REQUEST",
99
INVALID_QUERY_PARAM: "Invalid Query Parameters Passed",
1010
FILE_TOO_LARGE: (size) => `File too large, max accepted size is ${size} MB`,
11+
USER_DOES_NOT_EXIST_ERROR: "User does not exist!",
1112
};

constants/tasks.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ const TASK_STATUS = {
2020
RELEASED: "RELEASED",
2121
VERIFIED: "VERIFIED",
2222
DONE: "DONE",
23+
OVERDUE: "OVERDUE",
2324
};
2425

2526
// TODO: convert this to new task status

constants/userDataLevels.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const ACCESS_LEVEL = {
2+
PUBLIC: "public",
3+
INTERNAL: "internal",
4+
PRIVATE: "private",
5+
CONFIDENTIAL: "confidential",
6+
};
7+
8+
const ROLE_LEVEL = {
9+
private: ["super_user"],
10+
internal: ["super_user"],
11+
confidential: ["super_user"],
12+
};
13+
14+
const KEYS_NOT_ALLOWED = {
15+
public: ["email", "phone", "chaincode"],
16+
internal: ["phone", "chaincode"],
17+
private: ["chaincode"],
18+
confidential: [],
19+
};
20+
21+
module.exports = { ACCESS_LEVEL, KEYS_NOT_ALLOWED, ROLE_LEVEL };

constants/users.js

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@ const profileStatus = {
44
NOT_APPROVED: "NOT APPROVED",
55
};
66

7-
const USER_SENSITIVE_DATA = ["phone", "email", "chaincode", "tokens"];
8-
97
const USER_STATUS = {
108
OOO: "ooo",
119
IDLE: "idle",
@@ -19,9 +17,34 @@ const ALLOWED_FILTER_PARAMS = {
1917
ROLE: ["role"],
2018
};
2119

20+
const DOCUMENT_WRITE_SIZE = 500;
21+
22+
const USERS_PATCH_HANDLER_ACTIONS = {
23+
ARCHIVE_USERS: "archiveUsers",
24+
NON_VERFIED_DISCORD_USERS: "nonVerifiedDiscordUsers",
25+
};
26+
27+
const USERS_PATCH_HANDLER_ERROR_MESSAGES = {
28+
VALIDATE_PAYLOAD: "Invalid Payload",
29+
ARCHIVE_USERS: {
30+
NO_USERS_DATA_TO_UPDATE: "Couldn't find any users currently inactive in Discord but not archived.",
31+
BATCH_DATA_UPDATED_FAILED: "Firebase batch operation failed",
32+
},
33+
};
34+
35+
const USERS_PATCH_HANDLER_SUCCESS_MESSAGES = {
36+
ARCHIVE_USERS: {
37+
SUCCESSFULLY_UPDATED_DATA: "Successfully updated users archived role to true if in_discord role is false",
38+
SUCCESSFULLY_COMPLETED_BATCH_UPDATES: "Successfully completed batch updates",
39+
},
40+
};
41+
2242
module.exports = {
2343
profileStatus,
2444
USER_STATUS,
2545
ALLOWED_FILTER_PARAMS,
26-
USER_SENSITIVE_DATA,
46+
DOCUMENT_WRITE_SIZE,
47+
USERS_PATCH_HANDLER_ACTIONS,
48+
USERS_PATCH_HANDLER_ERROR_MESSAGES,
49+
USERS_PATCH_HANDLER_SUCCESS_MESSAGES,
2750
};

controllers/auth.js

Lines changed: 37 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,13 @@ const passport = require("passport");
22
const users = require("../models/users");
33
const QrCodeAuthModel = require("../models/qrCodeAuth");
44
const authService = require("../services/authService");
5-
const { SOMETHING_WENT_WRONG, DATA_ADDED_SUCCESSFULLY, BAD_REQUEST } = require("../constants/errorMessages");
5+
const dataAccess = require("../services/dataAccessLayer");
6+
const {
7+
SOMETHING_WENT_WRONG,
8+
DATA_ADDED_SUCCESSFULLY,
9+
USER_DOES_NOT_EXIST_ERROR,
10+
} = require("../constants/errorMessages");
11+
const { generateUniqueToken } = require("../utils/generateUniqueToken");
612

713
/**
814
* Makes authentication call to GitHub statergy
@@ -49,11 +55,10 @@ const githubAuthCallback = (req, res, next) => {
4955
logger.error(err);
5056
return res.boom.unauthorized("User cannot be authenticated");
5157
}
52-
5358
userData = {
5459
github_id: user.username,
5560
github_display_name: user.displayName,
56-
// github_account_created_at: user.created_at,
61+
github_created_at: Number(new Date(user._json.created_at).getTime()),
5762
created_at: Date.now(),
5863
updated_at: Date.now(),
5964
};
@@ -111,13 +116,12 @@ const storeUserDeviceInfo = async (req, res) => {
111116
authorization_status: "NOT_INIT",
112117
};
113118

114-
const userInfo = await QrCodeAuthModel.storeUserDeviceInfo(userJson);
119+
const userInfoData = await dataAccess.retrieveUsers({ id: userJson.user_id });
115120

116-
if (!userInfo) {
117-
return res.status(404).json({
118-
message: BAD_REQUEST,
119-
});
121+
if (!userInfoData.userExists) {
122+
return res.boom.notFound(USER_DOES_NOT_EXIST_ERROR);
120123
}
124+
const userInfo = await QrCodeAuthModel.storeUserDeviceInfo(userJson);
121125

122126
return res.status(201).json({
123127
...userInfo,
@@ -133,7 +137,11 @@ const updateAuthStatus = async (req, res) => {
133137
try {
134138
const userId = req.userData.id;
135139
const authStatus = req.params.authorization_status;
136-
const result = await QrCodeAuthModel.updateStatus(userId, authStatus);
140+
let token;
141+
if (authStatus === "AUTHORIZED") {
142+
token = await generateUniqueToken();
143+
}
144+
const result = await QrCodeAuthModel.updateStatus(userId, authStatus, token);
137145

138146
if (!result.userExists) {
139147
return res.boom.notFound("Document not found!");
@@ -151,8 +159,8 @@ const updateAuthStatus = async (req, res) => {
151159

152160
const fetchUserDeviceInfo = async (req, res) => {
153161
try {
154-
const deviceId = req.query.device_id;
155-
const userDeviceInfoData = await QrCodeAuthModel.retrieveUserDeviceInfo(deviceId);
162+
const { device_id: deviceId } = req.query;
163+
const userDeviceInfoData = await QrCodeAuthModel.retrieveUserDeviceInfo({ deviceId });
156164
if (!userDeviceInfoData.userExists) {
157165
return res.boom.notFound(`User with id ${deviceId} does not exist.`);
158166
}
@@ -166,11 +174,29 @@ const fetchUserDeviceInfo = async (req, res) => {
166174
}
167175
};
168176

177+
const fetchDeviceDetails = async (req, res) => {
178+
try {
179+
const userId = req.userData.id;
180+
const userDeviceInfoData = await QrCodeAuthModel.retrieveUserDeviceInfo({ userId });
181+
if (!userDeviceInfoData.userExists) {
182+
return res.boom.notFound(`User with id ${userId} does not exist.`);
183+
}
184+
return res.json({
185+
message: "Authentication document Exists",
186+
data: { device_info: userDeviceInfoData.data?.device_info },
187+
});
188+
} catch (error) {
189+
logger.error(`Error while fetching user device info: ${error}`);
190+
return res.boom.badImplementation(SOMETHING_WENT_WRONG);
191+
}
192+
};
193+
169194
module.exports = {
170195
githubAuthLogin,
171196
githubAuthCallback,
172197
signout,
173198
storeUserDeviceInfo,
174199
updateAuthStatus,
175200
fetchUserDeviceInfo,
201+
fetchDeviceDetails,
176202
};

controllers/discordactions.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,16 @@ const createGroupRole = async (req, res) => {
6666
const getAllGroupRoles = async (req, res) => {
6767
try {
6868
const { groups } = await discordRolesModel.getAllGroupRoles();
69+
const dev = req.query.dev === "true";
70+
if (dev) {
71+
// Placing the new changes under the feature flag.
72+
const discordId = req.userData?.discordId;
73+
const groupsWithMembershipInfo = await discordRolesModel.enrichGroupDataWithMembershipInfo(discordId, groups);
74+
return res.json({
75+
message: "Roles fetched successfully!",
76+
groups: groupsWithMembershipInfo,
77+
});
78+
}
6979
return res.json({
7080
message: "Roles fetched successfully!",
7181
groups,

controllers/events.js

Lines changed: 71 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
/* eslint-disable camelcase */
21
const { GET_ALL_EVENTS_LIMIT_MIN, UNWANTED_PROPERTIES_FROM_100MS } = require("../constants/events");
2+
const { INTERNAL_SERVER_ERROR } = require("../constants/errorMessages");
3+
34
const { EventTokenService, EventAPIService } = require("../services");
4-
const { removeUnwantedProperties } = require("../utils/events");
55
const eventQuery = require("../models/events");
6+
67
const logger = require("../utils/logger");
8+
const { removeUnwantedProperties } = require("../utils/events");
79

810
const tokenService = new EventTokenService();
911
const apiService = new EventAPIService(tokenService);
@@ -100,7 +102,7 @@ const joinEvent = async (req, res) => {
100102
});
101103
} catch (error) {
102104
logger.error({ error });
103-
return res.status(500).send("Internal Server Error");
105+
return res.boom.badImplementation(INTERNAL_SERVER_ERROR);
104106
}
105107
};
106108

@@ -193,11 +195,77 @@ const endActiveEvent = async (req, res) => {
193195
}
194196
};
195197

198+
/**
199+
* Adds a peer to an event.
200+
*
201+
* @async
202+
* @function
203+
* @param {Object} req - The Express request object.
204+
* @param {Object} res - The Express response object.
205+
* @returns {Promise<Object>} The JSON response with the added peer data and a success message.
206+
* @throws {Object} The JSON response with an error message if an error occurred while adding the peer.
207+
*/
208+
const addPeerToEvent = async (req, res) => {
209+
try {
210+
const data = await eventQuery.addPeerToEvent({
211+
peerId: req.body.peerId,
212+
name: req.body.name,
213+
role: req.body.role,
214+
joinedAt: req.body.joinedAt,
215+
eventId: req.params.id,
216+
});
217+
return res.status(200).json({
218+
data,
219+
message: `Selected Participant is added to the event.`,
220+
});
221+
} catch (error) {
222+
logger.error({ error });
223+
return res.status(500).json({
224+
error: error.code,
225+
message: "You can't add selected Participant. Please ask Admin or Host for help.",
226+
});
227+
}
228+
};
229+
230+
/**
231+
* Kicks out a peer from an event.
232+
*
233+
* @async
234+
* @function
235+
* @param {Object} req - The Express request object.
236+
* @param {Object} res - The Express response object.
237+
* @returns {Promise<Object>} The JSON response with a success message if the peer is successfully kicked out.
238+
* @throws {Object} The JSON response with an error message if an error occurred while kicking out the peer.
239+
*/
240+
const kickoutPeer = async (req, res) => {
241+
const { id } = req.params;
242+
const payload = {
243+
peer_id: req.body.peerId,
244+
reason: req.body.reason,
245+
};
246+
247+
try {
248+
await apiService.post(`/active-rooms/${id}/remove-peers`, payload);
249+
await eventQuery.kickoutPeer({ eventId: id, peerId: payload.peer_id, reason: req.body.reason });
250+
return res.status(200).json({
251+
message: `Selected Participant is removed from event.`,
252+
});
253+
} catch (error) {
254+
logger.error({ error });
255+
return res.status(500).json({
256+
error: error.code,
257+
message: "You can't remove selected Participant from Remove, Please ask Admin or Host for help.",
258+
});
259+
}
260+
};
261+
196262
module.exports = {
197263
createEvent,
198264
getAllEvents,
199265
joinEvent,
200266
getEventById,
201267
updateEvent,
202268
endActiveEvent,
269+
addPeerToEvent,
270+
kickoutPeer,
203271
};

controllers/extensionRequests.js

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
const extensionRequestsQuery = require("../models/extensionRequests");
22
const { addLog } = require("../models/logs");
33
const tasks = require("../models/tasks");
4-
const { getUsername } = require("../utils/users");
4+
const { getUsername, getUsernameElseUndefined, getUserIdElseUndefined } = require("../utils/users");
55
const { EXTENSION_REQUEST_STATUS } = require("../constants/extensionRequests");
66
const { INTERNAL_SERVER_ERROR } = require("../constants/errorMessages");
77
/**
@@ -14,11 +14,22 @@ const createTaskExtensionRequest = async (req, res) => {
1414
try {
1515
const extensionBody = req.body;
1616

17+
let assigneeUsername = await getUsernameElseUndefined(extensionBody.assignee);
18+
let assigneeId = extensionBody.assignee;
19+
if (!assigneeUsername) {
20+
assigneeId = await getUserIdElseUndefined(extensionBody.assignee);
21+
assigneeUsername = extensionBody.assignee;
22+
extensionBody.assignee = assigneeId;
23+
}
24+
25+
if (!assigneeId) {
26+
return res.boom.badRequest("User with this id or username doesn't exist.");
27+
}
28+
1729
if (req.userData.id !== extensionBody.assignee && !req.userData.roles?.super_user) {
18-
return res.boom.forbidden("Only Super User can create an extension request for this task.");
30+
return res.boom.forbidden("Only assigned user and super user can create an extension request for this task.");
1931
}
2032

21-
const assigneeUsername = await getUsername(extensionBody.assignee);
2233
const { taskData: task } = await tasks.fetchTask(extensionBody.taskId);
2334
if (!task) {
2435
return res.boom.badRequest("Task with this id or taskid doesn't exist.");

controllers/members.js

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
const ROLES = require("../constants/roles");
22
const members = require("../models/members");
33
const tasks = require("../models/tasks");
4-
const { SOMETHING_WENT_WRONG } = require("../constants/errorMessages");
4+
const { SOMETHING_WENT_WRONG, INTERNAL_SERVER_ERROR } = require("../constants/errorMessages");
55
const dataAccess = require("../services/dataAccessLayer");
6+
const { addLog } = require("../models/logs");
67
/**
78
* Fetches the data about our members
89
*
@@ -83,17 +84,33 @@ const archiveMembers = async (req, res) => {
8384
try {
8485
const { username } = req.params;
8586
const user = await dataAccess.retrieveUsers({ username });
87+
const superUserId = req.userData.id;
88+
const { reason } = req.body;
89+
const roles = req?.userData?.roles;
8690
if (user?.userExists) {
8791
const successObject = await members.addArchiveRoleToMembers(user.user.id);
8892
if (successObject.isArchived) {
8993
return res.boom.badRequest("User is already archived");
9094
}
95+
const body = {
96+
reason: reason || "",
97+
archived_user: {
98+
user_id: user.user.id,
99+
username: user.user.username,
100+
},
101+
archived_by: {
102+
user_id: superUserId,
103+
roles: roles,
104+
},
105+
};
106+
107+
addLog("archived-details", {}, body);
91108
return res.status(204).send();
92109
}
93110
return res.boom.notFound("User doesn't exist");
94111
} catch (err) {
95112
logger.error(`Error while retriving contributions ${err}`);
96-
return res.boom.badImplementation(SOMETHING_WENT_WRONG);
113+
return res.boom.badImplementation(INTERNAL_SERVER_ERROR);
97114
}
98115
};
99116

controllers/tasks.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,8 @@ const fetchPaginatedTasks = async (query) => {
126126

127127
const fetchTasks = async (req, res) => {
128128
try {
129-
const { dev, status, page, size, prev, next, q: queryString } = req.query;
130-
const transformedQuery = transformQuery(dev, status, size, page);
129+
const { dev, status, page, size, prev, next, q: queryString, assignee, title } = req.query;
130+
const transformedQuery = transformQuery(dev, status, size, page, assignee, title);
131131

132132
if (dev) {
133133
const paginatedTasks = await fetchPaginatedTasks({ ...transformedQuery, prev, next });

0 commit comments

Comments
 (0)