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

migration: added migration script for migrate old users status in new collections #2177

Draft
wants to merge 2 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
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
27 changes: 27 additions & 0 deletions controllers/userStatus.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const { INTERNAL_SERVER_ERROR } = require("../constants/errorMessages");
const dataAccess = require("../services/dataAccessLayer");
const userStatusModel = require("../models/userStatus");
const { userState, CANCEL_OOO } = require("../constants/userStatus");
const { migrateUserStatus } = require("../models/userStatusMigrationFinal");

/**
* Deletes a new User Status
Expand Down Expand Up @@ -240,6 +241,31 @@ const updateUserStatusController = async (req, res, next) => {
}
};

/**
* Controller function for migrating user statuses.
*
* @param req {Object} - The express request object.
* @param res {Object} - The express response object.
* @returns {Promise<void>}
*/

const migrateUserStatusController = async (req, res) => {
try {
const migrationResult = await migrateUserStatus();
return res.status(200).json({
message: "User Status migration completed successfully.",
data: migrationResult,
});
} catch (error) {
logger.error(`Error during User Status migration: ${error}`);
return res.status(500).json({
message:
"An error occurred during the User Status migration. Please contact the administrator for more information.",
error: error.message,
});
}
};

module.exports = {
deleteUserStatus,
getUserStatus,
Expand All @@ -250,4 +276,5 @@ module.exports = {
getUserStatusControllers,
batchUpdateUsersStatus,
updateUserStatusController,
migrateUserStatusController,
};
163 changes: 163 additions & 0 deletions models/userStatusMigrationFinal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
import admin from "firebase-admin";
import firestore from "../utils/firestore";

const oldUserStatusCollection = firestore.collection("usersStatus");
const newUserStatusCollection = firestore.collection("userStatus");
const newUserFutureStatusCollection = firestore.collection("userFutureStatus");

const BATCH_SIZE = 500;

interface OldUserStatus {
userId: string;
currentStatus?: {
from: number;
until?: number;
state: string;
message?: string;
};
futureStatus?: {
from: number;
until?: number;
state: string;
message?: string;
};
}

interface NewUserStatus {
userId: string;
appliedOn: Date;
status: string;
state: "CURRENT" | "PAST";
endedOn?: Date;
message?: string;
}

interface NewUserFutureStatus {
userId: string;
from: Date;
status: string;
state: "UPCOMING" | "APPLIED" | "NOT_APPLIED";
endsOn?: Date;
message?: string;
}

interface MigrationResult {
totalProcessed: number;
totalMigrated: number;
totalSkipped: number;
batches: {
processedCount: number;
migratedCount: number;
skippedCount: number;
}[];
}

async function fetchBatch(lastDoc?: admin.firestore.QueryDocumentSnapshot): Promise<admin.firestore.QuerySnapshot> {
let query = oldUserStatusCollection.orderBy("userId").limit(BATCH_SIZE);
if (lastDoc) {
query = query.startAfter(lastDoc);
}
return await query.get();
}

async function userExistsInNewCollections(userId: string): Promise<boolean> {
const existingStatus = await newUserStatusCollection.where("userId", "==", userId).limit(1).get();
const existingFutureStatus = await newUserFutureStatusCollection.where("userId", "==", userId).limit(1).get();
return !existingStatus.empty || !existingFutureStatus.empty;
}

function prepareStatus(data: OldUserStatus): NewUserStatus | null {
if (!data.currentStatus) return null;

return {
userId: data.userId,
appliedOn: new Date(data.currentStatus.from),
status: data.currentStatus.state,
state: "CURRENT",
endedOn: data.currentStatus.until ? new Date(data.currentStatus.until) : undefined,
message: data.currentStatus.message,
};
}

function prepareFutureStatus(data: OldUserStatus): NewUserFutureStatus | null {
if (!data.futureStatus) return null;

return {
userId: data.userId,
from: new Date(data.futureStatus.from),
status: data.futureStatus.state,
state: "UPCOMING",
endsOn: data.futureStatus.until ? new Date(data.futureStatus.until) : undefined,
message: data.futureStatus.message,
};
}

async function migrateBatch(
snapshot: admin.firestore.QuerySnapshot
): Promise<{ migratedCount: number; skippedCount: number }> {
const batch = firestore.batch();
let migratedCount = 0;
let skippedCount = 0;

for (const doc of snapshot.docs) {
const data = doc.data() as OldUserStatus;
const userId = data.userId;

if (await userExistsInNewCollections(userId)) {
skippedCount++;
continue;
}

const status = prepareStatus(data);
if (status) {
batch.set(newUserStatusCollection.doc(), status);
}

const futureStatus = prepareFutureStatus(data);
if (futureStatus) {
batch.set(newUserFutureStatusCollection.doc(), futureStatus);
}

migratedCount++;
}

await batch.commit();
return { migratedCount, skippedCount };
}

async function migrateUserStatus(): Promise<MigrationResult> {
let lastDoc: admin.firestore.QueryDocumentSnapshot | undefined = undefined;
let totalMigrated = 0;
let totalSkipped = 0;
let totalProcessed = 0;
const batches: MigrationResult["batches"] = [];

while (true) {
const snapshot = await fetchBatch(lastDoc);
if (snapshot.empty) {
break;
}

const { migratedCount, skippedCount } = await migrateBatch(snapshot);
totalMigrated += migratedCount;
totalSkipped += skippedCount;
totalProcessed += snapshot.size;

batches.push({
processedCount: snapshot.size,
migratedCount,
skippedCount,
});

lastDoc = snapshot.docs[snapshot.docs.length - 1];
}

return {
totalProcessed,
totalMigrated,
totalSkipped,
batches,
};
}

export { migrateUserStatus };
3 changes: 3 additions & 0 deletions routes/userStatus.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
batchUpdateUsersStatus,
getUserStatusControllers,
updateUserStatusController,
migrateUserStatusController,
} = require("../controllers/userStatus");
const router = express.Router();
const authenticate = require("../middlewares/authenticate");
Expand Down Expand Up @@ -35,4 +36,6 @@
router.patch("/:userId", authenticate, authorizeRoles([SUPERUSER]), validateUserStatus, updateUserStatus);
router.delete("/:userId", authenticate, authorizeRoles([SUPERUSER]), deleteUserStatus);

