Skip to content

NoMongo (fix): allow all organization admins to block users #3459

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

Conversation

Bittukr7479
Copy link

@Bittukr7479 Bittukr7479 commented Apr 23, 2025

What kind of change does this PR introduce?

Issue Number:

Fixes #3329

Snapshots/Videos:

If relevant, did you update the documentation?

Summary

Does this PR introduce a breaking change?

Checklist

CodeRabbit AI Review

  • I have reviewed and addressed all critical issues flagged by CodeRabbit AI
  • I have implemented or provided justification for each non-critical suggestion
  • I have documented my reasoning in the PR comments where CodeRabbit AI suggestions were not implemented

Test Coverage

  • I have written tests for all new changes/features
  • I have verified that test coverage meets or exceeds 95%
  • I have run the test suite locally and all tests pass

Other information

Have you read the contributing guide?

Summary by CodeRabbit

  • Bug Fixes
    • Improved authorization checks for blocking and unblocking users, ensuring only administrators can perform these actions.
    • Enhanced error handling with clearer messages when users or organizations are not found.
  • Refactor
    • Centralized administrator role verification into a new utility function for consistent authorization enforcement.
    • Streamlined validation steps by reorganizing data fetching and role checks for better clarity and maintainability.

Copy link

coderabbitai bot commented Apr 23, 2025

"""

Walkthrough

The changes refactor the data fetching and authorization logic in the blockUser and unblockUser GraphQL mutations. Both mutations now first verify the current user's global and organization-specific roles before fetching and validating the target user and block records. The code is reorganized to improve clarity and enforce that only administrators (globally or within the organization) can perform blocking and unblocking actions. No changes were made to the mutation signatures or exported entities.

Changes

Files Change Summary
src/graphql/types/Mutation/blockUser.ts, src/graphql/types/Mutation/unblockUser.ts Refactored data fetching and authorization logic: now checks admin role (global or org) before fetching target user/block records; reorganized control flow for clarity; error handling updated. No changes to mutation signatures.
src/utilities/authorization.ts Added assertOrganizationAdmin utility function to centralize admin role authorization checks and throw structured GraphQL errors on unauthorized access.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant GraphQLServer
    participant DB

    Client->>GraphQLServer: blockUser/unblockUser Mutation
    GraphQLServer->>DB: Fetch current user, org, and user-org membership
    DB-->>GraphQLServer: Return user, org, membership
    GraphQLServer->>GraphQLServer: Check admin role (global/org)
    alt Not authorized
        GraphQLServer-->>Client: Return unauthorized error
    else Authorized
        GraphQLServer->>DB: Fetch target user and block record
        DB-->>GraphQLServer: Return target user, block
        GraphQLServer->>GraphQLServer: Validate target user and block existence
        alt Valid
            GraphQLServer->>DB: Perform block/unblock transaction
            DB-->>GraphQLServer: Return updated block state
            GraphQLServer-->>Client: Return result
        else Invalid
            GraphQLServer-->>Client: Return validation error
        end
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Only organizations should have the ability to block/unblock users; ensure proper GraphQL mutation and resolver logic (#3329)
Add user-side leave functionality, introduce leave organization mutation (#3329) No leave organization mutation or related logic is present in the changes.

Suggested reviewers

  • palisadoes
    """

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1cd07a3 and de7cc90.

📒 Files selected for processing (3)
  • src/graphql/types/Mutation/blockUser.ts (3 hunks)
  • src/graphql/types/Mutation/unblockUser.ts (3 hunks)
  • src/utilities/authorization.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/utilities/authorization.ts (1)
src/utilities/TalawaGraphQLError.ts (1)
  • TalawaGraphQLError (264-277)
src/graphql/types/Mutation/blockUser.ts (1)
src/utilities/authorization.ts (1)
  • assertOrganizationAdmin (7-23)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run tests for talawa api
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (10)
src/utilities/authorization.ts (1)

7-23: Nice addition of centralized authorization logic!

The assertOrganizationAdmin utility function effectively centralizes the admin role verification logic, following the DRY principle. This is a good refactoring that ensures consistent authorization checks across mutations.

src/graphql/types/Mutation/blockUser.ts (4)

5-5: Good addition of the authorization utility import.

The import of the centralized assertOrganizationAdmin function aligns with best practices for code organization.


48-68: Improved data fetching strategy.

Restructuring the data fetching to first retrieve only the information needed for authorization checks before proceeding to other operations follows the principle of failing fast and improves security.


86-90: Great use of the new authorization utility.

Using the centralized assertOrganizationAdmin function reduces code duplication and ensures consistent authorization behavior between related mutations.


92-116: Well-structured sequential data fetching.

Fetching the target user details only after authorization checks is a good practice that avoids unnecessary database queries when a user doesn't have permission.

src/graphql/types/Mutation/unblockUser.ts (5)

6-6: Good addition of the authorization utility import.

The import of the centralized assertOrganizationAdmin function aligns with best practices for code organization.


49-69: Improved data fetching strategy.

Restructuring the data fetching to first retrieve only the information needed for authorization checks follows the principle of failing fast and improves security.


71-77: Good handling of missing user record.

The explicit check for when currentUser is undefined prevents misleading error messages and follows the suggestion from a previous review.


95-99: Effective use of centralized authorization.

Using the assertOrganizationAdmin utility function ensures consistent authorization behavior with the blockUser mutation.


101-114: Well-structured sequential data fetching.

Fetching additional data only after authorization is confirmed is a good practice that avoids unnecessary database queries.

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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.

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

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

Copy link

codecov bot commented Apr 23, 2025

Codecov Report

Attention: Patch coverage is 84.61538% with 18 lines in your changes missing coverage. Please review.

Project coverage is 59.63%. Comparing base (33d5b7b) to head (de7cc90).
Report is 1 commits behind head on develop-postgres.

Files with missing lines Patch % Lines
src/utilities/authorization.ts 44.44% 10 Missing ⚠️
src/graphql/types/Mutation/unblockUser.ts 83.67% 8 Missing ⚠️
Additional details and impacted files
@@                 Coverage Diff                  @@
##           develop-postgres    #3459      +/-   ##
====================================================
+ Coverage             59.60%   59.63%   +0.03%     
====================================================
  Files                   523      524       +1     
  Lines                 40782    40817      +35     
  Branches               1786     1787       +1     
====================================================
+ Hits                  24307    24343      +36     
  Misses                16464    16464              
+ Partials                 11       10       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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: 4

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 33d5b7b and d12a412.

📒 Files selected for processing (2)
  • src/graphql/types/Mutation/blockUser.ts (1 hunks)
  • src/graphql/types/Mutation/unblockUser.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/graphql/types/Mutation/unblockUser.ts (1)
src/utilities/TalawaGraphQLError.ts (1)
  • TalawaGraphQLError (264-277)
⏰ Context from checks skipped due to timeout of 90000ms (2)

@github-project-automation github-project-automation bot moved this from Backlog to In review in NoMongo: Talawa-API Apr 23, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Apr 23, 2025
@mpdesai90
Copy link

Please fix the failing test.

@Bittukr7479
Copy link
Author

Please fix the failing test.

Sure sir.

@Cioppolo14 Cioppolo14 added the ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files label Apr 28, 2025
Copy link
Member

@varshith257 varshith257 left a comment

Choose a reason for hiding this comment

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

The coderabbitai suggestion looks valid. Unresolve and Incorporate them

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: 2

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3b7450d and f17fa3f.

📒 Files selected for processing (1)
  • src/utilities/authorization.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/utilities/authorization.ts (1)
src/utilities/TalawaGraphQLError.ts (1)
  • TalawaGraphQLError (264-277)
🪛 GitHub Actions: Pull request workflow
src/utilities/authorization.ts

[error] 2-24: Prettier formatting check failed. Run 'prettier --write' to fix code style issues in this file.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (1)
src/utilities/authorization.ts (1)

1-23: Well-designed authorization utility function.

The new assertOrganizationAdmin utility function effectively centralizes authorization checks for administrative privileges, which follows the DRY principle and improves code maintainability. The function properly checks both global admin rights and organization-specific admin rights, which aligns with the PR objective to allow all organization admins to block users.

@Bittukr7479 Bittukr7479 requested a review from varshith257 April 28, 2025 18:05
@github-project-automation github-project-automation bot moved this from In review to Ready in NoMongo: Talawa-API May 3, 2025
@varshith257 varshith257 merged commit 5937880 into PalisadoesFoundation:develop-postgres May 3, 2025
20 of 24 checks passed
@github-project-automation github-project-automation bot moved this from Ready to Done in NoMongo: Talawa-API May 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

4 participants