fix(admin): 用户字段唯一性校验

This commit is contained in:
sophie committed 2026-06-18 10:18:18 +08:00
1 parent d46d61bfa1
commit 6757ad869f
2 files changed
+109 -21

No files matched your search

+50 -15
View File
@@ -41,6 +41,29 @@ def _raise_user_integrity_conflict(exc: IntegrityError) -> None:
raise ConflictError('Username already exists', code='USER.USERNAME_EXISTS')
raise ConflictError('Data uniqueness conflict', code='USER.UNIQUENESS_CONFLICT')
def _assert_user_unique_fields(exclude_user_id: int | None, **fields: str | None) -> None:
"""
校验用户唯一字段(邮箱、工号、手机号)不与其它账号冲突。
核心逻辑:对传入的非 None 字段查询 User 表;编辑时 exclude_user_id 排除当前用户。
@param exclude_user_id: 编辑场景传当前用户 id;创建场景传 None
@param fields: email / employee_id / phone_number 等待校验值
@raises ConflictError: 唯一字段已被占用
"""
checks = (
('email', 'USER.EMAIL_EXISTS', 'Email already exists'),
('employee_id', 'USER.EMPLOYEE_ID_EXISTS', 'Employee ID already exists'),
('phone_number', 'USER.PHONE_EXISTS', 'Phone number already exists'),
)
for field, code, message in checks:
value = fields.get(field)
if value is None:
continue
query = db.session.query(User.id).filter(getattr(User, field) == value)
if exclude_user_id is not None:
query = query.filter(User.id != exclude_user_id)
if query.first():
raise ConflictError(message, code=code, details={'field': field})
def _empty_to_none(value):
if value is None:
return None
@@ -564,13 +587,19 @@ def create_user():
email = _empty_to_none(data.get('email'))
if not _is_valid_email(email):
raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'})
_assert_user_unique_fields(
None,
email=email,
employee_id=_empty_to_none(data.get('employee_id')),
phone_number=_empty_to_none(data.get('phone_number')),
)
user = User(username=data['username'], email=email, department=_empty_to_none(data.get('department')), role=data.get('role', 'user'), status=data.get('status', 'active'), real_name=_empty_to_none(data.get('real_name')), employee_id=_empty_to_none(data.get('employee_id')), phone_number=_empty_to_none(data.get('phone_number')))
user.set_password(data['password'])
if data.get('agent_ids'):
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
user.agents = agents
db.session.add(user)
try:
if data.get('agent_ids'):
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
user.agents = agents
user_api._sync_casdoor_create_user(
username=user.username,
password=data['password'],
@@ -597,7 +626,7 @@ def create_user():
def update_user(id):
"""
管理端编辑用户:资料仅写本地库;仅改密时同步 Casdoor set-password。
核心逻辑:应用本地字段 →(有 new_password 时)_sync_casdoor_update_user → commit。
核心逻辑:唯一字段预校验 → 应用本地字段与 agent_ids →(有 new_password 时)_sync_casdoor_update_user → commit。
Request JSON: email, department, role, status, password 等;password 为空表示不改密
Returns:
{ status: ok };Casdoor 改密/唯一约束失败时抛出 AppError/ConflictError
@@ -611,19 +640,25 @@ 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'})
unique_updates = {
field: _empty_to_none(data[field])
for field in ('email', 'employee_id', 'phone_number')
if field in data
}
_assert_user_unique_fields(id, **unique_updates)
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 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:
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 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
if new_password:
user_api._sync_casdoor_update_user(user, new_password=new_password)
db.session.commit()
+59 -6
View File
@@ -1,7 +1,21 @@
import pytest
from app.models import User
from app.models import User, Agent
from app import db
def _error_message(response):
body = response.get_json() or {}
error = body.get('error')
if isinstance(error, dict):
return str(error.get('message') or '')
return str(error or '')
def _error_code(response):
body = response.get_json() or {}
error = body.get('error')
if isinstance(error, dict):
return str(error.get('code') or '')
return ''
def test_register_fields_validation(client):
"""
Test user registration field validation
@@ -40,7 +54,7 @@ def test_register_fields_validation(client):
}
response = client.post('/api/user/register', json=dup_user)
assert response.status_code == 400
assert "Employee ID already exists" in response.json['error']
assert "Employee ID already exists" in _error_message(response)
def test_admin_duplicate_employee_id(client, admin_headers):
"""
@@ -68,8 +82,8 @@ def test_admin_duplicate_employee_id(client, admin_headers):
"phone_number": "13800000012"
}
response = client.post('/api/admin/users', json=u2, headers=admin_headers)
assert response.status_code == 400
assert "Employee ID already exists" in response.json['error']
assert response.status_code == 409
assert "Employee ID already exists" in _error_message(response)
# 3. Update user to duplicate ID
# Create u3 with valid ID
@@ -86,5 +100,44 @@ def test_admin_duplicate_employee_id(client, admin_headers):
# Update u3 to ADM001 (which exists)
res = client.put(f'/api/admin/users/{u3_id}', json={"employee_id": "ADM001"}, headers=admin_headers)
assert res.status_code == 400
assert "Employee ID already exists" in res.json['error']
assert res.status_code == 409
assert "Employee ID already exists" in _error_message(res)
assert _error_code(res) == 'USER.EMPLOYEE_ID_EXISTS'
def test_admin_duplicate_phone_on_update_with_agent_ids(client, admin_headers):
"""
编辑用户时若手机号重复且同时提交 agent_ids,应在 autoflush 前返回冲突而非 500。
"""
existing = {
"username": "phone_owner",
"password": "pwd",
"email": "phone_owner@e.com",
"real_name": "Phone Owner",
"employee_id": "PHN001",
"phone_number": "123456",
}
target = {
"username": "phone_target",
"password": "pwd",
"email": "phone_target@e.com",
"real_name": "Phone Target",
"employee_id": "PHN002",
"phone_number": "13800009999",
}
assert client.post('/api/admin/users', json=existing, headers=admin_headers).status_code == 201
target_res = client.post('/api/admin/users', json=target, headers=admin_headers)
assert target_res.status_code == 201
target_id = target_res.json['id']
agent = Agent(name='Dup Phone Agent', dify_app_id='dup-phone-agent', type='chat')
db.session.add(agent)
db.session.commit()
res = client.put(
f'/api/admin/users/{target_id}',
json={'phone_number': '123456', 'agent_ids': [agent.id]},
headers=admin_headers,
)
assert res.status_code == 409
assert _error_code(res) == 'USER.PHONE_EXISTS'
assert "Phone number already exists" in _error_message(res)