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

persisting tokens in the session #11

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

Hammadkhan0034
Copy link

@Hammadkhan0034 Hammadkhan0034 commented Aug 20, 2024

Explain your changes

  1. CheckAuth plug checks if the access_token and refresh_token are stored in the session.
  2. If tokens are found, the SDK is initialized with the init_with_tokens/3 function, which has been added to the KindeClientSDK
  3. If tokens are missing, the plug redirects the user

Summary by CodeRabbit

  • New Features

    • Introduced improved session management for user authentication, including access and refresh tokens.
    • Added an authentication plug to ensure only authenticated users can access protected resources.
    • Established a new authentication pipeline in the routing logic to enforce authentication checks on specific routes.
  • Bug Fixes

    • Enhanced logout functionality to properly clear authentication tokens and improve security.
  • Documentation

    • Updated routing structure for better organization of authenticated and non-authenticated routes.

Copy link

coderabbitai bot commented Aug 20, 2024

Walkthrough

The recent changes enhance authentication and session management in the DemoElixirPhoenixWeb application. New functionality has been introduced to manage access and refresh tokens during login and logout processes. Additionally, an authentication plug ensures that users must be logged in to access protected routes, increasing the security of the application. Overall, these modifications streamline user authentication while maintaining a clear structure in the routing logic.

Changes

Files Change Summary
lib/demo_elixir_phoenix_web/controllers/page_controller.ex Introduced session management for access and refresh tokens in log_in and log_out functions.
lib/demo_elixir_phoenix_web/plugs/check_auth.ex Added CheckAuth plug for authentication, which processes tokens and redirects unauthorized users to the login page.
lib/demo_elixir_phoenix_web/router.ex Defined a new :authenticated pipeline for routing, enforcing authentication checks on user access to specific routes.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Frontend
    participant Router
    participant PageController
    participant CheckAuth

    User->>Frontend: Requests access to a protected route
    Frontend->>Router: Sends request
    Router->>CheckAuth: Checks authentication
    CheckAuth->>Session: Retrieves access_token and refresh_token
    alt Tokens present
        CheckAuth->>Router: Proceed with request
        Router->>PageController: Handle request
    else Tokens missing
        CheckAuth->>Frontend: Redirect to login page
    end
Loading

Poem

🐇 In a world of code so bright,
Tokens dance in morning light.
With a hop, we guard the gate,
Secure the paths where users wait.
Log in, log out, all is clear,
A safer web, let's all cheer! 🎉


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

Outside diff range, codebase verification and nitpick comments (2)
lib/demo_elixir_phoenix_web/router.ex (2)

Line range hint 22-37: Review route organization for clarity and maintainability.

The changes organize routes into authenticated and non-authenticated scopes, which enhances clarity. Ensure that all routes are correctly categorized and that no routes requiring authentication are accidentally placed in the non-authenticated scope.

Consider documenting the purpose of each scope for future maintainability.


13-15: Add tests for CheckAuth plug to handle edge cases

The CheckAuth plug checks for tokens in the session and redirects unauthenticated users. However, it does not explicitly handle edge cases like expired tokens or network issues during SDK initialization. Additionally, there are no automated tests found for this plug. Consider adding tests to verify its behavior under various scenarios.

  • File: lib/demo_elixir_phoenix_web/plugs/check_auth.ex
Analysis chain

Ensure CheckAuth plug is reliable and efficient.

The :authenticated pipeline uses the CheckAuth plug to enforce authentication. Ensure that the plug efficiently handles all edge cases, such as expired tokens or network issues during SDK initialization.

Consider adding tests to verify that the CheckAuth plug correctly redirects unauthenticated requests and allows authenticated ones.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the `CheckAuth` plug correctly handles authentication.

# Test: Ensure that the plug is redirecting unauthenticated requests.
rg --type elixir -A 5 'plug DemoElixirPhoenixWeb.Plugs.CheckAuth'

Length of output: 402


Script:

#!/bin/bash
# Locate the implementation of the CheckAuth plug.
fd 'CheckAuth.ex'

