Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(dashboard): Improve validation for missing permissions when creating new app #14395

Merged
merged 20 commits into from
Jan 27, 2025

Conversation

framitdavid
Copy link
Collaborator

@framitdavid framitdavid commented Jan 9, 2025

Description

This PR introduces an error message that informs users when they do not have the necessary permissions to create a repository in a org.

Spiller.inn.2025-01-09.224118.mp4

Related Issue(s)

Verification

  • Your code builds clean without any errors or warnings
  • Manual testing done (required)
  • Relevant automated test added (if you find this hard, leave it and we'll help out)

Summary by CodeRabbit

Release Notes

  • New Features

    • Added user organization permission checks for creating new applications.
    • Introduced a new optional property to handle selection changes in the Service Owner Selector.
    • Added a new endpoint for retrieving user permissions related to organizations.
  • Improvements

    • Enhanced form submission controls based on user permissions.
    • Expanded test coverage for user permissions and selection behavior.
  • Localization

    • Added Norwegian error message for permission-related scenarios.
  • Bug Fixes

    • Implemented safeguards to prevent unauthorized application creation.

@github-actions github-actions bot added area/dashboard Area: Related to the dashboard application solution/studio/designer Issues related to the Altinn Studio Designer solution. quality/testing Tests that are missing, needs to be created or could be improved. backend frontend labels Jan 9, 2025
@framitdavid framitdavid changed the title feat(desinger): endpoint to get UserRepositoryPermissions feat(dashboard): Improve validation for missing permissions when creating new app Jan 9, 2025
@framitdavid framitdavid marked this pull request as ready for review January 9, 2025 21:45
@framitdavid framitdavid marked this pull request as draft January 9, 2025 21:45
@framitdavid
Copy link
Collaborator Author

framitdavid commented Jan 9, 2025

Please ignore the backend diff in this PR. This PR dependes on #14389 to be merged first. Since this is a stack upon #14389 14389

@framitdavid framitdavid marked this pull request as ready for review January 9, 2025 22:35
@framitdavid framitdavid linked an issue Jan 9, 2025 that may be closed by this pull request
Copy link
Contributor

coderabbitai bot commented Jan 14, 2025

📝 Walkthrough

Walkthrough

This pull request introduces a comprehensive enhancement to the frontend application's user permission management system. The changes focus on implementing a new mechanism to check and control user permissions when creating applications within an organization. The implementation spans multiple files, introducing a new query hook, updating component logic, adding test cases, and including a new error message for Norwegian language support.

Changes

File Change Summary
frontend/dashboard/components/NewApplicationForm/... - Added state management for selected organization
- Integrated user organization permission query
- Updated form submission logic based on permissions
- Expanded test suite for permission checks
frontend/dashboard/components/ServiceOwnerSelector/... - Added onChange prop to handle selection changes
- Enhanced type safety in tests
frontend/dashboard/hooks/queries/useUserOrgPermissionsQuery.ts - Created new custom hook to fetch user organization permissions
frontend/language/src/nb.json - Added Norwegian error message for missing organization creation rights
frontend/packages/shared/src/api/... - Added new API path and query method for user organization permissions
- Updated queries and mocks
frontend/packages/shared/src/types/QueryKey.ts - Added new UserOrgPermissions enum entry

Possibly related PRs

  • fix: Handle errors in app content library #14430: The changes in the main PR enhance error handling in the NewApplicationForm component, which is related to the error message added in the AppContentLibrary component for data fetching issues. Both PRs focus on improving user feedback in scenarios where operations fail.

Suggested labels

area/ui-editor, kind/bug, quality/code, team/studio-domain1, skip-releasenotes, skip-documentation

Suggested reviewers

  • standeren
  • github-actions

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6804cde and 20a7a05.

📒 Files selected for processing (3)
  • frontend/language/src/nb.json (1 hunks)
  • frontend/packages/shared/src/api/paths.js (1 hunks)
  • frontend/packages/shared/src/mocks/queriesMock.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • frontend/packages/shared/src/mocks/queriesMock.ts
  • frontend/packages/shared/src/api/paths.js
  • frontend/language/src/nb.json
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: Testing
  • GitHub Check: CodeQL

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (6)
frontend/dashboard/components/ServiceOwnerSelector/ServiceOwnerSelector.tsx (1)

43-43: Consider adding null check for onChange callback.

While the implementation is correct, it would be more robust to add a null check before invoking the callback.

-      onChange={(event) => onChange(event.target.value)}
+      onChange={(event) => onChange?.(event.target.value)}
frontend/dashboard/components/ServiceOwnerSelector/ServiceOwnerSelector.test.tsx (1)

82-92: Consider adding edge cases to onChange tests.

While the basic onChange functionality is well tested, consider adding tests for:

  1. Handling undefined onChange prop
  2. Multiple selection changes
  3. Selection of the same value

Example additional test:

it('should handle undefined onChange prop gracefully', async () => {
  const user = userEvent.setup();
  renderServiceOwnerSelector({ onChange: undefined });
  
  const select = screen.getByLabelText(textMock('general.service_owner'));
  await user.selectOptions(select, 'organizationUsername');
  // Should not throw any errors
});
frontend/dashboard/hooks/queries/useUserOrgPermissionsQuery.ts (1)

10-20: Consider adding error handling for empty org parameter.

The implementation looks good, but it might benefit from additional validation.

 export const useUserOrgPermissionQuery = (
   org: string,
   options?: { enabled: boolean },
 ): UseQueryResult<UserOrgPermission> => {
+  if (!org?.trim()) {
+    throw new Error('Organization parameter is required');
+  }
   const { getUserOrgPermissions } = useServicesContext();
   return useQuery({
     queryKey: [QueryKey.UserOrgPermissions, org],
     queryFn: () => getUserOrgPermissions(org),
     ...options,
   });
 };
frontend/dashboard/components/NewApplicationForm/NewApplicationForm.tsx (1)

103-108: Consider adding loading state handling.

While the error handling is good, the UI might benefit from showing a loading state while permissions are being fetched.

 const createRepoAccessError: string =
-  !userOrgPermission?.canCreateOrgRepo && !isFetching
+  isFetching
+    ? ''
+    : !userOrgPermission?.canCreateOrgRepo
     ? t('dashboard.missing_service_owner_rights_error_message')
     : '';

 const hasCreateRepoAccessError: boolean = Boolean(createRepoAccessError);
+const isSubmitDisabled: boolean = hasCreateRepoAccessError || isFetching;
frontend/packages/shared/src/api/queries.ts (1)

141-141: Consider adding TypeScript return type.

The new getUserOrgPermissions function would benefit from an explicit return type definition for better type safety and developer experience.

-export const getUserOrgPermissions = (org: string) => get(userOrgPermissionsPath(org));
+export const getUserOrgPermissions = (org: string): Promise<{ hasPermission: boolean }> => get(userOrgPermissionsPath(org));
frontend/packages/shared/src/mocks/queriesMock.ts (1)

145-145: Enhance mock data to match expected API response.

The mock currently returns an empty object. Consider using more realistic mock data that matches the expected API response structure for better testing.

-  getUserOrgPermissions: jest.fn().mockImplementation(() => Promise.resolve({})),
+  getUserOrgPermissions: jest.fn().mockImplementation(() => Promise.resolve({ hasPermission: 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 60ea6c6 and d9a3504.

📒 Files selected for processing (10)
  • frontend/dashboard/components/NewApplicationForm/NewApplicationForm.test.tsx (5 hunks)
  • frontend/dashboard/components/NewApplicationForm/NewApplicationForm.tsx (5 hunks)
  • frontend/dashboard/components/ServiceOwnerSelector/ServiceOwnerSelector.test.tsx (3 hunks)
  • frontend/dashboard/components/ServiceOwnerSelector/ServiceOwnerSelector.tsx (3 hunks)
  • frontend/dashboard/hooks/queries/useUserOrgPermissionsQuery.ts (1 hunks)
  • frontend/language/src/nb.json (1 hunks)
  • frontend/packages/shared/src/api/paths.js (1 hunks)
  • frontend/packages/shared/src/api/queries.ts (2 hunks)
  • frontend/packages/shared/src/mocks/queriesMock.ts (1 hunks)
  • frontend/packages/shared/src/types/QueryKey.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Testing
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: CodeQL
🔇 Additional comments (11)
frontend/dashboard/components/ServiceOwnerSelector/ServiceOwnerSelector.tsx (1)

13-13: LGTM! Well-typed optional callback.

The onChange prop is properly typed as an optional callback, following TypeScript best practices.

frontend/dashboard/components/ServiceOwnerSelector/ServiceOwnerSelector.test.tsx (1)

Line range hint 9-24: LGTM! Improved type safety with explicit type annotation.

The addition of the ServiceOwnerSelectorProps type annotation to defaultProps enhances type safety and makes the interface requirements explicit.

frontend/dashboard/hooks/queries/useUserOrgPermissionsQuery.ts (1)

6-8: LGTM! Well-defined type for user organization permissions.

The UserOrgPermission type is clear, focused, and properly encapsulates the permission check.

frontend/packages/shared/src/types/QueryKey.ts (1)

53-53: LGTM! Well-placed enum value.

The new UserOrgPermissions enum value is properly placed and follows the existing pattern.

frontend/dashboard/components/NewApplicationForm/NewApplicationForm.tsx (2)

55-58: LGTM! Well-implemented permission query.

The permission query is properly set up with the current organization and enabled flag.


116-116: LGTM! Proper UI feedback implementation.

The error message display and button disabling are well implemented, providing clear feedback to users.

Also applies to: 118-118, 130-130

frontend/dashboard/components/NewApplicationForm/NewApplicationForm.test.tsx (3)

58-62: LGTM! Well-structured mock setup.

The mock setup is clean and properly initialized with a default positive case.


110-138: LGTM! Comprehensive test coverage.

The test cases thoroughly cover both permission scenarios with clear assertions.


141-152: LGTM! Well-implemented test helper.

The renderNewApplicationForm helper function improves test maintainability and reduces duplication.

frontend/packages/shared/src/api/paths.js (1)

20-22: LGTM! Clean implementation of the new endpoint path.

The new userOrgPermissionsPath function follows the established patterns and RESTful conventions. The section comment helps with code organization.

frontend/language/src/nb.json (1)

192-192: LGTM! Clear and well-structured error message.

The new error message is clear, follows naming conventions, and is appropriately placed in alphabetical order within the file.

@framitdavid framitdavid added the skip-manual-testing PRs that do not need to be tested manually label Jan 15, 2025
Copy link

codecov bot commented Jan 16, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 95.70%. Comparing base (b44b5c5) to head (20a7a05).
Report is 3 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14395   +/-   ##
=======================================
  Coverage   95.69%   95.70%           
=======================================
  Files        1902     1903    +1     
  Lines       24714    24730   +16     
  Branches     2829     2831    +2     
=======================================
+ Hits        23651    23667   +16     
  Misses        802      802           
  Partials      261      261           

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
frontend/dashboard/components/MakeCopyModal/MakeCopyModal.test.tsx (1)

19-21: Consider adding a test scenario where canCreateOrgRepo is false.
Currently, the mock always returns true. Testing negative or edge cases (e.g. user lacking permissions) ensures more robust coverage and confidence.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d9a3504 and 6804cde.

📒 Files selected for processing (2)
  • frontend/dashboard/components/MakeCopyModal/MakeCopyModal.test.tsx (1 hunks)
  • frontend/language/src/nb.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/language/src/nb.json
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Testing
  • GitHub Check: Build environment and run e2e test
🔇 Additional comments (2)
frontend/dashboard/components/MakeCopyModal/MakeCopyModal.test.tsx (2)

15-16: Import statement looks correct.
The import of useUserOrgPermissionQuery aligns with the usage in this test suite.


17-17: Mocking the hook is a good approach for test isolation.
Good practice. This allows testing behavior without relying on the real query implementation.

@framitdavid framitdavid merged commit 7e0f720 into main Jan 27, 2025
12 checks passed
@framitdavid framitdavid deleted the feat/verifyAccessToCreatOrgFrontend branch January 27, 2025 08:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/dashboard Area: Related to the dashboard application frontend quality/testing Tests that are missing, needs to be created or could be improved. skip-manual-testing PRs that do not need to be tested manually solution/studio/designer Issues related to the Altinn Studio Designer solution.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Improve error message for users with insufficient rights
2 participants