236 lines
8.2 KiB
Python
236 lines
8.2 KiB
Python
"""
|
|
backend/app/services/auth/wecom_auth_service.py
|
|
|
|
用途:企业微信 OAuth 身份解析、匹配规则与 access_token 缓存。
|
|
依赖:flask.current_app、requests、models.User。
|
|
逻辑:由 api/user 企微登录路由、services/admin/wecom_admin_service 调用。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
from datetime import datetime, timedelta
|
|
|
|
import requests
|
|
from flask import current_app
|
|
from sqlalchemy import and_, or_
|
|
|
|
from app import db
|
|
from app.models import User
|
|
|
|
ACCESS_TOKEN_CACHE: dict = {'token': None, 'expires_at': None}
|
|
STATE_CACHE: dict = {}
|
|
BIND_SESSION_CACHE: dict = {}
|
|
|
|
ALLOWED_MATCH_FIELDS = {'employee_id', 'mobile', 'email'}
|
|
|
|
|
|
def clean_str(value) -> str | 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 parse_field_list(raw_value, default_fields: list[str]) -> list[str]:
|
|
"""解析逗号分隔的企微匹配/输入字段列表。"""
|
|
if isinstance(raw_value, str):
|
|
pieces = [item.strip().lower() for item in raw_value.split(',')]
|
|
elif isinstance(raw_value, (list, tuple)):
|
|
pieces = [str(item).strip().lower() for item in raw_value]
|
|
else:
|
|
pieces = []
|
|
result = []
|
|
for piece in pieces:
|
|
if piece in ALLOWED_MATCH_FIELDS and piece not in result:
|
|
result.append(piece)
|
|
return result or list(default_fields)
|
|
|
|
|
|
def get_config_missing_fields() -> list[str]:
|
|
"""返回缺失的企微登录配置键名。"""
|
|
missing = []
|
|
if not current_app.config.get('WECOM_ENABLED'):
|
|
missing.append('WECOM_ENABLED')
|
|
if not clean_str(current_app.config.get('WECOM_CORP_ID')):
|
|
missing.append('WECOM_CORP_ID')
|
|
if not clean_str(current_app.config.get('WECOM_AGENT_ID')):
|
|
missing.append('WECOM_AGENT_ID')
|
|
if not clean_str(current_app.config.get('WECOM_SECRET')):
|
|
missing.append('WECOM_SECRET')
|
|
return missing
|
|
|
|
|
|
def is_configured() -> bool:
|
|
return len(get_config_missing_fields()) == 0
|
|
|
|
|
|
def get_access_token() -> str:
|
|
"""获取企微 access_token(带进程内缓存)。"""
|
|
now = datetime.utcnow()
|
|
token = ACCESS_TOKEN_CACHE.get('token')
|
|
expires_at = ACCESS_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}')
|
|
ACCESS_TOKEN_CACHE['token'] = data['access_token']
|
|
ACCESS_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60))
|
|
return data['access_token']
|
|
|
|
|
|
def normalize_mobile(mobile: str) -> str | None:
|
|
mobile = clean_str(mobile)
|
|
if not mobile:
|
|
return None
|
|
digits = re.sub(r'\D', '', mobile)
|
|
if not digits:
|
|
return mobile
|
|
if digits.startswith('0086'):
|
|
digits = digits[4:]
|
|
elif digits.startswith('86') and len(digits) > 11:
|
|
digits = digits[2:]
|
|
return digits
|
|
|
|
|
|
def extract_extattr_value(wecom_user: dict, key: str) -> str | None:
|
|
extattr = wecom_user.get('extattr') or {}
|
|
attrs = extattr.get('attrs') if isinstance(extattr, dict) else None
|
|
if not isinstance(attrs, list):
|
|
return None
|
|
for attr in attrs:
|
|
if not isinstance(attr, dict):
|
|
continue
|
|
if clean_str(attr.get('name')) != key:
|
|
continue
|
|
raw = attr.get('value')
|
|
if isinstance(raw, dict):
|
|
raw = raw.get('text') or raw.get('web') or raw.get('value')
|
|
return clean_str(raw)
|
|
return None
|
|
|
|
|
|
def get_match_config() -> tuple[list[str], str]:
|
|
raw_rules = current_app.config.get('WECOM_MATCH_RULES', 'employee_id,mobile')
|
|
rules = parse_field_list(raw_rules, ['employee_id', 'mobile'])
|
|
operator = str(current_app.config.get('WECOM_MATCH_OPERATOR', 'AND')).upper()
|
|
if operator not in {'AND', 'OR'}:
|
|
operator = 'AND'
|
|
return rules, operator
|
|
|
|
|
|
def get_first_login_bind_mode() -> str:
|
|
mode = clean_str(current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE')) or 'match_rules'
|
|
mode = mode.lower()
|
|
if mode not in {'match_rules', 'input_verify'}:
|
|
mode = 'match_rules'
|
|
return mode
|
|
|
|
|
|
def get_first_login_input_fields() -> list[str]:
|
|
raw_fields = current_app.config.get('WECOM_FIRST_LOGIN_INPUT_FIELDS', 'employee_id,mobile,email')
|
|
return parse_field_list(raw_fields, ['employee_id', 'mobile', 'email'])
|
|
|
|
|
|
def extract_identity(wecom_user: dict) -> dict:
|
|
"""从企微 user/get 响应提取标准化身份字段。"""
|
|
userid = clean_str(wecom_user.get('userid'))
|
|
unionid = clean_str(wecom_user.get('unionid'))
|
|
email = clean_str(wecom_user.get('email'))
|
|
mobile_raw = clean_str(wecom_user.get('mobile'))
|
|
normalize_flag = bool(current_app.config.get('WECOM_MOBILE_NORMALIZE', True))
|
|
mobile = normalize_mobile(mobile_raw) if normalize_flag else mobile_raw
|
|
employee_id_source = clean_str(current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE')) or 'userid'
|
|
if employee_id_source == 'userid':
|
|
employee_id = userid
|
|
elif employee_id_source.startswith('extattr:'):
|
|
employee_id = extract_extattr_value(wecom_user, employee_id_source.split(':', 1)[1])
|
|
else:
|
|
employee_id = clean_str(wecom_user.get(employee_id_source))
|
|
return {
|
|
'wecom_userid': userid,
|
|
'wecom_unionid': unionid,
|
|
'name': clean_str(wecom_user.get('name')) or userid or 'wecom_user',
|
|
'email': email,
|
|
'mobile': mobile,
|
|
'mobile_raw': mobile_raw,
|
|
'employee_id': employee_id,
|
|
}
|
|
|
|
|
|
def _mobile_candidates(identity: dict) -> list[str]:
|
|
values = []
|
|
for item in [identity.get('mobile'), identity.get('mobile_raw')]:
|
|
item = clean_str(item)
|
|
if item and item not in values:
|
|
values.append(item)
|
|
return values
|
|
|
|
|
|
def find_users_by_input_field(field: str, value):
|
|
field = clean_str(field)
|
|
if field not in ALLOWED_MATCH_FIELDS:
|
|
return [], 'invalid_field'
|
|
if field == 'employee_id':
|
|
needle = clean_str(value)
|
|
if not needle:
|
|
return [], 'employee_id'
|
|
return db.session.query(User).filter(User.employee_id == needle).all(), None
|
|
if field == 'email':
|
|
needle = clean_str(value)
|
|
if not needle:
|
|
return [], 'email'
|
|
return db.session.query(User).filter(User.email == needle).all(), None
|
|
if field == 'mobile':
|
|
raw_mobile = clean_str(value)
|
|
normalized_mobile = normalize_mobile(raw_mobile)
|
|
candidates = []
|
|
for item in [normalized_mobile, raw_mobile]:
|
|
item = clean_str(item)
|
|
if item and item not in candidates:
|
|
candidates.append(item)
|
|
if not candidates:
|
|
return [], 'mobile'
|
|
return db.session.query(User).filter(User.phone_number.in_(candidates)).all(), None
|
|
return [], 'invalid_field'
|
|
|
|
|
|
def find_users_by_match_rules(identity: dict, rules: list, operator: str) -> tuple[list[User], list[str]]:
|
|
filters = []
|
|
missing = []
|
|
for rule in rules:
|
|
if rule == 'employee_id':
|
|
employee_id = clean_str(identity.get('employee_id'))
|
|
if not employee_id:
|
|
missing.append('employee_id')
|
|
else:
|
|
filters.append(User.employee_id == employee_id)
|
|
elif rule == 'mobile':
|
|
candidates = _mobile_candidates(identity)
|
|
if not candidates:
|
|
missing.append('mobile')
|
|
else:
|
|
filters.append(User.phone_number.in_(candidates))
|
|
elif rule == 'email':
|
|
email = clean_str(identity.get('email'))
|
|
if not email:
|
|
missing.append('email')
|
|
else:
|
|
filters.append(User.email == email)
|
|
if missing:
|
|
return [], missing
|
|
if not filters:
|
|
return [], ['match_rules']
|
|
clause = and_(*filters) if operator == 'AND' else or_(*filters)
|
|
users = db.session.query(User).filter(clause).all()
|
|
return users, []
|