企业微信
This commit is contained in:
1 parent
46ac70f4c5
commit
a9fc852abb
33 files changed
+4875
-106
No files matched your search
@@ -3,6 +3,8 @@
|
||||
backend/app/__init__.py
|
||||
应用工厂
|
||||
"""
|
||||
import logging
|
||||
|
||||
from flask import Flask
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
@@ -12,6 +14,27 @@ from app.config import config
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _apply_persisted_settings(app: Flask) -> None:
|
||||
"""Pull the latest runtime-editable settings into ``app.config``.
|
||||
|
||||
Reads from the database first, then ``backend/.env``. Tolerates the
|
||||
common case where the table does not yet exist (fresh deploy before
|
||||
``flask db upgrade`` runs).
|
||||
"""
|
||||
from app.env_persistence import apply_env_settings
|
||||
|
||||
try:
|
||||
applied = apply_env_settings()
|
||||
except Exception as exc: # pragma: no cover - defensive
|
||||
logger.warning('Failed to refresh persisted settings: %s', exc)
|
||||
return
|
||||
for key, value in applied.items():
|
||||
app.config[key] = value
|
||||
|
||||
|
||||
def create_app(config_name='default'):
|
||||
app = Flask(__name__)
|
||||
app.config.from_object(config[config_name])
|
||||
@@ -35,4 +58,15 @@ def create_app(config_name='default'):
|
||||
# 当前用户相关接口(首页、常用问题等)
|
||||
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||
|
||||
# Eagerly load persisted runtime settings so the very first request after
|
||||
# a worker boot already sees the admin-saved configuration (otherwise the
|
||||
# window between worker boot and the first ``before_request`` would still
|
||||
# serve the defaults baked into config.py / the image).
|
||||
with app.app_context():
|
||||
_apply_persisted_settings(app)
|
||||
|
||||
@app.before_request
|
||||
def _sync_persisted_settings():
|
||||
_apply_persisted_settings(app)
|
||||
|
||||
return app
|
||||
+462
-5
@@ -4,19 +4,206 @@ backend/app/api/admin.py
|
||||
引用文件:flask, models, decorators
|
||||
逻辑关系:提供 Agent 配置管理、用户与权限管理接口,供前端 Admin 控制台使用
|
||||
"""
|
||||
from flask import Blueprint, request, jsonify
|
||||
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit
|
||||
from flask import Blueprint, request, jsonify, current_app
|
||||
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit
|
||||
from app.decorators import require_admin
|
||||
from app.config import Config
|
||||
from app import db
|
||||
from app.env_persistence import persist_env_settings
|
||||
from sqlalchemy import func, desc, inspect
|
||||
from datetime import datetime
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from datetime import datetime, timedelta
|
||||
import csv
|
||||
import io
|
||||
import requests
|
||||
import uuid
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
|
||||
admin_bp = Blueprint('admin', __name__)
|
||||
|
||||
|
||||
def _serialize_wecom_notify_settings():
|
||||
return {
|
||||
'enabled': bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)),
|
||||
'base_url': current_app.config.get('WECOM_NOTIFY_BASE_URL') or '',
|
||||
'events': [x for x in str(current_app.config.get('WECOM_NOTIFY_EVENTS', '')).split(',') if x],
|
||||
}
|
||||
|
||||
|
||||
def _serialize_wecom_system_settings():
|
||||
return {
|
||||
'enabled': bool(current_app.config.get('WECOM_ENABLED', False)),
|
||||
'corp_id': current_app.config.get('WECOM_CORP_ID') or '',
|
||||
'agent_id': str(current_app.config.get('WECOM_AGENT_ID') or ''),
|
||||
'secret': current_app.config.get('WECOM_SECRET') or '',
|
||||
'redirect_uri': current_app.config.get('WECOM_REDIRECT_URI') or '',
|
||||
'auto_create_user': bool(current_app.config.get('WECOM_AUTO_CREATE_USER', True)),
|
||||
'match_rules': current_app.config.get('WECOM_MATCH_RULES') or 'employee_id,mobile',
|
||||
'match_operator': str(current_app.config.get('WECOM_MATCH_OPERATOR') or 'AND').upper(),
|
||||
'first_login_bind_mode': str(current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE') or 'match_rules').lower(),
|
||||
'first_login_input_fields': current_app.config.get('WECOM_FIRST_LOGIN_INPUT_FIELDS') or 'employee_id,mobile,email',
|
||||
'employee_id_source': current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE') or 'userid',
|
||||
'mobile_normalize': bool(current_app.config.get('WECOM_MOBILE_NORMALIZE', True)),
|
||||
'callback_token': current_app.config.get('WECOM_CALLBACK_TOKEN') or '',
|
||||
'encoding_aes_key': current_app.config.get('WECOM_ENCODING_AES_KEY') or '',
|
||||
'callback_url': current_app.config.get('WECOM_CALLBACK_URL') or '',
|
||||
'homepage_url': current_app.config.get('WECOM_HOMEPAGE_URL') or '',
|
||||
'trusted_domain': current_app.config.get('WECOM_TRUSTED_DOMAIN') or '',
|
||||
'public_base_url': current_app.config.get('WECOM_PUBLIC_BASE_URL') or '',
|
||||
}
|
||||
|
||||
|
||||
def _default_public_base():
|
||||
for key in ('WECOM_PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'):
|
||||
configured = current_app.config.get(key) or ''
|
||||
if configured:
|
||||
return configured.rstrip('/')
|
||||
return request.host_url.rstrip('/')
|
||||
|
||||
|
||||
def _serialize_wecom_integration_manifest():
|
||||
settings = _serialize_wecom_system_settings()
|
||||
public_base = _default_public_base()
|
||||
callback_url = settings.get('callback_url') or f'{public_base}/api/user/wecom/callback'
|
||||
homepage_url = settings.get('homepage_url') or f'{public_base}/workspace'
|
||||
trusted_domain = settings.get('trusted_domain') or request.host.split(':')[0]
|
||||
|
||||
return {
|
||||
'public_base_url': public_base,
|
||||
'callback_url': callback_url,
|
||||
'callback_token': settings.get('callback_token') or '',
|
||||
'encoding_aes_key': settings.get('encoding_aes_key') or '',
|
||||
'oauth_redirect_uri': settings.get('redirect_uri') or homepage_url,
|
||||
'homepage_url': homepage_url,
|
||||
'trusted_domain': trusted_domain,
|
||||
'authorize_api': f'{public_base}/api/user/wecom/authorize-url',
|
||||
'login_api': f'{public_base}/api/user/wecom/login',
|
||||
}
|
||||
|
||||
|
||||
def _serialize_debug_match_user(user: User) -> dict:
|
||||
return {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'real_name': user.real_name,
|
||||
'employee_id': user.employee_id,
|
||||
'phone_number': user.phone_number,
|
||||
'email': user.email,
|
||||
'status': user.status,
|
||||
'wecom_userid': user.wecom_userid,
|
||||
'wecom_unionid': user.wecom_unionid,
|
||||
}
|
||||
|
||||
|
||||
def _build_wecom_match_preview(identity: dict, rules: list[str], operator: str) -> dict:
|
||||
from app.api import user as user_api
|
||||
|
||||
bind_mode = user_api._get_wecom_first_login_bind_mode()
|
||||
preview = {
|
||||
'bind_mode': bind_mode,
|
||||
'rules': {
|
||||
'fields': rules,
|
||||
'operator': operator,
|
||||
},
|
||||
'auto_create_user': bool(current_app.config.get('WECOM_AUTO_CREATE_USER', True)),
|
||||
}
|
||||
|
||||
bound_user = None
|
||||
if identity.get('wecom_userid'):
|
||||
bound_user = db.session.query(User).filter_by(wecom_userid=identity['wecom_userid']).first()
|
||||
if not bound_user and identity.get('wecom_unionid'):
|
||||
bound_user = db.session.query(User).filter_by(wecom_unionid=identity['wecom_unionid']).first()
|
||||
|
||||
if bound_user:
|
||||
preview['decision'] = 'already_bound'
|
||||
preview['bound_user'] = _serialize_debug_match_user(bound_user)
|
||||
return preview
|
||||
|
||||
if bind_mode == 'input_verify':
|
||||
preview['decision'] = 'input_verification_required'
|
||||
preview['allowed_fields'] = user_api._get_wecom_first_login_input_fields()
|
||||
return preview
|
||||
|
||||
matched_users, missing_fields = user_api._find_users_by_match_rules(identity, rules, operator)
|
||||
preview['missing_fields'] = missing_fields
|
||||
preview['matched_users'] = [_serialize_debug_match_user(user) for user in matched_users]
|
||||
|
||||
if missing_fields:
|
||||
preview['decision'] = 'missing_match_fields'
|
||||
elif len(matched_users) == 1:
|
||||
preview['decision'] = 'matched_existing_user'
|
||||
elif len(matched_users) > 1:
|
||||
preview['decision'] = 'ambiguous_match'
|
||||
elif preview['auto_create_user']:
|
||||
preview['decision'] = 'would_auto_create_user'
|
||||
else:
|
||||
preview['decision'] = 'bind_required'
|
||||
return preview
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/debug-user-by-code', methods=['POST'])
|
||||
@require_admin
|
||||
def debug_wecom_user_by_code():
|
||||
from app.api import user as user_api
|
||||
|
||||
if not user_api._is_wecom_configured():
|
||||
return jsonify({'error': 'WeCom login is not configured'}), 400
|
||||
|
||||
data = request.get_json() or {}
|
||||
code = str(data.get('code') or '').strip()
|
||||
if not code:
|
||||
return jsonify({'error': 'code is required'}), 400
|
||||
|
||||
access_token = user_api._get_wecom_access_token()
|
||||
info_resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo',
|
||||
params={'access_token': access_token, 'code': code},
|
||||
timeout=8,
|
||||
)
|
||||
auth_info = info_resp.json()
|
||||
userid = auth_info.get('userid') or auth_info.get('UserId')
|
||||
openid = auth_info.get('openid') or auth_info.get('OpenId')
|
||||
|
||||
payload = {
|
||||
'auth_info': auth_info,
|
||||
}
|
||||
|
||||
if auth_info.get('errcode') != 0:
|
||||
payload.update({
|
||||
'error': f"WeCom auth failed: {auth_info.get('errmsg', 'unknown error')}",
|
||||
'error_code': 'WECOM_AUTH_FAILED',
|
||||
})
|
||||
return jsonify(payload), 401
|
||||
|
||||
if not userid:
|
||||
payload.update({
|
||||
'error': '当前 code 对应的账号不在应用可见范围内,或不是本企业成员。',
|
||||
'error_code': 'WECOM_NOT_IN_AGENT_SCOPE',
|
||||
'openid': openid,
|
||||
})
|
||||
return jsonify(payload), 401
|
||||
|
||||
user_resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/user/get',
|
||||
params={'access_token': access_token, 'userid': userid},
|
||||
timeout=8,
|
||||
)
|
||||
wecom_user = user_resp.json()
|
||||
payload['wecom_user'] = wecom_user
|
||||
|
||||
if wecom_user.get('errcode') != 0:
|
||||
payload.update({
|
||||
'error': f"WeCom user fetch failed: {wecom_user.get('errmsg', 'unknown error')}",
|
||||
'error_code': 'WECOM_USER_FETCH_FAILED',
|
||||
})
|
||||
return jsonify(payload), 401
|
||||
|
||||
identity = user_api._extract_wecom_identity(wecom_user)
|
||||
rules, operator = user_api._get_wecom_match_config()
|
||||
payload['normalized_identity'] = identity
|
||||
payload['match_preview'] = _build_wecom_match_preview(identity, rules, operator)
|
||||
return jsonify(payload)
|
||||
|
||||
@admin_bp.route('/dashboard', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_stats():
|
||||
@@ -452,7 +639,17 @@ def batch_update_permissions():
|
||||
for agent in agents:
|
||||
if agent in user.agents:
|
||||
user.agents.remove(agent)
|
||||
|
||||
if user.wecom_userid:
|
||||
action_label = {'add': '新增', 'remove': '移除', 'set': '重置为'}[action]
|
||||
agent_names = '、'.join([a.name for a in agents]) if agents else '无'
|
||||
send_wecom_event_message(
|
||||
event_type='permission_batch_updated',
|
||||
user=user,
|
||||
title='应用权限已更新',
|
||||
content=f'管理员已{action_label}你的应用权限:{agent_names}',
|
||||
jump_path='/workspace',
|
||||
)
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'updated_count': len(users)})
|
||||
|
||||
@@ -510,7 +707,15 @@ def approve_request(id):
|
||||
agent = db.session.get(Agent, req.agent_id)
|
||||
if user and agent and agent not in user.agents:
|
||||
user.agents.append(agent)
|
||||
|
||||
if user and user.wecom_userid:
|
||||
send_wecom_event_message(
|
||||
event_type='permission_request_approved',
|
||||
user=user,
|
||||
title='权限申请已通过',
|
||||
content=f'你申请的应用权限已通过:{agent.name if agent else req.agent_id}',
|
||||
jump_path='/workspace',
|
||||
)
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@@ -521,6 +726,16 @@ def reject_request(id):
|
||||
if not req: return jsonify({'error': 'Not found'}), 404
|
||||
req.status = 'rejected'
|
||||
req.reviewed_at = datetime.utcnow()
|
||||
user = db.session.get(User, req.user_id)
|
||||
agent = db.session.get(Agent, req.agent_id)
|
||||
if user and user.wecom_userid:
|
||||
send_wecom_event_message(
|
||||
event_type='permission_request_rejected',
|
||||
user=user,
|
||||
title='权限申请未通过',
|
||||
content=f'你申请的应用权限未通过:{agent.name if agent else req.agent_id}',
|
||||
jump_path='/workspace',
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@@ -805,6 +1020,119 @@ def unbind_wecom_user():
|
||||
return jsonify({'status': 'ok', 'message': 'WeCom account unbound'})
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/provision', methods=['POST'])
|
||||
@require_admin
|
||||
def provision_wecom_user():
|
||||
"""
|
||||
Atomic admin helper to create user (optional), bind WeCom identity and assign agent permissions.
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
create_user = bool(data.get('create_user', True))
|
||||
user_data = data.get('user') or {}
|
||||
bind_data = data.get('bind') or {}
|
||||
user_id = data.get('user_id')
|
||||
permission_updated = False
|
||||
|
||||
wecom_userid = (bind_data.get('wecom_userid') or '').strip()
|
||||
wecom_unionid = (bind_data.get('wecom_unionid') or '').strip()
|
||||
if not wecom_userid:
|
||||
return jsonify({'error': 'bind.wecom_userid is required'}), 400
|
||||
|
||||
if create_user:
|
||||
username = (user_data.get('username') or '').strip()
|
||||
if not username:
|
||||
return jsonify({'error': 'user.username is required when create_user=true'}), 400
|
||||
if db.session.query(User).filter_by(username=username).first():
|
||||
return jsonify({'error': 'Username exists'}), 400
|
||||
|
||||
email = (user_data.get('email') or '').strip() or None
|
||||
employee_id = (user_data.get('employee_id') or '').strip() or None
|
||||
phone_number = (user_data.get('phone_number') or '').strip() or None
|
||||
if email and db.session.query(User).filter_by(email=email).first():
|
||||
return jsonify({'error': 'Email already exists'}), 400
|
||||
if employee_id and db.session.query(User).filter_by(employee_id=employee_id).first():
|
||||
return jsonify({'error': 'Employee ID already exists'}), 400
|
||||
if phone_number and db.session.query(User).filter_by(phone_number=phone_number).first():
|
||||
return jsonify({'error': 'Phone number already exists'}), 400
|
||||
|
||||
user = User(
|
||||
username=username,
|
||||
email=email,
|
||||
department=user_data.get('department'),
|
||||
role=user_data.get('role', 'user'),
|
||||
status=user_data.get('status', 'active'),
|
||||
real_name=user_data.get('real_name'),
|
||||
employee_id=employee_id,
|
||||
phone_number=phone_number,
|
||||
)
|
||||
password = user_data.get('password')
|
||||
user.set_password(password or uuid.uuid4().hex)
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
binding_status = 'created'
|
||||
else:
|
||||
if user_id is None:
|
||||
user_id = user_data.get('id')
|
||||
if user_id is None:
|
||||
return jsonify({'error': 'user_id is required when create_user=false'}), 400
|
||||
try:
|
||||
user_id = int(user_id)
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({'error': 'user_id must be integer'}), 400
|
||||
user = db.session.get(User, user_id)
|
||||
if not user:
|
||||
return jsonify({'error': 'User not found'}), 404
|
||||
binding_status = 'updated'
|
||||
|
||||
dup = db.session.query(User).filter(User.wecom_userid == wecom_userid, User.id != user.id).first()
|
||||
if dup:
|
||||
db.session.rollback()
|
||||
return jsonify({'error': f'wecom_userid already bound to user {dup.username}'}), 400
|
||||
if wecom_unionid:
|
||||
dup_union = db.session.query(User).filter(User.wecom_unionid == wecom_unionid, User.id != user.id).first()
|
||||
if dup_union:
|
||||
db.session.rollback()
|
||||
return jsonify({'error': f'wecom_unionid already bound to user {dup_union.username}'}), 400
|
||||
|
||||
user.wecom_userid = wecom_userid
|
||||
if wecom_unionid:
|
||||
user.wecom_unionid = wecom_unionid
|
||||
|
||||
has_agent_ids = 'agent_ids' in data
|
||||
if has_agent_ids:
|
||||
agent_ids = data.get('agent_ids', [])
|
||||
if not isinstance(agent_ids, list):
|
||||
db.session.rollback()
|
||||
return jsonify({'error': 'agent_ids must be array'}), 400
|
||||
if agent_ids:
|
||||
try:
|
||||
unique_ids = sorted({int(i) for i in agent_ids})
|
||||
except (TypeError, ValueError):
|
||||
db.session.rollback()
|
||||
return jsonify({'error': 'agent_ids must be integer array'}), 400
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(unique_ids)).all()
|
||||
if len(agents) != len(unique_ids):
|
||||
db.session.rollback()
|
||||
return jsonify({'error': 'Some agent_ids are invalid'}), 400
|
||||
user.agents = agents
|
||||
else:
|
||||
user.agents = []
|
||||
permission_updated = True
|
||||
|
||||
try:
|
||||
db.session.commit()
|
||||
except IntegrityError:
|
||||
db.session.rollback()
|
||||
return jsonify({'error': 'Provision failed due to data uniqueness conflict'}), 400
|
||||
|
||||
return jsonify({
|
||||
'status': 'ok',
|
||||
'user_id': user.id,
|
||||
'binding': binding_status,
|
||||
'permission_updated': permission_updated,
|
||||
}), 201 if create_user else 200
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/login-audits', methods=['GET'])
|
||||
@require_admin
|
||||
def get_wecom_login_audits():
|
||||
@@ -834,9 +1162,138 @@ def get_wecom_login_audits():
|
||||
'source': r.source,
|
||||
'status': r.status,
|
||||
'reason': r.reason,
|
||||
'error_code': r.error_code,
|
||||
'match_rules': r.match_rules,
|
||||
'match_operator': r.match_operator,
|
||||
'match_result': r.match_result,
|
||||
'wecom_userid': r.wecom_userid,
|
||||
'ip': r.ip,
|
||||
'user_agent': r.user_agent,
|
||||
'created_at': r.created_at.isoformat() if r.created_at else None,
|
||||
} for r in rows
|
||||
])
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/notify-settings', methods=['GET', 'PUT'])
|
||||
@require_admin
|
||||
def wecom_notify_settings():
|
||||
if request.method == 'GET':
|
||||
return jsonify(_serialize_wecom_notify_settings())
|
||||
|
||||
data = request.get_json() or {}
|
||||
updates = {}
|
||||
if 'enabled' in data:
|
||||
updates['WECOM_NOTIFY_ENABLED'] = bool(data.get('enabled'))
|
||||
if 'base_url' in data:
|
||||
updates['WECOM_NOTIFY_BASE_URL'] = str(data.get('base_url') or '').strip()
|
||||
if 'events' in data:
|
||||
events = data.get('events') or []
|
||||
if isinstance(events, list):
|
||||
updates['WECOM_NOTIFY_EVENTS'] = ','.join([str(x).strip() for x in events if str(x).strip()])
|
||||
|
||||
for key, value in updates.items():
|
||||
current_app.config[key] = value
|
||||
persist_env_settings(updates)
|
||||
|
||||
return jsonify({'status': 'ok', 'settings': _serialize_wecom_notify_settings()})
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/system-settings', methods=['GET', 'PUT'])
|
||||
@require_admin
|
||||
def wecom_system_settings():
|
||||
if request.method == 'GET':
|
||||
return jsonify(_serialize_wecom_system_settings())
|
||||
|
||||
data = request.get_json() or {}
|
||||
bool_keys = {
|
||||
'enabled': 'WECOM_ENABLED',
|
||||
'auto_create_user': 'WECOM_AUTO_CREATE_USER',
|
||||
'mobile_normalize': 'WECOM_MOBILE_NORMALIZE',
|
||||
}
|
||||
str_keys = {
|
||||
'corp_id': 'WECOM_CORP_ID',
|
||||
'agent_id': 'WECOM_AGENT_ID',
|
||||
'secret': 'WECOM_SECRET',
|
||||
'redirect_uri': 'WECOM_REDIRECT_URI',
|
||||
'match_rules': 'WECOM_MATCH_RULES',
|
||||
'match_operator': 'WECOM_MATCH_OPERATOR',
|
||||
'first_login_bind_mode': 'WECOM_FIRST_LOGIN_BIND_MODE',
|
||||
'first_login_input_fields': 'WECOM_FIRST_LOGIN_INPUT_FIELDS',
|
||||
'employee_id_source': 'WECOM_EMPLOYEE_ID_SOURCE',
|
||||
'callback_token': 'WECOM_CALLBACK_TOKEN',
|
||||
'encoding_aes_key': 'WECOM_ENCODING_AES_KEY',
|
||||
'callback_url': 'WECOM_CALLBACK_URL',
|
||||
'homepage_url': 'WECOM_HOMEPAGE_URL',
|
||||
'trusted_domain': 'WECOM_TRUSTED_DOMAIN',
|
||||
'public_base_url': 'WECOM_PUBLIC_BASE_URL',
|
||||
}
|
||||
|
||||
updates = {}
|
||||
for req_key, cfg_key in bool_keys.items():
|
||||
if req_key in data:
|
||||
updates[cfg_key] = bool(data.get(req_key))
|
||||
for req_key, cfg_key in str_keys.items():
|
||||
if req_key in data:
|
||||
updates[cfg_key] = str(data.get(req_key) or '').strip()
|
||||
|
||||
for key, value in updates.items():
|
||||
current_app.config[key] = value
|
||||
|
||||
if current_app.config.get('WECOM_MATCH_OPERATOR') not in {'AND', 'OR'}:
|
||||
current_app.config['WECOM_MATCH_OPERATOR'] = 'AND'
|
||||
updates['WECOM_MATCH_OPERATOR'] = 'AND'
|
||||
|
||||
if current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE') not in {'match_rules', 'input_verify'}:
|
||||
current_app.config['WECOM_FIRST_LOGIN_BIND_MODE'] = 'match_rules'
|
||||
updates['WECOM_FIRST_LOGIN_BIND_MODE'] = 'match_rules'
|
||||
|
||||
persist_env_settings(updates)
|
||||
|
||||
return jsonify({'status': 'ok', 'settings': _serialize_wecom_system_settings()})
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/integration-manifest', methods=['GET'])
|
||||
@require_admin
|
||||
def wecom_integration_manifest():
|
||||
return jsonify(_serialize_wecom_integration_manifest())
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/notify-metrics', methods=['GET'])
|
||||
@require_admin
|
||||
def wecom_notify_metrics():
|
||||
now = datetime.utcnow()
|
||||
from_time = now - timedelta(days=30)
|
||||
total = db.session.query(func.count(WecomNotifyAudit.id)).filter(WecomNotifyAudit.created_at >= from_time).scalar() or 0
|
||||
sent = db.session.query(func.count(WecomNotifyAudit.id)).filter(
|
||||
WecomNotifyAudit.created_at >= from_time,
|
||||
WecomNotifyAudit.status == 'sent'
|
||||
).scalar() or 0
|
||||
opened_24h = db.session.query(func.count(WecomNotifyAudit.id)).filter(
|
||||
WecomNotifyAudit.created_at >= from_time,
|
||||
WecomNotifyAudit.opened_at.isnot(None),
|
||||
).scalar() or 0
|
||||
|
||||
by_event_rows = db.session.query(
|
||||
WecomNotifyAudit.event_type,
|
||||
WecomNotifyAudit.status,
|
||||
func.count(WecomNotifyAudit.id)
|
||||
).filter(WecomNotifyAudit.created_at >= from_time).group_by(
|
||||
WecomNotifyAudit.event_type,
|
||||
WecomNotifyAudit.status
|
||||
).all()
|
||||
by_event = {}
|
||||
for event_type, status, cnt in by_event_rows:
|
||||
if event_type not in by_event:
|
||||
by_event[event_type] = {'sent': 0, 'failed': 0}
|
||||
by_event[event_type][status] = int(cnt)
|
||||
|
||||
return jsonify({
|
||||
'window_days': 30,
|
||||
'total': int(total),
|
||||
'sent': int(sent),
|
||||
'failed': int(total - sent),
|
||||
'send_success_rate': round((sent / total) * 100, 2) if total else 0,
|
||||
'opened_24h': int(opened_24h),
|
||||
'opened_24h_rate': round((opened_24h / sent) * 100, 2) if sent else 0,
|
||||
'by_event': by_event,
|
||||
})
|
||||
+860
-60
File diff suppressed because it is too large.
Load diff
@@ -47,6 +47,25 @@ class Config:
|
||||
WECOM_SECRET = os.getenv('WECOM_SECRET')
|
||||
WECOM_REDIRECT_URI = os.getenv('WECOM_REDIRECT_URI')
|
||||
WECOM_AUTO_CREATE_USER = os.getenv('WECOM_AUTO_CREATE_USER', 'true').lower() == 'true'
|
||||
WECOM_MATCH_RULES = os.getenv('WECOM_MATCH_RULES', 'employee_id,mobile')
|
||||
WECOM_MATCH_OPERATOR = os.getenv('WECOM_MATCH_OPERATOR', 'AND').upper()
|
||||
WECOM_FIRST_LOGIN_BIND_MODE = os.getenv('WECOM_FIRST_LOGIN_BIND_MODE', 'match_rules')
|
||||
WECOM_FIRST_LOGIN_INPUT_FIELDS = os.getenv('WECOM_FIRST_LOGIN_INPUT_FIELDS', 'employee_id,mobile,email')
|
||||
WECOM_EMPLOYEE_ID_SOURCE = os.getenv('WECOM_EMPLOYEE_ID_SOURCE', 'userid')
|
||||
WECOM_MOBILE_NORMALIZE = os.getenv('WECOM_MOBILE_NORMALIZE', 'true').lower() == 'true'
|
||||
WECOM_CALLBACK_TOKEN = os.getenv('WECOM_CALLBACK_TOKEN', '')
|
||||
WECOM_ENCODING_AES_KEY = os.getenv('WECOM_ENCODING_AES_KEY', '')
|
||||
WECOM_CALLBACK_URL = os.getenv('WECOM_CALLBACK_URL', '')
|
||||
WECOM_HOMEPAGE_URL = os.getenv('WECOM_HOMEPAGE_URL', '')
|
||||
WECOM_TRUSTED_DOMAIN = os.getenv('WECOM_TRUSTED_DOMAIN', '')
|
||||
# Public HTTPS origin for WeCom console URLs (takes priority over notify base + request host).
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL', '')
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL', '')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv(
|
||||
'WECOM_NOTIFY_EVENTS',
|
||||
'permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed',
|
||||
)
|
||||
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
"""Persistent storage for runtime-editable application settings.
|
||||
|
||||
Settings managed from the admin console (e.g. WeCom configuration) need to
|
||||
survive process restarts AND container/image rebuilds in production. Writing
|
||||
only to ``backend/.env`` is not enough on Docker deployments because the
|
||||
container's writable layer is discarded on every ``docker compose up --build``.
|
||||
|
||||
Storage strategy:
|
||||
|
||||
1. Database (``app_settings`` table) - canonical, always authoritative.
|
||||
2. ``backend/.env`` - best-effort secondary write so local/dev workflows that
|
||||
read the env file directly (or restart without DB access) still see updates.
|
||||
3. ``os.environ`` - mirrored on write so legacy ``os.getenv`` consumers stay
|
||||
in sync within the running process.
|
||||
|
||||
On read we merge .env (lowest priority) over DB (highest priority); the DB
|
||||
value wins whenever it exists.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
from dotenv import dotenv_values, set_key
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
BACKEND_ENV_PATH = Path(__file__).resolve().parents[1] / '.env'
|
||||
WECOM_BOOL_KEYS = {
|
||||
'WECOM_ENABLED',
|
||||
'WECOM_AUTO_CREATE_USER',
|
||||
'WECOM_MOBILE_NORMALIZE',
|
||||
'WECOM_NOTIFY_ENABLED',
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _ensure_env_file_exists() -> bool:
|
||||
try:
|
||||
BACKEND_ENV_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not BACKEND_ENV_PATH.exists():
|
||||
BACKEND_ENV_PATH.write_text('', encoding='utf-8')
|
||||
return True
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot create %s: %s', BACKEND_ENV_PATH, exc)
|
||||
return False
|
||||
|
||||
|
||||
def _to_env_string(value: object) -> str:
|
||||
if isinstance(value, bool):
|
||||
return 'true' if value else 'false'
|
||||
if value is None:
|
||||
return ''
|
||||
return str(value)
|
||||
|
||||
|
||||
def _parse_env_value(key: str, value: object) -> object:
|
||||
if value is None:
|
||||
return None
|
||||
if key in WECOM_BOOL_KEYS:
|
||||
return str(value).strip().lower() == 'true'
|
||||
return str(value)
|
||||
|
||||
|
||||
def _matches_prefixes(key: str, prefixes: Iterable[str]) -> bool:
|
||||
return any(key.startswith(prefix) for prefix in prefixes)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Database read/write (primary store)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _persist_to_db(values: dict[str, str]) -> bool:
|
||||
"""Write key/value pairs into the ``app_settings`` table.
|
||||
|
||||
Returns True if every value was committed, False otherwise. The function
|
||||
is defensive: it must not raise, because settings persistence is also
|
||||
written to ``.env`` and we don't want to fail the API request.
|
||||
"""
|
||||
if not values:
|
||||
return True
|
||||
try:
|
||||
from app import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover - import safety net
|
||||
logger.warning('AppSetting model unavailable: %s', exc)
|
||||
return False
|
||||
|
||||
try:
|
||||
for key, value in values.items():
|
||||
existing = db.session.get(AppSetting, key)
|
||||
if existing is None:
|
||||
db.session.add(AppSetting(key=key, value=value))
|
||||
else:
|
||||
existing.value = value
|
||||
db.session.commit()
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.warning('Failed to persist settings to DB: %s', exc)
|
||||
try:
|
||||
db.session.rollback()
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
try:
|
||||
from app import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover
|
||||
logger.debug('AppSetting model unavailable for read: %s', exc)
|
||||
return {}
|
||||
|
||||
try:
|
||||
rows = db.session.query(AppSetting).all()
|
||||
except Exception as exc:
|
||||
# Most common case: the migration has not been applied yet on a
|
||||
# freshly-built container. Degrade gracefully to .env-only mode.
|
||||
logger.debug('app_settings table not readable yet: %s', exc)
|
||||
try:
|
||||
db.session.rollback()
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
return {}
|
||||
|
||||
result: dict[str, str] = {}
|
||||
for row in rows:
|
||||
if row.key and _matches_prefixes(row.key, prefixes):
|
||||
result[row.key] = row.value if row.value is not None else ''
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# .env read/write (secondary store, best-effort)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _persist_to_env_file(values: dict[str, str]) -> bool:
|
||||
if not values:
|
||||
return True
|
||||
if not _ensure_env_file_exists():
|
||||
return False
|
||||
ok = True
|
||||
for key, value in values.items():
|
||||
try:
|
||||
set_key(str(BACKEND_ENV_PATH), key, value, quote_mode='auto')
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot write %s to %s: %s', key, BACKEND_ENV_PATH, exc)
|
||||
ok = False
|
||||
return ok
|
||||
|
||||
|
||||
def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
if not BACKEND_ENV_PATH.exists():
|
||||
return {}
|
||||
try:
|
||||
loaded = dotenv_values(BACKEND_ENV_PATH)
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot read %s: %s', BACKEND_ENV_PATH, exc)
|
||||
return {}
|
||||
return {
|
||||
key: (value if value is not None else '')
|
||||
for key, value in loaded.items()
|
||||
if key and _matches_prefixes(key, prefixes)
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public API
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
||||
"""Persist settings to the canonical store and mirror to ``os.environ``.
|
||||
|
||||
Order:
|
||||
1. Mirror to ``os.environ`` so the current process picks them up
|
||||
immediately.
|
||||
2. Persist to the database (canonical, survives container rebuilds).
|
||||
3. Best-effort write to ``backend/.env`` so dev workflows that grep the
|
||||
file or restart without DB access keep working.
|
||||
"""
|
||||
if not values:
|
||||
return {}
|
||||
|
||||
persisted: dict[str, str] = {}
|
||||
for key, value in values.items():
|
||||
env_value = _to_env_string(value)
|
||||
os.environ[key] = env_value
|
||||
persisted[key] = env_value
|
||||
|
||||
db_ok = _persist_to_db(persisted)
|
||||
file_ok = _persist_to_env_file(persisted)
|
||||
|
||||
if not db_ok and not file_ok:
|
||||
logger.error(
|
||||
'Failed to persist settings %s to BOTH database and .env file. '
|
||||
'Settings will be lost when the process restarts.',
|
||||
list(persisted.keys()),
|
||||
)
|
||||
|
||||
return persisted
|
||||
|
||||
|
||||
def apply_env_settings(prefixes: tuple[str, ...] = ('WECOM_',)) -> dict[str, object]:
|
||||
"""Load settings from the canonical store and apply to ``os.environ``.
|
||||
|
||||
DB values take priority over ``backend/.env`` values; both are merged so
|
||||
keys that only live in the env file (e.g. fresh deploy before any admin
|
||||
edit) are still honored.
|
||||
"""
|
||||
file_values = _load_from_env_file(prefixes)
|
||||
db_values = _load_from_db(prefixes)
|
||||
|
||||
merged: dict[str, str] = {**file_values, **db_values}
|
||||
|
||||
applied: dict[str, object] = {}
|
||||
for key, raw_value in merged.items():
|
||||
parsed = _parse_env_value(key, raw_value)
|
||||
os.environ[key] = _to_env_string(parsed)
|
||||
applied[key] = parsed
|
||||
return applied
|
||||
@@ -274,7 +274,71 @@ class LoginAudit(Base):
|
||||
source: Mapped[str] = mapped_column(String(20), default='password') # password / wecom
|
||||
status: Mapped[str] = mapped_column(String(20), default='success') # success / failed
|
||||
reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
match_rules: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
match_operator: Mapped[Optional[str]] = mapped_column(String(8), nullable=True)
|
||||
match_result: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ip: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
user_agent: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
|
||||
class WecomNotifyAudit(Base):
|
||||
"""
|
||||
企业微信触达审计表
|
||||
用途:记录企微消息发送结果与回流点击数据
|
||||
"""
|
||||
__tablename__ = 'wecom_notify_audits'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
event_type: Mapped[str] = mapped_column(String(64), index=True)
|
||||
status: Mapped[str] = mapped_column(String(20), default='sent', index=True) # sent / failed
|
||||
trace_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True, index=True)
|
||||
username: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
title: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
content: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
jump_url: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
opened_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
|
||||
|
||||
|
||||
class AppSetting(Base):
|
||||
"""
|
||||
应用运行时配置表(Key/Value)
|
||||
用途:将企业微信等管理员可编辑的配置长效保存到数据库,
|
||||
避免容器/部署重建后写入 backend/.env 的修改丢失。
|
||||
"""
|
||||
__tablename__ = 'app_settings'
|
||||
|
||||
key: Mapped[str] = mapped_column(String(128), primary_key=True)
|
||||
value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow
|
||||
)
|
||||
|
||||
|
||||
class WecomCallbackAudit(Base):
|
||||
"""
|
||||
企业微信回调审计表
|
||||
用途:记录消息与事件回调(安全模式解密后的内容摘要)
|
||||
"""
|
||||
__tablename__ = 'wecom_callback_audits'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
msg_signature: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
timestamp: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
nonce: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
encrypt_raw: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
decrypted_xml: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
msg_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
|
||||
event: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
from_user: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
|
||||
agent_id: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
msg_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
@@ -0,0 +1,93 @@
|
||||
"""
|
||||
WeCom (企业微信) callback crypto helpers — compatible with WXBizMsgCrypt layout.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import random
|
||||
import struct
|
||||
from typing import Optional
|
||||
|
||||
from Crypto.Cipher import AES
|
||||
|
||||
|
||||
def sha1_hex(parts: list[str]) -> str:
|
||||
merged = ''.join(sorted([str(p) for p in parts if p is not None]))
|
||||
return hashlib.sha1(merged.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _pkcs7_pad(data: bytes, block_size: int = 32) -> bytes:
|
||||
pad_len = block_size - (len(data) % block_size)
|
||||
return data + bytes([pad_len] * pad_len)
|
||||
|
||||
|
||||
def _pkcs7_unpad(data: bytes) -> bytes:
|
||||
if not data:
|
||||
return data
|
||||
pad_len = data[-1]
|
||||
if pad_len < 1 or pad_len > 32:
|
||||
raise ValueError('invalid pkcs7 padding')
|
||||
if data[-pad_len:] != bytes([pad_len] * pad_len):
|
||||
raise ValueError('invalid pkcs7 padding tail')
|
||||
return data[:-pad_len]
|
||||
|
||||
|
||||
def _aes_key_from_encoding_key(encoding_aes_key_b64: str) -> bytes:
|
||||
raw = (encoding_aes_key_b64 or '').strip()
|
||||
key = base64.b64decode(raw + '=')
|
||||
if len(key) != 32:
|
||||
raise ValueError('EncodingAESKey must decode to 32 bytes')
|
||||
return key
|
||||
|
||||
|
||||
def encrypt_wecom_aes(plain_text: str, encoding_aes_key_b64: str, corp_id: str) -> str:
|
||||
"""
|
||||
Encrypt plain text to base64 ciphertext (for tests / optional outbound use).
|
||||
"""
|
||||
aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64)
|
||||
iv = aes_key[:16]
|
||||
random_bytes = bytes(random.randint(0, 255) for _ in range(16))
|
||||
msg_bytes = plain_text.encode('utf-8')
|
||||
pack = (
|
||||
random_bytes
|
||||
+ struct.pack('>I', len(msg_bytes))
|
||||
+ msg_bytes
|
||||
+ corp_id.encode('utf-8')
|
||||
)
|
||||
padded = _pkcs7_pad(pack, 32)
|
||||
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
|
||||
encrypted = cipher.encrypt(padded)
|
||||
return base64.b64encode(encrypted).decode('ascii')
|
||||
|
||||
|
||||
def decrypt_wecom_aes(cipher_b64: str, encoding_aes_key_b64: str, corp_id: str) -> str:
|
||||
aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64)
|
||||
iv = aes_key[:16]
|
||||
cipher_bytes = base64.b64decode(cipher_b64)
|
||||
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
|
||||
plain_padded = cipher.decrypt(cipher_bytes)
|
||||
plain = _pkcs7_unpad(plain_padded)
|
||||
content = plain[16:]
|
||||
if len(content) < 4:
|
||||
raise ValueError('decrypted payload too short')
|
||||
xml_len = struct.unpack('>I', content[:4])[0]
|
||||
xml_bytes = content[4:4 + xml_len]
|
||||
tail = content[4 + xml_len:]
|
||||
if tail.decode('utf-8', errors='strict') != corp_id:
|
||||
raise ValueError('corp_id mismatch after decrypt')
|
||||
return xml_bytes.decode('utf-8')
|
||||
|
||||
|
||||
def extract_encrypt_field(xml_body: str) -> Optional[str]:
|
||||
if not xml_body:
|
||||
return None
|
||||
import re
|
||||
|
||||
m = re.search(r'<Encrypt><!\[CDATA\[(.*?)\]\]></Encrypt>', xml_body, re.DOTALL)
|
||||
if m:
|
||||
return m.group(1).strip()
|
||||
m2 = re.search(r'<Encrypt>(.*?)</Encrypt>', xml_body, re.DOTALL)
|
||||
if m2:
|
||||
return m2.group(1).strip()
|
||||
return None
|
||||
@@ -0,0 +1,146 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from urllib.parse import urlencode
|
||||
import uuid
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import User, WecomNotifyAudit
|
||||
|
||||
|
||||
_TOKEN_CACHE = {
|
||||
'token': None,
|
||||
'expires_at': None,
|
||||
}
|
||||
|
||||
|
||||
def _get_enabled_events() -> set[str]:
|
||||
raw = current_app.config.get('WECOM_NOTIFY_EVENTS', '')
|
||||
if isinstance(raw, str):
|
||||
return {x.strip() for x in raw.split(',') if x.strip()}
|
||||
if isinstance(raw, (list, tuple, set)):
|
||||
return {str(x).strip() for x in raw if str(x).strip()}
|
||||
return set()
|
||||
|
||||
|
||||
def _build_jump_url(path: str, trace_id: str, params: dict | None = None) -> str:
|
||||
base = current_app.config.get('WECOM_NOTIFY_BASE_URL') or ''
|
||||
if not base:
|
||||
return ''
|
||||
base = base.rstrip('/')
|
||||
if not path.startswith('/'):
|
||||
path = f'/{path}'
|
||||
merged = {'wecom_trace': trace_id}
|
||||
if params:
|
||||
merged.update({k: v for k, v in params.items() if v is not None})
|
||||
return f'{base}{path}?{urlencode(merged)}'
|
||||
|
||||
|
||||
def _get_access_token() -> str:
|
||||
now = datetime.utcnow()
|
||||
token = _TOKEN_CACHE.get('token')
|
||||
expires_at = _TOKEN_CACHE.get('expires_at')
|
||||
if token and expires_at and now < expires_at:
|
||||
return token
|
||||
|
||||
corp_id = current_app.config.get('WECOM_CORP_ID')
|
||||
secret = current_app.config.get('WECOM_SECRET')
|
||||
resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/gettoken',
|
||||
params={'corpid': corp_id, 'corpsecret': secret},
|
||||
timeout=8,
|
||||
)
|
||||
data = resp.json()
|
||||
if data.get('errcode') != 0 or not data.get('access_token'):
|
||||
raise RuntimeError(f"Failed to fetch WeCom token: {data}")
|
||||
|
||||
_TOKEN_CACHE['token'] = data['access_token']
|
||||
_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60))
|
||||
return data['access_token']
|
||||
|
||||
|
||||
def send_wecom_event_message(
|
||||
*,
|
||||
event_type: str,
|
||||
user: User,
|
||||
title: str,
|
||||
content: str,
|
||||
jump_path: str = '/workspace',
|
||||
jump_params: dict | None = None,
|
||||
) -> dict:
|
||||
trace_id = uuid.uuid4().hex
|
||||
audit = WecomNotifyAudit(
|
||||
event_type=event_type,
|
||||
status='failed',
|
||||
trace_id=trace_id,
|
||||
user_id=user.id if user else None,
|
||||
username=user.username if user else None,
|
||||
wecom_userid=user.wecom_userid if user else None,
|
||||
title=title,
|
||||
content=content,
|
||||
)
|
||||
db.session.add(audit)
|
||||
|
||||
if not current_app.config.get('WECOM_NOTIFY_ENABLED', True):
|
||||
audit.error_code = 'NOTIFY_DISABLED'
|
||||
audit.error_message = 'WECOM_NOTIFY_ENABLED=false'
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'notify_disabled'}
|
||||
|
||||
if event_type not in _get_enabled_events():
|
||||
audit.error_code = 'EVENT_DISABLED'
|
||||
audit.error_message = f'event {event_type} disabled'
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'event_disabled'}
|
||||
|
||||
if not user or not user.wecom_userid:
|
||||
audit.error_code = 'WECOM_USER_UNBOUND'
|
||||
audit.error_message = 'user has no wecom_userid'
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'user_unbound'}
|
||||
|
||||
try:
|
||||
token = _get_access_token()
|
||||
jump_url = _build_jump_url(jump_path, trace_id, jump_params)
|
||||
audit.jump_url = jump_url
|
||||
payload = {
|
||||
'touser': user.wecom_userid,
|
||||
'msgtype': 'textcard',
|
||||
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
||||
'textcard': {
|
||||
'title': title[:120],
|
||||
'description': (content or '')[:1024],
|
||||
'url': jump_url or (current_app.config.get('WECOM_NOTIFY_BASE_URL') or 'https://work.weixin.qq.com'),
|
||||
'btntxt': '查看详情',
|
||||
},
|
||||
'safe': 0,
|
||||
}
|
||||
resp = requests.post(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/message/send',
|
||||
params={'access_token': token},
|
||||
json=payload,
|
||||
timeout=8,
|
||||
)
|
||||
data = resp.json()
|
||||
if data.get('errcode') == 0:
|
||||
audit.status = 'sent'
|
||||
return {'ok': True, 'trace_id': trace_id}
|
||||
|
||||
audit.error_code = str(data.get('errcode'))
|
||||
audit.error_message = str(data.get('errmsg', 'unknown error'))[:255]
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'send_failed', 'raw': data}
|
||||
except Exception as exc:
|
||||
audit.error_code = 'EXCEPTION'
|
||||
audit.error_message = str(exc)[:255]
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'exception'}
|
||||
|
||||
|
||||
def mark_wecom_message_opened(trace_id: str) -> bool:
|
||||
if not trace_id:
|
||||
return False
|
||||
row = db.session.query(WecomNotifyAudit).filter_by(trace_id=trace_id).first()
|
||||
if not row:
|
||||
return False
|
||||
if not row.opened_at:
|
||||
row.opened_at = datetime.utcnow()
|
||||
return True
|
||||
Reference in new issue
Block a user