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: handle unauthorized error to redirect to login #351

Merged
merged 3 commits into from
Nov 4, 2024

Conversation

kshitij-k-osmosys
Copy link
Contributor

@kshitij-k-osmosys kshitij-k-osmosys commented Oct 28, 2024

Portal PR Checklist

Pre-requisites

  • I have gone through the Contributing guidelines for Submitting a Pull Request (PR) and ensured that this is not a duplicate PR.
  • I have performed unit testing for the new feature added or updated to ensure the new features added are working as expected.
  • I have performed preliminary testing to ensure that any existing features are not impacted and any new features are working as expected as a whole.

PR Details

PR details have been updated as per the given format (see below)

  • PR title adheres to the format specified in guidelines (e.g., feat: add admin login page)
  • Description has been added
  • Related changes have been added (optional)
  • Screenshots have been added (optional, may include unit testing screenshots as well)
  • Pending actions have been added (optional)
  • Any other additional notes have been added (optional)

Additional Information

  • Appropriate label(s) have been added (ready for review should be added if the PR is ready to be reviewed)
  • Assignee(s) and reviewer(s) have been added (optional)

Note: Reviewer should ensure that the checklist and description have been populated and followed correctly, and the PR should be merged only after resolving all conversations and verifying that CI checks pass.


Description:

Handle GraphQL response errors. Logout when unauthorized error is encountered

Related changes:

  • Add GraphQLFormattedError object in ApplicationResponse
  • Add code to handle GraphQL response error
  • Create logoutUser service function
  • Logout when unauthorized error is encountered
  • Test on local and docker environment

Screenshots:

Unauthorized token
https://github.com/user-attachments/assets/f41325b0-690d-4f78-8cf7-699576b2cafb

Non admin user login
https://github.com/user-attachments/assets/29b1e4ba-9fce-402a-9db2-20b12164634f

Pending actions:
NA

Additional notes:
NA

Summary by CodeRabbit

  • New Features

    • Introduced a logout functionality that navigates users to the login page.
    • Enhanced error handling in the applications service and notifications component, specifically addressing unauthorized access.
  • Bug Fixes

    • Improved error handling logic to manage unauthorized access and log errors effectively.
  • Documentation

    • Updated interfaces to include error handling properties for better response management.

Copy link

coderabbitai bot commented Oct 28, 2024

Walkthrough

The changes in this pull request involve modifications to several components and services within the application. The AuthService is updated to include a Router dependency and a new logoutUser method. The ApplicationResponse interface now accommodates error messages, and the ApplicationsService enhances error handling in the getApplications method. Additionally, the NotificationsComponent integrates AuthService to manage unauthorized access more effectively, utilizing the new logout functionality.

Changes

File Path Change Summary
apps/portal/src/app/auth/auth.service.ts - Constructor updated to inject Router.
- Added method logoutUser for user logout.
apps/portal/src/app/views/applications/application.model.ts - Added optional property errors to ApplicationResponse interface.
apps/portal/src/app/views/applications/applications.service.ts - Enhanced getApplications method to include errors in the response object.
apps/portal/src/app/views/notifications/notifications.component.ts - Integrated AuthService into constructor.
- Updated error handling in getApplications to manage unauthorized access.

Possibly related PRs

Suggested reviewers

  • xixas

Poem

In the burrows deep, where the code does creep,
A logout method hops, for users to keep.
With errors caught, and responses neat,
Our app now dances, with a rhythm sweet.
So let’s celebrate, with a joyful cheer,
For every change brings us closer, my dear! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7b60874 and 9c913fb.

📒 Files selected for processing (2)
  • apps/portal/src/app/auth/auth.service.ts (3 hunks)
  • apps/portal/src/app/views/notifications/notifications.component.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/portal/src/app/auth/auth.service.ts
🔇 Additional comments (2)
apps/portal/src/app/views/notifications/notifications.component.ts (2)

5-5: LGTM: Clean service integration.

The AuthService integration follows Angular best practices with proper import and dependency injection.

Also applies to: 87-87


126-152: Enhance error handling robustness and user experience.

While the error handling implementation is good, consider these improvements:

  1. Make error messages more user-friendly
  2. Add more context to non-unauthorized errors
  3. Implement consistent optional chaining
