Skip to content
Merged
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
1 change: 1 addition & 0 deletions apps/http-backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"cors": "^2.8.5",
"dotenv": "^17.2.3",
"express": "^5.1.0",
"googleapis": "^166.0.0",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Update googleapis to the latest version.

The current version of googleapis is 169.0.0, published 2 days ago. Version ^166.0.0 is outdated and will not receive updates beyond the 166.x range. Consider updating to ^169.0.0 for the latest bug fixes and improvements.

🤖 Prompt for AI Agents
In apps/http-backend/package.json at line 34 the dependency "googleapis":
"^166.0.0" is pinned to an outdated minor range; update the version string to
the current release range (for example "^169.0.0") in package.json, then run
your package manager to update the lockfile (npm install or yarn install) and
commit the updated package.json and lockfile so CI uses the new version.

"jsonwebtoken": "^9.0.2",
"next-auth": "^4.24.13"
}
Expand Down
4 changes: 4 additions & 0 deletions apps/http-backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { NodeRegistry } from "@repo/nodes/nodeClient";
import express from "express";
import { userRouter } from "./routes/userRoutes/userRoutes.js";
import cors from "cors"
import { sheetRouter } from "./routes/nodes.routes.js";
import { googleAuth } from "./routes/google_callback.js";

const app = express()

Expand All @@ -33,6 +35,8 @@ app.use(cookieParser());
// });

