From 98481c7ea760297be41e09f0fe1f0e8c9042e544 Mon Sep 17 00:00:00 2001 From: sophie Date: Wed, 17 Jun 2026 16:07:12 +0800 Subject: [PATCH] =?UTF-8?q?fix(admin):=20=E4=BF=AE=E6=94=B9=E7=94=A8?= =?UTF-8?q?=E6=88=B7=E6=97=B6=EF=BC=8C=E5=8F=AA=E6=9C=89=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E4=BA=86=E5=AF=86=E7=A0=81=E6=89=8D=E5=90=8C=E6=AD=A5=E7=BB=99?= =?UTF-8?q?casdoor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/admin.py | 18 +++---- backend/app/api/user.py | 50 +++++------------- .../tests/test_admin_create_user_casdoor.py | 51 +++++++++---------- 3 files changed, 43 insertions(+), 76 deletions(-) diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py index 10d616c2..8b383bc3 100644 --- a/backend/app/api/admin.py +++ b/backend/app/api/admin.py @@ -596,11 +596,11 @@ def create_user(): @require_admin def update_user(id): """ - 管理端编辑用户:本地变更 commit 前先同步 Casdoor update-user / set-password。 - 核心逻辑:应用本地字段 → _sync_casdoor_update_user → commit;Casdoor 失败则 rollback。 + 管理端编辑用户:资料仅写本地库;仅改密时同步 Casdoor set-password。 + 核心逻辑:应用本地字段 →(有 new_password 时)_sync_casdoor_update_user → commit。 Request JSON: email, department, role, status, password 等;password 为空表示不改密 Returns: - { status: ok };Casdoor/唯一约束失败时抛出 AppError/ConflictError + { status: ok };Casdoor 改密/唯一约束失败时抛出 AppError/ConflictError """ from app.api import user as user_api user = db.session.get(User, id) @@ -611,8 +611,6 @@ def update_user(id): email = _empty_to_none(data.get('email')) if email is not None and (not _is_valid_email(email)): raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'}) - profile_field_keys = {'email', 'department', 'status', 'real_name', 'phone_number'} - sync_profile = any(k in data for k in profile_field_keys) new_password = _empty_to_none(data.get('password')) for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']: if k in data: @@ -626,12 +624,8 @@ def update_user(id): agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all() user.agents = agents try: - if sync_profile or new_password: - user_api._sync_casdoor_update_user( - user, - new_password=new_password, - sync_profile=sync_profile, - ) + if new_password: + user_api._sync_casdoor_update_user(user, new_password=new_password) db.session.commit() except IntegrityError as e: db.session.rollback() @@ -641,7 +635,7 @@ def update_user(id): raise except RuntimeError as e: db.session.rollback() - user_api._raise_casdoor_update_user_error(e) + user_api._raise_casdoor_set_password_error(e) return jsonify({'status': 'ok'}) @admin_bp.route('/users/cleanup-rejected', methods=['POST']) diff --git a/backend/app/api/user.py b/backend/app/api/user.py index cf1a39a5..2e93d97a 100644 --- a/backend/app/api/user.py +++ b/backend/app/api/user.py @@ -463,22 +463,19 @@ def _sync_casdoor_admin_set_password(user: User, new_password: str): _raise_casdoor_user_not_in_idp(exc) _raise_casdoor_set_password_error(exc) -def _sync_casdoor_update_user(user: User, *, new_password: str | None = None, sync_profile: bool = True): +def _sync_casdoor_update_user(user: User, *, new_password: str | None = None): """ - 管理端编辑用户时同步 Casdoor:资料走 update-user,密码走 set-password(管理员 override)。 - 核心逻辑:Casdoor 已配置则必须成功;IdP 无账号且请求含新密码时 fallback add-user 补建。 + 管理端编辑用户时同步 Casdoor:仅改密时 set-password;IdP 无账号则 add-user 补建。 + 核心逻辑:资料字段只写本地库,不调用 update-user;无新密码则跳过 Casdoor。 @param user: 已应用本地变更但未 commit 的 User 实例 @param new_password: 管理员设置的新密码;None 表示不改密 - @param sync_profile: 是否同步资料字段(email/姓名/手机/部门/状态) Raises: - AppError / ConflictError: Casdoor 同步失败 + AppError / ConflictError: Casdoor 改密或补建失败 """ - if not _is_casdoor_configured(): + if not _is_casdoor_configured() or not new_password: return def _provision_missing_user_in_casdoor(): - if not new_password: - _raise_casdoor_user_not_in_idp() _sync_casdoor_create_user( username=user.username, password=new_password, @@ -489,36 +486,13 @@ def _sync_casdoor_update_user(user: User, *, new_password: str | None = None, sy department=user.department, ) - if sync_profile: - profile_payload = _build_casdoor_user_profile_payload( - username=user.username, - email=user.email, - real_name=user.real_name, - phone_number=user.phone_number, - status=user.status, - department=user.department, - ) - try: - _casdoor_update_user(profile_payload) - except AppError as exc: - if exc.code == 'CASDOOR_USER_NOT_IN_IDP': - _provision_missing_user_in_casdoor() - return - raise - except RuntimeError as exc: - if _is_casdoor_user_missing_error(str(exc)): - _provision_missing_user_in_casdoor() - return - _raise_casdoor_update_user_error(exc) - - if new_password: - try: - _sync_casdoor_admin_set_password(user, new_password) - except AppError as exc: - if exc.code == 'CASDOOR_USER_NOT_IN_IDP': - _provision_missing_user_in_casdoor() - return - raise + try: + _sync_casdoor_admin_set_password(user, new_password) + except AppError as exc: + if exc.code == 'CASDOOR_USER_NOT_IN_IDP': + _provision_missing_user_in_casdoor() + return + raise def _is_casdoor_password_error(message: str) -> bool: lowered = (message or '').lower() diff --git a/backend/tests/test_admin_create_user_casdoor.py b/backend/tests/test_admin_create_user_casdoor.py index febb5a3b..8682eede 100644 --- a/backend/tests/test_admin_create_user_casdoor.py +++ b/backend/tests/test_admin_create_user_casdoor.py @@ -137,9 +137,9 @@ def _create_local_user(username: str, email: str) -> User: return user -def test_admin_update_user_syncs_casdoor_profile(client, admin_headers, monkeypatch): +def test_admin_update_user_skips_casdoor_profile_sync(client, admin_headers, monkeypatch): """ - 编辑资料时应调用 update-user,且本地库成功更新。 + 编辑资料时不应调用 Casdoor update-user,仅更新本地库。 """ user = _create_local_user('edit_profile', 'edit_profile@example.com') client.application.config['CASDOOR_BASE_URL'] = 'http://casdoor.test' @@ -147,13 +147,16 @@ def test_admin_update_user_syncs_casdoor_profile(client, admin_headers, monkeypa client.application.config['CASDOOR_CLIENT_SECRET'] = 'client-secret' client.application.config['CASDOOR_ORGANIZATION'] = 'organization_HX' - casdoor_calls = {'update_user': 0, 'payload': None} + casdoor_calls = {'update_user': 0, 'set_password': 0} - def fake_update_user(payload): + def fake_update_user(_payload): casdoor_calls['update_user'] += 1 - casdoor_calls['payload'] = payload + + def fake_set_password(*_args, **_kwargs): + casdoor_calls['set_password'] += 1 monkeypatch.setattr(user_api, '_casdoor_update_user', fake_update_user) + monkeypatch.setattr(user_api, '_casdoor_set_password', fake_set_password) res = client.put( f'/api/admin/users/{user.id}', @@ -161,11 +164,7 @@ def test_admin_update_user_syncs_casdoor_profile(client, admin_headers, monkeypa headers=admin_headers, ) assert res.status_code == 200 - assert casdoor_calls['update_user'] == 1 - assert casdoor_calls['payload']['name'] == 'edit_profile' - assert casdoor_calls['payload']['email'] == 'updated@example.com' - assert casdoor_calls['payload']['displayName'] == 'Updated Name' - assert casdoor_calls['payload']['phone'] == '13800002222' + assert casdoor_calls == {'update_user': 0, 'set_password': 0} db.session.refresh(user) assert user.email == 'updated@example.com' @@ -201,9 +200,9 @@ def test_admin_update_user_syncs_casdoor_password(client, admin_headers, monkeyp assert user.check_password('new-admin-password') -def test_admin_update_user_rolls_back_when_casdoor_fails(client, admin_headers, monkeypatch): +def test_admin_update_user_rolls_back_when_casdoor_password_fails(client, admin_headers, monkeypatch): """ - Casdoor 更新失败时不应保留本地变更。 + Casdoor 改密失败时不应保留本地变更。 """ user = _create_local_user('rollback_edit', 'rollback_edit@example.com') client.application.config['CASDOOR_BASE_URL'] = 'http://casdoor.test' @@ -211,28 +210,28 @@ def test_admin_update_user_rolls_back_when_casdoor_fails(client, admin_headers, client.application.config['CASDOOR_CLIENT_SECRET'] = 'client-secret' client.application.config['CASDOOR_ORGANIZATION'] = 'organization_HX' - def fake_update_user(_payload): + def fake_set_password(_owner, _name, _old, _new): raise user_api.AppError( - code='CASDOOR_UPDATE_USER_FAILED', - message='Failed to update user in authentication system.', + code='CASDOOR_SET_PASSWORD_FAILED', + message='Failed to update password in authentication system.', http_status=502, ) - monkeypatch.setattr(user_api, '_casdoor_update_user', fake_update_user) + monkeypatch.setattr(user_api, '_casdoor_set_password', fake_set_password) res = client.put( f'/api/admin/users/{user.id}', - json={'email': 'should-not-save@example.com'}, + json={'password': 'should-not-save'}, headers=admin_headers, ) assert res.status_code == 502 db.session.refresh(user) - assert user.email == 'rollback_edit@example.com' + assert user.check_password('old-password') def test_admin_update_user_provisions_missing_casdoor_user_with_password(client, admin_headers, monkeypatch): """ - IdP 无账号且管理员同时提供新密码时,应 fallback 至 add-user 补建。 + IdP 无账号且管理员改密时,应 set-password 失败后 fallback 至 add-user,不调用 update-user。 """ user = _create_local_user('legacy_user', 'legacy_user@example.com') client.application.config['CASDOOR_BASE_URL'] = 'http://casdoor.test' @@ -240,21 +239,21 @@ def test_admin_update_user_provisions_missing_casdoor_user_with_password(client, client.application.config['CASDOOR_CLIENT_SECRET'] = 'client-secret' client.application.config['CASDOOR_ORGANIZATION'] = 'organization_HX' - casdoor_calls = {'update_user': 0, 'add_user': 0} + casdoor_calls = {'update_user': 0, 'add_user': 0, 'set_password': 0} def fake_update_user(_payload): casdoor_calls['update_user'] += 1 - raise user_api.AppError( - code='CASDOOR_USER_NOT_IN_IDP', - message='Your account has not been registered in the authentication system.', - http_status=409, - ) def fake_add_user(_payload): casdoor_calls['add_user'] += 1 + def fake_set_password(_owner, _name, _old, _new): + casdoor_calls['set_password'] += 1 + raise RuntimeError("Casdoor set-password failed: {'status': 'error', 'msg': \"The user: organization_HX/legacy_user doesn't exist\"}") + monkeypatch.setattr(user_api, '_casdoor_update_user', fake_update_user) monkeypatch.setattr(user_api, '_casdoor_add_user', fake_add_user) + monkeypatch.setattr(user_api, '_casdoor_set_password', fake_set_password) res = client.put( f'/api/admin/users/{user.id}', @@ -262,7 +261,7 @@ def test_admin_update_user_provisions_missing_casdoor_user_with_password(client, headers=admin_headers, ) assert res.status_code == 200 - assert casdoor_calls == {'update_user': 1, 'add_user': 1} + assert casdoor_calls == {'update_user': 0, 'add_user': 1, 'set_password': 1} db.session.refresh(user) assert user.real_name == 'Legacy Updated'