-        if (applicationResponse?.errors?.length) {
+        if (applicationResponse?.errors?.length > 0) {
           const unauthorizedError = applicationResponse.errors.find(
             (error) => error.message === 'Unauthorized',
           );

           this.applications = [];
           this.selectedApplication = null;

           if (unauthorizedError) {
             this.messageService.add({
               key: 'tst',
               severity: 'error',
               summary: 'Error',
-              detail: 'Unauthorized access. Please log in again.',
+              detail: 'Your session has expired. Please log in again to continue.',
             });
             this.authService.logoutUser();
           } else {
             applicationResponse.errors.forEach((error) => {
               this.messageService.add({
                 key: 'tst',
                 severity: 'error',
                 summary: 'Error',
-                detail: `GraphQL Error - Get Applications: ${error.message}`,
+                detail: `Unable to load applications: ${error.message}`,
               });
             });
           }
         }

Let's verify the error message consistency across the application:


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.

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (4)
apps/portal/src/app/auth/auth.service.ts (1)

Line range hint 1-50: Consider enhancing security measures.

The authentication service could benefit from additional security measures:

  1. Consider implementing CSRF protection for authentication endpoints
  2. Add refresh token mechanism for better session management
  3. Consider using a secure storage mechanism (like cookies with httpOnly flag) instead of localStorage for sensitive data
  4. Add events/observables for authentication state changes to better manage UI updates across the application

Would you like assistance in implementing any of these security enhancements?

apps/portal/src/app/views/applications/applications.service.ts (2)

Line range hint 35-39: Standardize error handling approach.

The current implementation mixes two error handling approaches: returning errors in the response object and throwing errors in catchError. This could lead to inconsistent error handling across the application.

Consider standardizing the error handling:

 catchError((error) => {
-  const errorMessage: string = error.message;
-  throw new Error(errorMessage);
+  return [{
+    applications: [],
+    total: 0,
+    offset: 0,
+    limit: 0,
+    errors: [{
+      message: this.sanitizeErrorMessage(error.message),
+      code: error.extensions?.code || 'UNKNOWN_ERROR'
+    }]
+  }];
 }),

Security concern confirmed: Unsafe token handling detected

The decodeToken method in ApplicationsService is indeed problematic as:

  1. It's only used for decoding without any signature validation
  2. The auth service doesn't show any token validation methods
  3. The method is exposed at class level, potentially allowing unauthorized access to token payloads

Recommendations:

  • Move token handling to the AuthService
  • Implement proper JWT verification using a cryptographic library
  • If payload inspection is needed, ensure it's done after signature validation
  • Consider marking sensitive payload data as private
🔗 Analysis chain

Line range hint 42-60: Review token handling security implications.

While not part of the current changes, given this PR's focus on unauthorized errors, it's worth noting that the decodeToken method:

  1. Doesn't validate the token signature
  2. Could expose sensitive information in the decoded payload
  3. Shouldn't be used for authentication purposes

Let's check if this method is used for authentication:


The previous command failed due to typescript extension not being recognized. Let's try a broader search to understand the usage context and potential authentication flows.


Let's verify if this is just a utility method or if it's actually used in authentication flows by checking the service implementations.


We need to understand the actual usage context of decodeToken and verify if proper token validation exists in the auth service.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check usage of decodeToken method
# Expected: Should not be used in authentication flows

rg -t typescript "decodeToken" -A 5

Length of output: 91


Script:

#!/bin/bash
# Let's try different approaches to find usages of decodeToken

# Search for decodeToken using ripgrep without file type restriction
rg "decodeToken" -B 2 -A 5

# Also search for potential authentication-related files
rg -l "auth|login|authenticate"

Length of output: 3010


Script:

#!/bin/bash
# Let's check how this decodeToken is being used in the applications service
rg -B 10 -A 10 "class ApplicationsService" apps/portal/src/app/views/applications/applications.service.ts

# Also check if there's a proper auth service handling token validation
rg -B 5 -A 10 "class AuthService" apps/portal/src/app/auth/auth.service.ts

Length of output: 1216


Script:

#!/bin/bash
# Let's check where this decodeToken is actually used within the applications service
rg -B 5 -A 10 "decodeToken\(" apps/portal/src/app/views/applications/applications.service.ts

# And check for any token validation in the auth service
rg "validateToken|verifyToken|jwt\.verify" apps/portal/src/app/auth/auth.service.ts

Length of output: 622

apps/portal/src/app/views/notifications/notifications.component.ts (1)

126-142: Consider implementing retry logic for non-auth errors.

While the unauthorized error handling is good, other transient errors might benefit from a retry mechanism.

Consider implementing a retry strategy using RxJS operators for non-auth errors:

import { retry, retryWhen, delay, take } from 'rxjs/operators';

// In your service:
getApplications(variables, loginToken).pipe(
  retryWhen(errors =>
    errors.pipe(
      delay(1000), // Wait 1s between retries
      take(3)      // Max 3 retries
    )
  )
)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f26d27e and 7b60874.

📒 Files selected for processing (4)
  • apps/portal/src/app/auth/auth.service.ts (3 hunks)
  • apps/portal/src/app/views/applications/application.model.ts (2 hunks)
  • apps/portal/src/app/views/applications/applications.service.ts (1 hunks)
  • apps/portal/src/app/views/notifications/notifications.component.ts (3 hunks)
🧰 Additional context used
🪛 Biome
apps/portal/src/app/views/notifications/notifications.component.ts

[error] 152-152: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (7)
apps/portal/src/app/views/applications/application.model.ts (2)

17-17: LGTM! Well-structured error handling.

The addition of the optional errors property using ReadonlyArray<GraphQLFormattedError> is a good practice for GraphQL error handling. This immutable approach ensures type safety and aligns with GraphQL specifications.


1-1: Verify GraphQL package dependency.

Please ensure that the graphql package is listed as a dependency in the project's package.json.

✅ Verification successful

GraphQL package dependency is properly configured

The graphql package is correctly listed as a dependency in apps/portal/package.json with version ^16.9.0, which supports the imported GraphQLFormattedError type.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if graphql is listed as a dependency
grep -r '"graphql"' package.json

Length of output: 80


Script:

#!/bin/bash
# Search for package.json files in the repository
fd package.json

# After finding package.json files, let's check their content for graphql dependency
fd package.json --exec grep -l "graphql" {}

Length of output: 161


Script:

#!/bin/bash
# Check the content of portal's package.json for graphql dependency details
cat apps/portal/package.json | grep -A 5 -B 5 '"graphql"'

Length of output: 404

apps/portal/src/app/auth/auth.service.ts (2)

4-4: LGTM!

The Router import is correctly added and necessary for the new navigation functionality.


17-20: LGTM!

The Router service is properly injected following Angular dependency injection patterns.

apps/portal/src/app/views/applications/applications.service.ts (1)

32-32: Verify ApplicationResponse type definition.

The errors property has been added to the response object, but we need to ensure the ApplicationResponse interface in application.model.ts is properly updated.

Let's verify the type definition:

#!/bin/bash
# Description: Check if ApplicationResponse interface includes the errors property
# Expected: Should find the interface definition with errors property

rg -t typescript "interface ApplicationResponse" -A 10
apps/portal/src/app/views/notifications/notifications.component.ts (2)

5-5: LGTM: Clean dependency injection implementation.

The AuthService integration follows Angular's dependency injection best practices.

Also applies to: 87-87


141-141: Verify AuthService.logoutUser implementation.

Ensure that the AuthService.logoutUser() method properly handles:

  1. Clearing all relevant session data
  2. Redirecting to the login page
  3. Cleaning up any active subscriptions
✅ Verification successful

Let me try a different search pattern to locate the AuthService implementation.


AuthService.logoutUser implementation is verified and properly handles logout

The implementation in apps/portal/src/app/auth/auth.service.ts correctly handles:

  1. ✓ Clearing session data via localStorage.clear()
  2. ✓ Redirecting to login page via router.navigate(['/login'])

The implementation is simple but sufficient for basic logout functionality. No issues found with the integration.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for AuthService implementation
echo "Searching for AuthService implementation..."
ast-grep --pattern 'class AuthService {
  $$$
  logoutUser() {
    $$$
  }
  $$$
}'

Length of output: 182


Script:

#!/bin/bash
# Search for AuthService class and logoutUser method with more flexible patterns
echo "Searching for AuthService class..."
rg -l "class AuthService" -g "*.ts"

echo -e "\nSearching for logoutUser method..."
rg "logoutUser\(" -g "*.ts" -A 5

Length of output: 1331

@kshitij-k-osmosys kshitij-k-osmosys removed the request for review from osm-vishnukyatannawar October 30, 2024 07:05
@xixas xixas changed the title feat: handle unauthorized error on portal feat: handle unauthorized error to redirect to login Nov 4, 2024
@xixas xixas merged commit addd012 into main Nov 4, 2024
6 checks passed
@xixas xixas deleted the feat/handle-unauthorized-error branch November 4, 2024 05:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants