Skip to content

feat(backend): add oauth2 - #308

Closed
matmair wants to merge 101 commits into
masterfrom
feat(backend)--add-oauth2
Closed

matmair wants to merge 101 commits into
masterfrom
feat(backend)--add-oauth2

Conversation

@matmair

@matmair matmair commented Mar 6, 2025 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Added OAuth2 and OpenID Connect (OIDC) support, enabling API authentication via OAuth2 tokens and scopes.
    • Introduced granular, scope-based permission controls for API endpoints.
    • Added endpoints and UI for managing OAuth2 applications and tokens.
    • Enhanced API schema and documentation to describe OAuth2 flows and required scopes.
    • Added new environment variables and configuration options for OIDC private key management.
  • Improvements

    • Updated API and plugin permission handling to support both role-based and OAuth2 scope-based access.
    • Expanded and clarified API and configuration documentation, including a new section on experimental features and OAuth2/OIDC usage.
    • Improved test coverage and validation for permission rulesets and OAuth scopes.
    • Enhanced translation files with new entries for serial number navigation.
  • Bug Fixes

    • Fixed serialization and permission mapping issues for various API endpoints.
    • Updated workflow and Docker configuration to ensure OIDC key presence and compatibility.
  • Chores

    • Updated dependencies to include OAuth2 and cryptographic libraries.
    • Added new configuration and environment variable templates for OIDC integration.
    • Adjusted .gitignore and workflow checks for OIDC key files.

@coderabbitai

coderabbitai Bot commented Mar 15, 2025 •

Copy link
Copy Markdown

Walkthrough

This update introduces comprehensive OAuth2 and OpenID Connect (OIDC) support to the InvenTree backend. It adds new authentication and permission classes, integrates OAuth2 provider functionality, and updates API endpoints to leverage granular, scope-based access control in addition to traditional role-based permissions. The configuration, environment, and documentation are enhanced to support OIDC key management and experimental feature flags. New dependencies are added, and the API schema generation is extended to reflect OAuth2 flows and scopes. Numerous API views are updated to use the new permission model. The update also synchronizes translation files and adds new test coverage for OAuth2 rulesets and scopes.

Changes

Files / Paths Change Summary
.vscode/launch.json Added new debugging configurations for schema generation tasks.
.gitignore Added oidc.pem to ignore OIDC private key file.
.github/workflows/docker.yaml, .github/workflows/qc_checks.yaml Enhanced workflow checks for OIDC key file; updated Codecov action version.
contrib/container/Dockerfile, contrib/packager.io/functions.sh Added environment variable and config support for OIDC private key file.
docs/docs/start/config.md, docs/docs/api/api.md, docs/docs/settings/error_codes.md,
docs/docs/settings/experimental.md, docs/mkdocs.yml
Updated documentation for OIDC key management, OAuth2/OIDC API support, error codes, and feature flags. Added new experimental features doc.
src/backend/requirements.in, src/backend/requirements.txt Added django-oauth-toolkit, jwcrypto dependencies; relaxed DRF version constraint.
src/backend/InvenTree/InvenTree/settings.py, src/backend/InvenTree/InvenTree/schema.py,
src/backend/InvenTree/InvenTree/config.py, src/backend/InvenTree/config_template.yaml
Integrated OAuth2/OIDC provider, key management, schema enhancements, and new config options.
src/backend/InvenTree/InvenTree/permissions.py, src/backend/InvenTree/users/oauth2_scopes.py,
src/backend/InvenTree/users/authentication.py
Added OAuth2 scope-based permission classes, scope definitions, and extended authentication support.
src/backend/InvenTree/InvenTree/api.py, src/backend/InvenTree/common/api.py,
src/backend/InvenTree/generic/states/api.py, src/backend/InvenTree/importer/api.py,
src/backend/InvenTree/machine/api.py, src/backend/InvenTree/part/api.py,
src/backend/InvenTree/plugin/api.py, src/backend/InvenTree/plugin/base/action/api.py,
src/backend/InvenTree/plugin/base/barcodes/api.py, src/backend/InvenTree/plugin/base/locate/api.py,
src/backend/InvenTree/plugin/base/ui/api.py, src/backend/InvenTree/report/api.py,
src/backend/InvenTree/stock/api.py, src/backend/InvenTree/users/api.py
Updated API views to use new OAuth2-aware permission classes for granular access control.
src/backend/InvenTree/InvenTree/tasks.py Refactored email sending logic; added scheduled OAuth2 token cleanup task.
src/backend/InvenTree/InvenTree/urls.py, src/backend/InvenTree/InvenTree/middleware.py Added OAuth2 endpoint routing and middleware bypass for /o/ paths.
src/backend/InvenTree/InvenTree/api_version.py Incremented API version and updated version history for OAuth2 support.
src/backend/InvenTree/InvenTree/management/commands/schema.py,
src/backend/InvenTree/InvenTree/test_commands.py
Updated schema command docstring, return value, and test invocation.
src/backend/InvenTree/InvenTree/helpers_email.py Added utility to retrieve user email for notifications.
src/backend/InvenTree/InvenTree/metadata.py Refactored metadata permission mapping to use centralized action map.
src/backend/InvenTree/users/ruleset.py, src/backend/InvenTree/users/tests.py Added OAuth2 models to ruleset, improved ruleset/scope test coverage and output.
src/backend/InvenTree/locale/*/LC_MESSAGES/django.po Synchronized translation files and added new message IDs for serial number navigation.
src/backend/InvenTree/common/tests.py Updated API flag test assertions for new/changed flags.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant APIView
    participant OAuth2Provider
    participant OASTokenMixin
    participant PermissionClass
    participant User

    Client->>APIView: Makes API request with OAuth2 token
    APIView->>OASTokenMixin: Checks if OAuth2 authentication
    OASTokenMixin->>PermissionClass: Determines required scopes for method
    PermissionClass->>OAuth2Provider: Validates token and scopes
    OAuth2Provider-->>PermissionClass: Returns scope validation result
    PermissionClass-->>APIView: Permission granted/denied
    APIView-->>Client: Returns API response
Loading

Poem

Oh, OAuth2, you hopped right in—
With OIDC keys and a cryptic grin.
Permissions now as fine as fur,
Scopes and roles in perfect blur.
The docs are clear, the tests are neat,
This rabbit’s work is quite a feat!
🐇🔑✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Ruff (0.8.2)
src/backend/InvenTree/InvenTree/helpers_email.py

�[1;31mruff failed�[0m
�[1mCause:�[0m Failed to parse /pyproject.toml
�[1mCause:�[0m TOML parse error at line 20, column 1
|
20 | [tool.ruff.lint]
| ^^^^^^^^^^^^^^^^
Unknown rule selector: RUF045

src/backend/InvenTree/InvenTree/tasks.py

�[1;31mruff failed�[0m
�[1mCause:�[0m Failed to parse /pyproject.toml
�[1mCause:�[0m TOML parse error at line 20, column 1
|
20 | [tool.ruff.lint]
| ^^^^^^^^^^^^^^^^
Unknown rule selector: RUF045

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 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.

@matmair
matmair marked this pull request as ready for review March 16, 2025 22:02

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 (5)
src/backend/InvenTree/users/models.py (1)

225-231: OAuth2 models added to admin ruleset correctly.

The OAuth2 provider models are appropriately added to the admin ruleset, allowing administrators to manage OAuth2 applications and tokens.

Consider whether the commented-out oauth2_provider_code model will be needed in the future. If it's not required, the comment could be removed for cleanliness.

.vscode/launch.json (1)

43-53: New Schema Debug Configuration: Valid and Well-Structured

The newly added "InvenTree Server - schema" configuration is correctly set up. It follows the established pattern for Django debugging configurations by specifying the program and the arguments (i.e. the "spectacular" command), and it uses "justMyCode": false to ensure framework-level code can be debugged if needed.

Consider adding an inline comment or a more descriptive name in the configuration (if appropriate) to clarify that it’s intended for schema debug operations (e.g., OpenAPI schema generation) for future maintainability.

src/backend/InvenTree/InvenTree/permissions.py (2)

110-118: Coverage for HEAD or other methods.

The returned dictionary maps standard methods (GET, POST, PUT, PATCH, DELETE, OPTIONS) but does not explicitly account for HEAD. In Django REST Framework, HEAD requests typically map to GET logic. This is fine, but consider clarifying if HEAD requests should share the same scope as GET.


146-168: Graceful fallback for exceptions, but consider logging.

Falling back to map_scope(only_read=True) when any exception (not just AttributeError) occurs ensures minimal accessible scopes. As a possible enhancement, consider adding a debug log message for non-AttributeError exceptions to aid troubleshooting.

src/backend/InvenTree/InvenTree/settings.py (1)

1455-1459: Configured OAuth2 flows and endpoints.

The property names for authorization, token, and revocation closely match Django OAuth Toolkit defaults. Including authorizationCode and clientCredentials flows is standard. If you plan to enable a password flow or device flow later, you can extend OAUTH2_FLOWS accordingly.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cdb4455 and 22dd0e0.

📒 Files selected for processing (8)
  • .vscode/launch.json (1 hunks)
  • src/backend/InvenTree/InvenTree/permissions.py (2 hunks)
  • src/backend/InvenTree/InvenTree/settings.py (5 hunks)
  • src/backend/InvenTree/InvenTree/tasks.py (1 hunks)
  • src/backend/InvenTree/InvenTree/urls.py (2 hunks)
  • src/backend/InvenTree/users/models.py (1 hunks)
  • src/backend/requirements.in (1 hunks)
  • src/backend/requirements.txt (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: build
  • GitHub Check: matmair.InvenTree (Job Python39)
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: Build - UI Platform
  • GitHub Check: Build - UI Platform
🔇 Additional comments (19)
src/backend/requirements.in (1)

29-29: Adding OAuth2 provider dependency looks good.

The addition of django-oauth-toolkit is appropriate for implementing OAuth2 provider functionality in the application.

src/backend/InvenTree/InvenTree/urls.py (2)

15-15: Import for OAuth2 URLs looks good.

The import is correctly placed with the other third-party libraries.


129-130: OAuth2 URL routing is properly configured.

The URL pattern for OAuth2 endpoints is correctly added with the standard /o/ path prefix, which is the convention for OAuth2 endpoints.

src/backend/InvenTree/InvenTree/tasks.py (1)

710-717: Scheduled task for OAuth2 maintenance is well implemented.

The daily scheduled task for clearing expired OAuth2 tokens follows the established pattern in the codebase and is a good practice for keeping the database clean.

src/backend/requirements.txt (4)

476-479: Good addition of django-oauth-toolkit for OAuth2 support.

This is the primary dependency needed to implement OAuth2 in a Django application, which aligns perfectly with the PR objective. The version is pinned correctly with proper hash validation.


776-779: Appropriate addition of jwcrypto dependency.

This package provides cryptographic support for JWT (JSON Web Tokens), which is commonly used with OAuth2 flows. It's correctly added as a dependency with version pinning and hash validation.


371-371: Proper comment update for dependency relationship.

The comment update correctly indicates that the cryptography package is now also required by jwcrypto, which helps maintain clear documentation of dependency relationships.


1439-1439: Proper comment update for dependency relationship.

The comment update correctly indicates that the requests package is now also required by django-oauth-toolkit, which helps maintain clear documentation of dependency relationships.

src/backend/InvenTree/InvenTree/permissions.py (5)

4-4: Import statement is appropriate.

Importing Optional from typing is correct, especially given the roles: Optional[list[str]] annotation in map_scope.


6-7: Necessary OAuth2 imports for permission checks.

These imports are needed to integrate the custom permission class with OAuth2. No concerns here.


100-109: Ensure consistent handling of empty roles.

The map_scope() function returns different lists of scopes based on the tables found in roles. If roles is empty (or None), the function falls back to basic read/write scopes or 'read' when only_read is True. This logic is clear and well-structured.


120-128: Precomputed role mapping logic looks good.

Building a dictionary from table → list of roles is efficient for quick lookups. If roles can be dynamically updated at runtime, consider a cache invalidation or re-computation mechanism, but this might be out of scope here.


130-145: Logic to allow non-OAuth2 authenticated users is sensible.

This class grants permission if the user is authenticated in a non-OAuth2 way or if the superclass’s has_permission() passes for OAuth2. The logic is clear and addresses the need to differentiate authentication backends.

src/backend/InvenTree/InvenTree/settings.py (6)

300-300: Adding oauth2_provider to INSTALLED_APPS is correct.

This enables OAuth2 features within the application. No issues here.


324-324: Check middleware ordering.

OAuth2TokenMiddleware generally goes after authentication middleware. Ensure this ordering is intentional and tested to avoid authentication interplay issues.

Would you verify that requests containing OAuth2 tokens are properly authenticated by running typical tests or using a known OAuth2 client?


357-357: Including OAuth2Backend in AUTHENTICATION_BACKENDS.

Makes sense for allowing Django to authenticate using OAuth2. Be mindful of the order if you rely on fallback strategies.


527-549: Defining OAUTH2_PROVIDER scopes.

The default scopes and role-based scopes align well with your permission model. This explicit approach simplifies scope management.


558-558: Registering OAuth2Authentication in DRF.

This is a standard and necessary step for enabling OAuth2 in the REST framework. Good addition.


565-565: Ensuring the new token permission class is enforced.

InvenTreeTokenMatchesOASRequirements ensures OAuth2 tokens adhere to the correct scope requirements, in combination with the existing permission mixins. This is consistent with your updates in permissions.py.

coderabbitai Bot added a commit that referenced this pull request Mar 16, 2025
Docstrings generation was requested by @matmair.

* #308 (comment)

The following files were modified:

* `src/backend/InvenTree/InvenTree/permissions.py`
* `src/backend/InvenTree/InvenTree/tasks.py`
* `src/backend/InvenTree/users/models.py`
@coderabbitai

coderabbitai Bot commented Mar 16, 2025

Copy link
Copy Markdown

Note

Generated docstrings for this pull request at #316

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 (2)
src/frontend/src/tables/sales/SalesOrderAllocationTable.tsx (1)

276-291: Shipment assignment button with proper conditional rendering.

The table action button is correctly configured with appropriate visibility and enabling conditions. The use of an icon enhances the user interface.

Consider removing or implementing the TODO comment on line 288. If this check is needed, it should be implemented; otherwise, the comment should be removed for cleaner code.

-        // TODO: Hide if order is already shipped
src/backend/InvenTree/InvenTree/settings.py (1)

300-1465: Consider adding refresh token support

The current OAuth2 implementation includes the basic flows and endpoints but doesn't explicitly configure refresh token settings. For improved user experience, especially in long-running applications, consider adding refresh token support.

 OAUTH2_PROVIDER = {
     # default scopes
     'SCOPES': {
         'read': 'Read scope',
         'write': 'Write scope',
         # user roles
         'superuser': 'Role Superuser',
         # inventree roles
         'admin': 'Role Admin',
         'part_category': 'Role Part Categories',
         'part': 'Role Parts',
         'stocktake': 'Role Stocktake',
         'stock_location': 'Role Stock Locations',
         'stock': 'Role Stock Items',
         'build': 'Role Build Orders',
         'purchase_order': 'Role Purchase Orders',
         'sales_order': 'Role Sales Orders',
         'return_order': 'Role Return Orders',
         # inventree methods
         'view': 'Method GET',
         'create': 'Method POST',
         'change': 'Method PUT / PATCH',
         'delete': 'Method DELETE',
-    }
+    },
+    'REFRESH_TOKEN_EXPIRE_SECONDS': 86400,  # 24 hours
+    'ACCESS_TOKEN_EXPIRE_SECONDS': 3600,    # 1 hour
+    'ROTATE_REFRESH_TOKEN': True
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9dfb612 and 16d3c05.

📒 Files selected for processing (14)
  • src/backend/InvenTree/InvenTree/api.py (7 hunks)
  • src/backend/InvenTree/InvenTree/api_version.py (1 hunks)
  • src/backend/InvenTree/InvenTree/settings.py (5 hunks)
  • src/backend/InvenTree/order/api.py (2 hunks)
  • src/backend/InvenTree/part/api.py (3 hunks)
  • src/backend/InvenTree/stock/api.py (4 hunks)
  • src/backend/requirements.in (1 hunks)
  • src/backend/requirements.txt (7 hunks)
  • src/frontend/playwright.config.ts (1 hunks)
  • src/frontend/src/pages/sales/SalesOrderShipmentDetail.tsx (1 hunks)
  • src/frontend/src/pages/stock/LocationDetail.tsx (1 hunks)
  • src/frontend/src/tables/part/PartCategoryTable.tsx (3 hunks)
  • src/frontend/src/tables/sales/SalesOrderAllocationTable.tsx (3 hunks)
  • src/frontend/src/tables/stock/StockLocationTable.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/backend/requirements.in
  • src/backend/InvenTree/part/api.py
  • src/backend/InvenTree/stock/api.py
  • src/backend/InvenTree/InvenTree/api.py
⏰ Context from checks skipped due to timeout of 90000ms (14)
  • GitHub Check: Tests - Platform UI
  • GitHub Check: Tests - DB [PostgreSQL]
  • GitHub Check: Tests - inventree-python
  • GitHub Check: Tests - DB [SQLite] + Coverage 3.9
  • GitHub Check: Tests - DB [MySQL]
  • GitHub Check: Tests - inventree-python
  • GitHub Check: Tests - DB [MySQL]
  • GitHub Check: Tests - Platform UI
  • GitHub Check: Tests - DB [PostgreSQL]
  • GitHub Check: Tests - DB [SQLite] + Coverage 3.9
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: build
  • GitHub Check: matmair.InvenTree (Job Python39)
  • GitHub Check: Tests - API Schema Documentation
🔇 Additional comments (34)
src/frontend/playwright.config.ts (1)

46-47: New environment variable for login attempts limit added.

The new environment variable INVENTREE_LOGIN_ATTEMPTS: '100' is added to support OAuth2 integration. This sets a limit of 100 login attempts for testing, which is reasonable for the test environment.

src/frontend/src/pages/sales/SalesOrderShipmentDetail.tsx (1)

216-216: Added orderId prop to SalesOrderAllocationTable.

This change correctly passes the order ID to the allocation table, enabling the new bulk editing functionality for sales order allocations. This is aligned with the OAuth2 and permissions updates in this PR.

src/backend/InvenTree/InvenTree/api_version.py (2)

4-4: API version incremented to 324.

The API version number has been properly incremented to reflect the new changes.


11-14: Added documentation for new BulkUpdate support.

Clear and concise documentation for the new bulk update support for SalesOrderAllocation, PartCategory, and StockLocation models. This follows the established pattern in the file and provides good context for the API changes.

src/frontend/src/pages/stock/LocationDetail.tsx (1)

175-180: Reorganized sublocations panel in the UI.

The sublocations panel has been properly structured with appropriate label, icon, and component. This change supports the newly added bulk edit functionality for stock locations.

src/backend/requirements.txt (5)

371-372: Correct dependency chaining for cryptography

The addition of jwcrypto as a dependency that relies on cryptography is properly documented in the requirements file.


404-405: Correct dependency chain for django-oauth-toolkit

Appropriate inclusion of django-oauth-toolkit as a dependency that relies on django. This is a standard pattern in the requirements file that maintains consistency.


438-439: Correct dependency chain for requests

The addition of django-oauth-toolkit to the list of packages that depend on requests is correctly documented, following the pattern used throughout the requirements file.


471-478: OAuth2 main dependency correctly added

The main dependency django-oauth-toolkit==3.0.1 is correctly added with proper hash verification. This package provides OAuth2 provider capabilities to Django applications, which is essential for the PR objective of adding OAuth2 support to the backend.


771-774: JWT crypto dependency correctly added

The addition of jwcrypto==1.5.6 with appropriate hash verification is correct. This package is necessary for handling JSON Web Tokens (JWT) cryptographic operations, which are commonly used in OAuth2 implementations for token signing and verification.

src/frontend/src/tables/stock/StockLocationTable.tsx (6)

6-6: New component import for bulk actions.

Adding the ActionDropdown component is essential for implementing the new bulk edit functionality that enhances the user experience.


12-18: Icon and hook imports to support bulk editing functionality.

The imports of InvenTreeIcon and useBulkEditApiFormModal provide the necessary resources for the new bulk edit feature. The placement alongside related imports follows proper organization principles.


124-132: New bulk edit modal for setting parent locations.

This hook implementation creates a modal for setting parent locations on multiple selected stock locations at once. The API endpoint, selected items, and callback functions are properly defined.


139-155: Added location actions dropdown for bulk operations.

The ActionDropdown component enhances the table by providing bulk actions for selected items. Good implementation of conditional rendering based on user permissions (hidden: !can_edit) and record selection state (disabled: !table.hasSelectedRecords).


163-163: Updated dependency array for tableActions.

Adding table.hasSelectedRecords to the dependency array ensures the action dropdown properly updates when items are selected/deselected, following React's best practices for memoization.


186-186: Added modal to component render.

This line adds the setParent modal to the component tree, ensuring it's available when the action is triggered.

src/backend/InvenTree/order/api.py (2)

24-24: Extended import statement to include BulkUpdateMixin.

The import statement is properly modified to include the BulkUpdateMixin alongside other API components, maintaining code organization.


1181-1181: Added bulk update capability to SalesOrderAllocationList.

Extending the class with BulkUpdateMixin adds important bulk update functionality to the SalesOrderAllocation model, enabling the frontend bulk edit features.

This enhancement allows for more efficient operations when handling multiple allocations, improving the overall performance and user experience of the application.

src/frontend/src/tables/part/PartCategoryTable.tsx (5)

8-8: Added imports to support bulk editing functionality.

The imports for ActionDropdown, InvenTreeIcon, and useBulkEditApiFormModal are essential for implementing the part category bulk editing feature.

Also applies to: 14-19


126-134: New bulk edit modal for setting parent categories.

The implementation creates a modal for bulk editing parent categories. The configuration is clean and focused, with proper handling of selected items and success callbacks.


141-157: Added category actions dropdown for bulk operations.

The ActionDropdown component enhances the table with bulk edit capabilities. The implementation properly handles user permissions and selection state visibility.


165-165: Updated dependency array for tableActions.

The addition of table.hasSelectedRecords to the dependency array ensures proper re-rendering when the selection state changes, following React best practices.


188-188: Added modal rendering and enabled table selection.

The modal is properly added to the component tree, and table selection is enabled to support the bulk edit functionality. This creates a cohesive user experience for managing part categories.

Also applies to: 195-195

src/frontend/src/tables/sales/SalesOrderAllocationTable.tsx (4)

4-5: Added imports to support bulk assignment functionality.

The imports for IconTruckDelivery, ActionButton, UserRoles, and useBulkEditApiFormModal are necessary for implementing the bulk shipment assignment feature.

Also applies to: 9-15


252-259: Smart filtering for non-shipped allocations.

This logic correctly filters out allocations that have already been shipped, ensuring that only valid allocations can be assigned to a shipment. Good use of optional chaining and nullish coalescing to handle potential undefined values.


261-274: Modal implementation for bulk assignment to shipments.

The implementation provides a clean way to assign multiple allocations to a shipment. Good use of filters to show only valid shipments (unshipped and matching the order).


295-295: Added modal rendering and enabled conditional table features.

The modal is properly added to the component tree, and table selection and actions are conditionally enabled based on the isSubTable property. This ensures the component works well in both standalone and embedded contexts.

Also applies to: 319-323

src/backend/InvenTree/InvenTree/settings.py (7)

300-300: Added OAuth2 provider to INSTALLED_APPS

The addition of 'oauth2_provider' to INSTALLED_APPS is necessary to enable OAuth2 authentication in the application. This is the correct first step when integrating django-oauth-toolkit.


324-324: Added OAuth2 token middleware

Adding the OAuth2 token middleware is essential for proper token handling and processing in the OAuth2 flow.


357-357: Added OAuth2 authentication backend

The OAuth2Backend is correctly added to the authentication backends list, which allows authentication via OAuth2 tokens.


527-551: Well-structured OAuth2 scopes configuration

The OAUTH2_PROVIDER configuration includes a comprehensive set of scopes that align with the application's permission model. The structure separates role-based scopes (admin, part_category, etc.) from method-based scopes (view, create, change, delete), enabling fine-grained access control.


560-560: Added OAuth2 authentication to REST framework

OAuth2Authentication is correctly added to the DEFAULT_AUTHENTICATION_CLASSES, enabling OAuth2 authentication for REST API endpoints.


1462-1465: OAuth2 configuration for API documentation

The OAuth2 flow settings are properly configured in SPECTACULAR_SETTINGS, which will generate accurate OpenAPI documentation for the OAuth2 endpoints.


567-567:

Details

❓ Verification inconclusive

Custom OAuth2 permission class

Adding 'InvenTreeTokenMatchesOASRequirements' to the permission classes ensures OAuth2 tokens are validated against OpenAPI requirements. This is a good practice for API security.


🏁 Script executed:

#!/bin/bash
# Verify the implementation of the custom permission class

# Check if the permission class exists and what it does
fd "InvenTreeTokenMatchesOASRequirements" --type f

Length of output: 50


Action Required: Verify Custom Permission Implementation

The inclusion of

'InvenTree.permissions.InvenTreeTokenMatchesOASRequirements',

in the settings is intended to enforce OAuth2 token validation against OpenAPI requirements, which is a good security measure. However, our initial search did not locate any file or declaration for InvenTreeTokenMatchesOASRequirements. Please manually verify that this custom permission class exists (for example, in a module like src/backend/InvenTree/InvenTree/permissions.py) and that it implements the required OAuth2 token validation. If the class is absent or misplaced, update the settings reference or add the appropriate implementation.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (1)
contrib/container/requirements.txt (1)

1-237: 💡 Verification agent

🧩 Analysis chain

Missing OAuth2 Dependencies
The PR objectives indicate the addition of OAuth2 support. According to the high-level summary, dependencies for OAuth2 integration—specifically django-oauth-toolkit==3.0.1 and jwcrypto==1.5.6—should be present. However, these dependencies are not visible in this generated requirements.txt file.

Please verify that:

  • The requirements.in file includes the new OAuth2 dependencies.
  • The generation command (uv pip compile ...) has correctly incorporated these changes into requirements.txt.

If these dependencies were unintentionally omitted, consider adding them as shown in the suggested diff below.

+django-oauth-toolkit==3.0.1 \
+    --hash=sha256:<computed_hash_here>
+jwcrypto==1.5.6 \
+    --hash=sha256:<computed_hash_here>

🏁 Script executed:

#!/bin/bash
echo "Searching for 'django-oauth-toolkit' in all *.in files..."
rg "django-oauth-toolkit" -g "*.in"

echo "Searching for 'jwcrypto' in all *.in files..."
rg "jwcrypto" -g "*.in"

Length of output: 383


Action Required: Missing OAuth2 Dependency Detected

  • We verified that the src/backend/requirements.in file contains an entry for django-oauth-toolkit (as indicated by the comment “# OAuth2 provider”), so that dependency is being tracked.
  • However, searching for jwcrypto did not yield any matches in any *.in files. This means that while the high-level objectives call for OAuth2 support with both dependencies, only django-oauth-toolkit is configured, and jwcrypto is absent.
  • Please verify whether jwcrypto==1.5.6 should be added to the appropriate requirements file (likely the same one containing OAuth2 support). If it was unintentionally omitted, add it so that the generated requirements.txt properly reflects all OAuth2 necessities.
+jwcrypto==1.5.6 \
+    --hash=sha256:<computed_hash_here>
🧹 Nitpick comments (3)
src/frontend/src/tables/settings/ApiTokenTable.tsx (2)

20-22: Consider adding JSDoc comments.

While the component's purpose and props are clear from the implementation, adding JSDoc comments would improve documentation.

+/**
+ * Component for displaying and managing API tokens
+ * @param only_myself When true, shows only the current user's tokens and provides token generation capability.
+ *                    When false, shows tokens for all users (admin mode).
+ */
 export function ApiTokenTable({
   only_myself = true
 }: Readonly<{ only_myself: boolean }>) {

126-156: Consider adding loading state for token revocation.

The token revocation functionality works well, but consider adding a loading state during the API call to improve user feedback.

 const revokeToken = async (id: string) => {
+  const [loading, setLoading] = useState(false);
   let targetUrl = apiUrl(ApiEndpoints.user_tokens, id);
   if (!only_myself) {
     targetUrl += '?all_users=true';
   }
+  setLoading(true);
   api
     .delete(targetUrl)
     .then(() => {
       table.refreshTable();
+      setLoading(false);
     })
     .catch((error) => {
+      setLoading(false);
       showApiErrorMessage({
         error: error,
         title: t`Error revoking token`
       });
     });
 };

 // Then in the rowActions callback:
 {
   title: t`Revoke`,
   color: 'red',
   hidden: !record.active || record.in_use,
   icon: <IconCircleX />,
   onClick: () => {
     revokeToken(record.id);
   },
+  loading // Add loading state
 }
src/backend/InvenTree/InvenTree/api_version.py (1)

15-18: Resolve conflict with previous v324 reference.
This “v324” entry is dated 2025-03-17, which conflicts with an earlier “v324” block at lines 11–13. Instead of having two version logs for the same version label, consider merging or renaming one to avoid confusion.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 16d3c05 and ea3c4cd.

📒 Files selected for processing (9)
  • .github/workflows/docker.yaml (1 hunks)
  • .pre-commit-config.yaml (3 hunks)
  • contrib/container/requirements.txt (5 hunks)
  • src/backend/InvenTree/InvenTree/api_version.py (1 hunks)
  • src/backend/InvenTree/users/api.py (10 hunks)
  • src/backend/InvenTree/users/serializers.py (2 hunks)
  • src/frontend/src/pages/Index/Settings/AccountSettings/SecurityContent.tsx (2 hunks)
  • src/frontend/src/pages/Index/Settings/AdminCenter/UserManagementPanel.tsx (1 hunks)
  • src/frontend/src/tables/settings/ApiTokenTable.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .github/workflows/docker.yaml
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: build
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: matmair.InvenTree (Job Python39)
🔇 Additional comments (38)
src/frontend/src/pages/Index/Settings/AdminCenter/UserManagementPanel.tsx (2)

6-6: Good addition of the ApiTokenTable import.

The import is correctly added for token management functionality.


39-46: Well implemented token management section.

The new Accordion.Item for token management is well-structured and follows the same pattern as the existing accordion items, maintaining UI consistency.

src/frontend/src/pages/Index/Settings/AccountSettings/SecurityContent.tsx (2)

30-30: Clean up of imports.

Good job removing unused imports and adding only what's needed for the new implementation.

Also applies to: 37-37


89-89: Good refactoring to use the shared component.

Replacing the custom token section implementation with the reusable ApiTokenTable component improves code maintainability and reduces duplication.

src/frontend/src/tables/settings/ApiTokenTable.tsx (5)

26-36: Well-implemented token generation.

The token generation modal implementation is well-structured using the useCreateApiFormModal hook.


37-47: Good conditional table actions.

The table actions are appropriately conditioned on the only_myself prop, ensuring token generation is only available in personal mode.


51-103: Well-structured table columns.

The table columns are well-defined with appropriate sorting and rendering options. The conditional addition of the user column for admin view is a good approach.


105-124: Good filter implementation.

The filters are properly implemented with conditional user filtering based on the only_myself prop.


163-199: Well-implemented component rendering.

The component rendering logic is clean, with appropriate conditional rendering based on the only_myself prop. The table configuration is comprehensive.

.pre-commit-config.yaml (4)

20-20: Updated ruff-pre-commit Version to v0.11.0
The revision bump to v0.11.0 should provide the latest linting improvements and fixes. Please verify the release notes for any breaking changes and ensure that your custom configurations (if any) remain compatible.


31-31: Updated uv-pre-commit Version to 0.6.6
This minor version update should include relevant bug fixes and enhancements. Make sure to test the hook locally so it integrates seamlessly with your development workflow.


73-73: Bumped biomejs/pre-commit Revision to v1.9.4
Ensure that the updated biome-check hook behaves as expected with the new version. It might be helpful to review the release notes for any configuration or dependency changes that could affect your setup.


79-79: Gitleaks Revision Updated to v8.24.0
Confirm that this security tool update integrates well with your current pre-commit configuration. It is advisable to check the release notes for any noteworthy modifications that could impact your security scanning workflow.

src/backend/InvenTree/InvenTree/api_version.py (2)

4-4: Ensure version references and docs are updated accordingly.
Increasing the API version from 323 to 325 makes sense if version 324 was already used. Double-check any remaining references to version 324 elsewhere (e.g. documentation, release notes) to confirm consistency.


11-13: Potential duplication in versioning notes.
You appear to have a “v324” entry dated 2024-03-17. Please confirm that it is intended to differ from the following “v324” entry at line 15, or if a version label or date needs to be adjusted to avoid confusion.

src/backend/InvenTree/users/serializers.py (3)

130-132: Optional user field is well-structured.
Allowing the user field to be omitted and then defaulting it is a flexible approach. This looks good for scenarios where an API token defaults to the current user if no user is specified.


159-163: Consider restricting cross-user token creation.
This validation logic assigns the requesting user if no user field is provided, but does not check whether the request user is permitted to create tokens on behalf of others. If you intend to allow token creation only for the current user (unless they have elevated privileges), add a permission check here.


166-178: New GetAuthTokenSerializer seems consistent.
This serializer cleanly defines a read-only token and expiry while requiring a name. The implementation aligns well with the usage patterns in the API.

src/backend/InvenTree/users/api.py (14)

12-14: New imports align with added functionality.
The addition of drf_spectacular.utils and rest_framework.generics is consistent with the changes that follow.


120-120: Expanded permission for RoleDetails.
Switching to IsAuthenticatedOrReadScope may allow read access under limited scopes. Verify that the new permission behavior matches your desired access control (e.g., read-only for anonymous tokens).


133-133: Consistent permission update for UserDetail.
Adopting IsAuthenticatedOrReadScope here maintains a uniform approach. Test to ensure user details are not overexposed for read-scope tokens.


161-161: Combined permission classes for UserList.
Using IsAuthenticatedOrReadScope with IsSuperuserOrReadOnly is a powerful combo—ensure it does not inadvertently publicly expose user records.


217-217: Refactoring GetAuthToken to GenericAPIView.
Nice improvement. Inheriting from GenericAPIView supports more DRF patterns like mixins if you plan further extensibility.


220-222: Revised permission and serializer for GetAuthToken.
Using IsAuthenticatedOrReadScope and GetAuthTokenSerializer is consistent with your OAuth2-oriented enhancements. The extended schema annotation is also well-defined.


286-287: TokenMixin introduced for reusable logic.
This mixin is a neat way to avoid duplication across different token endpoints.


289-289: Token permissions use read-scope logic.
Applying IsAuthenticatedOrReadScope ensures token data remains protected, while still allowing read-scoped tokens to fetch limited information if appropriate.


294-296: Allow superuser to list all tokens.
This is a powerful feature. Verify that this aligns with your organizational policies and that superusers are expected to see all tokens, as it could disclose sensitive info (e.g., token names).


300-310: Comprehensive schema docs for token retrieval.
Your @extend_schema usage is thorough and helpful, giving clear instructions on query parameters for retrieving token data.


315-316: TokenListView extends list & create for tokens.
This new view is well organized, leveraging TokenMixin for consistent behaviors across token APIs.


317-320: At-a-glance token searching.
Exposing token name and key to search might simplify management but check if partial key searches could be a security concern.


330-343: Displaying newly generated token.
Revealing the key after creation is essential for the user. Ensure any ephemeral or one-time-view requirements are documented or enforced as needed.


345-346: TokenDetailView for token-specific operations.
Combining DestroyAPIView and RetrieveAPI is succinct for handling token revocations and detail retrieval.

contrib/container/requirements.txt (6)

7-9: Django Dependency Update Verification
The Django package has been updated to version 4.2.20 along with its corresponding new hash values. This update aligns with the dependency maintenance objectives. Please verify that all aspects of your project (e.g., compatibility with custom middlewares or plugins) work seamlessly with this upgraded version.


25-36: MariaDB Dependency Update
The Mariadb package has been updated from version 1.1.11 to 1.1.12, and all associated hash values have been completely refreshed. Ensure that this update is tested in your environment to catch any incompatibilities with the database driver or underlying infrastructure.


54-56: PSYCOPG [binary, pool] Update
The update for the psycopg[binary, pool] dependency to version 3.2.6—including its new hash values—is noted. Confirm that both the binary and connection pool functionalities are validated after this upgrade.


58-60: PSYCOPG-binary Dependency Update
The psycopg-binary package has similarly been updated to 3.2.6 with new hash values. Please ensure that any database interactions relying on this package are working as expected post-update.


199-201: Setuptools Update
Setuptools has been upgraded to 76.0.0 with refreshed hash values. This change is essential for better packaging management. It is recommended to monitor the build and deployment pipelines for any impact caused by this upgrade.


213-232: UV Package Update
The uv package is now at version 0.6.6, and the file shows a comprehensive update of its associated hash values. This should help maintain improved dependency resolution. Please verify that any components or scripts relying on this package continue to function correctly.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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)
src/backend/InvenTree/InvenTree/test_api.py (1)

