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

chore(j-s): Redirect logged in user #16978

Merged
merged 3 commits into from
Nov 27, 2024
Merged

Conversation

unakb
Copy link
Member

@unakb unakb commented Nov 21, 2024

emailTail linkar á rettarvorslugatt.island.is sem tekur mann alltaf á forsíðu - þó maður sé loggaður inn.

What

Redirect logged in user to correct case list when going to log in screen

Why

So people don't log in more often than needed

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • Formatting passes locally with my changes
  • I have rebased against main before asking for a review

Summary by CodeRabbit

  • New Features
    • Enhanced user login experience with automatic redirection based on user roles (e.g., defense users, prison staff, court of appeals users).
  • Bug Fixes
    • Continued support for error handling during login, ensuring alerts are provided for various error codes.

@unakb unakb requested a review from a team as a code owner November 21, 2024 12:05
Copy link
Contributor

coderabbitai bot commented Nov 21, 2024

Walkthrough

The changes in the Login.tsx file involve the addition of new imports and a significant update to the component's logic. A useEffect hook is introduced to manage user redirection based on their roles after login. The component checks the authenticated user's role and redirects them to the appropriate route accordingly. The error handling function remains unchanged.

Changes

File Path Change Summary
apps/judicial-system/web/src/routes/Shared/Login/Login.tsx Added imports for case routes and user type checking functions. Introduced useEffect for user role redirection after login.

Suggested labels

automerge


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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

Documentation and Community

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

Copy link

codecov bot commented Nov 21, 2024

Codecov Report

Attention: Patch coverage is 0% with 13 lines in your changes missing coverage. Please review.

Project coverage is 36.54%. Comparing base (fdc3e12) to head (5d19d59).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...icial-system/web/src/routes/Shared/Login/Login.tsx 0.00% 13 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16978      +/-   ##
==========================================
+ Coverage   35.68%   36.54%   +0.86%     
==========================================
  Files        6937     6902      -35     
  Lines      147046   144903    -2143     
  Branches    41822    41439     -383     
==========================================
+ Hits        52477    52962     +485     
+ Misses      94569    91941    -2628     
Flag Coverage Δ
judicial-system-web 28.09% <0.00%> (-0.03%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...icial-system/web/src/routes/Shared/Login/Login.tsx 0.00% <0.00%> (ø)

... and 227 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update fdc3e12...5d19d59. Read the comment docs.

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

🧹 Outside diff range and nitpick comments (2)
apps/judicial-system/web/src/routes/Shared/Login/Login.tsx (2)

72-84: Consider adding loading state and error handling.

While the redirection logic is correct, the user experience could be improved by:

  1. Adding a loading state during redirection
  2. Handling potential navigation errors

Here's a suggested improvement:

+ const [isRedirecting, setIsRedirecting] = useState(false)

  useEffect(() => {
    if (user) {
+     setIsRedirecting(true)
      let targetRoute = CASES_ROUTE
      
      if (isDefenceUser(user)) {
        targetRoute = DEFENDER_CASES_ROUTE
      } else if (isPrisonStaffUser(user)) {
        targetRoute = PRISON_CASES_ROUTE
      } else if (isCourtOfAppealsUser(user)) {
        targetRoute = COURT_OF_APPEAL_CASES_ROUTE
      }

-     router.push(targetRoute)
+     router.push(targetRoute).catch(console.error).finally(() => {
+       setIsRedirecting(false)
+     })
    }
  }, [router, user])

+ if (isRedirecting) {
+   return <LoadingScreen />
+ }

72-84: Consider extracting redirection logic into a custom hook.

The role-based redirection logic could be reused in other components. Consider extracting it into a custom hook like useRoleBasedRedirect for better maintainability and reusability.

Example implementation:

// hooks/useRoleBasedRedirect.ts
export const useRoleBasedRedirect = (user: User | null) => {
  const router = useRouter()
  const [isRedirecting, setIsRedirecting] = useState(false)

  useEffect(() => {
    if (!user) return

    setIsRedirecting(true)
    const targetRoute = getTargetRouteForUser(user)
    
    router.push(targetRoute)
      .catch(console.error)
      .finally(() => setIsRedirecting(false))
  }, [router, user])

  return { isRedirecting }
}

// Usage in Login.tsx
const { isRedirecting } = useRoleBasedRedirect(user)
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 29bb191 and 02a30c7.

📒 Files selected for processing (1)
  • apps/judicial-system/web/src/routes/Shared/Login/Login.tsx (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/web/src/routes/Shared/Login/Login.tsx (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (3)
apps/judicial-system/web/src/routes/Shared/Login/Login.tsx (3)

1-1: LGTM! Import statements are well-organized.

The new imports are logically grouped and necessary for implementing the redirection functionality.

Also applies to: 6-16, 21-21


31-31: LGTM! Proper usage of React Context.

The user context is correctly destructured and follows React best practices.


72-84: Verify redirection behavior in different scenarios.

The implementation aligns with the PR objectives, but let's verify the behavior in various scenarios:

  1. User directly accessing login page
  2. User clicking back button after login
  3. Race conditions during login/logout
#!/bin/bash
# Search for other components that might need similar redirection logic
rg -t typescript -t tsx "router\.(push|replace)" apps/judicial-system/web/src

# Look for potential race conditions in auth state management
ast-grep --pattern 'useEffect($$$, [$$$user$$$])'

@datadog-island-is
Copy link

datadog-island-is bot commented Nov 21, 2024

Datadog Report

Branch report: j-s/redirect-logged-in-user
Commit report: 34baccd
Test service: judicial-system-web

✅ 0 Failed, 335 Passed, 0 Skipped, 1m 19.32s Total Time
🔻 Test Sessions change in coverage: 1 decreased (-0.02%)

🔻 Code Coverage Decreases vs Default Branch (1)

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

🧹 Outside diff range and nitpick comments (1)
apps/judicial-system/web/src/routes/Shared/Login/Login.tsx (1)

74-88: Consider adding loading state during redirection

The component might briefly show the login UI before redirecting. Consider adding a loading state to improve user experience.

Here's a suggested implementation:

+ const [isRedirecting, setIsRedirecting] = useState(false)

  useEffect(() => {
    if (user) {
+     setIsRedirecting(true)
      const redirectRoute = // ... existing logic ...
      router.push(redirectRoute)
    }
  }, [user])

  // Early return for redirecting state
+ if (isRedirecting) {
+   return <LoadingScreen />
+ }

  return (
    // ... existing JSX ...
  )
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 02a30c7 and c58727f.

📒 Files selected for processing (1)
  • apps/judicial-system/web/src/routes/Shared/Login/Login.tsx (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/web/src/routes/Shared/Login/Login.tsx (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (3)
apps/judicial-system/web/src/routes/Shared/Login/Login.tsx (3)

1-1: LGTM! Well-organized imports

The imports are properly organized and grouped by functionality, with clear separation between external dependencies, route constants, and internal utilities.

Also applies to: 6-24


33-33: LGTM! Proper context usage

The UserContext is correctly accessed using the useContext hook, following React best practices.


74-88: Verify redirection behavior for all user roles

Please ensure that the redirection logic is tested for all possible user roles and edge cases.

✅ Verification successful

Let me search for the Login component tests and role-based routing implementation to verify the redirection logic.


Let me search for the role check functions and route constants to verify the redirection logic completeness.


Based on the comprehensive code analysis, I can now provide a final response about the redirection logic in the Login component.

Redirection logic is correctly implemented for all user roles

The implementation correctly handles all user roles defined in the UserRole enum and redirects users to their appropriate routes:

  • Defence users -> DEFENDER_CASES_ROUTE
  • Prison staff users -> PRISON_CASES_ROUTE
  • Court of Appeals users -> COURT_OF_APPEAL_CASES_ROUTE
  • Admin users -> USERS_ROUTE
  • All other roles -> CASES_ROUTE

The role-checking functions (isDefenceUser, isPrisonStaffUser, isCourtOfAppealsUser) are consistently used throughout the codebase, and the route constants are properly defined and referenced. The redirection logic follows the same pattern in both the Login component and the Header component, ensuring consistent navigation behavior.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for related test files
fd -e test.tsx -e spec.tsx "Login" apps/judicial-system/web/src

# Look for existing role-based routing tests
rg -l "test|describe|it.*redirect.*role" apps/judicial-system/web/src

Length of output: 9433


Script:

#!/bin/bash
# Search for Login component tests
rg -A 10 "describe.*Login" apps/judicial-system/web/src

# Search for user role definitions and related functions
ast-grep --pattern 'enum UserRole {
  $$$
}'

# Search for role check functions
ast-grep --pattern 'function isDefenceUser($_) {
  $$$
}'

ast-grep --pattern 'function isPrisonStaffUser($_) {
  $$$
}'

ast-grep --pattern 'function isCourtOfAppealsUser($_) {
  $$$
}'

Length of output: 1810


Script:

#!/bin/bash
# Search for role check functions implementation
rg "isDefenceUser|isPrisonStaffUser|isCourtOfAppealsUser" -A 5 apps/judicial-system/web/src

# Search for route constants
rg "DEFENDER_CASES_ROUTE|PRISON_CASES_ROUTE|COURT_OF_APPEAL_CASES_ROUTE|USERS_ROUTE|CASES_ROUTE" apps/judicial-system/web/src

# Search for any Login component tests
rg -g "**/*Login*.{spec,test}.{ts,tsx}" . apps/judicial-system/web/src

Length of output: 55984

@gudjong gudjong added the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Nov 27, 2024
@kodiakhq kodiakhq bot merged commit 0226fb1 into main Nov 27, 2024
31 checks passed
@kodiakhq kodiakhq bot deleted the j-s/redirect-logged-in-user branch November 27, 2024 14:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
deprecated:automerge (Disabled) Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants