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: add enterprise id into token, remove wrong constraint #114

Merged
merged 3 commits into from
Feb 8, 2025

Conversation

GiaBaorr
Copy link
Collaborator

@GiaBaorr GiaBaorr commented Feb 5, 2025

Summary by CodeRabbit

  • New Features
    • User authentication now includes an enterprise ID in the user context, enhancing user data handling.
    • User search functionality has been improved to filter results based on the current user's enterprise ID.
    • A new method for creating enterprise users has been added, ensuring they are associated with the correct enterprise ID.
  • Chores
    • Updated the database schema by modifying the foreign key constraint on the enterprise users table to support new user management features.

Copy link

coderabbitai bot commented Feb 5, 2025

Walkthrough

This pull request introduces enterprise identifier support in user-related security and service components. It adds an enterpriseUUID in JWT authentication conversion, updates the UserContextData class with a new UUID field, and adjusts repository queries and service methods to filter by enterprise. Additionally, a new method in SecurityUtils retrieves the enterprise ID from the current user context. A migration script is also added to drop a foreign key constraint from the database.

Changes

Files Summary of Changes
sep490-commons/.../securities/JwtAuthenticationConverter.java
sep490-commons/.../securities/UserContextData.java
sep490-idp/.../security/MvcUserContextData.java
Added handling for enterprise ID: extracting enterpriseId from JWT claims, updating data model with a new UUID field, and modifying superclass constructor calls to include the enterprise ID.
sep490-commons/.../utils/SecurityUtils.java Introduced a new public static method getCurrentUserEnterpriseId() to retrieve the current user's enterprise ID from the context.
sep490-idp/.../repository/UserRepository.java Updated findByName method signature to include a UUID enterpriseId parameter and added a query condition to filter by enterprise.
sep490-idp/.../service/impl/UserInfoService.java Modified getCustomClaimsForJwtAuthenticationToken method to include an enterpriseId in the returned claims map.
sep490-idp/.../service/impl/UserServiceImpl.java Updated search method logic to retrieve the enterprise ID using SecurityUtils and pass it to the repository for scoped user searches.
sep490-idp/src/main/resources/db/migration/V0.0.1.7__RemoveConstraintUserEnterprise.sql Added SQL command to drop the foreign key constraint enterprise_users_fk_user from the enterprise_users table.

Possibly related PRs

Suggested labels

task

Suggested reviewers

  • thongdanghoang
  • huynhlephcvinh
  • nganntqe170236

Poem

Hoppin' through the code with glee,
I found an enterprise key for me.
UUIDs and claims set in a line,
Filtering users just fine.
A bunny celebrates this change so bright,
Leaping over bugs with delight!
🐰✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f14dd7 and 7f068c2.

📒 Files selected for processing (1)
  • sep490-idp/src/main/resources/db/migration/V0.0.1.7__RemoveConstraintUserEnterprise.sql (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • sep490-idp/src/main/resources/db/migration/V0.0.1.7__RemoveConstraintUserEnterprise.sql

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

🧹 Nitpick comments (2)
sep490-idp/src/main/java/sep490/idp/repository/UserRepository.java (1)

55-55: Consider renaming the method for clarity.

While the implementation is correct, the method name findByName could be more descriptive since it now filters by both name and enterprise. Consider renaming to findByNameAndEnterprise for better clarity.

-    Page<UUID> findByName(String name, UUID enterpriseId, Pageable pageable);
+    Page<UUID> findByNameAndEnterprise(String name, UUID enterpriseId, Pageable pageable);
sep490-idp/src/main/java/sep490/idp/security/MvcUserContextData.java (1)

19-20: LGTM! Good architectural change.

The addition of enterprise ID to the security context is a good architectural decision that:

  1. Enables proper multi-tenancy support
  2. Aligns with the PR objective of adding enterprise ID into token
  3. Maintains immutability by using List.copyOf()
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bb0d9b8 and 1672338.

📒 Files selected for processing (8)
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/securities/JwtAuthenticationConverter.java (2 hunks)
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/securities/UserContextData.java (1 hunks)
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/utils/SecurityUtils.java (2 hunks)
  • sep490-idp/src/main/java/sep490/idp/repository/UserRepository.java (1 hunks)
  • sep490-idp/src/main/java/sep490/idp/security/MvcUserContextData.java (1 hunks)
  • sep490-idp/src/main/java/sep490/idp/service/impl/UserInfoService.java (1 hunks)
  • sep490-idp/src/main/java/sep490/idp/service/impl/UserServiceImpl.java (2 hunks)
  • sep490-idp/src/main/resources/db/migration/V0.0.1.7__RemoveConstraintUserEnterprise.sql (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • sep490-idp/src/main/resources/db/migration/V0.0.1.7__RemoveConstraintUserEnterprise.sql
⏰ 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/sep490/idp/repository/UserRepository.java (1)

51-51: LGTM! Enterprise filtering added correctly.

The enterprise ID filter is properly integrated into the query using correct JPA entity navigation.

sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/securities/UserContextData.java (1)

16-16: LGTM! Clean addition of enterprise ID field.

The field is correctly marked as private and final, ensuring proper encapsulation and immutability. The Lombok annotations handle the constructor and getter generation appropriately.

sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/utils/SecurityUtils.java (1)

23-25: LGTM! Well-implemented utility method.

The method follows the established pattern in the class, using Optional for null safety and functional style for clean code.

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

4-4: LGTM!

The import is correctly added and follows package naming conventions.


102-113: Improve error handling for enterprise ID retrieval.

While the enterprise-level data isolation is a good security measure, the current implementation could be improved:

  1. The .orElseThrow() call should include a meaningful error message.
  2. Consider handling the case where enterprise ID is not present more gracefully.

Consider applying this improvement:

-        UUID enterpriseId = SecurityUtils.getCurrentUserEnterpriseId().orElseThrow();
+        UUID enterpriseId = SecurityUtils.getCurrentUserEnterpriseId()
+                .orElseThrow(() -> new BusinessException(
+                        "enterpriseId",
+                        "user.search.enterprise.required",
+                        Collections.emptyList()
+                ));

Let's verify if the BusinessException is consistently used across the codebase for similar scenarios:

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Search for similar patterns of throwing BusinessException
rg -A 2 "new BusinessException\\(" --type java

Length of output: 3303


Enhance enterprise ID error handling in search method

The updated suggestion to throw a custom BusinessException with a meaningful error message is consistent with similar patterns in the codebase (e.g., in DevResource.java and UserValidator.java). Using a lambda with detailed parameters is an improvement over the plain .orElseThrow(), as it provides clarity on the error context.

  • Update SecurityUtils.getCurrentUserEnterpriseId().orElseThrow() to include a lambda that throws a BusinessException with a meaningful error message (e.g., "user.search.enterprise.required").

@GiaBaorr GiaBaorr force-pushed the feature/authorize-recheck branch from 1672338 to 72ac1a7 Compare February 5, 2025 15:53
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 (1)
sep490-idp/src/main/java/sep490/idp/repository/UserRepository.java (1)

47-55: Consider adding an index for enterprise-based queries.

Since the repository now filters users by enterprise ID, consider adding a database index on the enterprise column to optimize query performance, especially for large datasets.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1672338 and 72ac1a7.

📒 Files selected for processing (8)
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/securities/JwtAuthenticationConverter.java (2 hunks)
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/securities/UserContextData.java (1 hunks)
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/utils/SecurityUtils.java (2 hunks)
  • sep490-idp/src/main/java/sep490/idp/repository/UserRepository.java (1 hunks)
  • sep490-idp/src/main/java/sep490/idp/security/MvcUserContextData.java (1 hunks)
  • sep490-idp/src/main/java/sep490/idp/service/impl/UserInfoService.java (2 hunks)
  • sep490-idp/src/main/java/sep490/idp/service/impl/UserServiceImpl.java (2 hunks)
  • sep490-idp/src/main/resources/db/migration/V0.0.1.7__RemoveConstraintUserEnterprise.sql (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (7)
  • sep490-idp/src/main/java/sep490/idp/service/impl/UserServiceImpl.java
  • sep490-idp/src/main/java/sep490/idp/service/impl/UserInfoService.java
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/utils/SecurityUtils.java
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/securities/UserContextData.java
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/securities/JwtAuthenticationConverter.java
  • sep490-idp/src/main/resources/db/migration/V0.0.1.7__RemoveConstraintUserEnterprise.sql
  • sep490-idp/src/main/java/sep490/idp/security/MvcUserContextData.java
🔇 Additional comments (2)
sep490-idp/src/main/java/sep490/idp/repository/UserRepository.java (2)

51-51: LGTM! Enterprise filtering condition is well-placed.

The enterprise filtering condition is correctly added and properly integrated with the existing query logic.


55-55: LGTM! Method signature properly updated.

The method signature has been correctly updated to include the enterprise ID parameter while maintaining proper parameter ordering and type safety.

@GiaBaorr GiaBaorr force-pushed the feature/authorize-recheck branch from 72ac1a7 to 4b415f7 Compare February 6, 2025 16:03
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: 3

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

137-146: Consider a more specific method name.

The current method name performCreateUserAction is too generic. Consider renaming it to better reflect its specific responsibility of handling password generation and notification for new users.

-    private void performCreateUserAction(UserEntity user) {
+    private void handleNewUserPasswordAndNotification(UserEntity user) {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 72ac1a7 and 4b415f7.

📒 Files selected for processing (9)
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/securities/JwtAuthenticationConverter.java (2 hunks)
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/securities/UserContextData.java (1 hunks)
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/utils/SecurityUtils.java (2 hunks)
  • sep490-idp/src/main/java/sep490/idp/mapper/decoratos/EnterpriseUserMapperDecorator.java (1 hunks)
  • sep490-idp/src/main/java/sep490/idp/repository/UserRepository.java (1 hunks)
  • sep490-idp/src/main/java/sep490/idp/security/MvcUserContextData.java (1 hunks)
  • sep490-idp/src/main/java/sep490/idp/service/impl/UserInfoService.java (2 hunks)
  • sep490-idp/src/main/java/sep490/idp/service/impl/UserServiceImpl.java (4 hunks)
  • sep490-idp/src/main/resources/db/migration/V0.0.1.7__RemoveConstraintUserEnterprise.sql (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • sep490-idp/src/main/resources/db/migration/V0.0.1.7__RemoveConstraintUserEnterprise.sql
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/utils/SecurityUtils.java
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/securities/JwtAuthenticationConverter.java
  • sep490-idp/src/main/java/sep490/idp/service/impl/UserInfoService.java
  • sep490-idp/src/main/java/sep490/idp/security/MvcUserContextData.java
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/securities/UserContextData.java
🔇 Additional comments (5)
sep490-idp/src/main/java/sep490/idp/mapper/decoratos/EnterpriseUserMapperDecorator.java (1)

30-35: Verify the enterprise ID retrieval logic.

The method relies on SecurityUtils.getCurrentUserEnterpriseId() to get the enterprise ID. Let's verify this implementation.

Run the following script to check the implementation:

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Check the implementation of getCurrentUserEnterpriseId.

# Test: Search for getCurrentUserEnterpriseId implementation.
ast-grep --pattern $'class SecurityUtils {
  $$$
  getCurrentUserEnterpriseId() {
    $$$
  }
  $$$
}'

Length of output: 103


🏁 Script executed:

#!/bin/bash
# Re-run search for SecurityUtils class and its getCurrentUserEnterpriseId implementation using ripgrep

echo "Searching for class SecurityUtils definition..."
rg "class SecurityUtils" -n .

echo "Searching for getCurrentUserEnterpriseId implementation..."
rg "getCurrentUserEnterpriseId" -n .

Length of output: 946


🏁 Script executed:

#!/bin/bash
# Print context around the getCurrentUserEnterpriseId implementation in SecurityUtils.java
sed -n '15,45p' sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/utils/SecurityUtils.java

Length of output: 1231


Enterprise ID retrieval logic verified.

The implementation of SecurityUtils.getCurrentUserEnterpriseId() correctly retrieves the enterprise ID by mapping the UserContextData to its enterpriseId property. The use of orElseThrow() in the EnterpriseUserMapperDecorator ensures that an exception is thrown when the ID is not present, which is the expected behavior.

  • Confirmed that SecurityUtils.getCurrentUserEnterpriseId() returns an Optional<UUID> by mapping UserContextData::getEnterpriseId.
  • The code in EnterpriseUserMapperDecorator properly sets the enterprise ID using this logic.
sep490-idp/src/main/java/sep490/idp/repository/UserRepository.java (2)

51-51: LGTM!

The enterprise filtering condition is correctly placed and uses the proper field path.


55-55: Verify all callers of findByName are updated.

The method signature change is correct. However, ensure all callers are updated to provide the enterprise ID parameter.

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Find all callers of findByName to verify they're updated with the new parameter.
rg -A 5 'findByName\(' --type java

Length of output: 1346


All callers of findByName have been correctly updated to provide the enterprise ID parameter.
The usage in UserServiceImpl.java shows that the call now includes the enterpriseId parameter as the second argument, aligning with the updated method signature in UserRepository.java.

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

4-4: LGTM!

The SecurityUtils import is correctly added and properly placed.


131-135: LGTM!

The refactoring improves code organization by extracting the create user logic into a separate method.

@thongdanghoang thongdanghoang force-pushed the feature/authorize-recheck branch from 4b415f7 to 8f14dd7 Compare February 8, 2025 06:19
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 (1)
sep490-idp/src/main/java/sep490/idp/repository/UserRepository.java (1)

50-52: LGTM! Consider adding an index for performance optimization.

The enterprise filtering condition is correctly placed and properly uses parameter binding.

Consider adding an index on the enterprise column to optimize query performance, especially if the table has a large number of 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 4b415f7 and 8f14dd7.

📒 Files selected for processing (9)
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/securities/JwtAuthenticationConverter.java (2 hunks)
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/securities/UserContextData.java (1 hunks)
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/utils/SecurityUtils.java (2 hunks)
  • sep490-idp/src/main/java/sep490/idp/mapper/decoratos/EnterpriseUserMapperDecorator.java (1 hunks)
  • sep490-idp/src/main/java/sep490/idp/repository/UserRepository.java (1 hunks)
  • sep490-idp/src/main/java/sep490/idp/security/MvcUserContextData.java (1 hunks)
  • sep490-idp/src/main/java/sep490/idp/service/impl/UserInfoService.java (2 hunks)
  • sep490-idp/src/main/java/sep490/idp/service/impl/UserServiceImpl.java (4 hunks)
  • sep490-idp/src/main/resources/db/migration/V0.0.1.7__RemoveConstraintUserEnterprise.sql (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (8)
  • sep490-idp/src/main/resources/db/migration/V0.0.1.7__RemoveConstraintUserEnterprise.sql
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/utils/SecurityUtils.java
  • sep490-idp/src/main/java/sep490/idp/mapper/decoratos/EnterpriseUserMapperDecorator.java
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/securities/JwtAuthenticationConverter.java
  • sep490-idp/src/main/java/sep490/idp/service/impl/UserInfoService.java
  • sep490-commons/springfw-impl/src/main/java/commons/springfw/impl/securities/UserContextData.java
  • sep490-idp/src/main/java/sep490/idp/security/MvcUserContextData.java
  • sep490-idp/src/main/java/sep490/idp/service/impl/UserServiceImpl.java
🔇 Additional comments (1)
sep490-idp/src/main/java/sep490/idp/repository/UserRepository.java (1)

55-55: LGTM! Method signature updated correctly.

The method signature has been properly updated to include the enterprise ID parameter, maintaining proper parameter ordering and return type.

@GiaBaorr GiaBaorr merged commit 1f3ba7d into main Feb 8, 2025
8 checks passed
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.

3 participants