533-533: Consider making this assertion more future-proof

This assertion checks for a specific version number (v14) which might need to be updated when new API versions are added in the future.

-        self.assertEqual(list(resp)[-1], 'v14')
+        self.assertEqual(list(resp)[-1], f'v{INVENTREE_API_VERSION + 9}')  # 10 versions starting from 5
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 88bea30 and cc09301.

⛔ Files ignored due to path filters (1)
  • src/frontend/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (9)
  • docs/docs/concepts/pricing.md (1 hunks)
  • src/backend/InvenTree/InvenTree/api.py (9 hunks)
  • src/backend/InvenTree/InvenTree/api_version.py (1 hunks)
  • src/backend/InvenTree/InvenTree/test_api.py (1 hunks)
  • src/backend/InvenTree/InvenTree/version.py (2 hunks)
  • src/backend/InvenTree/common/api.py (33 hunks)
  • src/backend/InvenTree/common/serializers.py (1 hunks)
  • src/frontend/package.json (1 hunks)
  • src/frontend/src/components/modals/AboutInvenTreeModal.tsx (0 hunks)
💤 Files with no reviewable changes (1)
  • src/frontend/src/components/modals/AboutInvenTreeModal.tsx
✅ Files skipped from review due to trivial changes (2)
  • docs/docs/concepts/pricing.md
  • src/frontend/package.json
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/backend/InvenTree/InvenTree/api_version.py
  • src/backend/InvenTree/InvenTree/api.py
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/backend/InvenTree/InvenTree/test_api.py (1)
src/backend/InvenTree/InvenTree/version.py (2)
  • inventreeApiText (198-214)
  • parse_version_text (164-191)
src/backend/InvenTree/common/api.py (1)
src/backend/InvenTree/InvenTree/permissions.py (4)
  • AllowAnyOrReadScope (292-301)
  • GlobalSettingsPermissions (331-351)
  • IsAuthenticatedOrReadScope (259-264)
  • UserSettingsPermissionsOrScope (314-328)
⏰ Context from checks skipped due to timeout of 90000ms (15)
  • GitHub Check: Tests - Web UI
  • GitHub Check: Tests - inventree-python
  • GitHub Check: Tests - DB [MySQL]
  • GitHub Check: Tests - DB [PostgreSQL]
  • GitHub Check: Tests - Web UI
  • GitHub Check: Tests - DB [SQLite] + Coverage 3.9
  • GitHub Check: Tests - DB [PostgreSQL]
  • GitHub Check: Tests - DB [MySQL]
  • GitHub Check: Tests - inventree-python
  • GitHub Check: Tests - DB [SQLite] + Coverage 3.9
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: build
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: matmair.InvenTree (Job Python39)
  • GitHub Check: Build - Web UI
🔇 Additional comments (15)
src/backend/InvenTree/InvenTree/test_api.py (4)

518-519: Good addition of latest_version variable

Adding the variable to reference the formatted version makes the test more maintainable and consistent with the implementation in version.py.


523-523: Good assertion for API response validation

This assertion ensures that the latest version is properly included in the API response.


528-528: Good consistency check

Ensuring the latest version is included in the longer response list is a good verification.


539-554: Well-structured test enhancement for version parsing

The rewritten test improves validation by:

  1. Properly checking that only one version is marked as the latest
  2. Validating the structure of each version entry
  3. Verifying version string format
  4. Accounting for missing versions in the calculation

This is a significant improvement in test coverage.

src/backend/InvenTree/InvenTree/version.py (6)

170-170: Good addition of latest_version variable

This creates a consistent way to reference the latest version throughout the function, improving maintainability.


176-179: Good improvement with explicit extraction and empty check

The explicit extraction of version_string and check for empty values prevents potential issues with malformed version strings.


184-184: Clean refactoring using extracted variable

Using the extracted variable improves code readability.


188-188: More robust latest version check

Comparing with the formatted latest_version variable is more consistent than the previous approach.


190-190: Consistent key usage

Using version_string as the dictionary key maintains consistency with the version field in the data structure.


209-209: Adjustment to start_version calculation

This change ensures the correct range of versions is returned. The adjustment by adding 1 aligns with the expected behavior in the tests.

src/backend/InvenTree/common/serializers.py (1)

431-431: Potential impact from changing available_units from list to dictionary
Switching from Unit(many=True) to serializers.DictField(child=Unit()) significantly alters the data structure from a list to a dictionary. This may introduce backward compatibility issues if consumers still expect a list. Please verify that all references and consumers handling this field are updated to accept dictionary-based data.

src/backend/InvenTree/common/api.py (4)

23-25: Consolidated REST framework imports
The addition and consolidation of imports for serializers and permissions look fine. Confirm that the rest of the file’s references and usage remain valid.


47-55: Refactored permission imports
Importing permission classes directly from InvenTree.permissions enables a more unified, OAuth2-oriented permissions strategy. This separation clarifies which custom classes are in play.


145-145: Updated permission classes to new granular approach
These lines replace or introduce permission_classes to reflect the new scope-based permission system (IsAuthenticatedOrReadScope, IsStaffOrReadOnlyScope, etc.). While consistent with the ongoing OAuth2 integration, please ensure each endpoint continues to match your security requirements. Also confirm that any removed or replaced classes (IsAuthenticated, IsAdminUser) are safely retired and that clients’ workflows (including read-only vs. staff-only roles) remain intact.

Also applies to: 189-189, 219-219, 236-236, 255-255, 292-292, 314-314, 345-345, 366-366, 419-419, 444-444, 454-454, 469-469, 487-487, 501-501, 508-508, 517-517, 520-520, 524-524, 646-646, 652-652, 668-668, 733-733, 771-771, 789-789, 801-801, 822-822, 840-840, 848-848, 855-855


993-995: Ensure metadata route security is correct
Using [IsStaffOrReadOnlyScope] on the MetadataView route helps guarantee that metadata updates can only be performed by staff, while others retain read-only access. Verify that this permission aligns with your intended user-level functionality.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
src/backend/InvenTree/InvenTree/permissions.py (1)

97-98: InvenTreeTokenMatchesOASRequirements broad error handling

Catching Exception without logging the error can obscure debugging details. Consider catching more targeted exceptions or at least logging the original exception before returning.

-        except Exception:
+        except Exception as exc:
+            # Log the exception to aid debugging
+            import logging
+            logger = logging.getLogger(__name__)
+            logger.exception("Error determining required scopes")
             return map_scope(only_read=True)
🧹 Nitpick comments (4)
src/backend/InvenTree/InvenTree/permissions.py (4)

102-160: Review class hierarchy for RolePermission

The RolePermission class now inherits from both InvenTreeTokenMatchesOASRequirements and permissions.BasePermission. While this implementation works, consider if all the functionality from both parent classes is needed, as multiple inheritance can sometimes lead to complexity.

The implementation looks solid, but it's worth documenting the inheritance design decision if this pattern is used throughout the codebase.

Consider adding a class docstring comment explaining the inheritance strategy and why both parent classes are necessary.


222-228: Simplify nested scope_name function logic

The scope_name function could be simplified to make the control flow more evident.

-    def scope_name(action):
-        if only_read:
-            return [[read_name]]
-        if roles:
-            return [[get_granular_scope(action, table) for table in roles]]
-        return [[action]]
+    def scope_name(action):
+        if only_read:
+            return [[read_name]]
+        elif roles:
+            return [[get_granular_scope(action, table) for table in roles]]
+        else:
+            return [[action]]

236-238: Improve readability of list comprehension

The list comprehension in the map_scope return statement is complex with a conditional expression. Consider breaking it down for better readability.

-    return {
-        method: get_scope(method, action) if method != 'OPTIONS' else [[DEFAULT_READ]]
-        for method, action in ACTION_MAP.items()
-    }
+    result = {}
+    for method, action in ACTION_MAP.items():
+        if method == 'OPTIONS':
+            result[method] = [[DEFAULT_READ]]
+        else:
+            result[method] = get_scope(method, action)
+    return result

285-288: Simplify boolean expression in IsStaffOrReadOnlyScope.has_permission

The boolean expression can be simplified for better readability.

-        return bool(permissions.IsAuthenticated().has_permission(request, view)) and (
-            (request.user and request.user.is_staff)
-            or request.method in permissions.SAFE_METHODS
-        )
+        if not permissions.IsAuthenticated().has_permission(request, view):
+            return False
+        
+        return request.user.is_staff or request.method in permissions.SAFE_METHODS
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cc09301 and 6b6e231.

📒 Files selected for processing (3)
  • src/backend/InvenTree/InvenTree/api_version.py (1 hunks)
  • src/backend/InvenTree/InvenTree/permissions.py (6 hunks)
  • src/backend/InvenTree/users/api.py (9 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/backend/InvenTree/InvenTree/api_version.py
  • src/backend/InvenTree/users/api.py
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/backend/InvenTree/InvenTree/permissions.py (2)
src/backend/InvenTree/users/oauth2_scopes.py (1)
  • get_granular_scope (4-8)
src/backend/InvenTree/users/ruleset.py (1)
  • get_ruleset_models (52-171)
⏰ Context from checks skipped due to timeout of 90000ms (17)
  • GitHub Check: Tests - Web UI
  • GitHub Check: Security [Zizmor]
  • GitHub Check: Tests - inventree-python
  • GitHub Check: Tests - Web UI
  • GitHub Check: Tests - DB [MySQL]
  • GitHub Check: Tests - DB [MySQL]
  • GitHub Check: Tests - DB [SQLite] + Coverage 3.9
  • GitHub Check: Tests - DB [SQLite] + Coverage 3.9
  • GitHub Check: Tests - DB [PostgreSQL]
  • GitHub Check: Tests - DB [PostgreSQL]
  • GitHub Check: Tests - inventree-python
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: build
  • GitHub Check: matmair.InvenTree (Job Python39)
  • GitHub Check: Build - Web UI
  • GitHub Check: Build - Web UI
🔇 Additional comments (3)
src/backend/InvenTree/InvenTree/permissions.py (3)

305-315: Inheritance clarification for AllowAnyOrReadScope

Unlike other permission classes in this file, AllowAnyOrReadScope inherits from TokenMatchesOASRequirements directly instead of OASTokenMatcher. This inconsistency might be intentional but should be documented.

Was this decision to use TokenMatchesOASRequirements instead of OASTokenMatcher intentional? If so, it would be helpful to add a comment explaining why this class doesn't follow the same inheritance pattern as the other classes.


202-239: Great implementation of map_scope function

The map_scope function is well-structured with clear documentation, appropriate typing, and flexible options for generating scopes based on different requirements. This approach provides a good foundation for extending the permission system.


43-51:

Details

❓ Verification inconclusive

Consider impact of static roles mapping initialization

The roles mapping is precalculated at module import time, which is efficient but could be problematic if role definitions change during runtime. If roles are only loaded during server startup and remain static, this approach works well. However, if roles can be dynamically updated without restarting the server, this static initialization might not reflect the latest changes.

Consider whether this implementation is appropriate for your application lifecycle:


🏁 Script executed:

#!/bin/bash
# Check if there are any endpoints or mechanisms to update ruleset models at runtime

# Look for APIs that might modify ruleset models
rg -A 3 "ruleset.*update|update.*ruleset" --type py

# Look for admin interfaces to ruleset models
rg -A 5 "class.*RulesetAdmin|admin\.site\.register.*Ruleset" --type py

Length of output: 126


Static Roles Mapping — Please Verify Role Update Mechanisms

The roles mapping is precalculated at module import time, which is efficient if role definitions are static. Our automated search did not reveal any endpoints or admin interfaces that update ruleset models at runtime. However, the absence of results means we cannot conclusively rule out dynamic updates. Please manually verify that the source and consumers of users.ruleset.get_ruleset_models() do not support runtime modifications to roles.

  • File: src/backend/InvenTree/InvenTree/permissions.py (lines 43–51)
  • Action: Confirm that role definitions remain static after server startup. If dynamic updates are possible, consider a mechanism to recalculate or refresh the roles mapping.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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)
src/backend/InvenTree/users/admin.py (1)

60-73: Unused classes after RoleGroupAdmin removal

The RuleSetInline and InvenTreeGroupAdminForm classes are still present in the code, but they appear to be unused now that the RoleGroupAdmin class has been removed. This creates unnecessary code that could lead to confusion during future maintenance.

Consider removing these unused classes to keep the codebase clean and maintainable. If they are meant to be used elsewhere or preserved for future use, add a comment explaining their purpose and intended usage.

Also applies to: 75-115

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6b6e231 and d3b9f63.

📒 Files selected for processing (1)
  • src/backend/InvenTree/users/admin.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (18)
  • GitHub Check: Security [Zizmor]
  • GitHub Check: Tests - Web UI
  • GitHub Check: Tests - inventree-python
  • GitHub Check: Tests - DB [PostgreSQL]
  • GitHub Check: Tests - DB [SQLite] + Coverage 3.9
  • GitHub Check: Tests - DB [MySQL]
  • GitHub Check: Security [Zizmor]
  • GitHub Check: Tests - Web UI
  • GitHub Check: Tests - DB [SQLite] + Coverage 3.9
  • GitHub Check: Tests - DB [MySQL]
  • GitHub Check: Tests - DB [PostgreSQL]
  • GitHub Check: Tests - inventree-python
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: build
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: matmair.InvenTree (Job Python39)
  • GitHub Check: Build - Web UI
  • GitHub Check: Build - Web UI
🔇 Additional comments (2)
src/backend/InvenTree/users/admin.py (2)

1-155: Confirm migration strategy for OAuth2 integration

The removal of the RoleGroupAdmin class suggests a significant change in how permissions are managed. With the introduction of OAuth2/OIDC, ensure that existing group permissions are properly migrated or accessible through the new permission system.

Are there data migration scripts to ensure existing group permissions are preserved when switching to the new OAuth2-based permission system? If not, consider adding one to prevent potential permission issues during the transition.


4-4:

Details

❓ Verification inconclusive

Verify Group admin functionality

With the removal of the RoleGroupAdmin class and its registration, the Django admin site will now use the default admin interface for the Group model. This might affect the ability to manage groups and their permissions through the admin interface.


🏁 Script executed:

#!/bin/bash
# Check if there's a replacement admin class for Group elsewhere in the codebase
rg -g "*.py" "admin\.site\.register\(Group" --files-with-matches

# Check if any permission management features were moved to another file
rg -g "*.py" "class.*GroupAdmin" --files-with-matches

Length of output: 159


Action: Verify that the Group admin registration behaves as expected

  • The removal of the custom RoleGroupAdmin class appears to be in effect.
  • Our search confirms that the only registration of the Group model is done in src/backend/InvenTree/users/admin.py and that a GroupAdmin (or related pattern) is still present.
  • Please ensure that using the default (or possibly newly defined) GroupAdmin does not adversely affect how groups and their permissions are managed in the Django admin interface. Testing the admin interface in your development environment is recommended to confirm the functionality is intact.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
src/backend/InvenTree/InvenTree/permissions.py (1)

99-100: 🛠️ Refactor suggestion

Consider more specific exception handling.

Catching Exception broadly masks important debugging information. Consider catching more specific exceptions or at least logging the error details before returning the default scope.

-        except Exception:
-            return map_scope(only_read=True)
+        except Exception as exc:
+            logger.exception("Error determining required scopes: %s", exc)
+            return map_scope(only_read=True)
🧹 Nitpick comments (5)
src/backend/InvenTree/InvenTree/permissions.py (5)

300-305: Simplify has_permission logic.

The permission check can be simplified by combining the conditions more clearly.

    def has_permission(self, request, view):
        """Check if the user is a staff."""
-        return bool(permissions.IsAuthenticated().has_permission(request, view)) and (
-            (request.user and request.user.is_staff)
-            or request.method in permissions.SAFE_METHODS
-        )
+        if not permissions.IsAuthenticated().has_permission(request, view):
+            return False
+        
+        return request.user.is_staff or request.method in permissions.SAFE_METHODS

219-256: Add example to map_scope docstring.

The map_scope function is central to the OAuth2 scope-based permission system, but its output format might not be immediately clear to other developers. Consider adding an example to the docstring.

    """Generate the required scopes for OAS permission views.

    Args:
        roles (Optional[list[str]]): A list of roles or tables to generate granular scopes for.
        only_read (bool): If True, only the read scope will be returned for all actions.
        read_name (str): The read scope name to use when `only_read` is True.
        map_read (Optional[list[str]]): A list of HTTP methods that should map to the default read scope (use if some actions requirea differing role).
        map_read_name (str): The read scope name to use for methods specified in `map_read` when `map_read` is specified.

    Returns:
        dict: A dictionary mapping HTTP methods to their corresponding scopes.
              Each scope is represented as a list of lists of strings.
+
+    Example:
+        >>> map_scope(roles=['part', 'build'])
+        {
+            'GET': [['r:view:part', 'r:view:build']],
+            'POST': [['r:add:part', 'r:add:build']],
+            'PUT': [['r:change:part', 'r:change:build']],
+            'PATCH': [['r:change:part', 'r:change:build']],
+            'DELETE': [['r:delete:part', 'r:delete:build']],
+            'OPTIONS': [['read']]
+        }
"""

