Repository navigation
Refactor user REST API - #14334
Refactor user REST API#14334
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughConsolidates authentication and user-management REST endpoints to the /api/v1 base (e.g., Changes
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ 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. Comment |
4f0d413 to
23cc25e
Compare
There was a problem hiding this comment.
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 | 🟡 MinorUpdate the
github_configexample to the new callback path (and fix the missing comma).The
oauth2andoidcexamples were migrated to/api/v1/auth/oauth/<channel>/callback, butgithub_configstill documents the removed/v1/user/oauth/callback/<channel>endpoint. Sinceapi/apps/restful_apis/user_api.pynow exposes only the generic/auth/oauth/<channel>/callbackroute (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 | 🟡 MinorPOST endpoint still reads
The captcha endpoint was moved from
GET /forget/captchatoPOST /auth/password/forgot/captcha, but the handler still extractsrequest.args.get("email")(query string) instead of a JSON body, and the docstring still describes it asGET /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 fromImageCaptcha.generate()(it's a PNG by default). Considerimage/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 | 🔴 CriticalTwo critical bugs in
forget_reset_passwordprevent password resets and cause 500 errors:
Decryption runs before input validation. Lines 811–813 call
decrypt()andbase64.b64decode()before the presence check (if not all([...])at line 818) and the verification check (line 815). Missing passwords causedecrypt(None)to raise an uncaught exception, surfacing as a 500 instead of the intendedARGUMENT_ERROR400. This also wastes CPU/security overhead decrypting unverified requests.Wrong password form persisted. Line 830 calls
UserService.update_user_password(user.id, new_pwd_base64)withnew_pwd_base64—the raw output ofdecrypt(), which is base64-encoded plaintext. Theupdate_user_passwordmethod then hashes this base64 string. In contrast,setting_user(line 336) usesgenerate_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 ofnew_pwd_base64when callingupdate_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 | 🔴 CriticalFix f-string syntax for Python 3.10/3.11 compatibility.
Line 160 uses nested double quotes in an f-string, which causes
SyntaxErroron 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.urlis a substring match, so it will also match paths like/api/v1/users/me/models. Themethod == "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 likere.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.
resis reassigned from theResponseobject to the parsed JSON dict on line 158, which also changes its declared type annotation. The existingconftest.pypattern (lines 134-135) does the same thing, so this is consistent with surrounding code but consider naming the JSON dictres_jsonfor 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
📒 Files selected for processing (17)
api/apps/auth/README.mdapi/apps/restful_apis/user_api.pysdk/python/test/conftest.pytest/benchmark/README.mdtest/benchmark/auth.pytest/benchmark/cli.pytest/playwright/auth/test_register_success_optional.pytest/playwright/auth/test_register_then_login_flow.pytest/playwright/auth/test_sso_optional.pytest/playwright/conftest.pytest/playwright/helpers/model_providers.pytest/testcases/conftest.pytest/testcases/test_admin_api/test_user_api_key_management/test_delete_user_api_key.pytest/testcases/test_web_api/test_user_app/test_user_app_unit.pyweb/src/services/user-service.tsweb/src/utils/api.tsweb/src/utils/llm-util.ts
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
Refactor user REST API
Type of change