Files
syops/backend/app/services/auth/casdoor_service.py
T

374 lines
14 KiB
Python

"""
backend/app/services/auth/casdoor_service.py
用途:Casdoor IdP 用户同步与 OAuth 错误映射(管理端创建/改密、用户域登录共用)。
依赖:flask.current_app、requests、app.core.errors。
逻辑:由 services/admin/user_service、api/user 登录路由调用。
"""
from __future__ import annotations
import ast
import json
import re
from typing import Any
import requests
from flask import current_app
from app.core.errors import AppError, ConflictError, ValidationError
from app.models import User
def clean_str(value) -> str | None:
"""Trim 字符串;空串返回 None。"""
if value is None:
return None
if isinstance(value, str):
value = value.strip()
return value or None
return str(value).strip() or None
def is_casdoor_configured() -> bool:
"""Casdoor 基础配置是否齐全。"""
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:
"""返回 Casdoor organization owner。"""
owner = clean_str(current_app.config.get('CASDOOR_ORGANIZATION'))
if not owner:
raise RuntimeError('CASDOOR_ORGANIZATION is not configured')
return owner
def extract_error_payload(source) -> dict:
"""从 Casdoor 响应或异常文本解析 JSON 错误体。"""
if isinstance(source, dict):
return source
text = str(source or '')
match = re.search(r'\{.*\}', text, re.DOTALL)
if match:
try:
parsed = ast.literal_eval(match.group(0))
if isinstance(parsed, dict):
return parsed
except (SyntaxError, ValueError):
pass
try:
parsed = json.loads(text)
if isinstance(parsed, dict):
return parsed
except (json.JSONDecodeError, TypeError):
pass
return {}
def is_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 is_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 is_user_missing_error(message: str) -> bool:
lowered = (message or '').lower()
return (
"doesn't exist" in lowered
or 'does not exist' in lowered
or 'user not found' in lowered
or 'no such user' in lowered
)
def raise_user_not_in_idp(source=None) -> None:
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
raise AppError(
code='CASDOOR_USER_NOT_IN_IDP',
message='Your account has not been registered in the authentication system. Please contact the administrator.',
http_status=409,
details={'technical': msg_text or str(source or '')[:300]},
)
def raise_add_user_error(source) -> None:
"""将 Casdoor add-user 失败映射为稳定业务错误码。"""
data = extract_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_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 raise_update_user_error(source) -> None:
"""将 Casdoor update-user 失败映射为稳定业务错误码。"""
data = extract_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_user_missing_error(lowered):
raise_user_not_in_idp(source)
if is_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 raise_set_password_error(source) -> None:
"""将 Casdoor set-password 失败映射为稳定业务错误码。"""
data = extract_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_password_error(lowered) or 'old password' in lowered or 'current password' in lowered:
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect current password', http_status=401)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400)
if is_user_missing_error(lowered):
raise_user_not_in_idp(source)
raise AppError(
code='CASDOOR_SET_PASSWORD_FAILED',
message='Failed to change password. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source)[:300]},
)
def raise_auth_error(source, *, context: str, status_code: int = 401) -> None:
"""Map Casdoor OAuth/API failures to stable business error codes."""
data = extract_error_payload(source)
raw = str(source or '')
oauth_error = clean_str(data.get('error')).lower()
if not oauth_error and 'invalid_grant' in raw.lower():
oauth_error = 'invalid_grant'
if not oauth_error and 'invalid_client' in raw.lower():
oauth_error = 'invalid_client'
if oauth_error == 'invalid_grant' or is_password_error(raw):
if context in ('password', 'verify'):
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect username or password', http_status=401)
raise AppError(code='CASDOOR_CODE_EXPIRED', message='Login session expired, please sign in again', http_status=401)
if oauth_error in ('invalid_client', 'unauthorized_client'):
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is misconfigured. Please contact the administrator.',
http_status=503,
details={'casdoor_error': oauth_error},
)
if oauth_error == 'access_denied':
raise AppError(code='CASDOOR_ACCESS_DENIED', message='Login was cancelled or denied', http_status=403)
if 'token endpoint missing' in raw.lower() or 'casdoor_base_url is not configured' in raw.lower() or 'casdoor is not configured' in raw.lower():
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is not configured. Please contact the administrator.',
http_status=503,
)
if 'invalid or expired casdoor state' in raw.lower():
raise ValidationError('Invalid or expired Casdoor state')
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s raw=%s', context, data, raw[:500])
raise AppError(
code='CASDOOR_AUTH_FAILED',
message='Authentication failed, please try again',
http_status=status_code,
details={'casdoor_error': oauth_error or None, 'technical': raw[:300]},
)
def build_user_profile_payload(
*,
username: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict:
"""组装 Casdoor 用户资料字段(不含 password)。"""
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_user_payload(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict:
"""组装 Casdoor add-user 请求体。"""
payload = build_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) -> None:
"""调用 Casdoor /api/add-user 创建 IdP 用户。"""
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_add_user_error(data)
def casdoor_update_user(user_payload: dict) -> None:
"""调用 Casdoor /api/update-user 更新 IdP 用户资料。"""
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_update_user_error(data)
def casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str) -> None:
"""调用 Casdoor /api/set-password。"""
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_set_password_error(data)
def sync_create_user(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> None:
"""管理端创建用户时同步至 Casdoor。"""
if not is_casdoor_configured():
return
payload = build_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 sync_admin_set_password(user: User, new_password: str) -> None:
"""管理端重设密码时同步 Casdoor(无旧密码)。"""
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_user_missing_error(str(exc)):
raise_user_not_in_idp(exc)
raise_set_password_error(exc)
def sync_update_user(user: User, *, new_password: str | None = None) -> None:
"""管理端编辑用户时同步 Casdoor:仅改密;IdP 无账号则 add-user 补建。"""
if not is_casdoor_configured() or not new_password:
return
def _provision_missing_user_in_casdoor():
sync_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,
)
try:
sync_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