fix(auth): 重构登录认证,并支持跳转到关联服务如图纸标注

This commit is contained in:
sophie committed 2026-07-29 13:22:31 +08:00
1 parent ce1fd59f61
commit affe139bf9
51 files changed
+1939 -132

No files matched your search

+35 -72
View File
@@ -20,10 +20,6 @@ from datetime import datetime, timedelta
import uuid
import requests
from urllib.parse import quote
import hashlib
import hmac
import base64
import json
import re
import ast
from app.core.errors import (
@@ -37,8 +33,9 @@ from app.core.errors import (
raise_for_status,
)
from app.services.auth import casdoor_service as _casdoor_svc
from app.services.auth.casdoor import get_casdoor_client
from app.services.auth.hxops.casdoor_authorize import CasdoorAuthorizeOptions
from app.services.auth.hxops.login_service import HxopsLoginService
from app.services.auth.hxops import casdoor_route_adapter as _casdoor_route_adapter
from app.services.auth import wecom_auth_service as _wecom_svc
user_bp = Blueprint('user', __name__)
_WECOM_ACCESS_TOKEN_CACHE = _wecom_svc.ACCESS_TOKEN_CACHE
@@ -139,43 +136,25 @@ def _is_wecom_configured() -> bool:
return _wecom_svc.is_configured()
def _issue_casdoor_state(redirect_uri: str):
exp_ts = int((datetime.utcnow() + timedelta(minutes=10)).timestamp())
nonce = uuid.uuid4().hex
payload = {'v': 1, 'exp': exp_ts, 'nonce': nonce, 'redirect_uri': redirect_uri}
payload_json = json.dumps(payload, separators=(',', ':'))
payload_b64 = base64.urlsafe_b64encode(payload_json.encode('utf-8')).decode('ascii').rstrip('=')
secret = str(current_app.config.get('SECRET_KEY') or '')
sign = hmac.new(secret.encode('utf-8'), payload_b64.encode('ascii'), hashlib.sha256).digest()
sign_b64 = base64.urlsafe_b64encode(sign).decode('ascii').rstrip('=')
return f'hxops_casdoor_v1.{payload_b64}.{sign_b64}'
"""兼容旧调用点:签发格式不变的 Casdoor state。"""
return _casdoor_route_adapter.issue_casdoor_state(redirect_uri)
def _consume_casdoor_state(state: str):
if not state:
return None
try:
parts = state.split('.')
if len(parts) != 3 or parts[0] != 'hxops_casdoor_v1':
return None
payload_b64 = parts[1]
sign_b64 = parts[2]
secret = str(current_app.config.get('SECRET_KEY') or '')
expected_sign = hmac.new(secret.encode('utf-8'), payload_b64.encode('ascii'), hashlib.sha256).digest()
expected_b64 = base64.urlsafe_b64encode(expected_sign).decode('ascii').rstrip('=')
if not hmac.compare_digest(expected_b64, sign_b64):
return None
padded = payload_b64 + '=' * (-len(payload_b64) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode('ascii')).decode('utf-8'))
except Exception:
return None
exp = int(payload.get('exp') or 0)
now_ts = int(datetime.utcnow().timestamp())
if exp <= now_ts:
return None
return _clean_str(payload.get('redirect_uri'))
"""兼容旧调用点:校验 Casdoor state 并恢复签名绑定的 redirect_uri。"""
return _casdoor_route_adapter.consume_casdoor_state(state)
def _get_casdoor_oidc_metadata():
"""兼容旧调用点:委托公共 CasdoorClient 获取 discovery 文档。"""
return get_casdoor_client().oidc_metadata()
return _casdoor_route_adapter.get_oidc_metadata()
def _build_casdoor_authorize_payload(options: CasdoorAuthorizeOptions) -> dict[str, str]:
"""兼容入口:使用旧 discovery/state 替换点构造 Casdoor 授权响应。"""
return _casdoor_route_adapter.build_authorize_payload(
options,
oidc_metadata=_get_casdoor_oidc_metadata,
issue_state=_issue_casdoor_state,
)
def _resolve_user_from_casdoor_claims(claims: dict):
"""兼容旧调用点:通过公共身份对象映射 HXOPS 用户。"""
@@ -232,32 +211,32 @@ def _issue_casdoor_api_token(user: User, claims: dict) -> str:
def _casdoor_exchange_code(code: str, redirect_uri: str):
"""兼容旧测试替换点:委托公共客户端执行 authorization code grant。"""
return get_casdoor_client().authorization_code_login(code, redirect_uri).as_dict()
return _casdoor_route_adapter.authorization_code_login(code, redirect_uri)
def _casdoor_refresh_token(refresh_token: str):
"""兼容旧测试替换点:委托公共客户端执行 refresh grant。"""
return get_casdoor_client().refresh(refresh_token).as_dict()
return _casdoor_route_adapter.refresh_token(refresh_token)
def _casdoor_userinfo(access_token: str):
"""兼容旧测试替换点:委托公共客户端读取 userinfo。"""
return get_casdoor_client().userinfo(access_token)
return _casdoor_route_adapter.userinfo(access_token)
def _casdoor_password_login(username: str, password: str):
"""
Resource-owner password login against Casdoor token endpoint.
Requires the Casdoor application to enable password grant.
"""
return get_casdoor_client().password_login(username, password).as_dict()
return _casdoor_route_adapter.password_login(username, password)
def _hxops_login_service() -> HxopsLoginService:
"""创建使用当前兼容代理的登录服务,使既有 monkeypatch 测试和调用方式保持有效。"""
return HxopsLoginService(
password_login=_casdoor_password_login,
authorization_code_login=_casdoor_exchange_code,
refresh_token=_casdoor_refresh_token,
userinfo=_casdoor_userinfo,
return _casdoor_route_adapter.create_login_service(
write_login_audit=_write_login_audit,
password_operation=_casdoor_password_login,
code_operation=_casdoor_exchange_code,
refresh_operation=_casdoor_refresh_token,
userinfo_operation=_casdoor_userinfo,
)
def _is_casdoor_login_mode() -> bool:
@@ -284,8 +263,9 @@ def _raise_casdoor_add_user_error(source) -> None:
def _casdoor_add_user(user_payload: dict):
return _casdoor_svc.casdoor_add_user(user_payload)
def _sync_casdoor_create_user(*, username: str, password: str, email: str, real_name=None, phone_number=None, status='active', department=None):
return _casdoor_svc.sync_create_user(username=username, password=password, email=email, real_name=real_name, phone_number=phone_number, status=status, department=department)
def _sync_casdoor_create_user(*, username: str, password: str, email: str, employee_id: str | None = None, real_name=None, phone_number=None, status='active', department=None):
"""兼容入口:同步创建 Casdoor 用户,并传递认证主映射工号。"""
return _casdoor_svc.sync_create_user(username=username, password=password, employee_id=employee_id, email=email, real_name=real_name, phone_number=phone_number, status=status, department=department)
def _raise_casdoor_update_user_error(source) -> None:
_casdoor_svc.raise_update_user_error(source)
@@ -798,30 +778,13 @@ def casdoor_authorize_url():
- Failed to build Casdoor authorize url: <detail>
"""
try:
meta = _get_casdoor_oidc_metadata()
authorize_endpoint = meta.get('authorization_endpoint')
if not authorize_endpoint:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Casdoor authorization endpoint missing', http_status=500)
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
redirect_uri = _clean_str(request.args.get('redirect_uri')) or (current_app.config.get('CASDOOR_REDIRECT_URI') or '')
scope = current_app.config.get('CASDOOR_SCOPE') or 'openid profile email'
if not client_id or not redirect_uri:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Casdoor client config is incomplete', http_status=500)
default_provider = (_clean_str(request.args.get('default_provider')) or '').lower()
provider_hint = _clean_str(request.args.get('provider_hint'))
if not provider_hint and default_provider == 'wecom':
provider_hint = current_app.config.get('CASDOOR_WECOM_PROVIDER_HINT') or ''
silent_raw = (_clean_str(request.args.get('silent_signin')) or '').lower()
silent_signin = silent_raw in ('1', 'true', 'yes')
if not silent_signin and default_provider == 'wecom':
silent_signin = bool(current_app.config.get('CASDOOR_WECOM_SILENT_SIGNIN'))
state = _issue_casdoor_state(redirect_uri)
url = f"{authorize_endpoint}?client_id={quote(client_id, safe='')}&response_type=code&redirect_uri={quote(redirect_uri, safe='')}&scope={quote(scope, safe='')}&state={quote(state, safe='')}"
if provider_hint:
url += f"&provider_hint={quote(provider_hint, safe='')}"
if silent_signin:
url += '&silentSignin=1'
return jsonify({'url': url, 'state': state, 'redirect_uri': redirect_uri})
options = CasdoorAuthorizeOptions(
redirect_uri=request.args.get('redirect_uri'),
provider_hint=request.args.get('provider_hint'),
default_provider=request.args.get('default_provider'),
silent_signin=request.args.get('silent_signin'),
)
return jsonify(_build_casdoor_authorize_payload(options))
except Exception as e:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'Failed to build Casdoor authorize url: {str(e)}', http_status=500)