Skip to content

feat/ add API to update impersonation requests#2446

Merged
iamitprakash merged 7 commits intoRealDevSquad:developfrom
Suvidh-kaushik:feat/update_impersonation_requests
Jun 28, 2025
Merged

feat/ add API to update impersonation requests#2446
iamitprakash merged 7 commits intoRealDevSquad:developfrom
Suvidh-kaushik:feat/update_impersonation_requests

Conversation

@Suvidh-kaushik
Copy link
Contributor

@Suvidh-kaushik Suvidh-kaushik commented Jun 21, 2025

Date: 21/06/2025

Developer Name: Suvidh Kaushik


Issue Ticket Number

Description

Documentation Updated?

  • Yes
  • No

Under Feature Flag

  • Yes
  • No

Database Changes

  • Yes
  • No

Breaking Changes

  • Yes
  • No

Development Tested?

  • Yes
  • No

Screenshots

Recordings Unauthorized to update
update_4.mp4

Rejected and already Rejected

update_2.mp4

Approved

update_1.mp4

Request does not exist

update_3.mp4

Test Coverage

Details

Unit Tests Coverage Report

Validator

Screenshot 2025-06-21 171114

Screenshot 2025-06-21 171133

Service
Screenshot 2025-06-21 171217

Screenshot 2025-06-21 171226

Model
Screenshot 2025-06-21 171005

Screenshot 2025-06-21 170950

Integration Tests Coverage Report

Screenshot 2025-06-21 172648

Screenshot 2025-06-21 173145

Screenshot 2025-06-21 173502

Screenshot 2025-06-21 173054

Screenshot 2025-06-21 173104

Additional Notes

Design Doc - LINK

PRD - LINK

Description by Korbit AI

What change is being made?

Add a new API endpoint to update the status of impersonation requests, including associated controllers, validators, services, models, and routes.

Why are these changes being made?

This change allows users with the appropriate roles to update the status of impersonation requests, enabling more dynamic management of these requests. The update functionality ensures compliance with request states and user roles, minimizing unauthorized actions, and improving the system's overall workflow efficiency.

Is this description stale? Ask me to generate a new description by commenting /korbit-generate-pr-description

@coderabbitai
Copy link

coderabbitai bot commented Jun 21, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Summary by CodeRabbit

  • New Features
    • Added the ability to update the status of impersonation requests (approve or reject) via a new PATCH endpoint.
    • Introduced validation for impersonation request updates to ensure only valid status changes are accepted.
  • Improvements
    • Enhanced type definitions for impersonation requests, providing clearer request and response structures.
    • Added more detailed filtering and pagination options for impersonation request queries.
  • Bug Fixes
    • Improved error handling and messaging for invalid or unauthorized impersonation request updates.

Walkthrough

This update introduces the ability for a normal user to approve or reject impersonation requests from privileged users. It adds a PATCH API endpoint to update the status of impersonation requests, with input validation, service-layer authorization and update logic, Firestore model changes, and expanded type definitions to support the new workflow.

Changes

File(s) Change Summary
controllers/impersonationRequests.ts Added controller for updating impersonation request status.
middlewares/validators/impersonationRequests.ts Introduced Joi-based validator for request status updates.
models/impersonationRequests.ts New model function for updating impersonation request documents in Firestore.
routes/impersonation.ts, routes/index.ts Added PATCH /impersonation/requests/:id route with authentication and validation.
services/impersonationRequests.ts Added service functions for validating and updating impersonation requests, including logging actions.
types/impersonationRequest.d.ts Refined and expanded type definitions for requests, responses, DTOs, and query parameters.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Router
    participant AuthMiddleware
    participant Validator
    participant Controller
    participant Service
    participant Model
    participant Logger

    Client->>Router: PATCH /impersonation/requests/:id
    Router->>AuthMiddleware: Authenticate user
    AuthMiddleware->>Validator: Validate request body (status)
    Validator->>Controller: Pass validated request
    Controller->>Service: validateUpdateImpersonationRequestService(requestId, userId)
    Service->>Model: Fetch impersonation request by ID
    Model-->>Service: Return request data
    Service->>Service: Check authorization & status
    Service-->>Controller: Validation success
    Controller->>Service: updateImpersonationRequestServie(updateData)
    Service->>Model: Update impersonation request in Firestore
    Model-->>Service: Return updated request
    Service->>Logger: addLog(action, details)
    Logger-->>Service: Log saved
    Service-->>Controller: Return updated request and message
    Controller->>Client: Respond with 200 and updated request
Loading

Assessment against linked issues

