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: add auth gemini #144

Merged
merged 2 commits into from
Feb 11, 2025
Merged

Conversation

bitfalt
Copy link
Member

@bitfalt bitfalt commented Feb 11, 2025

This PR does the following:

  • Add auth to the gemini endpoint
  • Fix some formatting, linting, and build errors.

Summary by CodeRabbit

  • Chores

    • Implemented consistent dynamic routing configurations across several API endpoints to ensure up-to-date content delivery.
  • Refactor

    • Enhanced session validation and error messaging to provide a more secure and reliable experience when accessing protected content.
  • Style

    • Improved code formatting and consistency, resulting in clearer structure and readability without affecting functionality.

Copy link
Contributor

coderabbitai bot commented Feb 11, 2025

Walkthrough

This pull request refactors several API routes for improved readability and consistency. Minor formatting changes have been applied in the confirm-payment and insights page files, while multiple routes now export a constant dynamic set to "force-dynamic". Additionally, the gemini-flash and public-figures routes incorporate a new TokenPayload interface and enhanced JWT verification, including stricter session validation. Overall, the functionality and control flow remain unchanged apart from clearer error handling and type management.

Changes

File(s) Change Summary
frontend/src/app/api/confirm-payment/route.ts Added a line break in the subscriptionExpiry declaration for improved formatting.
frontend/src/app/api/gemini-flash/route.ts, frontend/src/app/api/public-figures/route.ts Introduced new TokenPayload interface (extending JWTPayload) and enhanced JWT verification with additional session and address validations, plus refined error handling.
frontend/src/app/api/home/route.ts, frontend/src/app/api/insights/route.ts, frontend/src/app/api/nonce/route.ts, frontend/src/app/api/tests/route.ts, frontend/src/app/api/user/me/route.ts, frontend/src/app/api/user/subscription/route.ts Added export constant dynamic = "force-dynamic" to enforce dynamic route behavior without altering functionality.
frontend/src/app/insights/page.tsx Reformatted string literals (single to double quotes) and reordered import statements for consistency.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API
    participant JWTService
    participant GeminiAPI

    Client->>API: POST /gemini-flash
    API->>Client: Retrieve session token from cookies
    API->>JWTService: jwtVerify(token)
    JWTService-->>API: Return payload (with optional address)
    alt Valid token with address
        API->>API: Validate request body and scores
        API->>GeminiAPI: Request analysis
        GeminiAPI-->>API: Analysis response
        API->>Client: Return analysis data
    else Missing/invalid address
        API->>Client: Return 401 Unauthorized ("Invalid session")
    end
Loading

Possibly related PRs

Suggested reviewers

  • evgongora

Poem

I'm a rabbit with a hop in my stride,
Code changes bounce in a joyful glide.
Dynamic routes now shine so bright,
JWT checks keep our sessions tight.
Hoppy commits make the repo feel light! 🐰✨

✨ 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.

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

netlify bot commented Feb 11, 2025

Deploy Preview for lucent-florentine-971919 ready!

Name Link
🔨 Latest commit f770c97
🔍 Latest deploy log https://app.netlify.com/sites/lucent-florentine-971919/deploys/67abd6879bab2d00082538a3
😎 Deploy Preview https://deploy-preview-144--lucent-florentine-971919.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

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)
frontend/src/app/api/gemini-flash/route.ts (1)

128-131: Consider moving API key validation to initialization.

The API key validation could be moved to the top of the file alongside JWT_SECRET validation for consistent environment variable handling.

 const JWT_SECRET = process.env.JWT_SECRET;
 if (!JWT_SECRET) {
   throw new Error("JWT_SECRET environment variable is required");
 }
+
+const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
+if (!GEMINI_API_KEY) {
+  throw new Error("GEMINI_API_KEY environment variable is required");
+}
 
 const secret = new TextEncoder().encode(JWT_SECRET);
frontend/src/app/api/public-figures/route.ts (2)

161-176: Consider optimizing celebrity matching logic.

The current implementation iterates through all celebrities to find the best match. For better performance with large datasets, consider:

  1. Using database-level sorting/filtering
  2. Implementing pagination
  3. Caching frequently accessed celebrities
-      let bestMatch = celebrities[0];
-      let bestSimilarity = calculateSimilarity(
-        userScores,
-        celebrities[0].scores as UserScores,
-      );
-
-      for (const celebrity of celebrities) {
-        const similarity = calculateSimilarity(
-          userScores,
-          celebrity.scores as UserScores,
-        );
-        if (similarity < bestSimilarity) {
-          bestSimilarity = similarity;
-          bestMatch = celebrity;
-        }
-      }
+      // Calculate similarities in parallel
+      const celebritiesWithSimilarity = await Promise.all(
+        celebrities.map(async (celebrity) => ({
+          celebrity,
+          similarity: calculateSimilarity(
+            userScores,
+            celebrity.scores as UserScores,
+          ),
+        }))
+      );
+
+      // Find the best match
+      const { celebrity: bestMatch } = celebritiesWithSimilarity.reduce(
+        (best, current) =>
+          current.similarity < best.similarity ? current : best,
+        celebritiesWithSimilarity[0]
+      );

195-197: Consider providing more specific error messages.

The catch blocks could provide more specific error messages to help with debugging:

-    } catch {
+    } catch (error) {
+      console.error('Session verification failed:', error);
       return NextResponse.json({ error: "Invalid session" }, { status: 401 });
     }

Also applies to: 280-282

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 06401e9 and f770c97.

📒 Files selected for processing (10)
  • frontend/src/app/api/confirm-payment/route.ts (1 hunks)
  • frontend/src/app/api/gemini-flash/route.ts (5 hunks)
  • frontend/src/app/api/home/route.ts (1 hunks)
  • frontend/src/app/api/insights/route.ts (1 hunks)
  • frontend/src/app/api/nonce/route.ts (1 hunks)
  • frontend/src/app/api/public-figures/route.ts (5 hunks)
  • frontend/src/app/api/tests/route.ts (1 hunks)
  • frontend/src/app/api/user/me/route.ts (1 hunks)
  • frontend/src/app/api/user/subscription/route.ts (1 hunks)
  • frontend/src/app/insights/page.tsx (12 hunks)
✅ Files skipped from review due to trivial changes (7)
  • frontend/src/app/api/nonce/route.ts
  • frontend/src/app/api/insights/route.ts
  • frontend/src/app/api/user/subscription/route.ts
  • frontend/src/app/api/tests/route.ts
  • frontend/src/app/insights/page.tsx
  • frontend/src/app/api/confirm-payment/route.ts
  • frontend/src/app/api/home/route.ts
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Bundle Analysis
  • GitHub Check: Code Quality & Build
🔇 Additional comments (4)
frontend/src/app/api/user/me/route.ts (1)

19-19: LGTM! Dynamic rendering configuration added.

The addition of dynamic = "force-dynamic" ensures that the route is always dynamically rendered, which is appropriate for an API endpoint that needs to return fresh user data on each request.

frontend/src/app/api/gemini-flash/route.ts (2)

29-31: LGTM! JWT authentication and environment validation added.

Good security practices:

  • JWT verification for authentication
  • Early validation of JWT_SECRET environment variable
  • Type-safe TokenPayload interface

Also applies to: 33-39


42-55: Verify session token validation in other routes.

The session validation logic has been implemented correctly here. For consistency, ensure similar validation is implemented across all authenticated routes.

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Search for routes that might need session validation
echo "Searching for API routes..."
fd --type f "route.ts" "frontend/src/app/api"

echo -e "\nChecking for session token validation..."
rg -l "cookies\(\).get\(\"session\"\)" "frontend/src/app/api"

Length of output: 2037


The shell script output shows that many API routes contain a check for cookies().get("session"), which indicates that the token validation mechanism (based on session cookies) is used in a number of endpoints. To further confirm that these routes implement complete validation (for example, performing the JWT verification similar to the gemini-flash route), I'll search for the use of jwtVerify() in the API routes. This will help us verify that not only is the session token being read but that it is also properly verified.


🏁 Script executed:

#!/bin/bash
# Search for jwtVerify usage in API routes to verify full validation logic exists
echo "Searching for jwtVerify usage in API routes..."
rg -l "jwtVerify(" frontend/src/app/api

Length of output: 215


I'll run a corrected script to search for jwtVerify usage with an escaped parenthesis.


🏁 Script executed:

#!/bin/bash
echo "Searching for jwtVerify usage in API routes..."
rg -l "jwtVerify\\(" frontend/src/app/api

Length of output: 830


Session Token Validation Consistency Verified

Our investigation shows that several authenticated API routes (e.g., confirm-payment, ideology, home, initiate-payment, etc.) use both cookies().get("session") and jwtVerify(...) similarly to the gemini‑flash route. This suggests that session token validation is implemented consistently across the endpoints.

frontend/src/app/api/public-figures/route.ts (1)

7-9: LGTM! Consistent authentication pattern.

The TokenPayload interface matches the one in gemini-flash route, maintaining consistency across the codebase.

@bitfalt bitfalt merged commit 5dc34ea into MindVault-Inc:main Feb 11, 2025
8 checks passed
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