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

feature: Use hibernate filter to add condition to query #121

Merged
merged 1 commit into from
Feb 12, 2025

Conversation

GiaBaorr
Copy link
Collaborator

@GiaBaorr GiaBaorr commented Feb 11, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced user data management with dynamic filtering, ensuring users only see information aligned with their enterprise.
    • Introduced streamlined retrieval of user records to support management operations like deletion.
  • Refactor

    • Updated internal processes for user data access, integrating enterprise-aware filtering for more consistent and secure operations.

Copy link

coderabbitai bot commented Feb 11, 2025

Walkthrough

This pull request introduces enterprise-level filtering and an adapter-based data retrieval mechanism. A new AOP aspect applies a Hibernate filter based on the current user's enterprise ID for repository methods. The UserEntity is enhanced with new constants and filter annotations to support this filtering. Additionally, a UserRepositoryAdapter is added to retrieve users by their IDs, and the service implementation is updated to delegate user deletion to this adapter.

Changes

File(s) Change Summary
sep490-idp/.../aop/UserRepositoryAdvice.java
sep490-idp/.../entity/UserEntity.java
Introduces enterprise filtering support: the aspect applies a Hibernate filter on repository methods, and the entity is enhanced with constants and filter annotations for enterprise-specific data handling.
sep490-idp/.../repository/UserRepositoryAdapter.java
sep490-idp/.../service/impl/UserServiceImpl.java
Adds an adapter to retrieve users by IDs and updates the user deletion logic to use the new repository adapter.

Sequence Diagram(s)

sequenceDiagram
    participant Repo as UserRepository
    participant Aspect as UserRepositoryAdvice
    participant Session as Hibernate Session
    participant Security as SecurityUtils
    participant Caller as Application Code

    Caller->>Aspect: Call UserRepository method
    Aspect->>Session: Retrieve current Hibernate Session
    Session->>Aspect: Return Session
    Aspect->>Security: Get current user's enterprise ID
    Security-->>Aspect: Return enterprise ID
    Aspect->>Session: Enable enterprise filter with ID
    Aspect->>Repo: Proceed with repository method call
    Repo-->>Aspect: Return result
    Aspect->>Session: Disable filter (in finally)
    Aspect-->>Caller: Return filtered result
Loading
sequenceDiagram
    participant Service as UserServiceImpl
    participant Adapter as UserRepositoryAdapter
    participant Repo as UserRepository

    Service->>Adapter: findByIDs(userIds)
    Adapter->>Repo: Delegate retrieval fetching UserEntity objects
    Repo-->>Adapter: Return user list
    Adapter-->>Service: Return user list for deletion
Loading

Possibly related PRs

Suggested reviewers

  • nganntqe170236
  • huynhlephcvinh
  • thongdanghoang

Poem

I'm a rabbit with joy so fleet,
Hopping through code with a happy beat.
Enterprise filters now shine so bright,
Guiding each query just right.
Through adapters and aspects I sing,
A carrot of progress in every spring!
🥕🐇 Happy coding!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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. (Beta)
  • @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: 1

🧹 Nitpick comments (3)
sep490-idp/src/main/java/sep490/idp/repository/UserRepositoryAdapter.java (1)

16-18: Minor naming convention adjustment.

Method name uses “IDs”, but common Java naming prefers findByIds. Consider renaming to match typical camelCase style.

Example fix:

