Skip to content

feat(api): identify active membership in current user response - #12388

Merged
josema-xyz merged 2 commits into
masterfrom
feat/api-users-me-active-membership
Aug 7, 2026
Merged

josema-xyz merged 2 commits into
masterfrom
feat/api-users-me-active-membership

Conversation

@josema-xyz

@josema-xyz josema-xyz commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Context

The active tenant is part of the authentication context, but GET /api/v1/users/me returned all membership identifiers without indicating which membership matched that tenant. API clients, especially those using API keys, could not determine the active membership from the response.

Description

  • Add meta.active to each membership resource identifier returned by GET /api/v1/users/me
  • Set active by comparing the membership tenant with request.tenant_id
  • Support both JWT and API key authentication
  • Keep other user endpoints unchanged through an action-specific serializer
  • Update the existing multi-tenant API key integration test

Example relationship output:

{
  "memberships": {
    "data": [
      {
        "type": "memberships",
        "id": "membership-1",
        "meta": {
          "active": true
        }
      },
      {
        "type": "memberships",
        "id": "membership-2",
        "meta": {
          "active": false
        }
      }
    ],
    "meta": {
      "count": 2
    }
  }
}

Steps to review

  1. Authenticate with an API key for a user who belongs to multiple tenants.
  2. Request GET /api/v1/users/me.
  3. Confirm the membership associated with the API key tenant has meta.active: true.
  4. Confirm the other memberships have meta.active: false.
  5. Repeat with an API key for another tenant and confirm the active membership changes.
  6. Execute test suite.

Checklist

API

  • All issue/task requirements work as expected on the API
  • Endpoint response output (if applicable)
  • EXPLAIN ANALYZE output for new/modified queries or indexes (if applicable)
  • Performance test results (if applicable)
  • Any other relevant evidence of the implementation (if applicable)
  • Verify if API specs need to be regenerated.
  • Check if version updates are required (e.g., specs, uv, etc.).
  • Ensure a changelog fragment is added under api/changelog.d/, if applicable.

License

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

Summary by CodeRabbit

  • Bug Fixes

    • Corrected membership status reporting when accessing the API through different tenant API keys.
    • The membership for the current tenant is now marked active, while memberships for other tenants are marked inactive.
    • Updated the current-user endpoint to return accurate membership information for both API key and JWT authentication.
  • Documentation

    • Documented how to identify the active tenant membership in the current-user response.

@josema-xyz
josema-xyz requested review from a team and Copilot August 7, 2026 07:49
@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 65aa5756-cf64-4746-937b-d825fd663d42

📥 Commits

Reviewing files that changed from the base of the PR and between 302ddf5 and a3fdda4.

📒 Files selected for processing (1)
  • api/changelog.d/users-me-active-membership.changed.md

📝 Walkthrough

Walkthrough

The me endpoint now uses UserMeSerializer. Memberships include meta.active based on the request tenant. Integration coverage verifies the result for API keys from two tenants.

Changes

Tenant membership activity

Layer / File(s) Summary
Tenant-aware me serialization
api/src/backend/api/v1/serializers.py, api/src/backend/api/v1/views.py, api/changelog.d/users-me-active-membership.changed.md
UserMeSerializer uses ActiveMembershipRelatedField to add meta.active. UserViewSet selects this serializer for the me action and applies standard serializer context. The changelog documents the response metadata.
Multi-tenant authentication validation
api/src/backend/api/tests/integration/test_authentication.py
The test retains both membership records and verifies that each API key marks its tenant membership active and the other membership inactive.

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

Sequence Diagram(s)

sequenceDiagram
  participant APIClient
  participant UserViewSet
  participant UserMeSerializer
  participant ActiveMembershipRelatedField
  APIClient->>UserViewSet: Request the me action
  UserViewSet->>UserViewSet: Resolve UserMeSerializer
  UserViewSet->>UserMeSerializer: Serialize the current user
  UserMeSerializer->>ActiveMembershipRelatedField: Serialize memberships
  ActiveMembershipRelatedField-->>APIClient: Return memberships with meta.active
Loading

Suggested reviewers: adriiiprod

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main API change: identifying the active membership in the current user response.
Description check ✅ Passed The description explains the context, implementation, review steps, testing, API impact, and changelog update for the reported change.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 feat/api-users-me-active-membership

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.

@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

✅ All required changelog fragments are present.

@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

No Conflicts

No conflict markers, and the branch merges cleanly into its base.

Copilot AI 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.

Pull request overview

This PR updates the API’s GET /api/v1/users/me response so API clients can reliably determine which membership corresponds to the active tenant in the current authentication context, by annotating each returned membership resource identifier with meta.active.

Changes:

  • Introduces an action-specific UserMeSerializer that marks each membership relationship item with meta.active based on request.tenant_id.
  • Updates UserViewSet.me to use self.get_serializer(...) and routes the me action through the new serializer without affecting other user endpoints.
  • Extends the multi-tenant API key integration test to assert meta.active toggles correctly per tenant/API key.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.

File Description
api/src/backend/api/v1/views.py Selects an action-specific serializer for the me action and uses get_serializer() to ensure correct serializer/context usage.
api/src/backend/api/v1/serializers.py Adds a relationship field that injects meta.active into membership resource identifiers and a UserMeSerializer to scope the behavior to /users/me.
api/src/backend/api/tests/integration/test_authentication.py Updates the API key multi-tenant integration test to validate meta.active per membership for different tenant-bound API keys.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

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

🤖 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 `@api/src/backend/api/v1/serializers.py`:
- Around line 332-340: Update ActiveMembershipRelatedField.to_representation to
guard access to request.tenant_id before constructing representation["meta"];
when tenant context is absent, avoid raising AttributeError and preserve safe
relationship serialization, while retaining the existing active comparison when
tenant_id is available.
🪄 Autofix

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: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 5b825231-ffcf-42f9-a3f7-3d2abb921756

📥 Commits

Reviewing files that changed from the base of the PR and between fd555e2 and 302ddf5.

📒 Files selected for processing (3)
  • api/src/backend/api/tests/integration/test_authentication.py
  • api/src/backend/api/v1/serializers.py
  • api/src/backend/api/v1/views.py

Comment thread api/src/backend/api/v1/serializers.py
@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

🔒 Container Security Scan

Image: prowler-api:9de5f13
Last scan: 2026-08-07 08:23:54 UTC

✅ No Vulnerabilities Detected

The container image passed all security checks. No known CVEs were found.

📋 Resources:

@codecov

codecov Bot commented Aug 7, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.55%. Comparing base (cf558c5) to head (a3fdda4).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master   #12388   +/-   ##
=======================================
  Coverage   94.55%   94.55%           
=======================================
  Files         271      271           
  Lines       42211    42224   +13     
=======================================
+ Hits        39914    39927   +13     
  Misses       2297     2297           
Flag Coverage Δ
api 94.55% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Components Coverage Δ
prowler ∅ <ø> (∅)
api 94.55% <100.00%> (+<0.01%) ⬆️
mcp_server ∅ <ø> (∅)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

🔎 Container Security Scan (Grype)

Image: prowler-api:9de5f13
Last scan: 2026-08-07 08:24:49 UTC

✅ Nothing Blocking

No findings at critical or high severity.

Not blocking at this cutoff — medium: 20, low: 4, negligible: 1.

44 finding(s) excluded by .grype.yaml, each with a documented reason.


📋 Resources:

@josema-xyz
josema-xyz merged commit 3672b17 into master Aug 7, 2026
49 of 50 checks passed
@josema-xyz
josema-xyz deleted the feat/api-users-me-active-membership branch August 7, 2026 08:40
@josema-xyz
josema-xyz restored the feat/api-users-me-active-membership branch August 7, 2026 08:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants