Files
syops/backend/app/api/user/auth_wecom.py
T

197 lines
12 KiB
Python

"""
api/user/auth_wecom.py
用途:企业微信 OAuth、绑定与回调 HTTP 路由。
依赖:auth.auth_bp、auth_support 的企微签名、身份匹配和审计操作。
逻辑:将企微认证入口同本地/Casdoor 路由隔离,保持企业微信回调 URL 不变。
"""
from __future__ import annotations
from urllib.parse import quote
import requests
from flask import current_app, jsonify, request
from app import db
from app.core.errors import AppError, ConflictError, ForbiddenError, UnauthorizedError, ValidationError
from app.services.integrations.wecom.crypto import decrypt_wecom_aes, extract_encrypt_field
from . import auth as _compat
from .auth import auth_bp
@auth_bp.get('/wecom/authorize-url', endpoint='wecom_authorize_url')
def authorize_url():
"""生成企业微信 OAuth 授权地址。"""
if not _compat._is_wecom_configured():
raise ValidationError('WeCom login is not configured')
redirect_uri = request.args.get('redirect_uri') or current_app.config.get('WECOM_REDIRECT_URI')
if not redirect_uri:
raise ValidationError('redirect_uri is required')
state = _compat._issue_wecom_state()
corp_id = current_app.config.get('WECOM_CORP_ID')
agent_id = current_app.config.get('WECOM_AGENT_ID')
url = f"https://open.weixin.qq.com/connect/oauth2/authorize?appid={corp_id}&redirect_uri={quote(redirect_uri, safe='')}&response_type=code&scope=snsapi_base&state={quote(state, safe='')}&agentid={agent_id}#wechat_redirect"
return jsonify({'url': url, 'state': state})
@auth_bp.post('/wecom/login', endpoint='wecom_login')
def login():
"""完成企业微信 OAuth 登录并映射或绑定本地用户。"""
if not _compat._is_wecom_configured():
raise ValidationError('WeCom login is not configured')
data = request.get_json() or {}
code, state = data.get('code'), data.get('state')
if not code:
_compat._write_login_audit('wecom', 'failed', reason='missing_code')
db.session.commit()
raise ValidationError('code is required')
if not _compat._consume_wecom_state(state):
_compat._write_login_audit('wecom', 'failed', reason='invalid_state')
db.session.commit()
raise ValidationError('Invalid or expired WeCom state')
wecom_userid = None
try:
access_token = _compat._get_wecom_access_token()
info = requests.get('https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo', params={'access_token': access_token, 'code': code}, timeout=8).json()
wecom_userid = info.get('userid') or info.get('UserId')
if info.get('errcode') != 0:
raise UnauthorizedError(f"WeCom auth failed: {info.get('errmsg', 'unknown error')}")
if not wecom_userid:
raise AppError(code='WECOM_NOT_IN_AGENT_SCOPE', message='当前企业微信账号未授权登录该应用:账号不在自建应用的可见范围内,或不是本企业成员。请管理员到「企业微信后台 → 应用管理 → 该应用 → 可见范围」中加入该成员所在的部门或个人。', http_status=401)
wecom_user = requests.get('https://qyapi.weixin.qq.com/cgi-bin/user/get', params={'access_token': access_token, 'userid': wecom_userid}, timeout=8).json()
if wecom_user.get('errcode') != 0:
raise UnauthorizedError(f"WeCom user fetch failed: {wecom_user.get('errmsg', 'unknown error')}")
user, bind_status, rule_info = _compat._sync_or_create_user_from_wecom(wecom_user)
if user.status != 'active':
raise ForbiddenError('Account is disabled')
_compat._write_login_audit('wecom', 'success', user=user, wecom_userid=wecom_userid, match_rules=rule_info.get('fields'), match_operator=rule_info.get('operator'), match_result=bind_status)
db.session.commit()
return jsonify(_compat._build_login_payload(user, 'wecom', bind_status=bind_status))
except _compat.WeComLoginError as exc:
db.session.rollback()
_compat._write_login_audit('wecom', 'failed', reason=exc.reason or 'wecom_login_error', wecom_userid=wecom_userid, error_code=exc.error_code)
db.session.commit()
raise
except AppError as exc:
db.session.rollback()
_compat._write_login_audit('wecom', 'failed', reason=str(exc)[:160], wecom_userid=wecom_userid, error_code=exc.code)
db.session.commit()
raise
except Exception as exc:
db.session.rollback()
if _compat._is_users_pk_sequence_error(exc):
_compat._write_login_audit('wecom', 'failed', reason='db_sequence_misconfig', wecom_userid=wecom_userid, error_code='DB_SEQUENCE_MISCONFIG')
db.session.commit()
raise AppError(code='SYSTEM.DB_SEQUENCE_MISCONFIG', message='数据库主键自增配置异常,当前环境缺少 users.id 的自动序列。请执行数据库迁移后重试。', http_status=500) from exc
_compat._write_login_audit('wecom', 'failed', reason=f'exception:{str(exc)[:160]}', wecom_userid=wecom_userid)
db.session.commit()
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'WeCom login failed: {exc}', http_status=500) from exc
@auth_bp.post('/wecom/complete-bind', endpoint='wecom_complete_bind')
def complete_bind():
"""提交首登人工绑定信息并完成企业微信账号绑定。"""
if not _compat._is_wecom_configured():
raise ValidationError('WeCom login is not configured')
data = request.get_json() or {}
token, field, value = _compat._clean_str(data.get('binding_token')), _compat._clean_str(data.get('field')), data.get('value')
identity = _compat._get_wecom_bind_session(token)
if not identity:
raise AppError(code='WECOM_BIND_SESSION_EXPIRED', message='WeCom binding session expired. Please restart WeCom login.', http_status=400)
allowed_fields = _compat._get_wecom_first_login_input_fields()
if field not in allowed_fields:
raise AppError(code='WECOM_BIND_FIELD_NOT_ALLOWED', message='Selected bind field is not allowed', http_status=400, details={'allowed_fields': allowed_fields})
matched_users, missing_field = _compat._find_users_by_input_field(field, value)
if missing_field:
raise AppError(code='WECOM_BIND_INPUT_VALUE_REQUIRED', message=f'{field} is required', http_status=400, details={'field': field})
if not matched_users:
raise AppError(code='WECOM_BIND_INPUT_NOT_FOUND', message='No local account matched the verification value.', http_status=404, details={'field': field})
if len(matched_users) > 1:
raise ConflictError('Multiple local accounts matched the verification value.', code='WECOM_BIND_INPUT_AMBIGUOUS', details={'field': field, 'candidate_count': len(matched_users)})
user = matched_users[0]
if user.status != 'active':
raise ForbiddenError('Account is disabled')
try:
_compat._sync_user_from_wecom_identity(user, identity)
_compat._write_login_audit('wecom', 'success', user=user, wecom_userid=identity.get('wecom_userid'), match_rules=[field], match_operator='AND', match_result='input_verified_and_bound')
db.session.commit()
_compat._WECOM_BIND_SESSION_CACHE.pop(token, None)
return jsonify(_compat._build_login_payload(user, 'wecom', bind_status='input_verified_and_bound'))
except _compat.WeComLoginError as exc:
db.session.rollback()
_compat._write_login_audit('wecom', 'failed', user=user, reason=exc.reason or 'wecom_input_bind_error', wecom_userid=identity.get('wecom_userid'), error_code=exc.error_code, match_rules=[field], match_operator='AND')
db.session.commit()
raise
except Exception as exc:
db.session.rollback()
_compat._write_login_audit('wecom', 'failed', user=user, reason=f'exception:{str(exc)[:160]}', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_BIND_INPUT_EXCEPTION', match_rules=[field], match_operator='AND')
db.session.commit()
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'WeCom bind failed: {exc}', http_status=500) from exc
@auth_bp.route('/wecom/callback', methods=['GET', 'POST'], endpoint='wecom_callback')
def callback():
"""处理企业微信 URL 验证及加密事件回调。"""
signature = request.args.get('msg_signature') or request.args.get('signature')
timestamp, nonce = request.args.get('timestamp', ''), request.args.get('nonce', '')
token = current_app.config.get('WECOM_CALLBACK_TOKEN') or ''
aes_key, corp_id = current_app.config.get('WECOM_ENCODING_AES_KEY') or '', current_app.config.get('WECOM_CORP_ID') or ''
if not token:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='callback token not configured', http_status=500)
if request.method == 'GET':
echostr = request.args.get('echostr', '') or ''
if not _compat._verify_wecom_msg_signature(signature, token, timestamp, nonce, echostr):
raise ForbiddenError('invalid callback signature')
try:
plain = decrypt_wecom_aes(echostr, aes_key, corp_id) if aes_key else echostr
except Exception as exc:
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=echostr, error_message=f'decrypt_failed:{str(exc)[:200]}')
raise ValidationError('decrypt failed') from exc
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=echostr, decrypted_xml=plain, msg_type='url_verify' if aes_key else 'url_verify_plain')
return plain, 200, {'Content-Type': 'text/plain; charset=utf-8'}
payload = request.get_data(as_text=True) or ''
encrypt_field = extract_encrypt_field(payload) or ''
if not encrypt_field:
raise ValidationError('missing Encrypt field')
if not _compat._verify_wecom_msg_signature(signature, token, timestamp, nonce, encrypt_field):
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_field, error_message='invalid_msg_signature')
raise ForbiddenError('invalid callback signature')
decrypted = None
if aes_key:
try:
decrypted = decrypt_wecom_aes(encrypt_field, aes_key, corp_id)
except Exception as exc:
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_field, error_message=f'decrypt_failed:{str(exc)[:200]}')
raise ValidationError('decrypt failed') from exc
_compat._persist_wecom_callback_audit(
msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_field,
decrypted_xml=decrypted, msg_type=_compat._extract_xml_field(decrypted, 'MsgType') if decrypted else None,
event=_compat._extract_xml_field(decrypted, 'Event') if decrypted else None,
from_user=_compat._extract_xml_field(decrypted, 'FromUserName') if decrypted else None,
agent_id=_compat._extract_xml_field(decrypted, 'AgentID') if decrypted else None,
msg_id=_compat._extract_xml_field(decrypted, 'MsgId') if decrypted else None,
)
return 'success', 200, {'Content-Type': 'text/plain; charset=utf-8'}
@auth_bp.get('/wecom/binding', endpoint='get_wecom_binding')
def binding():
"""返回当前用户的企业微信绑定状态。"""
user = _compat._get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
return jsonify({'bound': bool(user.wecom_userid), 'wecom_userid': user.wecom_userid, 'wecom_unionid': user.wecom_unionid})
@auth_bp.post('/wecom/unbind', endpoint='unbind_wecom_self')
def unbind():
"""解除当前用户与企业微信账号的绑定。"""
user = _compat._get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
user.wecom_userid = None
user.wecom_unionid = None
db.session.commit()
return jsonify({'status': 'ok', 'message': 'WeCom account unbound'})