Objective Addressed Explanation
Privileged user can create an impersonation request for a normal user (#2200) This PR focuses on status updates, not creation.
Normal user can approve/reject impersonation request (#2200)
Request-based mechanism for impersonation approval/rejection (#2200)
Privileged user can start/perform impersonation once approved (#2200) No implementation for starting impersonation in this PR.
Restrict impersonation access to read-only during session (#2200) No session or access control logic present here.

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes found.

Suggested reviewers

  • AnujChhikara
  • Achintya-Chatterjee
  • iamitprakash
  • Shyam-Vishwakarma

Poem

A bunny in code, with ears held high,
Watched as requests for impersonation fly.
Approve or reject, the normal user decides,
With PATCH and validation, the logic abides.
Now logs are written, the status is set—
This rabbit’s quite proud of the best PR yet! 🐇✨


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 8

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6d16d08 and 81a6da9.

📒 Files selected for processing (7)
  • controllers/impersonationRequests.ts (1 hunks)
  • middlewares/validators/impersonationRequests.ts (1 hunks)
  • models/impersonationRequests.ts (1 hunks)
  • routes/impersonation.ts (1 hunks)
  • routes/index.ts (1 hunks)
  • services/impersonationRequests.ts (1 hunks)
  • types/impersonationRequest.d.ts (1 hunks)
🧰 Additional context used
🪛 ESLint
routes/impersonation.ts

[error] 3-3: Import in body of module; reorder to top.

(import/first)


[error] 4-4: Import in body of module; reorder to top.

(import/first)


[error] 5-5: Import in body of module; reorder to top.

(import/first)


[error] 7-7: Replace "/requests/:id",·authenticate,updateImpersonationRequestValidator,updateImpersonationRequestStatusController with ⏎··"/requests/:id",⏎··authenticate,⏎··updateImpersonationRequestValidator,⏎··updateImpersonationRequestStatusController⏎

(prettier/prettier)


[error] 9-9: Insert

(prettier/prettier)

🪛 GitHub Check: CodeQL
routes/impersonation.ts

[failure] 7-7: Missing rate limiting
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.

🪛 GitHub Check: build (22.10.0)
services/impersonationRequests.ts

[failure] 13-13:
Module '"../models/impersonationRequests"' has no exported member 'getImpersonationRequestById'.

🪛 GitHub Actions: Tests
services/impersonationRequests.ts

[error] 13-13: TypeScript error TS2305: Module '../models/impersonationRequests' has no exported member 'getImpersonationRequestById'.

🪛 Biome (1.9.4)
types/impersonationRequest.d.ts

[error] 83-83: Shouldn't redeclare 'Request'. Consider to delete it or rename it.

'Request' is defined here:

(lint/suspicious/noRedeclare)


[error] 83-83: Shouldn't redeclare 'Response'. Consider to delete it or rename it.

'Response' is defined here:

(lint/suspicious/noRedeclare)


[error] 84-84: Shouldn't redeclare 'REQUEST_STATE'. Consider to delete it or rename it.

'REQUEST_STATE' is defined here:

(lint/suspicious/noRedeclare)


[error] 85-85: Shouldn't redeclare 'Boom'. Consider to delete it or rename it.

'Boom' is defined here:

(lint/suspicious/noRedeclare)


[error] 86-86: Shouldn't redeclare 'RequestQuery'. Consider to delete it or rename it.

'RequestQuery' is defined here:

(lint/suspicious/noRedeclare)


[error] 87-87: Shouldn't redeclare 'userData'. Consider to delete it or rename it.

'userData' is defined here:

(lint/suspicious/noRedeclare)


[error] 88-88: Shouldn't redeclare 'Timestamp'. Consider to delete it or rename it.

'Timestamp' is defined here:

(lint/suspicious/noRedeclare)


[error] 90-90: Shouldn't redeclare 'ImpersonationRequest'. Consider to delete it or rename it.

'ImpersonationRequest' is defined here:

(lint/suspicious/noRedeclare)


[error] 106-106: Shouldn't redeclare 'CreateImpersonationRequestBody'. Consider to delete it or rename it.

'CreateImpersonationRequestBody' is defined here:

(lint/suspicious/noRedeclare)


[error] 121-121: Shouldn't redeclare 'UpdateImpersonationRequestDataBody'. Consider to delete it or rename it.

'UpdateImpersonationRequestDataBody' is defined here:

(lint/suspicious/noRedeclare)


[error] 127-127: Shouldn't redeclare 'UpdateImpersonationRequestStatusBody'. Consider to delete it or rename it.

'UpdateImpersonationRequestStatusBody' is defined here:

(lint/suspicious/noRedeclare)


[error] 146-146: Shouldn't redeclare 'ImpersonationRequestQuery'. Consider to delete it or rename it.

'ImpersonationRequestQuery' is defined here:

(lint/suspicious/noRedeclare)


[error] 158-158: Shouldn't redeclare 'ImpersonationRequestResponse'. Consider to delete it or rename it.

'ImpersonationRequestResponse' is defined here:

(lint/suspicious/noRedeclare)


[error] 162-162: Shouldn't redeclare 'RequestParams'. Consider to delete it or rename it.

'RequestParams' is defined here:

(lint/suspicious/noRedeclare)


[error] 166-166: Shouldn't redeclare 'CreateImpersonationRequest'. Consider to delete it or rename it.

'CreateImpersonationRequest' is defined here:

(lint/suspicious/noRedeclare)


[error] 179-179: Shouldn't redeclare 'PaginatedImpersonationRequests'. Consider to delete it or rename it.

'PaginatedImpersonationRequests' is defined here:

(lint/suspicious/noRedeclare)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (7)
routes/index.ts (1)

44-44: LGTM! Route integration follows established patterns.

The new impersonation route is correctly integrated with the dev flag middleware, consistent with other feature-flagged routes like subscription.

models/impersonationRequests.ts (1)

14-31: Model function is well-implemented but verify document existence handling.

The update function is correctly structured with good error handling and documentation. However, verify that the Firestore update behavior aligns with business requirements.

Firestore's update() method will throw an error if the document doesn't exist, which is likely the desired behavior for updating impersonation requests. Can you confirm this is the intended behavior vs. using set() with merge option?

#!/bin/bash
# Check if there are any error handling patterns for non-existent documents
ast-grep --pattern 'update($$$)'
rg -A 5 -B 5 "document.*not.*exist|document.*does.*not"
services/impersonationRequests.ts (2)

32-57: Validation logic is well-structured.

The function correctly validates business rules for impersonation request updates:

  • Checks request existence
  • Prevents updates to already processed requests
  • Ensures only the impersonated user can approve/reject requests

13-13: ```shell
#!/bin/bash

Locate model file

model_file=$(fd impersonationRequests.ts | grep 'models/impersonationRequests.ts' | head -n1)
echo "Model file: $model_file"

List all exports in the model file

echo "Exports in the model file:"
rg '^export ' "$model_file" || echo "(none found)"

Search for getImpersonationRequestById in the model file

echo "Occurrences of getImpersonationRequestById:"
rg -n 'getImpersonationRequestById' "$model_file" || echo "(not found)"

Locate service file

service_file=$(fd impersonationRequests.ts | grep 'services/impersonationRequests.ts' | head -n1)
echo "Service file: $service_file"

Check for typo in service function name

echo "Occurrences of updateImpersonationRequestServie:"
rg -n 'updateImpersonationRequestServie' "$service_file" || echo "(not found)"


</details>
<details>
<summary>types/impersonationRequest.d.ts (3)</summary>

`111-119`: **Approve the enhanced type definitions.**

The new `CreateImpersonationRequestModelDto` type properly separates the DTO structure from the request body type, improving type safety and clarity.

---

`133-144`: **Well-designed update types.**

The `UpdateImpersonationRequestModelDto` and `UpdateImpersonationStatusModelResponse` types provide clear contracts for the update operations, supporting both data and status updates.

---

`146-156`: **Enhanced query type supports comprehensive filtering.**

The expanded `ImpersonationRequestQuery` type adds valuable filtering capabilities (createdBy, createdFor, status, pagination) that weren't available in the original version.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Copy link

@korbit-ai korbit-ai bot left a comment

Choose a reason for hiding this comment

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

Review by Korbit AI

Korbit automatically attempts to detect when you fix issues in new commits.
Category Issue Status
Readability Typo in service name ▹ view ✅ Fix detected
Readability Inconsistent Middleware Spacing ▹ view ✅ Fix detected
Readability Unused import ▹ view ✅ Fix detected
Design Redundant Object Property ▹ view ✅ Fix detected
Logging Missing Request Context in Error Logging ▹ view ✅ Fix detected
Error Handling Insufficient Error Context in Logs ▹ view ✅ Fix detected
Functionality Misspelled Service Function Name ▹ view ✅ Fix detected
Error Handling Untyped Generic Error Handling ▹ view
Performance Sequential Async Operations ▹ view ✅ Fix detected
Security Unvalidated Object Spread in Database Update ▹ view ✅ Fix detected
Files scanned
File Path Reviewed
routes/impersonation.ts
middlewares/validators/impersonationRequests.ts
routes/index.ts
models/impersonationRequests.ts
controllers/impersonationRequests.ts
services/impersonationRequests.ts
types/impersonationRequest.d.ts

Explore our documentation to understand the languages and file types we support and the files we ignore.

Check out our docs on how you can make Korbit work best for you and your team.

Loving Korbit!? Share us on LinkedIn Reddit and X

@Suvidh-kaushik Suvidh-kaushik force-pushed the feat/update_impersonation_requests branch from af6daa7 to ca40fcb Compare June 23, 2025 17:27
MayankBansal12
MayankBansal12 previously approved these changes Jun 23, 2025
@iamitprakash iamitprakash merged commit 37afd2f into RealDevSquad:develop Jun 28, 2025
5 checks passed
@Achintya-Chatterjee Achintya-Chatterjee mentioned this pull request Jul 4, 2025
10 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Impersonation Feature For RDS priviledged users(super_user) #2

4 participants