app.use("/user" , userRouter)
app.use('/node', sheetRouter)
app.use('/google', googleAuth)
const PORT= 3002
async function startServer() {
await NodeRegistry.registerAll()
Expand Down
42 changes: 42 additions & 0 deletions apps/http-backend/src/routes/google_callback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { google } from 'googleapis';
import { GoogleOAuthService } from '@repo/nodes';
import type { OAuthTokens } from '@repo/nodes';
import { userMiddleware } from './userRoutes/userMiddleware.js';
import { Router, Request, Response } from 'express';

export const googleAuth: Router = Router()

googleAuth.get('/callback', async(req: Request, res: Response)=>{
const code = req.query.code;
const state = req.query.state; // userId
const Oauth = new GoogleOAuthService;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Missing parentheses in constructor call.

new GoogleOAuthService should be new GoogleOAuthService(). While JavaScript may still work without parentheses for parameterless constructors, it's inconsistent with the rest of the codebase and could cause issues.

-    const Oauth = new GoogleOAuthService;
+    const Oauth = new GoogleOAuthService();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const Oauth = new GoogleOAuthService;
const Oauth = new GoogleOAuthService();
🤖 Prompt for AI Agents
In apps/http-backend/src/routes/google_callback.ts around line 12, the
constructor invocation is missing parentheses; change the instantiation from
using "new GoogleOAuthService" to "new GoogleOAuthService()" to match the
codebase style and ensure a proper parameterless constructor call.

if (!code || typeof code !== 'string') {
return res.json({ error: 'Missing or invalid authorization code' });
}
Comment on lines +13 to +15

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Missing HTTP status code for error response.

Line 14 returns a JSON error but doesn't set an appropriate HTTP status code (defaults to 200). This should return a 400 Bad Request.

     if (!code || typeof code !== 'string') {
-        return res.json({ error: 'Missing or invalid authorization code' });
+        return res.status(400).json({ error: 'Missing or invalid authorization code' });
     }
🤖 Prompt for AI Agents
In apps/http-backend/src/routes/google_callback.ts around lines 13 to 15, the
handler returns a JSON error for a missing/invalid authorization code but fails
to set an HTTP status, implicitly sending 200; change the response to return a
400 Bad Request by setting the status before sending JSON (e.g., use
res.status(400).json({ error: 'Missing or invalid authorization code' })) so
clients receive the correct HTTP status.


const oauth2 = new google.auth.OAuth2(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET,
process.env.GOOGLE_REDIRECT_URI
);

try {
const { tokens } = await oauth2.getToken(code);

// Save tokens to database if userId (state) is provided
if (state && typeof state === 'string') {

await Oauth.saveCredentials(state, tokens as OAuthTokens)
}
Comment on lines +26 to +30

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

State parameter must be validated against session-stored value to prevent CSRF attacks.

Clients MUST prevent Cross-Site Request Forgery (CSRF) where requests to the redirection endpoint do not originate at the authorization server but at a malicious third party. Currently, any value passed in state is trusted without verification. Implement state validation:

  1. Before redirecting to Google OAuth, generate a cryptographically secure random state and store it in the user session
  2. On callback, verify the returned state matches the stored value
  3. Only then trust the userId and proceed with token saving

This is required by OAuth 2.0 security standards and is a preventable vulnerability.

🤖 Prompt for AI Agents
In apps/http-backend/src/routes/google_callback.ts around lines 26-30, the
callback is trusting any returned state and saving tokens immediately; update
the handler to first retrieve the expected state from the user session, compare
it to the incoming state using a constant-time equality check (or strict === if
stored as plain string), and if they match proceed to save credentials; if they
do not match or the session value is missing, reject the request (return
400/unauthorized), do not save tokens, log the mismatch, and clear the session
state token; additionally ensure (elsewhere on the initial OAuth redirect) a
cryptographically secure random state is generated and stored in the session
before redirecting to Google.


// Redirect to success page
return res.redirect('http://localhost:3000/workflow');

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Hardcoded localhost URL.

The redirect URL http://localhost:3000/workflow is hardcoded, which will break in production environments.

🔎 Use environment variable:
-        return res.redirect('http://localhost:3000/workflow');
+        const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3000';
+        return res.redirect(`${frontendUrl}/workflow`);

Similarly for line 37-38:

-        return res.redirect(
-        `http://localhost:3000/workflow?google=error&msg=${encodeURIComponent(err?.message ?? 'Token exchange failed')}`);
+        const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3000';
+        return res.redirect(
+        `${frontendUrl}/workflow?google=error&msg=${encodeURIComponent(err?.message ?? 'Token exchange failed')}`);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return res.redirect('http://localhost:3000/workflow');
const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3000';
return res.redirect(`${frontendUrl}/workflow`);
🤖 Prompt for AI Agents
In apps/http-backend/src/routes/google_callback.ts around line 33, the redirect
target is hardcoded to 'http://localhost:3000/workflow'; change this to use a
configurable environment variable (e.g. process.env.FRONTEND_URL or app config)
with a sensible default for local dev, and apply the same approach to the other
hardcoded redirects at lines ~37-38 so all redirect URLs come from
configuration; validate the env value (ensure it includes protocol) before
redirecting and fall back to a safe internal route if missing or invalid.

}
catch (err: any) {
console.error('Google token exchange error:', err);
return res.redirect(
`http://localhost:3000/workflow?google=error&msg=${encodeURIComponent(err?.message ?? 'Token exchange failed')}`);
}
})


183 changes: 78 additions & 105 deletions apps/http-backend/src/routes/nodes.routes.ts
Original file line number Diff line number Diff line change
@@ -1,109 +1,82 @@
// import { Router } from 'express';
// import { prismaClient } from '@repo/db/client'
// import { GoogleSheetNode } from '@repo/nodes/nodeClinet';
import { Response, Router } from "express";
import { AuthRequest, userMiddleware } from "./userRoutes/userMiddleware.js";
import { statusCodes } from "@repo/common/zod";
import { GoogleSheetsNodeExecutor } from "@repo/nodes";

// const router: Router = Router()
export const sheetRouter: Router = Router();
const sheetExecutor = new GoogleSheetsNodeExecutor()

// router.post('/test-execute', async(req, res)=>{
// try{
// const { userId, nodeType, config } = req.body;

// const workflow = await prismaClient.workflow.create({
// data : {
// id: `workflow_test_${Date.now()}`,
// userId: userId,
// name: `Test ${nodeType} - ${new Date().toISOString()}`,
// description: 'Auto-created for testing',
// status: 'Start',
// config: {}
// }
// });
sheetRouter.get("/getDocuments/:cred", userMiddleware, async(req: AuthRequest, res: Response)=>{
try{
if (!req.user)
return res
.status(statusCodes.BAD_GATEWAY)
.json({ message: "User isnot logged in /not authorized" });
const credId = req.params.cred
if(!credId){
return res
.status(statusCodes.BAD_REQUEST)
.json({message: "credentials id not provided"})
}
const userId = req.user.sub
console.log("userid from node route: ", userId)
if(!userId) return res
.status(statusCodes.NOT_FOUND)
.json({message: "User id not provided"})
const sheets = await sheetExecutor.getSheets({userId: userId, credId: credId})
if ((sheets as any)?.success === false) {
return res.status(statusCodes.NOT_FOUND).json({
message: "files not found",
files: sheets
});
}
return res.status(statusCodes.OK).json({
message: "sheets are fetched successfully",
files: (sheets as any)?.data?.data?.files || []
})
}catch(e){
console.log("Error Fetching the credentials ", e instanceof Error ? e.message : "Unkown reason");
return res
.status(statusCodes.INTERNAL_SERVER_ERROR)
.json({ message: "Internal server from fetching the credentials" });
}
})
Comment on lines +10 to +44

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Incorrect HTTP status codes.

  1. Line 14: BAD_GATEWAY (502) is incorrect for an unauthorized user. Use UNAUTHORIZED (401) instead.
  2. Line 25: NOT_FOUND (404) is incorrect for a missing user ID parameter. Use BAD_REQUEST (400) instead.
🔎 Fix status codes:
     try{
         if (!req.user)
             return res
-                .status(statusCodes.BAD_GATEWAY)
+                .status(statusCodes.UNAUTHORIZED)
                 .json({ message: "User isnot logged in /not authorized" });
         const credId = req.params.cred
         if(!credId){
             return res
                 .status(statusCodes.BAD_REQUEST)
                 .json({message: "credentials id not provided"})
         }
         const userId = req.user.sub
         console.log("userid from node route: ", userId)
         if(!userId) return res
-                .status(statusCodes.NOT_FOUND)
+                .status(statusCodes.BAD_REQUEST)
                 .json({message: "User id not provided"})
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
sheetRouter.get("/getDocuments/:cred", userMiddleware, async(req: AuthRequest, res: Response)=>{
try{
if (!req.user)
return res
.status(statusCodes.BAD_GATEWAY)
.json({ message: "User isnot logged in /not authorized" });
const credId = req.params.cred
if(!credId){
return res
.status(statusCodes.BAD_REQUEST)
.json({message: "credentials id not provided"})
}
const userId = req.user.sub
console.log("userid from node route: ", userId)
if(!userId) return res
.status(statusCodes.NOT_FOUND)
.json({message: "User id not provided"})
const sheets = await sheetExecutor.getSheets({userId: userId, credId: credId})
if ((sheets as any)?.success === false) {
return res.status(statusCodes.NOT_FOUND).json({
message: "files not found",
files: sheets
});
}
return res.status(statusCodes.OK).json({
message: "sheets are fetched successfully",
files: (sheets as any)?.data?.data?.files || []
})
}catch(e){
console.log("Error Fetching the credentials ", e instanceof Error ? e.message : "Unkown reason");
return res
.status(statusCodes.INTERNAL_SERVER_ERROR)
.json({ message: "Internal server from fetching the credentials" });
}
})
sheetRouter.get("/getDocuments/:cred", userMiddleware, async(req: AuthRequest, res: Response)=>{
try{
if (!req.user)
return res
.status(statusCodes.UNAUTHORIZED)
.json({ message: "User isnot logged in /not authorized" });
const credId = req.params.cred
if(!credId){
return res
.status(statusCodes.BAD_REQUEST)
.json({message: "credentials id not provided"})
}
const userId = req.user.sub
console.log("userid from node route: ", userId)
if(!userId) return res
.status(statusCodes.BAD_REQUEST)
.json({message: "User id not provided"})
const sheets = await sheetExecutor.getSheets({userId: userId, credId: credId})
if ((sheets as any)?.success === false) {
return res.status(statusCodes.NOT_FOUND).json({
message: "files not found",
files: sheets
});
}
return res.status(statusCodes.OK).json({
message: "sheets are fetched successfully",
files: (sheets as any)?.data?.data?.files || []
})
}catch(e){
console.log("Error Fetching the credentials ", e instanceof Error ? e.message : "Unkown reason");
return res
.status(statusCodes.INTERNAL_SERVER_ERROR)
.json({ message: "Internal server from fetching the credentials" });
}
})
🤖 Prompt for AI Agents
In apps/http-backend/src/routes/nodes.routes.ts around lines 10 to 44, the
handler uses incorrect HTTP status codes: replace the BAD_GATEWAY (502) returned
when req.user is missing with UNAUTHORIZED (401), and replace the NOT_FOUND
(404) returned when userId is missing with BAD_REQUEST (400); update the
res.status(...) calls accordingly while keeping the existing JSON response
bodies intact.


// const availableNode = await prismaClient.availableNode.findUnique({
// where:{
// type: nodeType
// }
// });

// if(!availableNode){
// return res.status(404).json({error:"NOde type not found"})
// }

// const node = await prismaClient.node.create({
// data:{
// id: `node_test_${Date.now()}`,
// workflowId: workflow.id,
// config: config,
// typeId: availableNode.id,
// position: 1,
// name: `${availableNode.name} Node`
// }
// })

// const workflowExecution = await prismaClient.workflowExecution.create({
// data : {
// id: `exec_${Date.now()}`,
// workflowId: workflow.id,
// status: 'InProgress',
// metadata: {}

// }
// });

// const nodeExecution = await prismaClient.nodeExecution.create({
// data: {
// id: `node_exec_${Date.now()}`,
// workflowExecId: workflowExecution.id,
// status: 'InProgress',
// nodeId: node.id
// }
// });

// const executor = GoogleSheetNode.getExecutor()
// const result = await executor.execute({
// nodeId: node.id,
// userId: userId,
// config: config,
// inputData: null
// });

// await prismaClient.nodeExecution.update({
// where: {
// id: nodeExecution.id
// },
// data:{
// status: result.success ? 'Completed' : 'Failed',
// outputData: result.output ? result.output : null,
// error: result.error ? result.error : null,
// completedAt: new Date()
// }
// });

// await prismaClient.workflowExecution.update({
// where:{
// id: workflowExecution.id
// },
// data: {
// status: result.success ? 'Completed' : 'Failed',
// completedAt: new Date()
// }
// });

// res.status(200).json({
// success: true,
// workflowId: workflow.id,
// nodeId: node.id,
// workflowExecutionId: workflowExecution.id,
// nodeExecution: nodeExecution.id,
// result: result
// });
// }
// catch(e){
// res.status(500).json({
// success: false,
// error: e instanceof Error ? e.message : 'Unknown error'
// })
// }
// });

// export default router;
sheetRouter.get('/getSheets/:cred/:sheetId', userMiddleware, async(req: AuthRequest, res: Response)=>{
try{
const userId = req.user?.sub
if (!userId)
return res
.status(statusCodes.BAD_GATEWAY)
.json({ message: "User isnot logged in /not authorized" });
const credId = req.params.cred
const sheetId = req.params.sheetId
if(!credId || !sheetId){
return res
.status(statusCodes.BAD_REQUEST)
.json({message: `credentials id not provided `})
}
if(!sheetExecutor){
return res.status(statusCodes.FORBIDDEN).json({
message: "sheet executor not configured well"
})
}
const sheets = await sheetExecutor.getSheetTabs({userId: userId, credId: credId}, sheetId)

if((sheets as any)?.success === false) return res.status(statusCodes.NOT_FOUND).json({
message: "files not found",
files: sheets
});

return res.status(statusCodes.OK).json({
message: "sheets are fetched successfully",
files: sheets
})
}catch(e){
console.log("Error Fetching the credentials ", e instanceof Error ? e.message : "Unkown reason");
return res
.status(statusCodes.INTERNAL_SERVER_ERROR)
.json({ message: "Internal server from fetching the credentials" });
}
})
Comment on lines +46 to +82

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Same status code issues and unnecessary check.

  1. Line 51: BAD_GATEWAY should be UNAUTHORIZED.
  2. Lines 60-64: The check if(!sheetExecutor) is unnecessary since sheetExecutor is a module-level constant initialized at line 7 and cannot be null/undefined at runtime.
🔎 Fix status code and remove unnecessary check:
     try{
         const userId = req.user?.sub
         if (!userId)
             return res
-                .status(statusCodes.BAD_GATEWAY)
+                .status(statusCodes.UNAUTHORIZED)
                 .json({ message: "User isnot logged in /not authorized" });
         const credId = req.params.cred
         const sheetId = req.params.sheetId
         if(!credId || !sheetId){
             return res
                 .status(statusCodes.BAD_REQUEST)
                 .json({message: `credentials id not provided `})
         }
-        if(!sheetExecutor){
-            return res.status(statusCodes.FORBIDDEN).json({
-                message: "sheet executor not configured well"
-            })
-        }
         const sheets = await sheetExecutor.getSheetTabs({userId: userId, credId: credId}, sheetId)
🤖 Prompt for AI Agents
In apps/http-backend/src/routes/nodes.routes.ts around lines 46 to 82, the
response for missing user uses statusCodes.BAD_GATEWAY (line 51) and should be
statusCodes.UNAUTHORIZED, and the runtime check for sheetExecutor (lines ~60-64)
is unnecessary because sheetExecutor is a module-level constant; change the
BAD_GATEWAY to UNAUTHORIZED and remove the entire if(!sheetExecutor) {...}
block, keeping the remaining logic intact and adjusting surrounding indentation
as needed.

67 changes: 55 additions & 12 deletions apps/http-backend/src/routes/userRoutes/userRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
TriggerSchema,
WorkflowSchema,
} from "@repo/common/zod";
import { GoogleSheetsNodeExecutor } from "@repo/nodes";
const router: Router = Router();
// router.post("/create", async (req, res) => {
// // const Data = req.body;
Expand Down Expand Up @@ -64,8 +65,7 @@ router.post("/createNode", async (req: AuthRequest, res: Response) => {
}
});

router.get(
"/getAvailableNodes",
router.get("/getAvailableNodes",
userMiddleware,
async (req: AuthRequest, res: Response) => {
if (!req.user) {
Expand All @@ -90,8 +90,7 @@ router.get(
}
);

router.post(
"/createTriggers",
router.post("/createTriggers",
userMiddleware,
async (req: AuthRequest, res: Response) => {
try {
Expand Down Expand Up @@ -125,8 +124,7 @@ router.post(
}
);

router.get(
"/getAvailableTriggers",
router.get("/getAvailableTriggers",
userMiddleware,
async (req: AuthRequest, res: Response) => {
try {
Expand All @@ -150,8 +148,55 @@ router.get(
}
);

router.post(
"/create/workflow",
router.get('/getCredentials/:type',
userMiddleware,
async (req: AuthRequest, res) =>{
try{
console.log("user from getcredentials: ",req.user)
if(!req.user){
return res.status(statusCodes.BAD_REQUEST).json({
message: "User is not Loggedin"
})
}
const userId = req.user.sub;
const type = req.params.type
console.log(userId," -userid")
if(!type || !userId){
return res.status(statusCodes.BAD_REQUEST).json({
message: "Incorrect type Input",
});
}
const executor = new GoogleSheetsNodeExecutor()
const response = await executor.getAllCredentials(userId,type)
// console.log( typeof(response));
// console.log("response: ",response)
const authUrl = typeof response === 'string' ? response : null
// console.log(authUrl);

const credentials = response instanceof Object ? response : null
// console.log(credentials)
if(authUrl){
return res.status(statusCodes.OK).json({
message: "Credentials not found create credentials using this auth url",
Data: authUrl,
});
}
else return res.status(statusCodes.OK).json({
message: "Credentials Fetched succesfully",
Data: credentials,
});
}
catch(e){
console.log("Error Fetching the credentials ", e instanceof Error ? e.message : "Unkown reason");
return res
.status(statusCodes.INTERNAL_SERVER_ERROR)
.json({ message: "Internal server from fetching the credentials" });
}
}
);
Comment on lines +151 to +196

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Inconsistent user ID access and fragile type checking.

Several issues in this new endpoint:

  1. Line 161: Uses req.user.sub but other routes in this file use req.user.id. This inconsistency could cause bugs if the JWT payload structure differs.

  2. Line 176: The check response instanceof Object is unreliable because strings are also objects in JavaScript. This could lead to incorrect branching.

  3. Line 173: The check typeof response === 'string' should be sufficient, but the subsequent instanceof Object check is redundant and potentially wrong.

🔎 Suggested fix:
-        const userId = req.user.sub;
+        const userId = req.user.sub as string;
         const type = req.params.type
         console.log(userId," -userid")
         if(!type || !userId){
           return res.status(statusCodes.BAD_REQUEST).json({
             message: "Incorrect type Input",
           });
         }
         const executor = new GoogleSheetsNodeExecutor()
         const response = await executor.getAllCredentials(userId,type)
-        // console.log( typeof(response));
-        // console.log("response: ",response)
-        const authUrl = typeof response === 'string' ? response : null
-        // console.log(authUrl);
-        
-        const credentials = response instanceof Object ? response : null
-        // console.log(credentials)
-        if(authUrl){
+        if(typeof response === 'string'){
           return res.status(statusCodes.OK).json({
           message: "Credentials not found create credentials using this auth url",
-          Data: authUrl,
+          Data: response,
         });
         }
-        else return res.status(statusCodes.OK).json({
+        return res.status(statusCodes.OK).json({
           message: "Credentials Fetched succesfully",
-          Data: credentials,
+          Data: response,
         });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
router.get('/getCredentials/:type',
userMiddleware,
async (req: AuthRequest, res) =>{
try{
console.log("user from getcredentials: ",req.user)
if(!req.user){
return res.status(statusCodes.BAD_REQUEST).json({
message: "User is not Loggedin"
})
}
const userId = req.user.sub;
const type = req.params.type
console.log(userId," -userid")
if(!type || !userId){
return res.status(statusCodes.BAD_REQUEST).json({
message: "Incorrect type Input",
});
}
const executor = new GoogleSheetsNodeExecutor()
const response = await executor.getAllCredentials(userId,type)
// console.log( typeof(response));
// console.log("response: ",response)
const authUrl = typeof response === 'string' ? response : null
// console.log(authUrl);
const credentials = response instanceof Object ? response : null
// console.log(credentials)
if(authUrl){
return res.status(statusCodes.OK).json({
message: "Credentials not found create credentials using this auth url",
Data: authUrl,
});
}
else return res.status(statusCodes.OK).json({
message: "Credentials Fetched succesfully",
Data: credentials,
});
}
catch(e){
console.log("Error Fetching the credentials ", e instanceof Error ? e.message : "Unkown reason");
return res
.status(statusCodes.INTERNAL_SERVER_ERROR)
.json({ message: "Internal server from fetching the credentials" });
}
}
);
router.get('/getCredentials/:type',
userMiddleware,
async (req: AuthRequest, res) =>{
try{
console.log("user from getcredentials: ",req.user)
if(!req.user){
return res.status(statusCodes.BAD_REQUEST).json({
message: "User is not Loggedin"
})
}
const userId = req.user.sub as string;
const type = req.params.type
console.log(userId," -userid")
if(!type || !userId){
return res.status(statusCodes.BAD_REQUEST).json({
message: "Incorrect type Input",
});
}
const executor = new GoogleSheetsNodeExecutor()
const response = await executor.getAllCredentials(userId,type)
if(typeof response === 'string'){
return res.status(statusCodes.OK).json({
message: "Credentials not found create credentials using this auth url",
Data: response,
});
}
return res.status(statusCodes.OK).json({
message: "Credentials Fetched succesfully",
Data: response,
});
}
catch(e){
console.log("Error Fetching the credentials ", e instanceof Error ? e.message : "Unkown reason");
return res
.status(statusCodes.INTERNAL_SERVER_ERROR)
.json({ message: "Internal server from fetching the credentials" });
}
}
);
🤖 Prompt for AI Agents
In apps/http-backend/src/routes/userRoutes/userRoutes.ts around lines 151 to
196, the handler inconsistently reads the user id via req.user.sub (line 161)
and uses a fragile response type check (lines 173/176); change to read the same
property used elsewhere (req.user.id) and replace the response checks with
robust typeof and null/array guards: treat a string as the authUrl when typeof
response === 'string', and treat credentials when typeof response === 'object'
&& response !== null && !Array.isArray(response); keep the existing status
branches but base them on these reliable checks and ensure the initial existence
checks still validate req.user and req.user.id.



router.post("/create/workflow",
userMiddleware,
async (req: AuthRequest, res) => {
try {
Expand Down Expand Up @@ -240,8 +285,7 @@ router.post(
}
);

router.get(
"/workflows",
router.get("/workflows",
userMiddleware,
async (req: AuthRequest, res: Response) => {
try {
Expand Down Expand Up @@ -269,8 +313,7 @@ router.get(
}
);

router.get(
"/workflow/:workflowId",
router.get("/workflow/:workflowId",
userMiddleware,
async (req: AuthRequest, res: Response) => {
try {
Expand Down
Loading