Skip to content

Added user location, resorting to IP if it can't get the location#167

Merged
breadddevv merged 2 commits into
mainfrom
change/sessions
Jul 13, 2026
Merged

Added user location, resorting to IP if it can't get the location#167
breadddevv merged 2 commits into
mainfrom
change/sessions

Conversation

@breadddevv

@breadddevv breadddevv commented Jul 13, 2026

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Active sessions now display the session’s region and country when available.
    • Session records include location details derived from the connection.
    • Added foundational support for forms, submissions, reviews, comments, and audit history.
  • UI Improvements

    • Updated toast notifications with refined styling and clearer success/error colors.
    • Added another late-night greeting variation.
  • Bug Fixes

    • Active session locations fall back to IP address and relative session time when location data is unavailable.

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@breadddevv, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 39 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 4a380c07-fbd1-4899-894c-8ba86e5abb09

📥 Commits

Reviewing files that changed from the base of the PR and between 91f8cf7 and 382843d.

📒 Files selected for processing (1)
  • components/topbar.tsx
📝 Walkthrough

Walkthrough

Session creation now stores IP-derived region and country data, exposes it through active-session APIs, and displays it in the topbar. Database migrations add session fields and form-related tables. Toast styling, PostHog error suppression, and a late-night greeting are also updated.

Changes

Session location flow

Layer / File(s) Summary
Session location schema
prisma/migrations/..., prisma/schema.prisma, utils/database.ts
AuthSession adds optional region and country fields, with corresponding migrations and Prisma type exports.
Geolocation during session creation
utils/session.ts
Session creation retrieves country_name and region from ipapi.co and persists them; active-session queries select both fields.
Active session location display
pages/api/user/sessions/index.ts, components/topbar.tsx
The API returns location fields, and the topbar displays region, country or falls back to the IP address and relative creation time.

Form persistence schema

Layer / File(s) Summary
Form data tables
prisma/migrations/20260713091923_added_locations/migration.sql
The migration creates form, question, submission, answer, review, comment, and audit-log tables.
Form indexes and relations
prisma/migrations/20260713091923_added_locations/migration.sql
Indexes and foreign keys connect form records to workspaces, users, and related form entities.

Application behavior adjustments

Layer / File(s) Summary
Toast and analytics handling
pages/_app.tsx
Toaster receives custom styling and icon themes, while selected PostHog reset errors are suppressed.
Late-night greeting content
utils/randomText.ts
One message is added to the late-night greeting set.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant SessionCreation
  participant Ipapi
  participant Database
  participant SessionsAPI
  participant Topbar
  SessionCreation->>Ipapi: Request IP geolocation
  Ipapi-->>SessionCreation: Return country and region
  SessionCreation->>Database: Persist session location
  SessionsAPI->>Database: Query active sessions
  Database-->>SessionsAPI: Return session location
  SessionsAPI-->>Topbar: Return active sessions
  Topbar->>Topbar: Render location or IP fallback
Loading

Possibly related PRs

Suggested reviewers: brennanpeters, buddywinte, cloudysatrn, maxjrc

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title matches the main change: adding user location to sessions with IP fallback when location lookup fails.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch change/sessions

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
utils/session.ts (1)

117-137: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Unhandled external call to ipapi.co can block all logins.

The axios.get call has no try/catch and no timeout. If ipapi.co is down, rate-limited (free tier: 1,000 req/day), or slow, the rejection propagates and createSession fails — users cannot log in. Geolocation is supplementary; it should never be a hard dependency of session creation.

🔒 Proposed fix: wrap geolocation in try/catch with timeout
   const rawToken = generateToken();

-  const info = await axios.get<IpapiRes>('https://ipapi.co/json');
-
+  let country: string | undefined;
+  let region: string | undefined;
+  try {
+    const info = await axios.get<IpapiRes>('https://ipapi.co/json', {
+      timeout: 5000,
+    });
+    country = info.data.country_name;
+    region = info.data.region;
+  } catch {
+    // Geolocation is optional; fall back to IP address display
+  }
+
   const { browser, os, device } = parseUA(userAgent)

   const session = await prisma.authSession.create({
     data: {
       id: crypto.randomUUID(),
       token: hashToken(rawToken),
       userId,
       expiresAt: new Date(
         Date.now() + 7 * 24 * 60 * 60 * 1000
       ),
       ipAddress: encrypt(ipAddress),
       userAgent: encrypt(userAgent),
       browser,
       os,
       device,
-      country: info.data.country_name,
-      region: info.data.region
+      country,
+      region
     },
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@utils/session.ts` around lines 117 - 137, Update createSession around the
axios.get geolocation request to use a bounded timeout and catch failures from
ipapi.co. Treat geolocation as optional by falling back to unset country and
region values, then continue creating the Prisma auth session even when the
external request fails.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@components/topbar.tsx`:
- Line 351: Update the location display expression in the topbar session
rendering so it uses any available geolocation field, showing country and region
when both exist and the available field when only one exists; fall back to the
IP address only when neither country nor region is available.

In `@utils/session.ts`:
- Line 119: Update the axios request in createSession to query ipapi.co using
the received ipAddress rather than the server’s own location. If ipAddress is
absent, skip the geolocation lookup and preserve safe handling for country and
region values.

---

Outside diff comments:
In `@utils/session.ts`:
- Around line 117-137: Update createSession around the axios.get geolocation
request to use a bounded timeout and catch failures from ipapi.co. Treat
geolocation as optional by falling back to unset country and region values, then
continue creating the Prisma auth session even when the external request fails.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 99c07dee-8656-42c0-b75e-d8cd485963f3

📥 Commits

Reviewing files that changed from the base of the PR and between 66aa274 and 91f8cf7.

📒 Files selected for processing (9)
  • components/topbar.tsx
  • pages/_app.tsx
  • pages/api/user/sessions/index.ts
  • prisma/migrations/20260713091923_added_locations/migration.sql
  • prisma/migrations/20260713092345_changed_to_region/migration.sql
  • prisma/schema.prisma
  • utils/database.ts
  • utils/randomText.ts
  • utils/session.ts

Comment thread components/topbar.tsx Outdated
Comment thread utils/session.ts
const rawToken = generateToken()
const rawToken = generateToken();

const info = await axios.get<IpapiRes>('https://ipapi.co/json');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

git ls-files utils/session.ts

Repository: PlanetaryOrbit/orbit

Length of output: 175


🏁 Script executed:

ast-grep outline utils/session.ts --view expanded

Repository: PlanetaryOrbit/orbit

Length of output: 1099


🏁 Script executed:

cat -n utils/session.ts | sed -n '1,220p'

Repository: PlanetaryOrbit/orbit

Length of output: 6195


🏁 Script executed:

rg -n "createSession\(" -S .

Repository: PlanetaryOrbit/orbit

Length of output: 679


🏁 Script executed:

cat -n pages/api/auth/login.ts | sed -n '140,190p'

Repository: PlanetaryOrbit/orbit

Length of output: 2125


🏁 Script executed:

cat -n pages/api/auth/discord/callback.ts | sed -n '145,175p'

Repository: PlanetaryOrbit/orbit

Length of output: 1260


🏁 Script executed:

cat -n pages/api/auth/google/callback.ts | sed -n '155,185p'

Repository: PlanetaryOrbit/orbit

Length of output: 1150


🏁 Script executed:

cat -n pages/api/auth/roblox/callback.ts | sed -n '145,175p'

Repository: PlanetaryOrbit/orbit

Length of output: 1170


🏁 Script executed:

cat -n pages/api/auth/signup/finish.ts | sed -n '75,105p'

Repository: PlanetaryOrbit/orbit

Length of output: 1241


🏁 Script executed:

cat -n pages/api/setupworkspace.ts | sed -n '115,135p'

Repository: PlanetaryOrbit/orbit

Length of output: 1323


Use the request IP for the geolocation lookup
createSession already receives the client IP from its callers, but ipapi.co/json still geolocates the server. Pass ipAddress into the URL here (or skip the lookup when it’s missing) so country/region match the user instead of the datacenter.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@utils/session.ts` at line 119, Update the axios request in createSession to
query ipapi.co using the received ipAddress rather than the server’s own
location. If ipAddress is absent, skip the geolocation lookup and preserve safe
handling for country and region values.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@breadddevv breadddevv merged commit 3c674ae into main Jul 13, 2026
4 of 5 checks passed
@breadddevv breadddevv deleted the change/sessions branch July 13, 2026 16:49
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