- public List<UserEntity> findByIDs(Set<UUID> ids) {
+ public List<UserEntity> findByIds(Set<UUID> ids) {
sep490-idp/src/main/java/sep490/idp/entity/UserEntity.java (1)

37-38: Filter usage looks good!

The defined “belongEnterpriseFilter” matches your aspect logic, ensuring users are scoped by enterprise. Continue verifying that the subselect-based condition meets your performance requirements for large datasets. If performance becomes an issue, consider a join-based filter or caching mechanism.

sep490-idp/src/main/java/sep490/idp/service/impl/UserServiceImpl.java (1)

121-121: Verify enterprise-specific filtering in the adapter.

The change to use userRepositoryAdapter looks good, but we should ensure that the adapter properly applies the enterprise-specific filtering to prevent unauthorized access across enterprises.

Let's verify the implementation of the adapter:

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Check if UserRepositoryAdapter properly implements enterprise filtering

# Look for filter definition in UserEntity
echo "Checking UserEntity for filter definition:"
rg -A 5 "@FilterDef.*belongEnterpriseFilter" --type java

# Look for filter enablement in UserRepositoryAdapter
echo "\nChecking UserRepositoryAdapter implementation:"
rg -A 10 "class UserRepositoryAdapter" --type java

# Look for filter usage in AOP advice
echo "\nChecking AOP advice for filter enablement:"
rg -A 10 "UserRepositoryAdvice" --type java

Length of output: 3025


Action: Confirm enterprise-specific filtering is correctly implemented via AOP.

  • The UserEntity properly defines the enterprise filter with @FilterDef and @Filter.
  • The UserRepositoryAdapter delegates to userRepo.findByIDs without bypassing any filtering logic.
  • The AOP advice (UserRepositoryAdvice) targets all methods within the UserRepositoryAdapter, ensuring the filter is applied automatically before repository calls execute.

Based on the evidence, the adapter’s usage is sound, and enterprise-specific filtering will be enforced.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ee76dc9 and 9b5a94b.

📒 Files selected for processing (4)
  • sep490-idp/src/main/java/sep490/idp/aop/UserRepositoryAdvice.java (1 hunks)
  • sep490-idp/src/main/java/sep490/idp/entity/UserEntity.java (2 hunks)
  • sep490-idp/src/main/java/sep490/idp/repository/UserRepositoryAdapter.java (1 hunks)
  • sep490-idp/src/main/java/sep490/idp/service/impl/UserServiceImpl.java (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build Java Modules (sep490-enterprise)
🔇 Additional comments (2)
sep490-idp/src/main/java/sep490/idp/aop/UserRepositoryAdvice.java (1)

23-24: Consider removing final from the EntityManager field or dropping @RequiredArgsConstructor.

@PersistenceContext is typically used with field or setter injection, whereas @RequiredArgsConstructor injects final fields via the constructor. Mixing both can cause unexpected issues or conflicts in managed bean lifecycles.

sep490-idp/src/main/java/sep490/idp/service/impl/UserServiceImpl.java (1)

45-45: LGTM!

The field declaration follows proper encapsulation principles and dependency injection patterns.

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

🧹 Nitpick comments (1)
sep490-idp/src/main/java/sep490/idp/entity/UserEntity.java (1)

37-51: Well-designed multi-tenancy implementation using Hibernate filters.

The implementation provides a robust and reusable mechanism for enterprise-level data isolation. Consider adding documentation to explain:

  1. When and how the filter should be enabled/disabled
  2. Performance implications and monitoring strategies
  3. Integration points with security context

Would you like me to help generate the documentation for this feature?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9b5a94b and 74386c3.

📒 Files selected for processing (4)
  • sep490-idp/src/main/java/sep490/idp/aop/UserRepositoryAdvice.java (1 hunks)
  • sep490-idp/src/main/java/sep490/idp/entity/UserEntity.java (3 hunks)
  • sep490-idp/src/main/java/sep490/idp/repository/UserRepositoryAdapter.java (1 hunks)
  • sep490-idp/src/main/java/sep490/idp/service/impl/UserServiceImpl.java (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • sep490-idp/src/main/java/sep490/idp/service/impl/UserServiceImpl.java
  • sep490-idp/src/main/java/sep490/idp/repository/UserRepositoryAdapter.java
  • sep490-idp/src/main/java/sep490/idp/aop/UserRepositoryAdvice.java
🔇 Additional comments (2)
sep490-idp/src/main/java/sep490/idp/entity/UserEntity.java (2)

18-20: LGTM!

The imports are correctly organized and specific to the new filter functionality.

Also applies to: 28-28


50-51: LGTM!

The filter constants follow proper naming conventions and are used consistently throughout the class.

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

🧹 Nitpick comments (3)
sep490-idp/src/main/java/green_buildings/idp/aop/UserRepositoryAdvice.java (1)

33-50: Ensure robust handling of absent enterprise ID.
Currently, SecurityUtils.getCurrentUserEnterpriseId().orElseThrow() will throw if no enterprise ID is available. This is a legitimate approach, but consider adding a more descriptive exception or logging to simplify troubleshooting in scenarios where an enterprise ID is unexpectedly absent.

sep490-idp/src/main/java/green_buildings/idp/repository/UserRepositoryAdapter.java (1)

16-18: Add handling or logging for empty ID sets.
If ids is empty, findByIDs will likely return an empty list. While this is generally fine, consider logging or short-circuiting to avoid unnecessary repository calls and to improve traceability.

 public List<UserEntity> findByIDs(Set<UUID> ids) {
+    if (ids.isEmpty()) {
+        return Collections.emptyList();
+    }
     return userRepo.findByIDs(ids);
 }
sep490-idp/src/main/java/green_buildings/idp/service/impl/UserServiceImpl.java (1)

192-192: Consider using adapter for saving users.

For consistency, consider delegating the save operation to the adapter as well, similar to how retrieval is handled.

-        userRepo.saveAll(users);
+        userRepositoryAdapter.saveAll(users);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 74386c3 and cd7c364.

📒 Files selected for processing (4)
  • sep490-idp/src/main/java/green_buildings/idp/aop/UserRepositoryAdvice.java (1 hunks)
  • sep490-idp/src/main/java/green_buildings/idp/entity/UserEntity.java (3 hunks)
  • sep490-idp/src/main/java/green_buildings/idp/repository/UserRepositoryAdapter.java (1 hunks)
  • sep490-idp/src/main/java/green_buildings/idp/service/impl/UserServiceImpl.java (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build Java Modules (sep490-enterprise)
🔇 Additional comments (5)
sep490-idp/src/main/java/green_buildings/idp/aop/UserRepositoryAdvice.java (1)

32-48: Consider verifying filter applicability for non-session contexts.
The code correctly checks for a non-null session and only then applies/disables the filter. Verify that all necessary repository operations will have a valid session; otherwise, logic may vary in different application flows.

sep490-idp/src/main/java/green_buildings/idp/entity/UserEntity.java (2)

36-38: Validate existence of the 'enterprise_users' table and columns.
The filter condition references the subselect on enterprise_users with fields user_id and enterprise_id. Ensure that the naming and schema match exactly at runtime to avoid runtime exceptions or empty results.


47-49: Great use of descriptive constants.
The constants clearly communicate the filter and parameter names. This enhances readability and maintainability of the filtering logic.

sep490-idp/src/main/java/green_buildings/idp/service/impl/UserServiceImpl.java (2)

21-21: LGTM! Clean dependency injection setup.

The import and field addition for UserRepositoryAdapter are properly implemented with constructor injection via @RequiredArgsConstructor.

Also applies to: 58-58


179-179: LGTM! Good use of adapter for enterprise filtering.

The change correctly delegates user retrieval to UserRepositoryAdapter, which applies enterprise-level filtering through AOP.

@GiaBaorr GiaBaorr merged commit 7247c55 into main Feb 12, 2025
8 checks passed
@GiaBaorr GiaBaorr deleted the authorize-funny branch February 12, 2025 15:35
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.

2 participants