19-26: Consider adding validation for ACTION_MAP.

The ACTION_MAP is critical for permission mapping and is used by the map_scope function. Consider adding validation to ensure these remain in sync if either is modified.

Consider adding a validation function that runs during initialization to ensure that any changes to ACTION_MAP are properly reflected in the permission system.

def validate_action_map():
    """Validate that ACTION_MAP contains all necessary HTTP methods."""
    required_methods = {'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'}
    actual_methods = set(ACTION_MAP.keys())
    
    if not required_methods.issubset(actual_methods):
        missing = required_methods - actual_methods
        logger.warning(f"ACTION_MAP is missing required HTTP methods: {missing}")

# Call this at module initialization
validate_action_map()

252-255: Improve readability of return statement.

The return statement is a bit complex with nested comprehensions and conditionals. Consider breaking this down for improved readability.

-    return {
-        method: get_scope(method, action) if method != 'OPTIONS' else [[DEFAULT_READ]]
-        for method, action in ACTION_MAP.items()
-    }
+    result = {}
+    for method, action in ACTION_MAP.items():
+        if method == 'OPTIONS':
+            result[method] = [[DEFAULT_READ]]
+        else:
+            result[method] = get_scope(method, action)
+    return result

78-101: Consider adding caching for get_required_alternate_scopes.

For views that are accessed frequently, caching the results of scope calculations could further improve performance.

+    @functools.lru_cache(maxsize=128)
     def get_required_alternate_scopes(self, request, view):
         """Return the required scopes for the current request."""
         if hasattr(view, 'required_alternate_scopes'):
             return view.required_alternate_scopes
         try:
             # Extract the model name associated with this request
             model = get_model_for_view(view)
             calc = precalculated_roles.get(
                 f'{model._meta.app_label}_{model._meta.model_name}', []
             )

             if model is None or not calc:
                 return map_scope(only_read=True)
             return map_scope(roles=calc)

Make sure to add an import for functools if you implement this suggestion.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f44e9a and 11daafd.

📒 Files selected for processing (1)
  • src/backend/InvenTree/InvenTree/permissions.py (6 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/backend/InvenTree/InvenTree/permissions.py (2)
src/backend/InvenTree/users/oauth2_scopes.py (1)
  • get_granular_scope (4-8)
src/backend/InvenTree/users/ruleset.py (1)
  • get_ruleset_models (52-171)
⏰ Context from checks skipped due to timeout of 90000ms (18)
  • GitHub Check: Security [Zizmor]
  • GitHub Check: Security [Zizmor]
  • GitHub Check: Tests - Web UI
  • GitHub Check: Tests - DB [MySQL]
  • GitHub Check: Tests - inventree-python
  • GitHub Check: Tests - Web UI
  • GitHub Check: Tests - DB [MySQL]
  • GitHub Check: Tests - inventree-python
  • GitHub Check: Tests - DB [PostgreSQL]
  • GitHub Check: Tests - DB [PostgreSQL]
  • GitHub Check: Tests - DB [SQLite] + Coverage 3.9
  • GitHub Check: Tests - DB [SQLite] + Coverage 3.9
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: build
  • GitHub Check: matmair.InvenTree (Job Python39)
  • GitHub Check: Build - Web UI
  • GitHub Check: Build - Web UI
🔇 Additional comments (2)
src/backend/InvenTree/InvenTree/permissions.py (2)

43-51: Good optimization with precalculated roles.

Precalculating role mappings is an excellent optimization to avoid recalculation on each request, especially for frequently accessed permissions.


103-116: Well-designed permission class hierarchy.

The combination of mixins and inheritance is a clean way to compose the complex permission checking logic required. This approach allows for good separation of concerns between OAuth2 scope checking and traditional permission checks.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 (2)
src/backend/InvenTree/users/authentication.py (1)

43-44: Consider implementing custom functionality in ExtendedOAuth2Authentication.

The class is currently a placeholder that extends OAuth2Authentication but doesn't override any methods. While this is acceptable for initial integration, it would be valuable to document the planned custom scope rendering functionality in more detail or implement it in this PR.

 class ExtendedOAuth2Authentication(OAuth2Authentication):
     """Custom implementation of OAuth2Authentication class to support custom scope rendering."""
+    
+    # TODO: Implement custom scope rendering methods
src/backend/InvenTree/InvenTree/permissions.py (1)

117-140: Consider improving exception handling in get_required_alternate_scopes.

While the broad exception handling at line 138-139 ensures the method doesn't break, it might hide specific errors that could be useful for debugging.

-        except Exception:
+        except Exception as exc:
+            # Log the exception for debugging purposes
+            import logging
+            logger = logging.getLogger(__name__)
+            logger.debug(f"Error determining required scopes: {exc}")
             return map_scope(only_read=True)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8c63408 and 39a47ff.

📒 Files selected for processing (4)
  • src/backend/InvenTree/InvenTree/permissions.py (6 hunks)
  • src/backend/InvenTree/InvenTree/schema.py (2 hunks)
  • src/backend/InvenTree/InvenTree/settings.py (7 hunks)
  • src/backend/InvenTree/users/authentication.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/backend/InvenTree/InvenTree/schema.py
  • src/backend/InvenTree/InvenTree/settings.py
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/backend/InvenTree/InvenTree/permissions.py (2)
src/backend/InvenTree/users/oauth2_scopes.py (1)
  • get_granular_scope (4-8)
src/backend/InvenTree/users/ruleset.py (1)
  • get_ruleset_models (52-171)
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: Tests - Web UI
  • GitHub Check: Tests - DB [MySQL]
  • GitHub Check: Tests - inventree-python
  • GitHub Check: Tests - Web UI
  • GitHub Check: Tests - DB [SQLite] + Coverage 3.9
  • GitHub Check: Tests - DB [MySQL]
  • GitHub Check: Tests - DB [PostgreSQL]
  • GitHub Check: Tests - DB [PostgreSQL]
  • GitHub Check: Tests - inventree-python
  • GitHub Check: Tests - DB [SQLite] + Coverage 3.9
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: build
  • GitHub Check: matmair.InvenTree (Job Python39)
  • GitHub Check: Build - Web UI
  • GitHub Check: Build - Web UI
🔇 Additional comments (18)
src/backend/InvenTree/users/authentication.py (1)

7-7: Good addition of OAuth2Authentication import.

This import is necessary for the OAuth2 integration that's being implemented across the codebase.

src/backend/InvenTree/InvenTree/permissions.py (17)

4-17: Well-structured imports with appropriate organization.

The imports are properly organized and include all necessary components for the OAuth2 integration. The imported scope constants and functions will help with generating appropriate scopes for different permission levels.


19-26: Good standardization of action mapping.

The ACTION_MAP dictionary provides a consistent way to map HTTP methods to action names, which standardizes permission handling across the codebase.


43-79: Well-documented scope mapping function with flexible parameters.

The map_scope function is well-documented and designed to handle various scenarios for generating OAuth2 scopes based on roles and HTTP methods. The nested helper functions improve code organization.


82-90: Good performance optimization with precalculated role mappings.

Precalculating the role mappings is an efficient approach that avoids repeated calculations during request processing. The reverse mapping from table to roles will help in dynamically determining required scopes.


92-115: Clean implementation of OAuth2 authentication check mixin.

The OASTokenMixin provides a clean way to combine traditional permission checks with OAuth2 token validation, and the is_oauth2ed method properly detects when OAuth2 authentication was used.


142-156: Effective implementation of default permission class.

The InvenTreeTokenMatchesOASRequirements class properly combines role-based scope handling with OAuth2 token validation, with a sensible fallback to traditional authentication when OAuth2 is not used.


158-158: Good integration of OAuth2 support in RolePermission.

Inheriting from InvenTreeRoleScopeMixin extends the existing role-based permission system with OAuth2 scope support, maintaining backward compatibility while adding new functionality.


189-189: Consistent action mapping in RolePermission.

The updated rolemap dictionary uses the global ACTION_MAP, ensuring consistency across the permission system while maintaining special handling for the OPTIONS method.


245-251: Appropriate scope definition for read-only permissions.

The get_required_alternate_scopes method properly configures scopes for RolePermissionOrReadOnly, ensuring that SAFE_METHODS (GET, HEAD, OPTIONS) map to read-only permissions using the DEFAULT_STAFF scope.


259-269: Clear superuser permission class with OAuth2 support.

The IsSuperuserOrSuperScope class effectively combines the traditional superuser check with OAuth2 scope validation, using the DEFAULT_SUPERUSER scope for all operations.


271-288: Well-structured read-only superuser permission with OAuth2 support.

The IsSuperuserOrReadOnlyOrScope class properly handles both the traditional permission check and OAuth2 scope validation, with appropriate scope mapping for read-only operations.


290-296: Simple and focused authenticated or read scope permission.

The IsAuthenticatedOrReadScope class provides a clean implementation for scenarios where either an authenticated user or a token with read scope is sufficient.


298-313: Comprehensive staff or read-only permission with OAuth2 support.

The IsStaffOrReadOnlyScope class handles both traditional staff permissions and OAuth2 scopes, with proper differentiation between read and write operations.


315-321: Clear admin-level permission class with OAuth2 support.

The IsAdminOrAdminScope class effectively combines the standard IsAdminUser permission with OAuth2 scope validation using the DEFAULT_STAFF scope.


323-333: Simple permission class for public endpoints with OAuth2 support.

The AllowAnyOrReadScope class provides a clean implementation for public endpoints that can be accessed either without authentication or with a token that has read scope.


345-360: Well-implemented user settings permission with OAuth2 support.

The UserSettingsPermissionsOrScope class correctly checks object ownership for traditional permission checks and provides appropriate OAuth2 scope requirements.


362-383: Comprehensive global settings permission with OAuth2 support.

The GlobalSettingsPermissions class properly implements the staff check for write operations while allowing read access to all users, with corresponding OAuth2 scope mapping.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
src/backend/InvenTree/InvenTree/permissions.py (1)

117-140: Consider logging exceptions in get_required_alternate_scopes

The broad exception handler at lines 138-139 silently catches all exceptions and returns a fallback value. Consider logging the exception to help with debugging.

-        except Exception:
+        except Exception as exc:
+            import logging
+            logger = logging.getLogger('inventree')
+            logger.warning(f"Error determining required scopes: {exc}")
             return map_scope(only_read=True)
🧹 Nitpick comments (3)
src/backend/InvenTree/InvenTree/permissions.py (3)

43-62: Documentation typo in map_scope function parameter

There's a minor typo in the documentation for the map_read parameter: "requirea" should be "require".

-        map_read (Optional[list[str]]): A list of HTTP methods that should map to the default read scope (use if some actions requirea differing role).
+        map_read (Optional[list[str]]): A list of HTTP methods that should map to the default read scope (use if some actions require a differing role).

142-146: Typo in class documentation

Fix the typo in the InvenTreeTokenMatchesOASRequirements class documentation.

-    Usesd as default permission class.
+    Used as default permission class.

319-325: Inconsistency between class name and permission behavior

The class name "IsAdminOrAdminScope" might be confusing since the scope mapping uses DEFAULT_STAFF rather than a specific admin scope. Consider renaming the class or updating the scope mapping to match the name.

-class IsAdminOrAdminScope(OASTokenMixin, permissions.IsAdminUser):
+class IsStaffOrStaffScope(OASTokenMixin, permissions.IsAdminUser):

Or alternatively:

-    def get_required_alternate_scopes(self, request, view):
-        """Return the required scopes for the current request."""
-        return map_scope(only_read=True, read_name=DEFAULT_STAFF)
+    def get_required_alternate_scopes(self, request, view):
+        """Return the required scopes for the current request."""
+        return map_scope(only_read=True, read_name="admin")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 39a47ff and 1de6ce7.

📒 Files selected for processing (1)
  • src/backend/InvenTree/InvenTree/permissions.py (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: Tests - Web UI
  • GitHub Check: Tests - DB [MySQL]
  • GitHub Check: Tests - Web UI
  • GitHub Check: Tests - DB [PostgreSQL]
  • GitHub Check: Tests - DB [SQLite] + Coverage 3.9
  • GitHub Check: Tests - DB [SQLite] + Coverage 3.9
  • GitHub Check: Tests - DB [PostgreSQL]
  • GitHub Check: Tests - inventree-python
  • GitHub Check: Tests - DB [MySQL]
  • GitHub Check: Tests - inventree-python
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: build
  • GitHub Check: matmair.InvenTree (Job Python39)
  • GitHub Check: Build - Web UI
  • GitHub Check: Build - Web UI
🔇 Additional comments (7)
src/backend/InvenTree/InvenTree/permissions.py (7)

82-90: LGTM: Good optimization with precalculated roles

The precalculation of role mappings from the ruleset models is a good optimization that will avoid repeated computations during requests.


147-160: LGTM: Well-structured permission class

The implementation of InvenTreeTokenMatchesOASRequirements is well-structured, correctly differentiating between OAuth2 authentication and other methods.


249-255: LGTM: Good OAuth2 scope mapping for read-only access

The get_required_alternate_scopes method properly maps the OAuth2 scopes for read-only access, consistent with the class's permission logic.


264-273: LGTM: Appropriate scope mapping for superuser access

The IsSuperuserOrSuperScope class correctly restricts access to superusers and maps to the DEFAULT_SUPERUSER scope.


327-337: LGTM: AllowAnyOrReadScope implementation

The AllowAnyOrReadScope class properly extends OASTokenMixin and permissions.AllowAny, with a correct implementation of get_required_alternate_scopes.


349-364: LGTM: User settings permission class with scope support

The UserSettingsPermissionsOrScope class appropriately checks object ownership and provides scope mapping.


366-387: LGTM: GlobalSettingsPermissions implementation

The GlobalSettingsPermissions class correctly implements permission checking based on staff status for non-safe methods and properly maps OAuth2 scopes.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (1)
src/backend/InvenTree/locale/el/LC_MESSAGES/django.po (1)

8738-8749: Add translations for new OAuth2-related permission messages.

These new strings related to user permissions are part of the OAuth2 integration but currently lack Greek translations. Without translations, Greek users will see these messages in English.

Consider adding appropriate Greek translations for these permission messages to ensure a consistent user experience for Greek 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 1de6ce7 and d4585af.

📒 Files selected for processing (29)
  • .devcontainer/devcontainer.json (1 hunks)
  • .devcontainer/docker-compose.yml (1 hunks)
  • .github/workflows/qc_checks.yaml (4 hunks)
  • .github/workflows/scorecard.yaml (1 hunks)
  • src/backend/InvenTree/InvenTree/api_version.py (1 hunks)
  • src/backend/InvenTree/InvenTree/helpers.py (2 hunks)
  • src/backend/InvenTree/locale/ar/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/bg/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/cs/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/da/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/de/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/el/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/en/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/es/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/es_MX/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/et/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/fa/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/fi/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/fr/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/he/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/hi/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/hu/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/id/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/it/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/ja/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/ko/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/lt/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/lv/LC_MESSAGES/django.po (22 hunks)
  • src/backend/InvenTree/locale/nl/LC_MESSAGES/django.po (22 hunks)
✅ Files skipped from review due to trivial changes (12)
  • .devcontainer/devcontainer.json
  • .github/workflows/scorecard.yaml
  • src/backend/InvenTree/InvenTree/api_version.py
  • .github/workflows/qc_checks.yaml
  • src/backend/InvenTree/locale/ar/LC_MESSAGES/django.po
  • src/backend/InvenTree/locale/et/LC_MESSAGES/django.po
  • src/backend/InvenTree/locale/hi/LC_MESSAGES/django.po
  • src/backend/InvenTree/locale/es/LC_MESSAGES/django.po
  • src/backend/InvenTree/locale/fr/LC_MESSAGES/django.po
  • src/backend/InvenTree/locale/bg/LC_MESSAGES/django.po
  • src/backend/InvenTree/locale/he/LC_MESSAGES/django.po
  • src/backend/InvenTree/locale/es_MX/LC_MESSAGES/django.po
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: Tests - inventree-python
  • GitHub Check: Tests - Web UI
  • GitHub Check: Tests - DB [SQLite] + Coverage 3.9
  • GitHub Check: Tests - DB [MySQL]
  • GitHub Check: Tests - DB [PostgreSQL]
  • GitHub Check: Tests - Web UI
  • GitHub Check: Tests - DB [SQLite] + Coverage 3.9
  • GitHub Check: Tests - inventree-python
  • GitHub Check: Tests - DB [MySQL]
  • GitHub Check: Tests - DB [PostgreSQL]
  • GitHub Check: build
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: matmair.InvenTree (Job Python39)
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: Build - Web UI
  • GitHub Check: Build - Web UI
🔇 Additional comments (85)
.devcontainer/docker-compose.yml (1)

27-28: Port mapping for development is correct and necessary.

Exposing port 8000 for the inventree service is appropriate for local development and supports OAuth2/OIDC integration. No issues found.

src/backend/InvenTree/InvenTree/helpers.py (5)

35-35: Good addition of a well-documented constant.

The new INT_CLIP_MAX constant clearly defines the maximum allowed integer value (0x7FFFFFFF, maximum signed 32-bit integer), improving code maintainability.


38-48: Well-structured function signature enhancement.

The improved function signature adds useful capabilities:

  • Using INT_CLIP_MAX as default for clip parameter
  • Adding the try_hex boolean parameter for hex parsing
  • Adding allow_negative parameter for controlling negative values
  • Thorough documentation of all parameters

These changes make the function more flexible without breaking existing usage.


52-74: Great design with a nested helper function.

The introduction of the do_clip helper function centralizes the clipping logic that was previously scattered throughout the function. It:

  1. Properly handles the special case where clip is None
  2. Enforces the INT_CLIP_MAX limit
  3. Applies the correct handling for negative values

This significantly improves maintainability and reduces code duplication.


81-95: Improved logic flow with early returns.

The refactored initial parsing logic now:

  1. Attempts direct integer conversion first
  2. Returns immediately on success (more efficient)
  3. Tries hexadecimal parsing if applicable
  4. Falls back to regex extraction only when needed

This approach improves performance by avoiding unnecessary parsing steps when simpler methods succeed.


118-118: Good update to use the centralized clipping function.

Replacing the inline clipping logic with a call to the new do_clip helper function ensures consistent behavior throughout the function.

src/backend/InvenTree/locale/lt/LC_MESSAGES/django.po (10)

5-6: Update of translation template timestamps.

These lines show the updated timestamps for when the translation template was created and revised, reflecting recent processing of the file for translation updates.


24-49: Updated source file references for API messages.

These changes reflect updated line numbers for translation strings in InvenTree/api.py as part of the backend refactoring. The actual message content remains unchanged, but their locations in the source code have shifted.


688-690: Updated reference to "Build Orders" string.

The string "Build Orders" was previously only in build/models.py but is now also referenced in the new users/ruleset.py file, indicating the permission system reorganization mentioned in the PR objectives.


5158-5201: Permission strings moved to ruleset module.

Several part-related permission strings have been relocated from their original locations to also appear in users/ruleset.py, supporting the custom permission implementation mentioned in the PR objectives.


6070-6071: Stock-related permission strings moved to ruleset module.

Stock-related permission strings now also appear in the new ruleset module, further indicating the implementation of custom permission handling across different modules.

Also applies to: 7685-7686


8674-8693: New permission category strings added.

New permission category strings have been added in the users/ruleset.py module, establishing the framework for granular permission control mentioned in the PR objectives.


8742-8748: New user creation permission messages.

These new strings in users/serializers.py add permission checks for user creation functionality, enhancing the security of the system by ensuring only staff users can create new accounts.


6365-6424: Updated barcode handling API message references.

References to barcode-related messages have been updated, reflecting changes to the barcode handling API functionality as part of the backend refactoring.


1396-1411: Updated API permission messages for attachments.

These changes update references to permission-related messages for attachment handling in the API, aligning with the permission system refactoring.


1969-2002: Updated notification system message references.

References to notification messages have been updated, ensuring proper integration with the new permission system while maintaining the existing notification functionality.

src/backend/InvenTree/locale/it/LC_MESSAGES/django.po (5)

5-6: LGTM! Updated timestamp for translation file.

The POT-Creation-Date and PO-Revision-Date have been updated to reflect the latest changes to the translation file.


24-53: LGTM! Updated line reference numbers.

These changes update source file references to match the current code structure. This is normal maintenance for translation files as the codebase evolves.


688-693: LGTM! Updated permission reference path.

Reference path has been updated from users/models.py to users/ruleset.py, which aligns with the PR's objective of replacing standard DRF permissions with custom InvenTree permissions.


8741-8750: LGTM! New untranslated permission messages added.

These new message strings related to user permissions are part of the OAuth2 integration. The empty msgstr fields indicate they haven't been translated to Italian yet, which is expected for newly added strings.


8678-8693: LGTM! Permission messages moved to ruleset module.

These permission-related message references have been moved from users/models.py to users/ruleset.py, which is consistent with the architectural changes mentioned in the PR summary.

src/backend/InvenTree/locale/nl/LC_MESSAGES/django.po (8)

688-690: Reference path updated to reflect code reorganization

The reference path for "Build Orders" has been changed from users/models.py to users/ruleset.py, correctly reflecting the backend refactoring for OAuth2 integration. This is a positive change as it maintains proper localization references after code restructuring.


1067-1068: Reference update for "Location" translation

The reference path has been updated to include users/models.py for the "Location" translation string. This correctly maintains the translation reference after the reorganization of code for OAuth2 support.


5159-5161: Reference path updated for "Part Categories"

The reference path for "Part Categories" translation has been correctly updated to use users/ruleset.py instead of its previous location, aligning with the backend refactoring for permission handling.


6071-6073: Reference path updated for "Stock Items"

The reference path for "Stock Items" has been updated to include users/ruleset.py, which aligns with the backend reorganization for OAuth2-based permission model.


7686-7688: Reference path updated for "Stock Locations"

The reference path has been updated to include users/ruleset.py for the "Stock Locations" translation string, correctly reflecting the permission system refactoring.


8740-8742: New permission message translation added

A new translation has been added for "Only a superuser can adjust this field", which replaces previous permission messages. This change supports the new OAuth2 permission model and provides clearer error messaging to users.


8743-8746: New permission messages for user creation

Two new translations have been added for user creation permissions:

  • "Only staff users can create new users"
  • "You do not have permission to create users"

These provide clearer permission messaging as part of the new OAuth2-based authorization system.

Also applies to: 8747-8750


5-6:

Details

✅ Verification successful

Updated dates in PO file metadata

The creation and revision dates have been updated to "2025-04-13", which is one year in the future compared to the current date (April 2024). While this doesn't affect functionality, it might cause confusion for translators or in version control.


🏁 Script executed:

#!/bin/bash
date

Length of output: 35


PO File Metadata Dates Verified

The dates in the PO file (creation: "2025-04-13 23:06+0000" and revision: "2025-04-13 23:08") now align with the current system date (Tue Apr 15 06:38:36 UTC 2025). The earlier concern about the dates being one year in the future (relative to April 2024) is no longer applicable.

  • File: src/backend/InvenTree/locale/nl/LC_MESSAGES/django.po, Lines 5-6
  • Verification: System date confirms that the metadata dates are consistent with the current timeframe.
src/backend/InvenTree/locale/en/LC_MESSAGES/django.po (5)

11-11: POT-Creation-Date has been updated.

The POT-Creation-Date shows a future date (2025-04-14), which is likely fine as this is a future facing project timestamp rather than a critical issue.


25-53: Properly updated API message references.

Source code line numbers for InvenTree/api.py messages have been updated to reflect recent code restructuring. This is a normal maintenance task for translation files.


689-689: Build Orders message reference updated for new OAuth2 structure.

The message reference has been properly updated to point to the new location in users/ruleset.py:37 instead of the previous location, as part of the OAuth2 integration refactoring.


8675-8694: User role permission messages relocated to ruleset module.

Role-based permission strings have been properly moved from users/models.py to users/ruleset.py as part of the OAuth2/OIDC integration. This aligns with the backend refactoring to support scope-based permission handling.


8740-8749: Updated permission validation messages.

New permission-related messages have been added for better user feedback during permission checks, including superuser and staff-only operations. These changes support the enhanced OAuth2-based permission system.

src/backend/InvenTree/locale/lv/LC_MESSAGES/django.po (6)

5-6: Translation file dates have been updated.

The POT-Creation-Date and PO-Revision-Date have been updated to April 2025, which is consistent with the ongoing development timeline for this PR.


24-52: API endpoint references have been properly updated.

The file path references for various API endpoints have been updated to reflect changes in the codebase structure. This ensures translations are correctly linked to their source code locations.


688-688: References to user roles updated correctly.

The source references have been updated to match the new location of user role definitions, which have been moved from users/models.py to users/ruleset.py as part of the OAuth2 implementation.

Also applies to: 1067-1067, 1487-1487, 1526-1526


1399-1411: New API notification references added properly.

References to common API notification handlers have been added to support the OAuth2/OIDC integration. These entries ensure proper internationalization of notification messages.


8674-8693: User role definitions correctly moved to ruleset module.

User role definitions such as "Admin", "Stocktake", "Purchase Orders", "Sales Orders", and "Return Orders" have been appropriately relocated from users/models.py to users/ruleset.py to align with the new permission model that supports OAuth2 scopes.


8738-8749: Permission validation messages properly updated.

User permission validation messages have been updated to reflect the new user creation flow, which now includes staff user creation permissions relevant to the OAuth2 integration.

src/backend/InvenTree/locale/el/LC_MESSAGES/django.po (1)

688-690: Reference path updates for ruleset.

The reference path has been updated to point to the new location in users/ruleset.py instead of users/models.py, which aligns with the OAuth2 integration changes. This is the correct approach for maintaining translations when refactoring code.

src/backend/InvenTree/locale/ko/LC_MESSAGES/django.po (5)

5-6: POT file timestamp updated correctly.

The translation template creation and revision dates have been updated to match the current codebase changes.


24-27: Line reference update for API message.

This is a standard line reference update for the existing "API endpoint not found" message, reflecting changes in the source code structure caused by the OAuth2 implementation.


1396-1402: Line reference updates for UI component messages.

Source file references for "Is Link" and "Is File" messages have been updated to reflect changes in the common/api.py file structure after the OAuth2 implementation.


8739-8741: Updated permission message for OAuth2 permissions.

The permission error message has been updated to be more specific about superuser requirements for certain fields, which aligns with the more granular permission system introduced with OAuth2.


8742-8748: User creation permission messages updated for OAuth2.

Permission messages related to user creation have been refined to be more specific about the required permissions, which is consistent with the OAuth2 scope-based permission model being implemented.

src/backend/InvenTree/locale/da/LC_MESSAGES/django.po (7)

5-6: Updated translation metadata timestamp.

The translation file's creation and revision dates have been updated to April 2025, which is appropriate for tracking when these translation updates were made.


24-52: Source references updated correctly for API endpoints.

The line references for messages in InvenTree/api.py have been properly updated to reflect changes in the backend code structure. This is necessary to maintain the connection between translated strings and their source locations.


354-354: Updated reference to include magic login module.

The addition of InvenTree/magic_login.py in the source reference reflects the new authentication flows being implemented as part of the OAuth2 integration.


688-688: Reference relocated to user ruleset module.

Build order translation reference has been correctly moved from build/models.py to users/ruleset.py, aligning with the backend's reorganization of permission and role definitions.


1067-1068: Updated location field reference.

The "Location" string reference has been appropriately updated to reflect its new location in the user models, which is part of the reorganization for OAuth2 support.


8675-8693: Added new role definitions for translation.

New user role entries have been added from users/ruleset.py, supporting the expanded role definitions introduced with OAuth2 scope-based permission handling. These entries currently have empty translations that will need to be filled for Danish users.


8738-8749: Added new permission-related messages.

New messages related to user permissions have been added, reflecting the revised permission logic implemented as part of the OAuth2 integration. These messages communicate important permission constraints to users and will need Danish translations.

src/backend/InvenTree/locale/ja/LC_MESSAGES/django.po (5)

5-6: Timestamps updated for translation file.

The POT-Creation-Date and PO-Revision-Date have been updated to April 2025, indicating this translation file has been refreshed with the latest source strings.


688-690: Source reference updated to match ruleset reorganization.

The source reference for "Build Orders" translation string has been correctly updated from a model file to users/ruleset.py, reflecting the backend reorganization where permissions and user roles have been moved to dedicated ruleset files.


8741-8748: New untranslated permission-related strings added.

Three new permission-related strings have been added but remain untranslated:

  • "Only a superuser can adjust this field"
  • "Only staff users can create new users"
  • "You do not have permission to create users"

These align with the OAuth2 scope-based permission system being implemented in this PR.


1526-1528: Source reference updated for Token translation.

The reference for the "Token" translation has been updated to include both the original common/models.py and the new users/models.py locations, which supports the OAuth2 implementation.


7685-7687: User ruleset reference updated for "Stock Locations".

The source reference has been properly updated to include the ruleset reference, supporting the new permission structure being implemented with OAuth2.

src/backend/InvenTree/locale/fi/LC_MESSAGES/django.po (2)

8674-8693: New user role translations added for OAuth2 integration.

These new message entries for user roles in users/ruleset.py have been added to support the OAuth2 integration, but they don't have Finnish translations yet. This is expected for new strings, but they should be translated eventually.


8738-8748: Added permission-related translation entries.

New translation entries for permission messages have been added to support the OAuth2 permission framework. These messages relate to user role changes and user creation permissions, which aligns with the OAuth2 scope-based permission handling implemented in this PR.

src/backend/InvenTree/locale/de/LC_MESSAGES/django.po (4)

8740-8741: New permission message requires German translation.

This new superuser permission message has been added but hasn't been translated to German yet. This is expected during the initial integration of OAuth2 features, but translation will be needed before release.


8744-8745: New staff permission message requires German translation.

This staff permission restriction message has been added but hasn't been translated to German yet. This is part of the new OAuth2 permission model.


8747-8748: New user creation permission message requires German translation.

This user creation permission message has been added but hasn't been translated to German yet. This is part of the new user permission restrictions.


5-6:

Details

✅ Verification successful

Verify the timestamp dates.

The creation and revision dates are set to April 13, 2025, which appears to be in the future. Consider updating these to reflect the actual date when the translations were processed.


🏁 Script executed:

#!/bin/bash
# Check the current date for reference
date
echo "Compared to dates in the translation file: 2025-04-13"

Length of output: 152


Timestamp Dates Verified

The shell script output shows the current date as April 15, 2025, while the translation file timestamps are set to April 13, 2025. Since these dates are in the past relative to the current date, no changes are needed.

src/backend/InvenTree/locale/hu/LC_MESSAGES/django.po (2)

8675-8694: Approve the ruleset reference updates.

The user role definitions have been correctly moved from users/models.py to users/ruleset.py as part of the OAuth2 implementation. These changes align with the PR objectives and maintain proper translation references.


354-356: Review and approve updated source references.

The changes to source file references throughout the translation file (for API endpoints, notification systems, and barcode functionality) are consistent with the codebase reorganization needed to support OAuth2. These reference updates ensure translations remain correctly linked to their source code.

Also applies to: 1397-1487, 4661-5693

src/backend/InvenTree/locale/cs/LC_MESSAGES/django.po (7)

5-6: LGTM: Date fields updated appropriately

The POT creation and revision dates have been updated, which is expected when modifying translation files.


24-52: LGTM: Updated line references for API endpoints

These changes simply update the line references for existing translations to match code changes in the InvenTree API module, which is expected during code refactoring.


1397-1403: LGTM: Updated references for user-related messages

Reference paths have been updated to reflect the movement of user-related translation strings as part of the OAuth2 permission refactoring, with no changes to the actual translation content.

Also applies to: 1486-1487, 1517-1519, 1526-1528, 4379-4379, 4874-4876


1969-1977: LGTM: Updated notification message references

Line references for notification-related messages have been updated to match changes in the source files.


6361-6420: LGTM: Barcode API reference updates

Line references for barcode handling messages have been updated to match changes in the barcode API modules.


8674-8693: LGTM: Rule set references moved

Permission-related translation entries have been moved from users/models.py to users/ruleset.py, aligning with the refactoring of permission-related code for OAuth2 integration.


8738-8749: LGTM: Permission control message references updated

User permission message references have been updated as part of the broader permission refactoring for OAuth2 support.

src/backend/InvenTree/locale/fa/LC_MESSAGES/django.po (5)

5-6: Translation file timestamps updated

The POT-Creation-Date and PO-Revision-Date have been updated to 2025-04-13, reflecting when the translation source file was updated.


24-52: API reference paths synchronized correctly

The file references for API-related translations have been properly updated to match the current paths in the codebase. This ensures translations are correctly associated with their source locations.


8675-8693: New role-based permission entries added

The translation entries for role-based permissions ("Admin", "Stocktake", "Purchase Orders", "Sales Orders", "Return Orders") have been properly moved from users/models.py to users/ruleset.py. This aligns with the OAuth2/OIDC implementation which introduces more granular access control.


8738-8748: User permission messages updated

User permission-related messages have been revised to provide clearer feedback for authorization scenarios. These changes support the new OAuth2 permission system by providing appropriate messages when users attempt actions beyond their permission scope.


1067-1547: Model and serializer references synchronized

References to user models, serializers, and related components have been updated to reflect their new locations in the codebase. This is essential for maintaining proper translation mappings after the permission system refactoring.

src/backend/InvenTree/locale/id/LC_MESSAGES/django.po (7)

5-6: LGTM - Updated file generation timestamps.

The POT-Creation-Date and PO-Revision-Date timestamps have been properly updated to reflect the recent changes.


24-52: LGTM - Updated source code references for InvenTree/api.py.

The line number references for the InvenTree/api.py file have been properly updated to match the current code structure, ensuring proper translation mapping.


688-690: LGTM - Added "Build Orders" mapping to ruleset.py.

New connection between "Build Orders" translation string and the users/ruleset.py file, which aligns with the OAuth2 permission scopes being added.


1067-1069: LGTM - Updated path for "Location" string.

Path reference has been updated to include users/models.py, reflecting the restructuring of code for OAuth2 integration.


1486-1488: LGTM - Updated reference for "User" translation.

Reference path now includes users/models.py:130 and users/models.py:503, properly mapping this string for OAuth2 user management.


8674-8693: LGTM - Added new role-based permission strings from ruleset.py.

New translation entries for "Admin", "Stocktake", "Purchase Orders", "Sales Orders", and "Return Orders" have been added from users/ruleset.py, supporting the new role-based permission system implemented with OAuth2.


8738-8748: LGTM - Added new user permission messages.

New translation entries for user creation permissions have been added, supporting the enhanced permission handling for OAuth2 integration.

Comment on lines +5 to +6
"POT-Creation-Date: 2025-04-13 23:06+0000\n"
"PO-Revision-Date: 2025-04-13 23:08\n"

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

Check the POT creation and revision dates.

The dates in the POT-Creation-Date and PO-Revision-Date fields are set to 2025, which is in the future. This might cause issues with translation tools or create confusion for translators.

-"POT-Creation-Date: 2025-04-13 23:06+0000\n"
-"PO-Revision-Date: 2025-04-13 23:08\n"
+"POT-Creation-Date: 2023-04-13 23:06+0000\n"
+"PO-Revision-Date: 2023-04-13 23:08\n"
📝 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
"POT-Creation-Date: 2025-04-13 23:06+0000\n"
"PO-Revision-Date: 2025-04-13 23:08\n"
"POT-Creation-Date: 2023-04-13 23:06+0000\n"
"PO-Revision-Date: 2023-04-13 23:08\n"

Comment on lines +8678 to +8693
#: users/ruleset.py:34
msgid "Stocktake"
msgstr ""

#: users/ruleset.py:38
msgid "Purchase Orders"
msgstr ""

#: users/ruleset.py:39
msgid "Sales Orders"
msgstr ""

#: users/ruleset.py:40
msgid "Return Orders"
msgstr ""

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

New permission role strings added for OAuth2 integration.

New user permission role names have been added to the translation file as part of the OAuth2/OIDC integration. These include "Admin", "Stocktake", "Purchase Orders", "Sales Orders", and "Return Orders". Note that these strings don't have Korean translations yet.

The new permission role strings should be translated to Korean to maintain the localization quality. Consider providing translations for these new strings before release.

Comment on lines +5 to +6
"POT-Creation-Date: 2025-04-13 23:06+0000\n"
"PO-Revision-Date: 2025-04-13 23:08\n"

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

Future date used in POT-Creation-Date and PO-Revision-Date.

The translation file has been updated with dates in 2025, which appears to be incorrect as we're currently in 2024.

Apply this diff to correct the dates:

-"POT-Creation-Date: 2025-04-13 23:06+0000\n"
-"PO-Revision-Date: 2025-04-13 23:08\n"
+"POT-Creation-Date: 2024-04-13 23:06+0000\n"
+"PO-Revision-Date: 2024-04-13 23:08\n"
📝 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
"POT-Creation-Date: 2025-04-13 23:06+0000\n"
"PO-Revision-Date: 2025-04-13 23:08\n"
"POT-Creation-Date: 2024-04-13 23:06+0000\n"
"PO-Revision-Date: 2024-04-13 23:08\n"

Comment on lines +5 to +6
"POT-Creation-Date: 2025-04-13 23:06+0000\n"
"PO-Revision-Date: 2025-04-13 23:08\n"

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

Check the future timestamp in translation file headers.

The POT-Creation-Date and PO-Revision-Date are set to 2025-04-13, which is a future date (one year ahead). These timestamps should reflect when the translation file was actually created or modified.

-"POT-Creation-Date: 2025-04-13 23:06+0000\n"
-"PO-Revision-Date: 2025-04-13 23:08\n"
+"POT-Creation-Date: 2024-04-13 23:06+0000\n"
+"PO-Revision-Date: 2024-04-13 23:08\n"
📝 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
"POT-Creation-Date: 2025-04-13 23:06+0000\n"
"PO-Revision-Date: 2025-04-13 23:08\n"
"POT-Creation-Date: 2024-04-13 23:06+0000\n"
"PO-Revision-Date: 2024-04-13 23:08\n"

Comment on lines +8741 to +8749
msgstr ""

#: users/serializers.py:328
msgid "Only superusers can create new users"
msgstr "Csak a superuser-ek hozhatnak létre felhasználókat"
#: users/serializers.py:395
msgid "Only staff users can create new users"
msgstr ""

#: users/serializers.py:400
msgid "You do not have permission to create users"
msgstr ""

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

Add Hungarian translations for new permission messages.

These new message strings related to permissions are missing their Hungarian translations. All message strings should be translated to maintain a consistent user experience for Hungarian users.

 #: users/serializers.py:341
 msgid "Only a superuser can adjust this field"
-msgstr ""
+msgstr "Csak egy rendszergazda változtathatja meg ezt a mezőt"

 #: users/serializers.py:395
 msgid "Only staff users can create new users"
-msgstr ""
+msgstr "Csak személyzeti felhasználók hozhatnak létre új felhasználókat"

 #: users/serializers.py:400
 msgid "You do not have permission to create users"
-msgstr ""
+msgstr "Nincs jogosultsága új felhasználók létrehozásához"
📝 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
msgstr ""
#: users/serializers.py:328
msgid "Only superusers can create new users"
msgstr "Csak a superuser-ek hozhatnak létre felhasználókat"
#: users/serializers.py:395
msgid "Only staff users can create new users"
msgstr ""
#: users/serializers.py:400
msgid "You do not have permission to create users"
msgstr ""
#: users/serializers.py:341
msgid "Only a superuser can adjust this field"
msgstr "Csak egy rendszergazda változtathatja meg ezt a mezőt"
#: users/serializers.py:395
msgid "Only staff users can create new users"
msgstr "Csak személyzeti felhasználók hozhatnak létre új felhasználókat"
#: users/serializers.py:400
msgid "You do not have permission to create users"
msgstr "Nincs jogosultsága új felhasználók létrehozásához"

matmair and others added 5 commits April 15, 2025 23:27
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Bumps the dependencies group with 1 update: [codecov/codecov-action](https://github.com/codecov/codecov-action).


Updates `codecov/codecov-action` from 5.4.0 to 5.4.2
- [Release notes](https://github.com/codecov/codecov-action/releases)
- [Changelog](https://github.com/codecov/codecov-action/blob/main/CHANGELOG.md)
- [Commits](codecov/codecov-action@0565863...ad3126e)

---
updated-dependencies:
- dependency-name: codecov/codecov-action
  dependency-version: 5.4.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Oliver <[email protected]>
* Fix for email sending

- Extract valid email for user
- Do not send if email not configured for user

* Improve email address filtering logic

* Fix return type hint

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (1)
src/backend/InvenTree/InvenTree/helpers_email.py (1)

94-108: 🛠️ Refactor suggestion

Consider handling the no-email case.

The new get_email_for_user function provides a good hierarchical lookup for user emails, but doesn't handle the case where no email is found (neither in user.email nor in the EmailAddress model). This would cause the function to implicitly return None, contradicting the -> str return type annotation.

def get_email_for_user(user) -> str:
    """Find an email address for the specified user."""
    # First check if the user has an associated email address
    if user.email:
        return user.email

    # Otherwise, find first matching email
    # Priority is given to primary or verified email addresses
    if (
        email := EmailAddress.objects.filter(user=user)
        .order_by('-primary', '-verified')
        .first()
    ):
        return email.email
+    
+    # Return empty string or raise exception if no email found
+    return ""  # or consider: raise ValueError(f"No email found for user {user.username}")
♻️ Duplicate comments (2)
src/backend/InvenTree/locale/el/LC_MESSAGES/django.po (1)

5-6: Check the POT creation and revision dates.

The dates in the POT-Creation-Date and PO-Revision-Date fields are set to 2025, which is in the future. This might cause issues with translation tools or create confusion for translators.

-"POT-Creation-Date: 2025-04-15 02:43+0000\n"
-"PO-Revision-Date: 2025-04-15 02:46\n"
+"POT-Creation-Date: 2023-04-15 02:43+0000\n"
+"PO-Revision-Date: 2023-04-15 02:46\n"
src/backend/InvenTree/locale/hu/LC_MESSAGES/django.po (1)

5-6: ⚠️ Potential issue

Fix the future timestamp in translation file headers.

The POT-Creation-Date and PO-Revision-Date are set to 2025-04-15, which is a future date (one year ahead). These timestamps should reflect when the translation file was actually created or modified.

-"POT-Creation-Date: 2025-04-15 02:43+0000\n"
-"PO-Revision-Date: 2025-04-15 02:46\n"
+"POT-Creation-Date: 2024-04-15 02:43+0000\n"
+"PO-Revision-Date: 2024-04-15 02:46\n"
🧹 Nitpick comments (3)
src/backend/InvenTree/locale/el/LC_MESSAGES/django.po (1)

8027-8044: Add translations for new serial number navigation strings.

Two new untranslated strings have been added for the serial number navigation feature. These will need to be translated to Greek to maintain a consistent user experience.

msgid "Next Serial Number"
msgstr ""

msgid "Previous Serial Number"
msgstr ""
src/backend/InvenTree/locale/de/LC_MESSAGES/django.po (1)

8227-8244: New untranslated strings should be translated to German.

Two new strings have been added for serial number navigation but don't have German translations yet. Consider providing translations for "Next Serial Number" and "Previous Serial Number" before final release.

#: stock/serializers.py:1827
msgid "Next Serial Number"
-msgstr ""
+msgstr "Nächste Seriennummer"

#: stock/serializers.py:1833
msgid "Previous Serial Number"
-msgstr ""
+msgstr "Vorherige Seriennummer"
src/backend/InvenTree/locale/cs/LC_MESSAGES/django.po (1)

8238-8243: New untranslated strings added.

Two new untranslated message IDs have been added: "Next Serial Number" and "Previous Serial Number". These appear to be UI elements for navigation between serial-numbered items. These strings need to be translated in a future update.

Would you like me to create a task to get these new strings translated to Czech?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 298a8ac and 2301c1b.

📒 Files selected for processing (22)
  • .devcontainer/docker-compose.yml (0 hunks)
  • .github/workflows/qc_checks.yaml (3 hunks)
  • .gitignore (1 hunks)
  • docs/mkdocs.yml (1 hunks)
  • src/backend/InvenTree/InvenTree/helpers_email.py (2 hunks)
  • src/backend/InvenTree/InvenTree/tasks.py (1 hunks)
  • src/backend/InvenTree/locale/ar/LC_MESSAGES/django.po (39 hunks)
  • src/backend/InvenTree/locale/bg/LC_MESSAGES/django.po (39 hunks)
  • src/backend/InvenTree/locale/cs/LC_MESSAGES/django.po (39 hunks)
  • src/backend/InvenTree/locale/da/LC_MESSAGES/django.po (39 hunks)
  • src/backend/InvenTree/locale/de/LC_MESSAGES/django.po (39 hunks)
  • src/backend/InvenTree/locale/el/LC_MESSAGES/django.po (39 hunks)
  • src/backend/InvenTree/locale/en/LC_MESSAGES/django.po (39 hunks)
  • src/backend/InvenTree/locale/es/LC_MESSAGES/django.po (39 hunks)
  • src/backend/InvenTree/locale/es_MX/LC_MESSAGES/django.po (39 hunks)
  • src/backend/InvenTree/locale/et/LC_MESSAGES/django.po (39 hunks)
  • src/backend/InvenTree/locale/fa/LC_MESSAGES/django.po (39 hunks)
  • src/backend/InvenTree/locale/fi/LC_MESSAGES/django.po (39 hunks)
  • src/backend/InvenTree/locale/fr/LC_MESSAGES/django.po (39 hunks)
  • src/backend/InvenTree/locale/he/LC_MESSAGES/django.po (39 hunks)
  • src/backend/InvenTree/locale/hi/LC_MESSAGES/django.po (39 hunks)
  • src/backend/InvenTree/locale/hu/LC_MESSAGES/django.po (39 hunks)
💤 Files with no reviewable changes (1)
  • .devcontainer/docker-compose.yml
✅ Files skipped from review due to trivial changes (9)
  • src/backend/InvenTree/locale/fi/LC_MESSAGES/django.po
  • docs/mkdocs.yml
  • src/backend/InvenTree/locale/fa/LC_MESSAGES/django.po
  • src/backend/InvenTree/locale/et/LC_MESSAGES/django.po
  • src/backend/InvenTree/locale/he/LC_MESSAGES/django.po
  • src/backend/InvenTree/locale/fr/LC_MESSAGES/django.po
  • src/backend/InvenTree/locale/es_MX/LC_MESSAGES/django.po
  • src/backend/InvenTree/locale/ar/LC_MESSAGES/django.po
  • src/backend/InvenTree/locale/en/LC_MESSAGES/django.po
🚧 Files skipped from review as they are similar to previous changes (3)
  • .gitignore
  • .github/workflows/qc_checks.yaml
  • src/backend/InvenTree/InvenTree/tasks.py
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: Tests - Web UI
  • GitHub Check: Tests - inventree-python
  • GitHub Check: Tests - DB [MySQL]
  • GitHub Check: Tests - DB [PostgreSQL]
  • GitHub Check: Tests - DB [SQLite] + Coverage 3.9
  • GitHub Check: Tests - Web UI
  • GitHub Check: Tests - DB [PostgreSQL]
  • GitHub Check: Tests - DB [SQLite] + Coverage 3.9
  • GitHub Check: Tests - DB [MySQL]
  • GitHub Check: Tests - inventree-python
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: build
  • GitHub Check: matmair.InvenTree (Job Python39)
  • GitHub Check: Tests - API Schema Documentation
  • GitHub Check: Build - Web UI
  • GitHub Check: Build - Web UI
🔇 Additional comments (18)
src/backend/InvenTree/locale/bg/LC_MESSAGES/django.po (4)

5-6: LGTM! Translation file timestamps updated.

The POT-Creation-Date and PO-Revision-Date have been properly updated to reflect the recent changes to the codebase.


91-115: LGTM! Reference updates for stock and serializer files.

Line reference updates accurately reflect the changes made to the underlying source files, which is expected when implementing OAuth2 and OpenID Connect functionality.


127-162: LGTM! Helper reference updates.

References to helper functions have been properly updated to match the new line numbers in the source files.


8238-8243: New translation strings for serial number navigation added.

Two new untranslated message IDs have been added: "Next Serial Number" and "Previous Serial Number". These correspond to the new API endpoint mentioned in the summary that adds extra serial number information for StockItem objects.

src/backend/InvenTree/locale/es/LC_MESSAGES/django.po (3)

5-6: Timestamp updates look good.

The updated POT-Creation-Date and PO-Revision-Date reflect the current state of the translation file.


91-115: Source file references updated correctly.

The file references and line numbers have been updated to match the current source code positions after the OAuth2 implementation. This is a normal maintenance task when source code changes and doesn't affect the translations themselves.

Also applies to: 127-158, 556-558, 907-909, 943-944, 981-982, 1067-1068, 1174-1175, 1751-1752, 1826-1827


8241-8244: New untranslated strings need Spanish translations.

Two new strings for serial number navigation have been added without translations:

  • "Next Serial Number"
  • "Previous Serial Number"

These should eventually be translated to Spanish, but it's normal to add them untranslated first.

Are these strings visible in the UI? If they're customer-facing, consider getting translations before release.

src/backend/InvenTree/locale/de/LC_MESSAGES/django.po (2)

5-6: Timestamp updates reflect translation file regeneration.

The update to POT-Creation-Date and PO-Revision-Date shows the file has been regenerated as part of the OAuth2 integration work. This is routine maintenance of translation files.


91-93: Line reference updates reflect code reorganization.

These changes update source code references for existing translated strings, indicating the location of these strings has shifted due to code reorganization for the OAuth2 implementation. This is expected maintenance and doesn't affect translations themselves.

Also applies to: 111-116, 127-164

src/backend/InvenTree/locale/hi/LC_MESSAGES/django.po (3)

91-91: Source line references updated correctly.

The changes in this file are primarily updates to source code references, reflecting shifts in the codebase due to the OAuth2 integration. This is normal maintenance of the translation file when code structure changes.

Also applies to: 111-114, 127-156, 556-558, 682-685, 794-796, 850-851, 854-856, 907-909, 943-944, 979-982, 1038-1039, 1042-1043, 1079-1080, 1673-1674, 1751-1752, 1827-1844


8241-8244: New translation strings added for serial number navigation.

Two new untranslated message IDs have been added: "Next Serial Number" and "Previous Serial Number". These strings align with the new API functionality for serial number pagination introduced as part of the OAuth2 support.


5-6:

Details

❌ Incorrect review comment

Note about future dates in the translation file.

The POT-Creation-Date and PO-Revision-Date timestamps show dates in 2025 (April 15, 2025). This is likely due to a system configuration issue, as these dates are in the future.


🏁 Script executed:

#!/bin/bash
# Check system date configuration
date

Length of output: 35


No issue with translation file timestamps

The system date (Fri Apr 18 06:39:30 UTC 2025) is after the POT-Creation-Date and PO-Revision-Date (Apr 15 2025), so those entries are not in the future. No action required.

Likely an incorrect or invalid review comment.

src/backend/InvenTree/locale/da/LC_MESSAGES/django.po (3)

5-6: LGTM - Updated timestamps for the Danish translation file.

These are standard timestamp updates generated during translation file regeneration.


91-1962: LGTM - Source code reference line numbers updated.

These changes synchronize the source code reference line numbers across multiple modules to reflect recent code changes related to the OAuth2 integration. This is an expected maintenance task when the codebase is modified.


8237-8244: New untranslated message entries added.

Two new message IDs have been added: "Next Serial Number" and "Previous Serial Number". These correspond to new API features for navigating serial numbers introduced in the stock serializers, as mentioned in the summary. They're properly formatted and ready for translation into Danish.

src/backend/InvenTree/InvenTree/helpers_email.py (1)

7-7: Import addition is appropriate.

The import of EmailAddress from allauth.account.models is necessary for the new email lookup functionality.

src/backend/InvenTree/locale/cs/LC_MESSAGES/django.po (2)

5-6: Updated translation file timestamps.

The POT-Creation-Date and PO-Revision-Date have been updated to April 15, 2025, which is appropriate for this updated translation file.


91-4881: Updated source code reference line numbers.

The changes throughout the file are primarily adjustments to source code reference line numbers in various modules like InvenTree/helpers.py, stock/models.py, stock/serializers.py, etc. These updates reflect shifts in the codebase due to the OAuth2 implementation but do not affect the actual translation strings.

Comment on lines +8242 to 8248
#: stock/serializers.py:1833
msgid "Previous Serial Number"
msgstr ""

#: stock/status_codes.py:11
msgid "OK"
msgstr "Rendben"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add Hungarian translations for new serial number navigation messages.

These new message strings related to serial number navigation are missing their Hungarian translations. Please translate them to maintain a consistent user experience for Hungarian users.

 #: stock/serializers.py:1827
 msgid "Next Serial Number"
-msgstr ""
+msgstr "Következő sorozatszám"
 
 #: stock/serializers.py:1833
 msgid "Previous Serial Number"
-msgstr ""
+msgstr "Előző sorozatszám"
📝 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
#: stock/serializers.py:1833
msgid "Previous Serial Number"
msgstr ""
#: stock/status_codes.py:11
msgid "OK"
msgstr "Rendben"
#: stock/serializers.py:1827
msgid "Next Serial Number"
msgstr "Következő sorozatszám"
#: stock/serializers.py:1833
msgid "Previous Serial Number"
msgstr "Előző sorozatszám"
#: stock/status_codes.py:11
msgid "OK"
msgstr "Rendben"

@matmair

matmair commented Apr 19, 2025

Copy link
Copy Markdown
Owner Author

Upstream is merged

@matmair matmair closed this Apr 19, 2025
@matmair
matmair deleted the feat(backend)--add-oauth2 branch April 19, 2025 13:37
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