# Search for test files that might verify the behavior of the CheckAuth plug.
fd 'check_auth_test.exs'

# If the file is found, extract the implementation of the CheckAuth plug.
ast-grep --lang elixir --pattern 'defmodule DemoElixirPhoenixWeb.Plugs.CheckAuth do
  $$$
end'

Length of output: 1648

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 274bed7 and 14ca5fa.

Files selected for processing (3)
  • lib/demo_elixir_phoenix_web/controllers/page_controller.ex (2 hunks)
  • lib/demo_elixir_phoenix_web/plugs/check_auth.ex (1 hunks)
  • lib/demo_elixir_phoenix_web/router.ex (2 hunks)
Additional comments not posted (2)
lib/demo_elixir_phoenix_web/controllers/page_controller.ex (2)

31-32: Ensure secure handling of session tokens.

The callback function stores access_token and refresh_token in the session. Ensure these tokens are securely handled to prevent session hijacking or token leakage.

Consider setting appropriate session options, such as secure and http_only, to enhance security.


80-81: Ensure tokens are fully cleared on logout.

The log_out function deletes access_token and refresh_token from the session. Verify that the session is fully cleared to prevent unauthorized access.

Consider adding tests to ensure that logging out effectively invalidates the session.

Comment on lines +1 to +20
defmodule DemoElixirPhoenixWeb.Plugs.CheckAuth do
import Plug.Conn
alias KindeClientSDK

def init(default), do: default

def call(conn, _opts) do
access_token = get_session(conn, :access_token)
refresh_token = get_session(conn, :refresh_token)

if access_token && refresh_token do
conn = KindeClientSDK.init_with_tokens(conn, access_token, refresh_token)
conn
else
conn
|> Phoenix.Controller.redirect(to: "/log-in")
|> halt()
end
end
end
Copy link

Choose a reason for hiding this comment

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

Ensure proper error handling and logging.

The CheckAuth module effectively manages authentication by checking for tokens in the session. However, it lacks error handling and logging, which are crucial for debugging and monitoring.

Consider adding logging to track when tokens are missing and when a user is redirected. Additionally, handle potential errors from KindeClientSDK.init_with_tokens/3 to ensure robustness.

def call(conn, _opts) do
  access_token = get_session(conn, :access_token)
  refresh_token = get_session(conn, :refresh_token)

  if access_token && refresh_token do
    case KindeClientSDK.init_with_tokens(conn, access_token, refresh_token) do
      {:ok, conn} -> conn
      {:error, reason} ->
        Logger.error("Failed to initialize SDK: #{reason}")
        redirect_to_login(conn)
    end
  else
    Logger.warn("Missing tokens, redirecting to login")
    redirect_to_login(conn)
  end
end

defp redirect_to_login(conn) do
  conn
  |> Phoenix.Controller.redirect(to: "/log-in")
  |> halt()
end

@tcoopman
Copy link

@Hammadkhan0034 so I'm trying this PR, but I'm not sure I get it working correctly.

When I login (successfully) I get all the user details, but as soon as I click on permissions or user details or refresh, the user is always nil.

Am I doing something wrong?

@mhtouseef9
Copy link

@Hammadkhan0034 so I'm trying this PR, but I'm not sure I get it working correctly.

When I login (successfully) I get all the user details, but as soon as I click on permissions or user details or refresh, the user is always nil.

Am I doing something wrong?

@tcoopman as per Andre message
It appears that you're using the Client Credentials flow instead of the Authorization Code flow.
The Client Credentials flow is typically used for machine-to-machine authentication and doesn't involve a user login. This explains why the user, oauth_code_verifier, refresh_token, id_token, and expiring_time_stamp fields are nil.

@tcoopman
Copy link

I'll try again and I'll set-up a reproduction repository if I don't get it to work.

Thanks

@mhtouseef9
Copy link

I am not able to get refresh token after login with client credentials grant type. Can anyone let me how can I get it and what I am doing wrong.

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.

3 participants