Skip to content

Refactor user REST API - #14334

Merged
wangq8 merged 2 commits into
infiniflow:mainfrom
wangq8:refactor/api-user
Apr 24, 2026
Merged

wangq8 merged 2 commits into
infiniflow:mainfrom
wangq8:refactor/api-user

Conversation

@wangq8

@wangq8 wangq8 commented Apr 23, 2026 •

Copy link
Copy Markdown
Collaborator

What problem does this PR solve?

Refactor user REST API

Type of change

  • Refactoring

@coderabbitai

coderabbitai Bot commented Apr 23, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2389bf5e-9e7f-4876-b902-995144cc28ce

📥 Commits

Reviewing files that changed from the base of the PR and between 23cc25e and 911fcd8.

📒 Files selected for processing (1)
  • api/apps/restful_apis/user_api.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/apps/restful_apis/user_api.py

📝 Walkthrough

Walkthrough

Consolidates authentication and user-management REST endpoints to the /api/v1 base (e.g., /api/v1/auth/..., /api/v1/users/...), adjusts HTTP methods (logout → POST, tenant updates → PATCH), updates frontend/test callers, and removes GitHub/Feishu-specific OAuth callback handlers and related tests/docs.

Changes

Cohort / File(s) Summary
Backend docs & auth README
api/apps/auth/README.md
Updated OAuth/OIDC redirect_uri examples to /api/v1/auth/oauth/<channel>/callback.
Backend API routes
api/apps/restful_apis/user_api.py
Rebound many routes to /auth/... and /users/..., moved OAuth callback paths, removed GitHub/Feishu callback handlers and their helper functions, removed unused imports.
Frontend API mappings & services
web/src/utils/api.ts, web/src/services/user-service.ts, web/src/utils/llm-util.ts
Switched endpoints to /api/v1 paths; changed logout to POST and tenant endpoints (setting/setTenantInfo) to PATCH; updated tenant-param whitelist to /api/v1/users/me/models.
Python SDK / Test fixtures
sdk/python/test/conftest.py, test/testcases/conftest.py, test/playwright/conftest.py
Redirected test fixtures to new endpoints (POST /api/v1/users, POST /api/v1/auth/login, GET/PATCH /api/v1/users/me/models) and adjusted HTTP methods to PATCH where applicable.
Playwright tests & helpers
test/playwright/helpers/model_providers.py, test/playwright/auth/test_register_success_optional.py, test/playwright/auth/test_register_then_login_flow.py, test/playwright/auth/test_sso_optional.py
Updated request-matching/response-capture conditions to new URLs and methods for registration, login, SSO initiation, and tenant model updates.
Unit & integration tests
test/testcases/test_web_api/test_user_app/test_user_app_unit.py, test/testcases/test_admin_api/.../test_delete_user_api_key.py
Repointed registration in tests; removed extensive unit tests covering GitHub/Feishu OAuth flows and their helpers.
Benchmark tooling
test/benchmark/README.md, test/benchmark/auth.py, test/benchmark/cli.py
Updated benchmark CLI docs and auth benchmark calls to use /users, /auth/login, and /users/me/models (GET/PATCH) with API base selection.

Sequence Diagram(s)

sequenceDiagram
    participant UserAgent as User (Browser/Test)
    participant Frontend as Frontend
    participant API as API (/api/v1)
    participant AuthHandler as user_api / auth handlers
    participant DB as User DB

    UserAgent->>Frontend: Submit registration (POST /api/v1/users)
    Frontend->>API: Forward POST /api/v1/users
    API->>AuthHandler: Create user / validate
    AuthHandler->>DB: Insert user record
    DB-->>AuthHandler: Created user
    AuthHandler-->>API: 201 Created
    API-->>Frontend: 201 Created (response)
    Frontend-->>UserAgent: Show success / proceed to login
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

☯️ refactor, 🐖api, 🧪 test

Suggested reviewers

  • yingfeng
  • yuzhichang
  • yongtenglei

Poem

🐰 New paths I hop along the trail,
/auth and /users tell a tidy tale,
Callbacks pruned, tests retune the song,
API V1 marches steady and strong,
Hoppity-hop — the rabbit cheers, all day long! 🥕

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description matches the template structure with 'What problem does this PR solve?' section and 'Type of change' checkbox selection, but the problem description is minimal and merely repeats the title without substantive context. Expand the 'What problem does this PR solve?' section to explain the rationale for the refactoring, such as the benefits of the new endpoint structure or architectural improvements. Provide context to help reviewers understand the scope and impact of API changes.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Refactor user REST API' accurately summarizes the main change in the changeset, which involves a comprehensive refactoring of user authentication and related REST API endpoints across the codebase.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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 and usage tips.

@wangq8
wangq8 force-pushed the refactor/api-user branch from 4f0d413 to 23cc25e Compare April 23, 2026 12:54
@wangq8 wangq8 added the ci Continue Integration label Apr 23, 2026
@wangq8
wangq8 marked this pull request as ready for review April 23, 2026 12:56
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 23, 2026

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

Caution

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

⚠️ Outside diff range comments (4)
api/apps/auth/README.md (1)

36-41: ⚠️ Potential issue | 🟡 Minor

Update the github_config example to the new callback path (and fix the missing comma).

The oauth2 and oidc examples were migrated to /api/v1/auth/oauth/<channel>/callback, but github_config still documents the removed /v1/user/oauth/callback/<channel> endpoint. Since api/apps/restful_apis/user_api.py now exposes only the generic /auth/oauth/<channel>/callback route (the dedicated GitHub/Feishu callbacks were removed), this example will mislead integrators.

Also, line 38 is missing a trailing comma after "type": "github", which makes the snippet invalid Python.

📝 Proposed fix
 # Github OAuth configuration
 github_config = {
-    "type": "github"
+    "type": "github",
     "client_id": "your_client_id",
     "client_secret": "your_client_secret",
-    "redirect_uri": "https://your-app.com/v1/user/oauth/callback/<channel>"
+    "redirect_uri": "https://your-app.com/api/v1/auth/oauth/<channel>/callback"
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/auth/README.md` around lines 36 - 41, The github_config example is
outdated and has a syntax error: add the missing comma after the "type":
"github" entry and update the redirect_uri to the new callback path used by the
app; specifically change the redirect_uri value from
"https://your-app.com/v1/user/oauth/callback/<channel>" to
"https://your-app.com/api/v1/auth/oauth/<channel>/callback" in the github_config
example so it matches the route exposed by user_api.py and fix the
trailing-comma omission.
api/apps/restful_apis/user_api.py (2)

635-660: ⚠️ Potential issue | 🟡 Minor

POST endpoint still reads email from query string; docstring is stale.

The captcha endpoint was moved from GET /forget/captcha to POST /auth/password/forgot/captcha, but the handler still extracts email via request.args.get("email") (query string) instead of a JSON body, and the docstring still describes it as GET /forget/captcha?email=<email>. Clients migrating to the new path will likely send the email in the body and this endpoint will reject them with "email is required".

📝 Suggested fix
-    """
-    GET /forget/captcha?email=<email>
-    - Generate an image captcha and cache it in Redis under key captcha:{email} with TTL = OTP_TTL_SECONDS.
-    - Returns the captcha as a PNG image.
-    """
-    email = (request.args.get("email") or "")
+    """
+    POST /auth/password/forgot/captcha
+    - Body: {"email": "<email>"}
+    - Generate an image captcha and cache it in Redis under key captcha:{email} with TTL = OTP_TTL_SECONDS.
+    - Returns the captcha as a PNG image.
+    """
+    req = await get_request_json() or {}
+    email = (req.get("email") or "").strip()

Also worth noting: response.headers.set("Content-Type", "image/JPEG") on L659 is inconsistent with the actual PNG output from ImageCaptcha.generate() (it's a PNG by default). Consider image/png.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/user_api.py` around lines 635 - 660, The handler
forget_get_captcha is still reading email from the query string and has a stale
GET docstring and wrong Content-Type/TTL; change it to read the email from the
POST body (use request.get_json(silent=True) or request.json and fall back to
request.form if needed), update the docstring to reflect POST
/auth/password/forgot/captcha, store the captcha in Redis using the
OTP_TTL_SECONDS constant instead of hardcoded 60 via
REDIS_CONN.set(captcha_key(email), captcha_text, OTP_TTL_SECONDS), and set the
response Content-Type to image/png because ImageCaptcha.generate() returns PNG
by default. Ensure you still validate email and user existence using
UserService.query(email=email) as currently implemented.

805-833: ⚠️ Potential issue | 🔴 Critical

Two critical bugs in forget_reset_password prevent password resets and cause 500 errors:

  1. Decryption runs before input validation. Lines 811–813 call decrypt() and base64.b64decode() before the presence check (if not all([...]) at line 818) and the verification check (line 815). Missing passwords cause decrypt(None) to raise an uncaught exception, surfacing as a 500 instead of the intended ARGUMENT_ERROR 400. This also wastes CPU/security overhead decrypting unverified requests.

  2. Wrong password form persisted. Line 830 calls UserService.update_user_password(user.id, new_pwd_base64) with new_pwd_base64—the raw output of decrypt(), which is base64-encoded plaintext. The update_user_password method then hashes this base64 string. In contrast, setting_user (line 336) uses generate_password_hash(decrypt(new_password)) directly on the plaintext. Users cannot log in after password reset: the stored hash is of a base64 string, but login attempts hash plaintext.

Fix: Reorder checks (validate presence and verification before decryption); use the plaintext new_pwd_string (already decoded at line 812) instead of new_pwd_base64 when calling update_user_password().

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/user_api.py` around lines 805 - 833, In
forget_reset_password reorder logic so you validate inputs and email
verification before calling decrypt/base64.b64decode: check that email,
new_password and confirm_new_password are present (and that
REDIS_CONN.get(_verified_key(email)) is truthy) then perform decrypt() +
base64.b64decode() to produce new_pwd_string/new_pwd2_string; finally, when
calling UserService.update_user_password(user.id, ...), pass the plaintext
new_pwd_string (matching how setting_user uses
generate_password_hash(decrypt(new_password))) instead of the raw new_pwd_base64
to avoid storing the wrong hashed value and prevent decrypt(None) causing 500s.
test/testcases/test_admin_api/test_user_api_key_management/test_delete_user_api_key.py (1)

160-160: ⚠️ Potential issue | 🔴 Critical

Fix f-string syntax for Python 3.10/3.11 compatibility.

Line 160 uses nested double quotes in an f-string, which causes SyntaxError on Python 3.10 and 3.11. PEP 701 (Python 3.12+) allows this; earlier versions require different quote styles inside nested expressions.

Fix
-            raise Exception(f"Failed to create second user: {res.get("message")}")
+            raise Exception(f"Failed to create second user: {res.get('message')}")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@test/testcases/test_admin_api/test_user_api_key_management/test_delete_user_api_key.py`
at line 160, The f-string in the exception uses nested double quotes and breaks
on Python 3.10/3.11; update the expression to use single quotes or escape the
inner quotes—e.g., change raise Exception(f"Failed to create second user:
{res.get('message')}") (or otherwise escape the inner quotes) so the f-string is
valid across Python versions; locate the raise Exception line that references
res.get("message") in test_delete_user_api_key.py and make this change.
🧹 Nitpick comments (2)
test/playwright/auth/test_register_then_login_flow.py (1)

174-175: Consider a more precise URL match.

"/api/v1/users" in resp.url is a substring match, so it will also match paths like /api/v1/users/me/models. The method == "POST" constraint filters most out since tenant/profile updates use PATCH/GET, but if any future POST is added under /api/v1/users/... this capture could bind to the wrong response. Consider an endswith/regex check like re.search(r"/api/v1/users/?(\?|$)", resp.url) for robustness.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/playwright/auth/test_register_then_login_flow.py` around lines 174 -
175, The current response predicate used in the lambda (lambda resp:
resp.request.method == "POST" and "/api/v1/users" in resp.url) uses a substring
match that can falsely match longer paths; change the predicate to a precise URL
match (e.g., use re.search(r"/api/v1/users/?(\\?|$)", resp.url) or
resp.url.endswith("/api/v1/users") with optional query handling) and import re
if needed so the wait_for_response/wait_for_request call only matches exact POST
requests to the users endpoint.
test/testcases/test_admin_api/test_user_api_key_management/test_delete_user_api_key.py (1)

154-158: Minor: variable reassignment shadowing.

res is reassigned from the Response object to the parsed JSON dict on line 158, which also changes its declared type annotation. The existing conftest.py pattern (lines 134-135) does the same thing, so this is consistent with surrounding code but consider naming the JSON dict res_json for readability.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@test/testcases/test_admin_api/test_user_api_key_management/test_delete_user_api_key.py`
around lines 154 - 158, The test reassigns the name res from the
requests.Response to the parsed JSON dict which causes shadowing and confusing
type annotations; change the second variable to a new name (e.g., res_json) and
update its type annotation to dict[str, Any], then replace subsequent uses of
the parsed response to reference res_json instead of res to preserve the
original Response object returned by requests.post and improve readability (look
for the requests.post(...) call and the subsequent res = res.json() assignment).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@api/apps/auth/README.md`:
- Around line 36-41: The github_config example is outdated and has a syntax
error: add the missing comma after the "type": "github" entry and update the
redirect_uri to the new callback path used by the app; specifically change the
redirect_uri value from "https://your-app.com/v1/user/oauth/callback/<channel>"
to "https://your-app.com/api/v1/auth/oauth/<channel>/callback" in the
github_config example so it matches the route exposed by user_api.py and fix the
trailing-comma omission.

In `@api/apps/restful_apis/user_api.py`:
- Around line 635-660: The handler forget_get_captcha is still reading email
from the query string and has a stale GET docstring and wrong Content-Type/TTL;
change it to read the email from the POST body (use
request.get_json(silent=True) or request.json and fall back to request.form if
needed), update the docstring to reflect POST /auth/password/forgot/captcha,
store the captcha in Redis using the OTP_TTL_SECONDS constant instead of
hardcoded 60 via REDIS_CONN.set(captcha_key(email), captcha_text,
OTP_TTL_SECONDS), and set the response Content-Type to image/png because
ImageCaptcha.generate() returns PNG by default. Ensure you still validate email
and user existence using UserService.query(email=email) as currently
implemented.
- Around line 805-833: In forget_reset_password reorder logic so you validate
inputs and email verification before calling decrypt/base64.b64decode: check
that email, new_password and confirm_new_password are present (and that
REDIS_CONN.get(_verified_key(email)) is truthy) then perform decrypt() +
base64.b64decode() to produce new_pwd_string/new_pwd2_string; finally, when
calling UserService.update_user_password(user.id, ...), pass the plaintext
new_pwd_string (matching how setting_user uses
generate_password_hash(decrypt(new_password))) instead of the raw new_pwd_base64
to avoid storing the wrong hashed value and prevent decrypt(None) causing 500s.

In
`@test/testcases/test_admin_api/test_user_api_key_management/test_delete_user_api_key.py`:
- Line 160: The f-string in the exception uses nested double quotes and breaks
on Python 3.10/3.11; update the expression to use single quotes or escape the
inner quotes—e.g., change raise Exception(f"Failed to create second user:
{res.get('message')}") (or otherwise escape the inner quotes) so the f-string is
valid across Python versions; locate the raise Exception line that references
res.get("message") in test_delete_user_api_key.py and make this change.

---

Nitpick comments:
In `@test/playwright/auth/test_register_then_login_flow.py`:
- Around line 174-175: The current response predicate used in the lambda (lambda
resp: resp.request.method == "POST" and "/api/v1/users" in resp.url) uses a
substring match that can falsely match longer paths; change the predicate to a
precise URL match (e.g., use re.search(r"/api/v1/users/?(\\?|$)", resp.url) or
resp.url.endswith("/api/v1/users") with optional query handling) and import re
if needed so the wait_for_response/wait_for_request call only matches exact POST
requests to the users endpoint.

In
`@test/testcases/test_admin_api/test_user_api_key_management/test_delete_user_api_key.py`:
- Around line 154-158: The test reassigns the name res from the
requests.Response to the parsed JSON dict which causes shadowing and confusing
type annotations; change the second variable to a new name (e.g., res_json) and
update its type annotation to dict[str, Any], then replace subsequent uses of
the parsed response to reference res_json instead of res to preserve the
original Response object returned by requests.post and improve readability (look
for the requests.post(...) call and the subsequent res = res.json() assignment).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c68c0ff9-8f58-467a-8618-a83c34097095

📥 Commits

Reviewing files that changed from the base of the PR and between d84438f and 23cc25e.

📒 Files selected for processing (17)
  • api/apps/auth/README.md
  • api/apps/restful_apis/user_api.py
  • sdk/python/test/conftest.py
  • test/benchmark/README.md
  • test/benchmark/auth.py
  • test/benchmark/cli.py
  • test/playwright/auth/test_register_success_optional.py
  • test/playwright/auth/test_register_then_login_flow.py
  • test/playwright/auth/test_sso_optional.py
  • test/playwright/conftest.py
  • test/playwright/helpers/model_providers.py
  • test/testcases/conftest.py
  • test/testcases/test_admin_api/test_user_api_key_management/test_delete_user_api_key.py
  • test/testcases/test_web_api/test_user_app/test_user_app_unit.py
  • web/src/services/user-service.ts
  • web/src/utils/api.ts
  • web/src/utils/llm-util.ts

@codecov

codecov Bot commented Apr 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.97%. Comparing base (d4fa573) to head (911fcd8).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14334   +/-   ##
=======================================
  Coverage   95.97%   95.97%           
=======================================
  Files          10       10           
  Lines         695      695           
  Branches      111      111           
=======================================
  Hits          667      667           
  Misses         11       11           
  Partials       17       17           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

@wangq8
wangq8 merged commit 199fbce into infiniflow:main Apr 24, 2026
1 check passed
@wangq8 wangq8 mentioned this pull request Apr 24, 2026
1 task done
@coderabbitai coderabbitai Bot mentioned this pull request Apr 30, 2026
1 of 4 tasks
@coderabbitai coderabbitai Bot mentioned this pull request May 6, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant