fix(addmin): 添加修改用户时同步到casdoor
This commit is contained in:
1 parent
7544361c05
commit
1eb6bf4aad
4 files changed
+573
-5
No files matched your search
@@ -1,8 +1,9 @@
|
||||
"""
|
||||
backend/app/api/admin.py
|
||||
文件用途:管理员相关 API 路由
|
||||
引用文件:flask, models, decorators
|
||||
逻辑关系:提供 Agent 配置管理、用户与权限管理接口,供前端 Admin 控制台使用
|
||||
|
||||
用途:管理员相关 API 路由(Agent、用户、权限、企业微信等)。
|
||||
依赖:flask、models、decorators、app.api.user(Casdoor 用户同步)。
|
||||
逻辑:供前端 Admin 控制台调用;创建/编辑用户时委托 user._sync_casdoor_* 与 IdP 保持同步。
|
||||
"""
|
||||
from flask import Blueprint, request, jsonify, current_app
|
||||
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit, AgentGuide
|
||||
@@ -463,6 +464,14 @@ def list_users():
|
||||
@admin_bp.route('/users', methods=['POST'])
|
||||
@require_admin
|
||||
def create_user():
|
||||
"""
|
||||
管理端创建用户:本地入库前先同步 Casdoor add-user,与改密一样保持 IdP 一致。
|
||||
核心逻辑:校验 → 构建 User → _sync_casdoor_create_user → commit;Casdoor 失败则 rollback。
|
||||
Request JSON: username, password, email, real_name, employee_id, phone_number 等
|
||||
Returns:
|
||||
201 + { id };Casdoor/唯一约束失败时抛出 AppError/ConflictError
|
||||
"""
|
||||
from app.api import user as user_api
|
||||
data = request.get_json() or {}
|
||||
required_field_errors = (
|
||||
('username', 'USER.USERNAME_REQUIRED', 'Username is required'),
|
||||
@@ -487,15 +496,38 @@ def create_user():
|
||||
user.agents = agents
|
||||
db.session.add(user)
|
||||
try:
|
||||
user_api._sync_casdoor_create_user(
|
||||
username=user.username,
|
||||
password=data['password'],
|
||||
email=email,
|
||||
real_name=user.real_name,
|
||||
phone_number=user.phone_number,
|
||||
status=user.status,
|
||||
department=user.department,
|
||||
)
|
||||
db.session.commit()
|
||||
except IntegrityError as e:
|
||||
db.session.rollback()
|
||||
_raise_user_integrity_conflict(e)
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except RuntimeError as e:
|
||||
db.session.rollback()
|
||||
user_api._raise_casdoor_add_user_error(e)
|
||||
return (jsonify({'id': user.id}), 201)
|
||||
|
||||
@admin_bp.route('/users/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_user(id):
|
||||
"""
|
||||
管理端编辑用户:本地变更 commit 前先同步 Casdoor update-user / set-password。
|
||||
核心逻辑:应用本地字段 → _sync_casdoor_update_user → commit;Casdoor 失败则 rollback。
|
||||
Request JSON: email, department, role, status, password 等;password 为空表示不改密
|
||||
Returns:
|
||||
{ status: ok };Casdoor/唯一约束失败时抛出 AppError/ConflictError
|
||||
"""
|
||||
from app.api import user as user_api
|
||||
user = db.session.get(User, id)
|
||||
if not user:
|
||||
raise NotFoundError('User not found')
|
||||
@@ -504,22 +536,37 @@ 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:
|
||||
if k in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||||
setattr(user, k, _empty_to_none(data[k]))
|
||||
else:
|
||||
setattr(user, k, data[k])
|
||||
if data.get('password'):
|
||||
user.set_password(data['password'])
|
||||
if new_password:
|
||||
user.set_password(new_password)
|
||||
if 'agent_ids' in data:
|
||||
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,
|
||||
)
|
||||
db.session.commit()
|
||||
except IntegrityError as e:
|
||||
db.session.rollback()
|
||||
_raise_user_integrity_conflict(e)
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except RuntimeError as e:
|
||||
db.session.rollback()
|
||||
user_api._raise_casdoor_update_user_error(e)
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
|
||||
|
||||
@@ -282,6 +282,244 @@ def _casdoor_set_password(user_owner: str, user_name: str, old_password: str, ne
|
||||
if data.get('status') != 'ok':
|
||||
_raise_casdoor_set_password_error(data)
|
||||
|
||||
def _is_casdoor_user_exists_error(message: str) -> bool:
|
||||
lowered = (message or '').lower()
|
||||
return 'already exist' in lowered or 'duplicate' in lowered or 'has existed' in lowered
|
||||
|
||||
def _raise_casdoor_add_user_error(source) -> None:
|
||||
"""
|
||||
将 Casdoor add-user 失败映射为稳定业务错误码,供管理端创建用户时展示。
|
||||
@param source: Casdoor JSON 响应、RuntimeError 文本或其它异常来源
|
||||
Raises:
|
||||
ConflictError: Casdoor 侧用户名/邮箱已存在
|
||||
AppError: 密码策略或 IdP 同步失败
|
||||
"""
|
||||
data = _extract_casdoor_error_payload(source)
|
||||
msg_text = _clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
|
||||
lowered = (msg_text or str(source or '')).lower()
|
||||
if _is_casdoor_user_exists_error(lowered):
|
||||
raise ConflictError('Username already exists in Casdoor', code='USER.USERNAME_EXISTS', details={'field': 'username', 'technical': msg_text})
|
||||
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
|
||||
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='Password does not meet security requirements', http_status=400)
|
||||
raise AppError(code='CASDOOR_ADD_USER_FAILED', message='Failed to create user in authentication system. Please try again or contact the administrator.', http_status=502, details={'technical': msg_text or str(source or '')[:300]})
|
||||
|
||||
def _build_casdoor_user_profile_payload(*, username: str, email: str, real_name=None, phone_number=None, status='active', department=None) -> dict:
|
||||
"""
|
||||
组装 Casdoor 用户资料字段(create/update 共用),不含 password。
|
||||
@param username: Casdoor name(与本地 username 一致)
|
||||
@param email: 邮箱
|
||||
@param real_name: 显示名/真实姓名
|
||||
@param phone_number: 手机号
|
||||
@param status: 本地账号状态;非 active 时 Casdoor 设为禁用
|
||||
@param department: 部门,映射至 affiliation
|
||||
Returns:
|
||||
Casdoor User JSON 对象(资料部分)
|
||||
"""
|
||||
display_name = _clean_str(real_name) or username
|
||||
payload = {
|
||||
'owner': _casdoor_user_owner(),
|
||||
'name': username,
|
||||
'email': email or '',
|
||||
'displayName': display_name,
|
||||
'realName': _clean_str(real_name) or '',
|
||||
'phone': _clean_str(phone_number) or '',
|
||||
'isForbidden': _clean_str(status) not in (None, 'active'),
|
||||
}
|
||||
department_value = _clean_str(department)
|
||||
if department_value:
|
||||
payload['affiliation'] = department_value
|
||||
return payload
|
||||
|
||||
def _build_casdoor_user_payload(*, username: str, password: str, email: str, real_name=None, phone_number=None, status='active', department=None) -> dict:
|
||||
"""
|
||||
组装 Casdoor add-user 请求体,字段与本地 User 模型对齐。
|
||||
@param username: Casdoor name(与本地 username 一致)
|
||||
@param password: 初始明文密码
|
||||
@param email: 邮箱
|
||||
@param real_name: 显示名/真实姓名
|
||||
@param phone_number: 手机号
|
||||
@param status: 本地账号状态;非 active 时 Casdoor 设为禁用
|
||||
@param department: 部门,映射至 affiliation
|
||||
Returns:
|
||||
Casdoor User JSON 对象
|
||||
"""
|
||||
payload = _build_casdoor_user_profile_payload(
|
||||
username=username,
|
||||
email=email,
|
||||
real_name=real_name,
|
||||
phone_number=phone_number,
|
||||
status=status,
|
||||
department=department,
|
||||
)
|
||||
payload['password'] = password
|
||||
return payload
|
||||
|
||||
def _casdoor_add_user(user_payload: dict):
|
||||
"""
|
||||
调用 Casdoor /api/add-user 创建 IdP 用户。
|
||||
核心逻辑:使用 Client ID/Secret Basic Auth,与 set-password 管理 API 一致。
|
||||
@param user_payload: Casdoor User 对象(owner/name/password 等)
|
||||
Raises:
|
||||
RuntimeError: HTTP 或配置异常
|
||||
AppError: Casdoor 返回业务错误(经 _raise_casdoor_add_user_error 映射)
|
||||
"""
|
||||
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/add-user'
|
||||
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
|
||||
try:
|
||||
data = resp.json() or {}
|
||||
except ValueError:
|
||||
raise RuntimeError(f'Casdoor add-user failed: HTTP {resp.status_code} {resp.text[:200]}')
|
||||
if data.get('status') != 'ok':
|
||||
_raise_casdoor_add_user_error(data)
|
||||
|
||||
def _sync_casdoor_create_user(*, username: str, password: str, email: str, real_name=None, phone_number=None, status='active', department=None):
|
||||
"""
|
||||
管理端创建用户时同步至 Casdoor,与改密逻辑一致:Casdoor 已配置则必须成功,否则跳过。
|
||||
核心逻辑:构建 add-user payload → 调 _casdoor_add_user;本地库 commit 由调用方负责。
|
||||
@param username: 本地 username,同步为 Casdoor name
|
||||
@param password: 初始明文密码
|
||||
@param email: 邮箱
|
||||
@param real_name: 真实姓名
|
||||
@param phone_number: 手机号
|
||||
@param status: 本地账号状态
|
||||
@param department: 部门
|
||||
Raises:
|
||||
AppError / ConflictError: Casdoor 创建失败
|
||||
"""
|
||||
if not _is_casdoor_configured():
|
||||
return
|
||||
payload = _build_casdoor_user_payload(
|
||||
username=username,
|
||||
password=password,
|
||||
email=email,
|
||||
real_name=real_name,
|
||||
phone_number=phone_number,
|
||||
status=status,
|
||||
department=department,
|
||||
)
|
||||
_casdoor_add_user(payload)
|
||||
|
||||
def _raise_casdoor_update_user_error(source) -> None:
|
||||
"""
|
||||
将 Casdoor update-user 失败映射为稳定业务错误码,供管理端编辑用户时展示。
|
||||
@param source: Casdoor JSON 响应、RuntimeError 文本或其它异常来源
|
||||
Raises:
|
||||
ConflictError: Casdoor 侧邮箱等唯一字段冲突
|
||||
AppError: IdP 同步失败
|
||||
"""
|
||||
data = _extract_casdoor_error_payload(source)
|
||||
msg_text = _clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
|
||||
lowered = (msg_text or str(source or '')).lower()
|
||||
if _is_casdoor_user_missing_error(lowered):
|
||||
_raise_casdoor_user_not_in_idp(source)
|
||||
if _is_casdoor_user_exists_error(lowered) or ('email' in lowered and 'already' in lowered):
|
||||
raise ConflictError('Email already exists in Casdoor', code='USER.EMAIL_EXISTS', details={'field': 'email', 'technical': msg_text})
|
||||
raise AppError(code='CASDOOR_UPDATE_USER_FAILED', message='Failed to update user in authentication system. Please try again or contact the administrator.', http_status=502, details={'technical': msg_text or str(source or '')[:300]})
|
||||
|
||||
def _casdoor_update_user(user_payload: dict):
|
||||
"""
|
||||
调用 Casdoor /api/update-user 更新 IdP 用户资料。
|
||||
核心逻辑:使用 Client ID/Secret Basic Auth,与 add-user/set-password 管理 API 一致。
|
||||
@param user_payload: Casdoor User 对象(owner/name 及待更新字段)
|
||||
Raises:
|
||||
RuntimeError: HTTP 或配置异常
|
||||
AppError: Casdoor 返回业务错误(经 _raise_casdoor_update_user_error 映射)
|
||||
"""
|
||||
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/update-user'
|
||||
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
|
||||
try:
|
||||
data = resp.json() or {}
|
||||
except ValueError:
|
||||
raise RuntimeError(f'Casdoor update-user failed: HTTP {resp.status_code} {resp.text[:200]}')
|
||||
if data.get('status') != 'ok':
|
||||
_raise_casdoor_update_user_error(data)
|
||||
|
||||
def _sync_casdoor_admin_set_password(user: User, new_password: str):
|
||||
"""
|
||||
管理端重设密码时同步 Casdoor(无旧密码,与 token 重置一致)。
|
||||
IdP 用户不存在时抛出 CASDOOR_USER_NOT_IN_IDP,由上层决定是否 fallback add-user。
|
||||
@param user: 本地用户
|
||||
@param new_password: 新密码明文
|
||||
Raises:
|
||||
AppError: Casdoor 策略或 IdP 同步失败
|
||||
"""
|
||||
if not _is_casdoor_configured():
|
||||
return
|
||||
user_owner = _casdoor_user_owner()
|
||||
try:
|
||||
_casdoor_set_password(user_owner, user.username, '', new_password)
|
||||
except RuntimeError as exc:
|
||||
if _is_casdoor_user_missing_error(str(exc)):
|
||||
_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):
|
||||
"""
|
||||
管理端编辑用户时同步 Casdoor:资料走 update-user,密码走 set-password(管理员 override)。
|
||||
核心逻辑:Casdoor 已配置则必须成功;IdP 无账号且请求含新密码时 fallback add-user 补建。
|
||||
@param user: 已应用本地变更但未 commit 的 User 实例
|
||||
@param new_password: 管理员设置的新密码;None 表示不改密
|
||||
@param sync_profile: 是否同步资料字段(email/姓名/手机/部门/状态)
|
||||
Raises:
|
||||
AppError / ConflictError: Casdoor 同步失败
|
||||
"""
|
||||
if not _is_casdoor_configured():
|
||||
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,
|
||||
email=user.email,
|
||||
real_name=user.real_name,
|
||||
phone_number=user.phone_number,
|
||||
status=user.status,
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
"""
|
||||
tests/test_admin_create_user_casdoor.py
|
||||
|
||||
用途:验证管理端创建/编辑用户时 Casdoor 同步行为。
|
||||
依赖:admin create_user/update_user、user._sync_casdoor_*。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.api import user as user_api
|
||||
|
||||
|
||||
NEW_USER_PAYLOAD = {
|
||||
'username': 'casdoor_new',
|
||||
'email': 'casdoor_new@example.com',
|
||||
'role': 'user',
|
||||
'password': 'password123',
|
||||
'real_name': 'Casdoor User',
|
||||
'employee_id': 'EMP-CAS-001',
|
||||
'phone_number': '13800000099',
|
||||
}
|
||||
|
||||
|
||||
def test_admin_create_user_syncs_casdoor(client, admin_headers, monkeypatch):
|
||||
"""
|
||||
Casdoor 已配置时,管理端创建用户应调用 add-user 且本地库成功入库。
|
||||
断言:add-user 被调用一次;响应 201;本地可查到新用户。
|
||||
"""
|
||||
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 = {'add_user': 0, 'payload': None}
|
||||
|
||||
def fake_add_user(payload):
|
||||
casdoor_calls['add_user'] += 1
|
||||
casdoor_calls['payload'] = payload
|
||||
|
||||
monkeypatch.setattr(user_api, '_casdoor_add_user', fake_add_user)
|
||||
|
||||
res = client.post('/api/admin/users', json=NEW_USER_PAYLOAD, headers=admin_headers)
|
||||
assert res.status_code == 201
|
||||
assert casdoor_calls['add_user'] == 1
|
||||
assert casdoor_calls['payload']['owner'] == 'organization_HX'
|
||||
assert casdoor_calls['payload']['name'] == 'casdoor_new'
|
||||
assert casdoor_calls['payload']['password'] == 'password123'
|
||||
assert casdoor_calls['payload']['email'] == 'casdoor_new@example.com'
|
||||
assert casdoor_calls['payload']['displayName'] == 'Casdoor User'
|
||||
assert casdoor_calls['payload']['phone'] == '13800000099'
|
||||
assert casdoor_calls['payload']['isForbidden'] is False
|
||||
|
||||
user = db.session.query(User).filter_by(username='casdoor_new').first()
|
||||
assert user is not None
|
||||
assert user.email == 'casdoor_new@example.com'
|
||||
|
||||
|
||||
def test_admin_create_user_skips_casdoor_when_not_configured(client, admin_headers, monkeypatch):
|
||||
"""
|
||||
Casdoor 未配置时应仅写本地库,不调用 add-user。
|
||||
"""
|
||||
client.application.config.pop('CASDOOR_BASE_URL', None)
|
||||
client.application.config.pop('CASDOOR_CLIENT_ID', None)
|
||||
client.application.config.pop('CASDOOR_CLIENT_SECRET', None)
|
||||
|
||||
casdoor_calls = {'add_user': 0}
|
||||
|
||||
def fake_add_user(_payload):
|
||||
casdoor_calls['add_user'] += 1
|
||||
|
||||
monkeypatch.setattr(user_api, '_casdoor_add_user', fake_add_user)
|
||||
|
||||
payload = dict(NEW_USER_PAYLOAD)
|
||||
payload.update({
|
||||
'username': 'local_only',
|
||||
'email': 'local_only@example.com',
|
||||
'employee_id': 'EMP-LOCAL-001',
|
||||
'phone_number': '13800000098',
|
||||
})
|
||||
res = client.post('/api/admin/users', json=payload, headers=admin_headers)
|
||||
assert res.status_code == 201
|
||||
assert casdoor_calls['add_user'] == 0
|
||||
|
||||
|
||||
def test_admin_create_user_rolls_back_when_casdoor_fails(client, admin_headers, monkeypatch):
|
||||
"""
|
||||
Casdoor 创建失败时不应留下本地用户(事务 rollback)。
|
||||
"""
|
||||
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_add_user(_payload):
|
||||
raise user_api.AppError(
|
||||
code='CASDOOR_ADD_USER_FAILED',
|
||||
message='Failed to create user in authentication system.',
|
||||
http_status=502,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(user_api, '_casdoor_add_user', fake_add_user)
|
||||
|
||||
payload = dict(NEW_USER_PAYLOAD)
|
||||
payload.update({
|
||||
'username': 'rollback_user',
|
||||
'email': 'rollback_user@example.com',
|
||||
'employee_id': 'EMP-RB-001',
|
||||
'phone_number': '13800000097',
|
||||
})
|
||||
res = client.post('/api/admin/users', json=payload, headers=admin_headers)
|
||||
assert res.status_code == 502
|
||||
assert db.session.query(User).filter_by(username='rollback_user').first() is None
|
||||
|
||||
|
||||
def test_raise_casdoor_add_user_error_maps_duplicate(app):
|
||||
with app.app_context():
|
||||
with pytest.raises(user_api.ConflictError) as exc:
|
||||
user_api._raise_casdoor_add_user_error({'status': 'error', 'msg': 'The user: organization_HX/foo already exists'})
|
||||
assert exc.value.code == 'USER.USERNAME_EXISTS'
|
||||
|
||||
|
||||
def _create_local_user(username: str, email: str) -> User:
|
||||
user = User(
|
||||
username=username,
|
||||
email=email,
|
||||
role='user',
|
||||
status='active',
|
||||
real_name='Local User',
|
||||
employee_id=f'EMP-{username}',
|
||||
phone_number=f'138{abs(hash(username)) % 100000000:08d}'[-11:],
|
||||
)
|
||||
user.set_password('old-password')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return user
|
||||
|
||||
|
||||
def test_admin_update_user_syncs_casdoor_profile(client, admin_headers, monkeypatch):
|
||||
"""
|
||||
编辑资料时应调用 update-user,且本地库成功更新。
|
||||
"""
|
||||
user = _create_local_user('edit_profile', 'edit_profile@example.com')
|
||||
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 = {'update_user': 0, 'payload': None}
|
||||
|
||||
def fake_update_user(payload):
|
||||
casdoor_calls['update_user'] += 1
|
||||
casdoor_calls['payload'] = payload
|
||||
|
||||
monkeypatch.setattr(user_api, '_casdoor_update_user', fake_update_user)
|
||||
|
||||
res = client.put(
|
||||
f'/api/admin/users/{user.id}',
|
||||
json={'email': 'updated@example.com', 'real_name': 'Updated Name', 'phone_number': '13800002222'},
|
||||
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'
|
||||
|
||||
db.session.refresh(user)
|
||||
assert user.email == 'updated@example.com'
|
||||
assert user.real_name == 'Updated Name'
|
||||
|
||||
|
||||
def test_admin_update_user_syncs_casdoor_password(client, admin_headers, monkeypatch):
|
||||
"""
|
||||
管理员重设密码时应以空旧密码调用 set-password(override)。
|
||||
"""
|
||||
user = _create_local_user('edit_password', 'edit_password@example.com')
|
||||
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((user_owner, user_name, old_password, new_password))
|
||||
|
||||
monkeypatch.setattr(user_api, '_casdoor_set_password', fake_set_password)
|
||||
|
||||
res = client.put(
|
||||
f'/api/admin/users/{user.id}',
|
||||
json={'password': 'new-admin-password'},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
assert casdoor_calls == [('organization_HX', 'edit_password', '', 'new-admin-password')]
|
||||
|
||||
db.session.refresh(user)
|
||||
assert user.check_password('new-admin-password')
|
||||
|
||||
|
||||
def test_admin_update_user_rolls_back_when_casdoor_fails(client, admin_headers, monkeypatch):
|
||||
"""
|
||||
Casdoor 更新失败时不应保留本地变更。
|
||||
"""
|
||||
user = _create_local_user('rollback_edit', 'rollback_edit@example.com')
|
||||
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_update_user(_payload):
|
||||
raise user_api.AppError(
|
||||
code='CASDOOR_UPDATE_USER_FAILED',
|
||||
message='Failed to update user in authentication system.',
|
||||
http_status=502,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(user_api, '_casdoor_update_user', fake_update_user)
|
||||
|
||||
res = client.put(
|
||||
f'/api/admin/users/{user.id}',
|
||||
json={'email': 'should-not-save@example.com'},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert res.status_code == 502
|
||||
db.session.refresh(user)
|
||||
assert user.email == 'rollback_edit@example.com'
|
||||
|
||||
|
||||
def test_admin_update_user_provisions_missing_casdoor_user_with_password(client, admin_headers, monkeypatch):
|
||||
"""
|
||||
IdP 无账号且管理员同时提供新密码时,应 fallback 至 add-user 补建。
|
||||
"""
|
||||
user = _create_local_user('legacy_user', 'legacy_user@example.com')
|
||||
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 = {'update_user': 0, 'add_user': 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
|
||||
|
||||
monkeypatch.setattr(user_api, '_casdoor_update_user', fake_update_user)
|
||||
monkeypatch.setattr(user_api, '_casdoor_add_user', fake_add_user)
|
||||
|
||||
res = client.put(
|
||||
f'/api/admin/users/{user.id}',
|
||||
json={'real_name': 'Legacy Updated', 'password': 'provision-password'},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
assert casdoor_calls == {'update_user': 1, 'add_user': 1}
|
||||
|
||||
db.session.refresh(user)
|
||||
assert user.real_name == 'Legacy Updated'
|
||||
assert user.check_password('provision-password')
|
||||
@@ -34,6 +34,20 @@ def test_raise_casdoor_set_password_error_maps_policy(app):
|
||||
assert exc.value.code == 'CASDOOR_PASSWORD_POLICY'
|
||||
|
||||
|
||||
def test_raise_casdoor_add_user_error_maps_policy(app):
|
||||
with app.app_context():
|
||||
with pytest.raises(user_api.AppError) as exc:
|
||||
user_api._raise_casdoor_add_user_error({'status': 'error', 'msg': 'password is too short'})
|
||||
assert exc.value.code == 'CASDOOR_PASSWORD_POLICY'
|
||||
|
||||
|
||||
def test_raise_casdoor_update_user_error_maps_missing(app):
|
||||
with app.app_context():
|
||||
with pytest.raises(user_api.AppError) as exc:
|
||||
user_api._raise_casdoor_update_user_error({'status': 'error', 'msg': "The user: organization_HX/26050001 doesn't exist"})
|
||||
assert exc.value.code == 'CASDOOR_USER_NOT_IN_IDP'
|
||||
|
||||
|
||||
def test_extract_casdoor_error_payload_from_runtime_message():
|
||||
raw = "Casdoor password login failed: {'error': 'invalid_grant', 'error_description': 'wrong password'}"
|
||||
payload = user_api._extract_casdoor_error_payload(raw)
|
||||
|
||||
Reference in new issue
Block a user