router.post("/migrate", authenticate, authorizeRoles([SUPERUSER]), migrateUserStatusController);

Check failure

Code scanning / CodeQL

Missing rate limiting High

This route handler performs
authorization
, but is not rate-limited.
This route handler performs
authorization
, but is not rate-limited.
This route handler performs
authorization
, but is not rate-limited.

Copilot Autofix AI 4 months ago

To fix the problem, we will add a rate-limiting middleware to the Express application. We will use the express-rate-limit package to limit the number of requests to the /migrate endpoint. This will help prevent abuse and potential DoS attacks.

  1. Install the express-rate-limit package if it is not already installed.
  2. Import the express-rate-limit package in the routes/userStatus.js file.
  3. Configure a rate limiter with appropriate settings (e.g., maximum of 100 requests per 15 minutes).
  4. Apply the rate limiter to the /migrate route.
Suggested changeset 2
routes/userStatus.js

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/routes/userStatus.js b/routes/userStatus.js
--- a/routes/userStatus.js
+++ b/routes/userStatus.js
@@ -1,2 +1,3 @@
 const express = require("express");
+const RateLimit = require("express-rate-limit");
 const {
@@ -24,2 +25,8 @@
 
+// set up rate limiter: maximum of 100 requests per 15 minutes
+const limiter = RateLimit({
+  windowMs: 15 * 60 * 1000, // 15 minutes
+  max: 100, // max 100 requests per windowMs
+});
+
 router.get("/", validateGetQueryParams, getUserStatusControllers);
@@ -38,3 +45,3 @@
 
-router.post("/migrate", authenticate, authorizeRoles([SUPERUSER]), migrateUserStatusController);
+router.post("/migrate", limiter, authenticate, authorizeRoles([SUPERUSER]), migrateUserStatusController);
 
EOF
@@ -1,2 +1,3 @@
const express = require("express");
const RateLimit = require("express-rate-limit");
const {
@@ -24,2 +25,8 @@

// set up rate limiter: maximum of 100 requests per 15 minutes
const limiter = RateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // max 100 requests per windowMs
});

router.get("/", validateGetQueryParams, getUserStatusControllers);
@@ -38,3 +45,3 @@

router.post("/migrate", authenticate, authorizeRoles([SUPERUSER]), migrateUserStatusController);
router.post("/migrate", limiter, authenticate, authorizeRoles([SUPERUSER]), migrateUserStatusController);

package.json
Outside changed files

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/package.json b/package.json
--- a/package.json
+++ b/package.json
@@ -39,3 +39,4 @@
     "rate-limiter-flexible": "5.0.3",
-    "winston": "3.13.0"
+    "winston": "3.13.0",
+    "express-rate-limit": "^7.4.0"
   },
EOF
@@ -39,3 +39,4 @@
"rate-limiter-flexible": "5.0.3",
"winston": "3.13.0"
"winston": "3.13.0",
"express-rate-limit": "^7.4.0"
},
This fix introduces these dependencies
Package Version Security advisories
express-rate-limit (npm) 7.4.0 None
Copilot is powered by AI and may make mistakes. Always verify output.
Positive Feedback
Negative Feedback

Provide additional feedback

Please help us improve GitHub Copilot by sharing more details about this comment.

Please select one or more of the options

module.exports = router;
Loading