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

More idiomatic supabase auth #139

Merged
merged 2 commits into from
Aug 31, 2024
Merged

More idiomatic supabase auth #139

merged 2 commits into from
Aug 31, 2024

Conversation

scosman
Copy link
Contributor

@scosman scosman commented Aug 31, 2024

Follow official guide: https://supabase.com/docs/guides/auth/server-side/sveltekit

Differences from guide:

  • only run the auth layout under /account and /login, want fast unauthed marketing pages with no JS
  • Be even more explicit in maing getSession safe by not calling it on the server at all

Summary by CodeRabbit

  • New Features

    • Enhanced session management with a new property for session handling.
    • Introduced authentication middleware to manage access to routes based on user authentication status.
    • Improved logic for handling user sessions and routing to ensure security.
  • Bug Fixes

    • Resolved redundancy in user declarations to streamline global state management.
  • Refactor

    • Simplified session retrieval logic to enhance security and efficiency.
    • Adjusted the order of operations in session handling for clarity.

…es/auth/server-side/sveltekit

Differences:
 - only run the auth layout under /account and /login, want fast unauthed marketing pages with no JS
 - Be even more explicit in maing getSession safe by not calling it on the server at all
Copy link

cloudflare-workers-and-pages bot commented Aug 31, 2024

Deploying saasstarter with  Cloudflare Pages  Cloudflare Pages

Latest commit: 3d0cf79
Status: ✅  Deploy successful!
Preview URL: https://d2a2a919.saasstarter.pages.dev
Branch Preview URL: https://ssr-redux.saasstarter.pages.dev

View logs

Copy link

coderabbitai bot commented Aug 31, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes involve modifications to session management and user authentication across multiple files in the application. Key alterations include the addition of a session property in global declarations, renaming and redefining middleware functions for improved request handling, and streamlining session retrieval processes in various routes. These updates enhance the application's structure and control flow regarding user sessions and access management.

Changes

Files Change Summary
src/app.d.ts Added `session: Session
src/hooks.server.ts Renamed handle to supabase; added authGuard middleware for authentication checks; redefined handle to use sequence of middleware.
src/routes/(admin)/account/+layout.server.ts Removed previous session checks; now directly accesses session from locals and simplifies return statement.
src/routes/(admin)/account/+layout.ts Introduced conditional session retrieval based on browser context; streamlined session handling and user profile data fetching.
src/routes/(marketing)/login/+layout.server.ts Reordered session retrieval logic; simplified return statement for clarity.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Middleware
    participant Supabase
    participant App

    User->>Middleware: Request
    Middleware->>Supabase: Initialize Client
    Middleware->>Middleware: AuthGuard Check
    Middleware->>App: Proceed with Request
    App->>User: Response
Loading

🐰 In fields so green and bright,
I hop with joy, oh what a sight!
Sessions now are clear and neat,
With guards to keep us safe and sweet.
So let us dance, oh what a thrill,
For changes made, we celebrate still! 🌼✨


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

Outside diff range, codebase verification and nitpick comments (1)
src/hooks.server.ts (1)

Line range hint 13-87: Approve the changes to the supabase function with a suggestion for improvement.

The initialization of two Supabase clients—one for general use and one with a service role—is a good practice that separates concerns effectively. The custom cookie handling setup is also well-thought-out, ensuring compatibility with SvelteKit's API.

However, consider documenting the use of suppressGetSessionWarning more thoroughly, as it is not part of the official API and could lead to future maintenance issues.

Add documentation for the use of suppressGetSessionWarning:

+ // Note: suppressGetSessionWarning is used here to suppress a specific warning
+ // related to getSession. This is not part of the official Supabase API and should
+ // be used with caution as it may be subject to change.
  if ("suppressGetSessionWarning" in event.locals.supabase.auth) {
    // @ts-expect-error - suppressGetSessionWarning is not part of the official API
    event.locals.supabase.auth.suppressGetSessionWarning = true
  } else {
    console.warn(
      "SupabaseAuthClient#suppressGetSessionWarning was removed. See https://github.com/supabase/auth-js/issues/888.",
    )
  }
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f6231b8 and a1a7ba5.

Files selected for processing (5)
  • src/app.d.ts (1 hunks)
  • src/hooks.server.ts (2 hunks)
  • src/routes/(admin)/account/+layout.server.ts (1 hunks)
  • src/routes/(admin)/account/+layout.ts (2 hunks)
  • src/routes/(marketing)/login/+layout.server.ts (1 hunks)
Additional comments not posted (5)
src/routes/(admin)/account/+layout.server.ts (1)

4-10: Simplification of session handling noted. Verify upstream validation.

The changes in the load function simplify the session handling by directly accessing the session object and returning it with cookies. This assumes that session validation is handled upstream, possibly by middleware.

Ensure that the session validation logic is robust and securely implemented before this point in the code flow to maintain security and functionality.

Verification successful

Session validation is handled upstream.

The safeGetSession function in src/hooks.server.ts validates the session before it is used in the load function. This confirms that the simplification in session handling is appropriate and secure.

  • src/hooks.server.ts: safeGetSession validates the JWT before returning the session.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that session validation is handled upstream.

# Test: Search for middleware or hooks that validate the session before this function is called.
rg --type typescript -A 5 $'session validation'

Length of output: 83


Script:

#!/bin/bash
# Description: Verify that session validation is handled upstream.

# Test: Search for middleware or hooks that validate the session before this function is called.
rg --type ts -A 5 $'session validation'

Length of output: 40


Script:

#!/bin/bash
# Description: Search for session-related middleware or hooks that might handle validation.

# Test: Look for common session handling patterns or functions in TypeScript files.
rg --type ts -A 5 'session' | rg 'middleware|hook'

Length of output: 2320

src/routes/(marketing)/login/+layout.server.ts (1)

10-10: Optimization and simplification of session handling approved.

The repositioning of the session retrieval to just before the redirect logic optimizes the function by avoiding unnecessary session fetches. The direct return of the session variable simplifies the code and enhances clarity.

Verify that this change does not impact other functionalities that depend on the session data being manipulated or checked in a specific way.

src/app.d.ts (1)

16-16: Addition of session property approved.

The addition of the session property to the global declarations enhances session management and aligns with the PR's objectives to improve authentication handling.

src/routes/(admin)/account/+layout.ts (1)

63-67: Approve user profile retrieval changes.

Fetching the user profile directly from the database using the user's ID is a robust approach that ensures data integrity and freshness. This change is well-implemented and improves the accuracy of the profile data retrieved.

src/hooks.server.ts (1)

88-102: Approve the changes to the authGuard function.

The implementation of the authGuard function is crucial for maintaining secure access to specific routes based on user authentication status. The logic for redirecting users based on their authentication status is well-implemented and enhances the application's security.

src/app.d.ts Show resolved Hide resolved
Comment on lines +34 to +43
// on server populated on server by LayoutData, using authGuard hook
let session = data.session
if (isBrowser()) {
// Only call getSession in browser where it's safe.
const getSessionResponse = await supabase.auth.getSession()
session = getSessionResponse.data.session
}
if (!session) {
redirect(303, "/login")
}
Copy link

Choose a reason for hiding this comment

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

Approve session management changes with a suggestion for improvement.

The conditional session management logic is a significant improvement, enhancing security by ensuring that session retrieval only occurs in the browser context. This approach aligns well with best practices.

However, consider adding error handling for the getSession call to manage potential failures gracefully.

Add error handling around the getSession call:

-    const getSessionResponse = await supabase.auth.getSession()
+    let getSessionResponse;
+    try {
+      getSessionResponse = await supabase.auth.getSession()
+    } catch (error) {
+      console.error('Failed to retrieve session:', error);
+      redirect(303, '/login');
+      return;
+    }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// on server populated on server by LayoutData, using authGuard hook
let session = data.session
if (isBrowser()) {
// Only call getSession in browser where it's safe.
const getSessionResponse = await supabase.auth.getSession()
session = getSessionResponse.data.session
}
if (!session) {
redirect(303, "/login")
}
// on server populated on server by LayoutData, using authGuard hook
let session = data.session
if (isBrowser()) {
// Only call getSession in browser where it's safe.
let getSessionResponse;
try {
getSessionResponse = await supabase.auth.getSession()
} catch (error) {
console.error('Failed to retrieve session:', error);
redirect(303, '/login');
return;
}
session = getSessionResponse.data.session
}
if (!session) {
redirect(303, "/login")
}

@scosman scosman merged commit 4d9111d into main Aug 31, 2024
11 checks passed
@scosman scosman deleted the ssr_redux branch August 31, 2024 01:14
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.

1 participant