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: Code split for logout success handler #39296

Merged
merged 3 commits into from
Feb 18, 2025
Merged

Conversation

abhvsn
Copy link
Contributor

@abhvsn abhvsn commented Feb 14, 2025

Description

Description

Added redirect URL on user logout

Fixes #38933

Automation

/ok-to-test tags="@tag.Sanity"

🔍 Cypress test results

Tip

🟢 🟢 🟢 All cypress tests have passed! 🎉 🎉 🎉
Workflow run: https://github.com/appsmithorg/appsmith/actions/runs/13369328042
Commit: 5b4bbe9
Cypress dashboard.
Tags: @tag.Sanity
Spec:


Mon, 17 Feb 2025 12:14:39 UTC

Communication

Should the DevRel and Marketing teams inform users about this change?

  • Yes
  • No

Summary by CodeRabbit

  • New Features
    • Users are now automatically redirected to the login page after logout for a smoother navigation experience.
  • Refactor
    • Simplified the logout request process to consistently use the "POST" method, enhancing reliability.
    • Streamlined the interception logic for logout API calls, improving overall consistency.

Copy link
Contributor

coderabbitai bot commented Feb 14, 2025

Walkthrough

The pull request revises the logout success handling in LogoutSuccessHandlerCE.java. It refactors the response construction by separating JSON serialization from error handling and introduces new helper methods for post-logout redirection and session clearance. A new protected field is added to store the default redirect URI, while the control flow in the onLogoutSuccess method is organized to better manage response creation and redirection logic. Additionally, the logout request handling in both HomePage.ts and commands.js is simplified to consistently use the "POST" method.

Changes

File Change Summary
app/server/appsmith-server/.../LogoutSuccessHandlerCE.java - Added protected field postLogoutRedirectUri with default value "/user/login".
- Refactored onLogoutSuccess for clearer JSON response construction and error handling.
- Introduced helper methods: generatePostLogoutRedirectUri, getUriComponents, postLogoutRedirectUri, and clearOAuthSessionIfRequired.
app/client/cypress/support/Pages/HomePage.ts - Updated LogOutviaAPI method to consistently use "POST" for logout requests, removing the conditional logic based on CURRENT_REPO.
app/client/cypress/support/commands.js - Simplified logout API request handling by removing conditional logic for HTTP method and consolidating intercepts into a single "POST" intercept.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant LS as LogoutSuccessHandler
    participant GC as URI Generator
    participant OS as OAuth Session Manager
    U->>LS: Initiate logout
    LS->>LS: Build ResponseDTO & serialize JSON
    LS->>GC: generatePostLogoutRedirectUri()
    GC-->>LS: Return redirect URI
    LS->>OS: clearOAuthSessionIfRequired() if needed
    OS-->>LS: Session cleared
    LS-->>U: Send response with redirect URI
Loading

Poem

In the realm of logout, new logic shines bright,
Redirects and clear sessions in a seamless flight.
Methods align and responses now flow,
A tidy code dance that continues to grow.
Cheers to our refined commit tonight!


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f3660a0 and 8688f88.

📒 Files selected for processing (2)
  • app/client/cypress/support/Pages/HomePage.ts (1 hunks)
  • app/client/cypress/support/commands.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`app/client/cypress/**/**.*`: Review the following e2e test ...

app/client/cypress/**/**.*: Review the following e2e test code written using the Cypress test library. Ensure that:

  • Follow best practices for Cypress code and e2e automation.
  • Avoid using cy.wait in code.
  • Avoid using cy.pause in code.
  • Avoid using agHelper.sleep().
  • Use locator variables for locators and do not use plain strings.
  • Use data-* attributes for selectors.
  • Avoid Xpaths, Attributes and CSS path.
  • Avoid selectors like .btn.submit or button[type=submit].
  • Perform logins via API with LoginFromAPI.
  • Perform logout via API with LogOutviaAPI.
  • Perform signup via API with SignupFromAPI.
  • Avoid using it.only.
  • Avoid using after and aftereach in test cases.
  • Use multiple assertions for expect statements.
  • Avoid using strings for assertions.
  • Do not use duplicate filenames even with different paths.
  • Avoid using agHelper.Sleep, this.Sleep in any file in code.
  • app/client/cypress/support/commands.js
  • app/client/cypress/support/Pages/HomePage.ts
🔇 Additional comments (3)
app/client/cypress/support/Pages/HomePage.ts (1)

360-370: LGTM! Consistent HTTP method for logout.

The change to use POST consistently for logout requests aligns with REST principles and simplifies the implementation.

app/client/cypress/support/commands.js (2)

223-242: LGTM! Simplified logout command implementation.

The command now consistently uses POST method and includes proper response verification.


582-583: LGTM! Simplified route interception for logout.

The interception now handles only POST requests, aligning with the standardized logout implementation.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

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.

@abhvsn abhvsn added the ok-to-test Required label for CI label Feb 14, 2025
@github-actions github-actions bot added Enhancement New feature or request skip-changelog Adding this label to a PR prevents it from being listed in the changelog and removed Enhancement New feature or request labels Feb 14, 2025
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 (3)
app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/LogoutSuccessHandlerCE.java (3)

48-61: Consider refactoring duplicated buffer allocation logic.

The buffer allocation code is duplicated in both the error handling and success paths. Consider extracting this into a helper method.

+    private DataBuffer createResponseBuffer(ServerWebExchange exchange, String responseStr) {
+        return exchange.getResponse()
+                .bufferFactory()
+                .allocateBuffer(responseStr.length())
+                .write(responseStr.getBytes());
+    }

     @Override
     public Mono<Void> onLogoutSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
         // ... existing code ...
         try {
             responseStr = objectMapper.writeValueAsString(responseBody);
         } catch (JsonProcessingException e) {
             log.error("Unable to write to response json. Cause: ", e);
             responseStr = "{\"responseMeta\":{\"status\":500,\"success\":false},\"data\":false}";
-            DataBuffer buffer = exchange.getResponse()
-                    .bufferFactory()
-                    .allocateBuffer(responseStr.length())
-                    .write(responseStr.getBytes());
+            DataBuffer buffer = createResponseBuffer(exchange, responseStr);
             return response.writeWith(Mono.just(buffer));
         }

-        DataBuffer buffer = exchange.getResponse()
-                .bufferFactory()
-                .allocateBuffer(responseStr.length())
-                .write(responseStr.getBytes());
+        DataBuffer buffer = createResponseBuffer(exchange, responseStr);

Also applies to: 63-66


80-98: LGTM! Well-structured URI handling methods.

The URI manipulation logic is robust with proper null checks. Consider adding validation for port number handling in postLogoutRedirectUri.

     protected String postLogoutRedirectUri(ServerHttpRequest request) {
         UriComponents uriComponents = getUriComponents(request);
         String scheme = uriComponents.getScheme();
         String host = uriComponents.getHost();
+        int port = uriComponents.getPort();
         return UriComponentsBuilder.newInstance()
                 .scheme((scheme != null) ? scheme : "")
                 .host((host != null) ? host : "")
+                .port(port == -1 ? null : port)
                 .path(this.getPostLogoutRedirectUri())
                 .build()
                 .toUriString();
     }

100-102: Add documentation for OAuth session clearing hook.

This template method would benefit from JavaDoc explaining its purpose and when subclasses should override it.

+    /**
+     * Hook method for clearing OAuth session data if required.
+     * Subclasses should override this method to implement OAuth-specific cleanup.
+     *
+     * @param logoutRedirectUri the URI to redirect to after logout
+     * @return Mono<Void> completing when cleanup is done
+     */
     protected Mono<Void> clearOAuthSessionIfRequired(String logoutRedirectUri) {
         return Mono.empty();
     }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2782994 and f3660a0.

📒 Files selected for processing (1)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/LogoutSuccessHandlerCE.java (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: perform-test / rts-build / build
  • GitHub Check: perform-test / server-build / server-unit-tests
  • GitHub Check: perform-test / client-build / client-build
  • GitHub Check: server-spotless / spotless-check
  • GitHub Check: server-unit-tests / server-unit-tests
🔇 Additional comments (1)
app/server/appsmith-server/src/main/java/com/appsmith/server/authentication/handlers/ce/LogoutSuccessHandlerCE.java (1)

32-33: LGTM! Well-structured field declaration.

The protected field with restricted getter access aligns with good encapsulation practices.

@abhvsn
Copy link
Contributor Author

abhvsn commented Feb 14, 2025

/build-deploy-preview skip-tests=true

Copy link

Deploying Your Preview: https://github.com/appsmithorg/appsmith/actions/runs/13328114565.
Workflow: On demand build Docker image and deploy preview.
skip-tests: true.
env: ``.
PR: 39296.
recreate: .

Copy link

Deploy-Preview-URL: https://ce-39296.dp.appsmith.com

@abhvsn abhvsn requested a review from trishaanand February 14, 2025 12:27
@github-actions github-actions bot added the Enhancement New feature or request label Feb 17, 2025
@github-actions github-actions bot added Enhancement New feature or request and removed Enhancement New feature or request labels Feb 17, 2025
@abhvsn abhvsn merged commit e4ed590 into release Feb 18, 2025
43 checks passed
@abhvsn abhvsn deleted the logout-redirect-uri branch February 18, 2025 06:49
abhvsn added a commit that referenced this pull request Feb 18, 2025
## Description
## Description

Added redirect URL on user logout

Fixes #38933

## Automation

/ok-to-test tags="@tag.Sanity"

### 🔍 Cypress test results
<!-- This is an auto-generated comment: Cypress test results  -->
> [!TIP]
> 🟢 🟢 🟢 All cypress tests have passed! 🎉 🎉 🎉
> Workflow run:
<https://github.com/appsmithorg/appsmith/actions/runs/13369328042>
> Commit: 5b4bbe9
> <a
href="https://internal.appsmith.com/app/cypress-dashboard/rundetails-65890b3c81d7400d08fa9ee5?branch=master&workflowId=13369328042&attempt=1"
target="_blank">Cypress dashboard</a>.
> Tags: `@tag.Sanity`
> Spec:
> <hr>Mon, 17 Feb 2025 12:14:39 UTC
<!-- end of auto-generated comment: Cypress test results  -->

## Communication
Should the DevRel and Marketing teams inform users about this change?
- [ ] Yes
- [x] No

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
- Users are now automatically redirected to the login page after logout
for a smoother navigation experience.
- **Refactor**
- Simplified the logout request process to consistently use the "POST"
method, enhancing reliability.
- Streamlined the interception logic for logout API calls, improving
overall consistency.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Albin <[email protected]>
(cherry picked from commit e4ed590)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Enhancement New feature or request ok-to-test Required label for CI skip-changelog Adding this label to a PR prevents it from being listed in the changelog
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Feature]: Client: Preserve redirect URL on 401 response
3 participants