diff --git a/.env.dev b/.env.dev index a34e7d96..724f402f 100644 --- a/.env.dev +++ b/.env.dev @@ -17,7 +17,7 @@ AUTH_LOGIN_MODE=password # 如果需要用户密码登录,修改该值为password #AUTH_LOGIN_MODE=casdoor -AUTH_JWT_ISSUER=http://192.168.100.192:8870 +AUTH_JWT_ISSUER=http://ait.well-trust.com:8872 AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4 AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks @@ -31,6 +31,7 @@ CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab # 本地开发常用;若用其它入口访问前端,请在 Casdoor 该应用的 Redirect URLs 中一并登记 CASDOOR_REDIRECT_URI=http://localhost:8881/casdoor-callback CASDOOR_SCOPE=openid profile email +CASDOOR_ORGANIZATION=organization_HX # Casdoor Providers → wecom(Name=wecom,与 prod 共用同一 Provider 即可) CASDOOR_WECOM_PROVIDER_HINT=wecom diff --git a/.env.prod b/.env.prod index 3eb08a6f..e1b581b3 100644 --- a/.env.prod +++ b/.env.prod @@ -22,7 +22,7 @@ AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4 AUTH_JWT_JWKS_URL=http://192.168.100.230:8870/.well-known/jwks # Casdoor -CASDOOR_BASE_URL=http://192.168.100.230:8870 +CASDOOR_BASE_URL=http://ai.well-trust.com:8870 # 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致 CASDOOR_CLIENT_ID=758be5fcba2df784fdb4 CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab @@ -31,6 +31,7 @@ CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab # http://ai.well-trust.com:8881/casdoor-callback CASDOOR_REDIRECT_URI=http://192.168.100.230:8881/casdoor-callback CASDOOR_SCOPE=openid profile email +CASDOOR_ORGANIZATION=organization_HX # Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo CASDOOR_WECOM_PROVIDER_HINT=wecom diff --git a/.env.test b/.env.test index d1d8bf4f..a0c664b9 100644 --- a/.env.test +++ b/.env.test @@ -17,7 +17,7 @@ AUTH_LOGIN_MODE=casdoor # 如果需要用户密码登录,修改该值为password #AUTH_LOGIN_MODE=casdoor -AUTH_JWT_ISSUER=http://192.168.100.192:8870 +AUTH_JWT_ISSUER=http://ait.well-trust.com:8872 AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4 AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks @@ -31,6 +31,7 @@ CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab # http://ai.well-trust.com:8881/casdoor-callback CASDOOR_REDIRECT_URI=http://192.168.100.192:8881/casdoor-callback CASDOOR_SCOPE=openid profile email +CASDOOR_ORGANIZATION=organization_HX # Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo CASDOOR_WECOM_PROVIDER_HINT=wecom diff --git a/backend/app/api/user.py b/backend/app/api/user.py index de7c7d76..298d0a0a 100644 --- a/backend/app/api/user.py +++ b/backend/app/api/user.py @@ -225,6 +225,78 @@ def _casdoor_password_login(username: str, password: str): raise RuntimeError(f'Casdoor password login failed: {data}') return data +def _is_casdoor_login_mode() -> bool: + return (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() == 'casdoor' + +def _is_casdoor_configured() -> bool: + if not _clean_str(current_app.config.get('CASDOOR_ORGANIZATION')): + return False + base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/') + client_id = current_app.config.get('CASDOOR_CLIENT_ID') or '' + client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or '' + return bool(base and client_id and client_secret) + +def _casdoor_user_owner() -> str: + owner = _clean_str(current_app.config.get('CASDOOR_ORGANIZATION')) + if not owner: + raise RuntimeError('CASDOOR_ORGANIZATION is not configured') + return owner + +def _verify_casdoor_password(username: str, password: str): + _casdoor_password_login(username, password) + +def _casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str): + base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/') + client_id = current_app.config.get('CASDOOR_CLIENT_ID') or '' + client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or '' + if not base or not client_id or not client_secret: + raise RuntimeError('Casdoor is not configured') + url = f'{base}/api/set-password' + resp = requests.post(url, files={'userOwner': (None, user_owner), 'userName': (None, user_name), 'oldPassword': (None, old_password), 'newPassword': (None, new_password)}, auth=(client_id, client_secret), timeout=8) + try: + data = resp.json() or {} + except ValueError: + raise RuntimeError(f'Casdoor set-password failed: HTTP {resp.status_code} {resp.text[:200]}') + if data.get('status') != 'ok': + raise RuntimeError(data.get('msg') or f'Casdoor set-password failed: {data}') + +def _is_casdoor_password_error(message: str) -> bool: + lowered = (message or '').lower() + return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered + +def _raise_incorrect_current_password(): + raise AppError( + code='AUTH.INCORRECT_CURRENT_PASSWORD', + message='Incorrect current password', + http_status=403, + ) + +def _verify_current_password_for_change(user, current_password: str): + if user.check_password(current_password): + return + if not _is_casdoor_configured(): + _raise_incorrect_current_password() + try: + _verify_casdoor_password(user.username, current_password) + except RuntimeError as e: + if _is_casdoor_password_error(str(e)): + _raise_incorrect_current_password() + raise + +def _sync_casdoor_password(username: str, current_password: str, new_password: str): + if not _is_casdoor_configured(): + return + user_owner = _casdoor_user_owner() + try: + _casdoor_set_password(user_owner, username, current_password, new_password) + except RuntimeError as first_error: + if _is_casdoor_password_error(str(first_error)): + _raise_incorrect_current_password() + try: + _casdoor_set_password(user_owner, username, '', new_password) + except RuntimeError: + raise first_error + def _cleanup_wecom_state_cache(): now = datetime.utcnow() expired = [k for k, v in _WECOM_STATE_CACHE.items() if not v or v < now] @@ -1362,7 +1434,10 @@ def user_profile(): @user_bp.route('/change-password', methods=['POST']) def change_password(): """ - Change password + Change password for the current user. + + Verify current password against local DB and/or Casdoor, then update both stores + to keep them in sync regardless of AUTH_LOGIN_MODE or login method. """ user = _get_current_user() if not user: @@ -1372,12 +1447,21 @@ def change_password(): new_password = data.get('new_password') if not current_password or not new_password: raise ValidationError('Current and new password are required') - if not user.check_password(current_password): - raise ForbiddenError('Incorrect current password') try: + _verify_current_password_for_change(user, current_password) + _sync_casdoor_password(user.username, current_password, new_password) user.set_password(new_password) db.session.commit() return jsonify({'message': 'Password changed successfully'}) + except AppError: + raise + except RuntimeError as e: + db.session.rollback() + message = str(e) + if _is_casdoor_password_error(message): + _raise_incorrect_current_password() + current_app.logger.exception('[change_password] Casdoor failed user=%s', user.username) + raise AppError(code='SYSTEM.HTTP_ERROR', message=f'Failed to change password: {message}', http_status=502, details={'error_code': 'CASDOOR_SET_PASSWORD_FAILED'}) except Exception as e: db.session.rollback() raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500) diff --git a/backend/app/config.py b/backend/app/config.py index f8a7137c..abeec2ce 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -139,6 +139,8 @@ class Config: # Casdoor Application must whitelist every origin users hit, e.g. IP and domain on port 8881. CASDOOR_REDIRECT_URI = os.getenv('CASDOOR_REDIRECT_URI') CASDOOR_SCOPE = os.getenv('CASDOOR_SCOPE') + # Casdoor organization (userOwner) for set-password and other management APIs. + CASDOOR_ORGANIZATION = (os.getenv('CASDOOR_ORGANIZATION') or 'organization_HX').strip() # WeCom as Casdoor IdP: provider Name from Casdoor Providers page (used with default_provider=wecom on authorize-url). CASDOOR_WECOM_PROVIDER_HINT = os.getenv('CASDOOR_WECOM_PROVIDER_HINT').strip() CASDOOR_WECOM_SILENT_SIGNIN = os.getenv('CASDOOR_WECOM_SILENT_SIGNIN', 'false').lower() == 'true' diff --git a/backend/tests/test_change_password.py b/backend/tests/test_change_password.py new file mode 100644 index 00000000..1fbc9b92 --- /dev/null +++ b/backend/tests/test_change_password.py @@ -0,0 +1,374 @@ +import pytest + +from app import create_app, db + +from app.models import User + +from app.api import user as user_api + + + + + +@pytest.fixture + +def client(): + + app = create_app('testing') + + app.config['AUTH_LOGIN_MODE'] = 'password' + + + + with app.test_client() as client: + + with app.app_context(): + + db.create_all() + + user = User(username='testuser', role='user', email='test@example.com') + + user.set_password('old-password') + + db.session.add(user) + + db.session.commit() + + yield client + + db.session.remove() + + db.drop_all() + + + + + +def _auth_headers(client): + + res = client.post('/api/user/login', json={'username': 'testuser', 'password': 'old-password'}) + + data = res.get_json() + + return { + + 'X-User-Id': str(data['id']), + + 'X-Username': data['username'], + + 'X-Role': data['role'], + + } + + + + + +def test_change_password_local_mode(client): + + headers = _auth_headers(client) + + res = client.post( + + '/api/user/change-password', + + headers=headers, + + json={'current_password': 'old-password', 'new_password': 'new-password'}, + + ) + + assert res.status_code == 200 + + + + user = db.session.query(User).filter_by(username='testuser').first() + + assert user.check_password('new-password') + + assert not user.check_password('old-password') + + + + + +def test_change_password_local_mode_syncs_casdoor(client, monkeypatch): + + client.application.config['CASDOOR_BASE_URL'] = 'http://casdoor.test' + + client.application.config['CASDOOR_CLIENT_ID'] = 'client-id' + + client.application.config['CASDOOR_CLIENT_SECRET'] = 'client-secret' + + client.application.config['CASDOOR_ORGANIZATION'] = 'organization_HX' + + casdoor_calls = {'set_password': 0} + + + + def fake_set_password(user_owner, user_name, old_password, new_password): + + casdoor_calls['set_password'] += 1 + + assert user_owner == 'organization_HX' + + assert user_name == 'testuser' + + assert old_password == 'old-password' + + assert new_password == 'new-password' + + + + monkeypatch.setattr(user_api, '_casdoor_set_password', fake_set_password) + + + + headers = _auth_headers(client) + + res = client.post( + + '/api/user/change-password', + + headers=headers, + + json={'current_password': 'old-password', 'new_password': 'new-password'}, + + ) + + assert res.status_code == 200 + + assert casdoor_calls == {'set_password': 1} + + + + + +def test_change_password_local_mode_wrong_current(client): + + headers = _auth_headers(client) + + res = client.post( + + '/api/user/change-password', + + headers=headers, + + json={'current_password': 'wrong-password', 'new_password': 'new-password'}, + + ) + + assert res.status_code == 403 + + + + + +def test_change_password_casdoor_mode(client, monkeypatch): + + client.application.config['AUTH_LOGIN_MODE'] = 'casdoor' + + client.application.config['CASDOOR_BASE_URL'] = 'http://casdoor.test' + + client.application.config['CASDOOR_CLIENT_ID'] = 'client-id' + + client.application.config['CASDOOR_CLIENT_SECRET'] = 'client-secret' + + client.application.config['CASDOOR_ORGANIZATION'] = 'organization_HX' + + casdoor_calls = {'set_password': 0} + + + + def fake_set_password(user_owner, user_name, old_password, new_password): + + casdoor_calls['set_password'] += 1 + + assert user_owner == 'organization_HX' + + assert user_name == 'testuser' + + assert old_password == 'old-password' + + assert new_password == 'new-password' + + + + monkeypatch.setattr(user_api, '_casdoor_set_password', fake_set_password) + + + + headers = _auth_headers(client) + + res = client.post( + + '/api/user/change-password', + + headers=headers, + + json={'current_password': 'old-password', 'new_password': 'new-password'}, + + ) + + assert res.status_code == 200 + + assert casdoor_calls == {'set_password': 1} + + + + user = db.session.query(User).filter_by(username='testuser').first() + + assert user.check_password('new-password') + + + + + +def test_change_password_accepts_casdoor_password_when_local_out_of_sync(client, monkeypatch): + + client.application.config['CASDOOR_BASE_URL'] = 'http://casdoor.test' + + client.application.config['CASDOOR_CLIENT_ID'] = 'client-id' + + client.application.config['CASDOOR_CLIENT_SECRET'] = 'client-secret' + + client.application.config['CASDOOR_ORGANIZATION'] = 'organization_HX' + + + + user = db.session.query(User).filter_by(username='testuser').first() + user.set_password('stale-local-password') + db.session.commit() + headers = { + 'X-User-Id': str(user.id), + 'X-Username': user.username, + 'X-Role': user.role, + } + + def fake_verify(username, password): + + assert username == 'testuser' + + assert password == 'casdoor-password' + + + + def fake_set_password(user_owner, user_name, old_password, new_password): + + assert old_password == 'casdoor-password' + + assert new_password == 'new-password' + + + + monkeypatch.setattr(user_api, '_verify_casdoor_password', fake_verify) + monkeypatch.setattr(user_api, '_casdoor_set_password', fake_set_password) + + res = client.post( + + '/api/user/change-password', + + headers=headers, + + json={'current_password': 'casdoor-password', 'new_password': 'new-password'}, + + ) + + assert res.status_code == 200 + + + + user = db.session.query(User).filter_by(username='testuser').first() + + assert user.check_password('new-password') + + + + + +def test_change_password_casdoor_mode_wrong_current(client, monkeypatch): + + client.application.config['AUTH_LOGIN_MODE'] = 'casdoor' + + client.application.config['CASDOOR_BASE_URL'] = 'http://casdoor.test' + + client.application.config['CASDOOR_CLIENT_ID'] = 'client-id' + + client.application.config['CASDOOR_CLIENT_SECRET'] = 'client-secret' + + client.application.config['CASDOOR_ORGANIZATION'] = 'organization_HX' + + + + def fake_verify(username, password): + + raise RuntimeError('Casdoor password login failed: invalid_grant') + + + + monkeypatch.setattr(user_api, '_verify_casdoor_password', fake_verify) + + + + headers = _auth_headers(client) + + res = client.post( + + '/api/user/change-password', + + headers=headers, + + json={'current_password': 'wrong-password', 'new_password': 'new-password'}, + + ) + + assert res.status_code == 403 + + + + + +def test_change_password_casdoor_admin_override_when_old_password_mismatch(client, monkeypatch): + + client.application.config['CASDOOR_BASE_URL'] = 'http://casdoor.test' + + client.application.config['CASDOOR_CLIENT_ID'] = 'client-id' + + client.application.config['CASDOOR_CLIENT_SECRET'] = 'client-secret' + + client.application.config['CASDOOR_ORGANIZATION'] = 'organization_HX' + + casdoor_calls = [] + + + + def fake_set_password(user_owner, user_name, old_password, new_password): + + casdoor_calls.append((old_password, new_password)) + + if old_password: + + raise RuntimeError('Casdoor set-password failed: old password is incorrect') + + + + monkeypatch.setattr(user_api, '_casdoor_set_password', fake_set_password) + + + + headers = _auth_headers(client) + + res = client.post( + + '/api/user/change-password', + + headers=headers, + + json={'current_password': 'old-password', 'new_password': 'new-password'}, + + ) + + assert res.status_code == 200 + + assert casdoor_calls == [('old-password', 'new-password'), ('', 'new-password')] + diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index 4ac01447..fa974603 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -64,6 +64,15 @@ function resolveLocalizedErrorMessage(code?: string, fallbackMessage?: string): if (normalizedCode === 'VALIDATION_INVALID_PARAM' && fallback && !isGenericFallback(fallback) && fallback !== localized) { return `${localized} ${fallback}`; } + if ( + normalizedCode === 'AUTH_FORBIDDEN' + && fallback + && !isGenericFallback(fallback) + && fallback.toLowerCase() !== 'forbidden' + && fallback !== localized + ) { + return fallback; + } return localized; } if (fallback) return fallback; diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts index bdaf6815..57426b50 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -157,6 +157,7 @@ const messages = { codes: { AUTH_UNAUTHORIZED: 'Please log in first.', AUTH_INCORRECT_PASSWORD: 'Incorrect password', + AUTH_INCORRECT_CURRENT_PASSWORD: 'Incorrect current password', AUTH_USER_NOT_FOUND: 'User not found', AUTH_ACCOUNT_DISABLED: 'Account is disabled', AUTH_FORBIDDEN: 'You do not have permission to perform this action.', @@ -1651,6 +1652,7 @@ const messages = { codes: { AUTH_UNAUTHORIZED: '请先登录。', AUTH_INCORRECT_PASSWORD: '密码错误', + AUTH_INCORRECT_CURRENT_PASSWORD: '当前密码不正确', AUTH_USER_NOT_FOUND: '用户不存在', AUTH_ACCOUNT_DISABLED: '账号已禁用', AUTH_FORBIDDEN: '你没有权限执行该操作。', @@ -3110,6 +3112,7 @@ const messages = { codes: { AUTH_UNAUTHORIZED: '請先登入。', AUTH_INCORRECT_PASSWORD: '密碼錯誤', + AUTH_INCORRECT_CURRENT_PASSWORD: '當前密碼不正確', AUTH_USER_NOT_FOUND: '用戶不存在', AUTH_ACCOUNT_DISABLED: '帳號已禁用', AUTH_FORBIDDEN: '你沒有權限執行此操作。', @@ -4443,6 +4446,7 @@ const messages = { codes: { AUTH_UNAUTHORIZED: 'กรุณาเข้าสู่ระบบก่อน', AUTH_INCORRECT_PASSWORD: 'รหัสผ่านไม่ถูกต้อง', + AUTH_INCORRECT_CURRENT_PASSWORD: 'รหัสผ่านปัจจุบันไม่ถูกต้อง', AUTH_USER_NOT_FOUND: 'ไม่พบผู้ใช้', AUTH_ACCOUNT_DISABLED: 'บัญชีถูกปิดใช้งาน', AUTH_FORBIDDEN: 'คุณไม่มีสิทธิ์ดำเนินการนี้', diff --git a/frontend/src/views/WorkspaceView.vue b/frontend/src/views/WorkspaceView.vue index cf54bd5d..042c9d07 100644 --- a/frontend/src/views/WorkspaceView.vue +++ b/frontend/src/views/WorkspaceView.vue @@ -746,8 +746,9 @@ const isProfileLoading = ref(false); const isProfileSaving = ref(false); const isProfileEditing = ref(false); const showPasswordModal = ref(false); + // TODO(casdoor): set true when Casdoor change-password is ready -const CHANGE_PASSWORD_ENABLED = false; +const CHANGE_PASSWORD_ENABLED = true; const handleChangePasswordClick = () => { if (!CHANGE_PASSWORD_ENABLED) { @@ -2302,7 +2303,7 @@ onBeforeUnmount(() => { - +