1848 lines
85 KiB
Python
1848 lines
85 KiB
Python
"""
|
||
backend/app/api/user.py
|
||
|
||
用途:当前用户域 API(Casdoor 登录、企微 OAuth、首页、FAQ、反馈等)。
|
||
依赖:app.core.auth.jwt、app.core.errors、models、wecom/dify 相关 services。
|
||
逻辑:薄路由层鉴权与参数校验;Casdoor/企微 OAuth 委托 services/auth/*。
|
||
"""
|
||
from flask import Blueprint, request, jsonify, current_app
|
||
from app import db
|
||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
|
||
from app.services.feedback_notify import send_feedback_group_notification
|
||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
||
from app.core.auth.jwt import get_current_user as _auth_current_user
|
||
from app.core.auth.jwt import issue_local_access_token
|
||
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
|
||
from sqlalchemy import and_, or_, inspect, insert
|
||
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 (
|
||
AppError,
|
||
ConflictError,
|
||
ForbiddenError,
|
||
NotFoundError,
|
||
ServiceUnavailableError,
|
||
UnauthorizedError,
|
||
ValidationError,
|
||
raise_for_status,
|
||
)
|
||
from app.services.auth import casdoor_service as _casdoor_svc
|
||
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
|
||
_WECOM_STATE_CACHE = _wecom_svc.STATE_CACHE
|
||
_WECOM_BIND_SESSION_CACHE = _wecom_svc.BIND_SESSION_CACHE
|
||
_PASSWORD_RESET_RATE_CACHE = {}
|
||
_PASSWORD_RESET_GENERIC_MESSAGE = 'If the account exists and WeCom is bound, a reset link has been sent to your WeCom.'
|
||
_ALLOWED_WECOM_MATCH_FIELDS = {'employee_id', 'mobile', 'email'}
|
||
_LOGIN_AUDIT_COLUMNS_CACHE = None
|
||
_CASDOOR_OIDC_CACHE = {'value': None, 'expires_at': None}
|
||
|
||
def _token_brief(token: str) -> str:
|
||
if not token:
|
||
return 'empty'
|
||
text = str(token)
|
||
if len(text) <= 16:
|
||
return f'len={len(text)}:{text}'
|
||
return f'len={len(text)}:{text[:8]}...{text[-8:]}'
|
||
|
||
def _is_users_pk_sequence_error(exc: Exception) -> bool:
|
||
message = str(exc)
|
||
return 'null value in column "id"' in message and 'relation "users"' in message
|
||
|
||
class WeComLoginError(AppError):
|
||
def __init__(self, error: str, error_code: str, status_code: int, reason: str = None, extra: dict = None):
|
||
details = dict(extra or {})
|
||
if reason:
|
||
details['reason'] = reason
|
||
super().__init__(code=error_code, message=error, http_status=status_code, details=details)
|
||
self.error = error
|
||
self.error_code = error_code
|
||
self.status_code = status_code
|
||
self.reason = reason
|
||
self.extra = extra or {}
|
||
|
||
def _write_login_audit(source: str, status: str, user: User=None, username: str=None, reason: str=None, wecom_userid: str=None, error_code: str=None, match_rules: list=None, match_operator: str=None, match_result: str=None):
|
||
payload = {'user_id': user.id if user else None, 'username': username or (user.username if user else None), 'source': source, 'status': status, 'reason': reason, 'error_code': error_code, 'match_rules': ','.join(match_rules) if isinstance(match_rules, list) else match_rules, 'match_operator': match_operator, 'match_result': match_result, 'wecom_userid': wecom_userid, 'ip': request.headers.get('X-Forwarded-For', request.remote_addr), 'user_agent': (request.user_agent.string or '')[:255], 'created_at': datetime.utcnow()}
|
||
try:
|
||
supported_columns = _get_login_audit_supported_columns()
|
||
if not supported_columns:
|
||
return
|
||
filtered_payload = {key: value for key, value in payload.items() if key in supported_columns}
|
||
if not filtered_payload:
|
||
return
|
||
_execute_login_audit_insert(filtered_payload)
|
||
except Exception:
|
||
pass
|
||
|
||
def _get_login_audit_supported_columns():
|
||
global _LOGIN_AUDIT_COLUMNS_CACHE
|
||
if _LOGIN_AUDIT_COLUMNS_CACHE is not None:
|
||
return _LOGIN_AUDIT_COLUMNS_CACHE
|
||
try:
|
||
columns = {column['name'] for column in inspect(db.engine).get_columns(LoginAudit.__tablename__)}
|
||
except Exception:
|
||
columns = set()
|
||
_LOGIN_AUDIT_COLUMNS_CACHE = columns
|
||
return columns
|
||
|
||
def _execute_login_audit_insert(payload: dict):
|
||
nested = db.session.begin_nested()
|
||
try:
|
||
db.session.execute(insert(LoginAudit.__table__).values(**payload))
|
||
db.session.flush()
|
||
nested.commit()
|
||
except Exception:
|
||
nested.rollback()
|
||
raise
|
||
|
||
def _get_current_user():
|
||
"""
|
||
Resolve current authenticated user for API handlers.
|
||
|
||
Behavior:
|
||
1) Prefer JWT Bearer token validation (Casdoor JWKS).
|
||
2) Optional legacy header fallback depends on AUTH_LEGACY_HEADER_ENABLED.
|
||
3) Returns None when authentication cannot be established.
|
||
"""
|
||
return _auth_current_user()
|
||
|
||
def _run_db_with_retry(operation, *, label: str):
|
||
try:
|
||
return operation()
|
||
except (OperationalError, DatabaseError) as exc:
|
||
current_app.logger.warning('%s failed on first attempt: %s', label, exc)
|
||
db.session.rollback()
|
||
db.session.remove()
|
||
try:
|
||
db.engine.dispose()
|
||
except Exception as dispose_exc:
|
||
current_app.logger.warning('%s dispose engine failed: %s', label, dispose_exc)
|
||
return operation()
|
||
|
||
def _get_wecom_config_missing_fields() -> list[str]:
|
||
return _wecom_svc.get_config_missing_fields()
|
||
|
||
|
||
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}'
|
||
|
||
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'))
|
||
|
||
def _get_casdoor_oidc_metadata():
|
||
now = datetime.utcnow()
|
||
cached = _CASDOOR_OIDC_CACHE.get('value')
|
||
exp = _CASDOOR_OIDC_CACHE.get('expires_at')
|
||
if cached and exp and (exp > now):
|
||
return cached
|
||
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
|
||
if not base:
|
||
raise RuntimeError('CASDOOR_BASE_URL is not configured')
|
||
resp = requests.get(f'{base}/.well-known/openid-configuration', timeout=8)
|
||
resp.raise_for_status()
|
||
data = resp.json() or {}
|
||
_CASDOOR_OIDC_CACHE['value'] = data
|
||
_CASDOOR_OIDC_CACHE['expires_at'] = now + timedelta(minutes=10)
|
||
return data
|
||
|
||
def _resolve_user_from_casdoor_claims(claims: dict):
|
||
username = _clean_str(claims.get('preferred_username')) or _clean_str(claims.get('name'))
|
||
email = _clean_str(claims.get('email'))
|
||
current_app.logger.info('[casdoor_login] claims preferred_username=%s name=%s email=%s sub=%s', _clean_str(claims.get('preferred_username')), _clean_str(claims.get('name')), email, _clean_str(claims.get('sub')))
|
||
user = None
|
||
if username:
|
||
user = db.session.query(User).filter_by(username=username).first()
|
||
if not user and email:
|
||
user = db.session.query(User).filter_by(email=email).first()
|
||
if not user:
|
||
raise WeComLoginError(error='No local user matched Casdoor identity. Please contact admin to provision account.', error_code='CASDOOR_USER_NOT_FOUND', status_code=403)
|
||
if user.status != 'active':
|
||
raise WeComLoginError(error='Account is disabled', error_code='ACCOUNT_DISABLED', status_code=403)
|
||
return user
|
||
|
||
def _casdoor_exchange_code(code: str, redirect_uri: str):
|
||
meta = _get_casdoor_oidc_metadata()
|
||
token_endpoint = meta.get('token_endpoint')
|
||
if not token_endpoint:
|
||
raise RuntimeError('Casdoor token endpoint missing')
|
||
payload = {'grant_type': 'authorization_code', 'code': code, 'client_id': current_app.config.get('CASDOOR_CLIENT_ID') or '', 'client_secret': current_app.config.get('CASDOOR_CLIENT_SECRET') or '', 'redirect_uri': redirect_uri or (current_app.config.get('CASDOOR_REDIRECT_URI') or '')}
|
||
resp = requests.post(token_endpoint, data=payload, timeout=8)
|
||
data = resp.json() or {}
|
||
if not resp.ok or not data.get('access_token'):
|
||
_raise_casdoor_auth_error(data, context='code')
|
||
return data
|
||
|
||
def _casdoor_refresh_token(refresh_token: str):
|
||
meta = _get_casdoor_oidc_metadata()
|
||
token_endpoint = meta.get('token_endpoint')
|
||
payload = {'grant_type': 'refresh_token', 'refresh_token': refresh_token, 'client_id': current_app.config.get('CASDOOR_CLIENT_ID') or '', 'client_secret': current_app.config.get('CASDOOR_CLIENT_SECRET') or ''}
|
||
resp = requests.post(token_endpoint, data=payload, timeout=8)
|
||
data = resp.json() or {}
|
||
if not resp.ok or not data.get('access_token'):
|
||
_raise_casdoor_auth_error(data, context='refresh')
|
||
return data
|
||
|
||
def _casdoor_userinfo(access_token: str):
|
||
meta = _get_casdoor_oidc_metadata()
|
||
userinfo_endpoint = meta.get('userinfo_endpoint')
|
||
if not userinfo_endpoint:
|
||
raise RuntimeError('Casdoor userinfo endpoint missing')
|
||
resp = requests.get(userinfo_endpoint, headers={'Authorization': f'Bearer {access_token}'}, timeout=8)
|
||
data = resp.json() or {}
|
||
if not resp.ok:
|
||
raise RuntimeError(f'Casdoor userinfo failed: {data}')
|
||
return data
|
||
|
||
def _casdoor_password_login(username: str, password: str):
|
||
"""
|
||
Resource-owner password login against Casdoor token endpoint.
|
||
Requires the Casdoor application to enable password grant.
|
||
"""
|
||
meta = _get_casdoor_oidc_metadata()
|
||
token_endpoint = meta.get('token_endpoint')
|
||
if not token_endpoint:
|
||
raise RuntimeError('Casdoor token endpoint missing')
|
||
payload = {'grant_type': 'password', 'username': username, 'password': password, 'client_id': current_app.config.get('CASDOOR_CLIENT_ID') or '', 'client_secret': current_app.config.get('CASDOOR_CLIENT_SECRET') or '', 'scope': current_app.config.get('CASDOOR_SCOPE') or 'openid profile email'}
|
||
resp = requests.post(token_endpoint, data=payload, timeout=8)
|
||
data = resp.json() or {}
|
||
if not resp.ok or not data.get('access_token'):
|
||
_raise_casdoor_auth_error(data, context='password')
|
||
return data
|
||
|
||
def _is_casdoor_login_mode() -> bool:
|
||
return (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() == 'casdoor'
|
||
|
||
def _is_casdoor_configured() -> bool:
|
||
return _casdoor_svc.is_casdoor_configured()
|
||
|
||
def _casdoor_user_owner() -> str:
|
||
return _casdoor_svc.casdoor_user_owner()
|
||
|
||
def _verify_casdoor_password(username: str, password: str):
|
||
_casdoor_password_login(username, password)
|
||
|
||
def _casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str):
|
||
return _casdoor_svc.casdoor_set_password(user_owner, user_name, old_password, new_password)
|
||
|
||
def _is_casdoor_user_exists_error(message: str) -> bool:
|
||
return _casdoor_svc.is_user_exists_error(message)
|
||
|
||
def _raise_casdoor_add_user_error(source) -> None:
|
||
_casdoor_svc.raise_add_user_error(source)
|
||
|
||
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 _raise_casdoor_update_user_error(source) -> None:
|
||
_casdoor_svc.raise_update_user_error(source)
|
||
|
||
def _casdoor_update_user(user_payload: dict):
|
||
return _casdoor_svc.casdoor_update_user(user_payload)
|
||
|
||
def _sync_casdoor_admin_set_password(user: User, new_password: str):
|
||
return _casdoor_svc.sync_admin_set_password(user, new_password)
|
||
|
||
def _sync_casdoor_update_user(user: User, *, new_password: str | None = None):
|
||
return _casdoor_svc.sync_update_user(user, new_password=new_password)
|
||
|
||
def _is_casdoor_password_error(message: str) -> bool:
|
||
return _casdoor_svc.is_password_error(message)
|
||
|
||
def _is_casdoor_user_missing_error(message: str) -> bool:
|
||
return _casdoor_svc.is_user_missing_error(message)
|
||
|
||
def _raise_casdoor_user_not_in_idp(source=None) -> None:
|
||
_casdoor_svc.raise_user_not_in_idp(source)
|
||
|
||
def _extract_casdoor_error_payload(source) -> dict:
|
||
return _casdoor_svc.extract_error_payload(source)
|
||
|
||
def _raise_casdoor_auth_error(source, *, context: str, status_code: int = 401) -> None:
|
||
_casdoor_svc.raise_auth_error(source, context=context, status_code=status_code)
|
||
|
||
def _raise_casdoor_set_password_error(source) -> None:
|
||
_casdoor_svc.raise_set_password_error(source)
|
||
|
||
def _raise_incorrect_current_password():
|
||
raise AppError(
|
||
code='AUTH.INCORRECT_CURRENT_PASSWORD',
|
||
message='Incorrect current password',
|
||
http_status=403,
|
||
)
|
||
|
||
def _verify_current_password_for_change(user, current_password: str):
|
||
if user.check_password(current_password):
|
||
return
|
||
if not _is_casdoor_configured():
|
||
_raise_incorrect_current_password()
|
||
try:
|
||
_verify_casdoor_password(user.username, current_password)
|
||
except AppError as e:
|
||
if e.code == 'CASDOOR_INVALID_CREDENTIALS':
|
||
_raise_incorrect_current_password()
|
||
raise
|
||
except RuntimeError as e:
|
||
if _is_casdoor_password_error(str(e)):
|
||
_raise_incorrect_current_password()
|
||
raise
|
||
|
||
def _sync_casdoor_password(username: str, current_password: str, new_password: str):
|
||
if not _is_casdoor_configured():
|
||
return
|
||
user_owner = _casdoor_user_owner()
|
||
try:
|
||
_casdoor_set_password(user_owner, username, current_password, new_password)
|
||
except AppError as first_error:
|
||
if first_error.code in ('CASDOOR_INVALID_CREDENTIALS', 'AUTH.INCORRECT_CURRENT_PASSWORD'):
|
||
_raise_incorrect_current_password()
|
||
raise
|
||
except RuntimeError as first_error:
|
||
if _is_casdoor_user_missing_error(str(first_error)):
|
||
_raise_casdoor_user_not_in_idp(first_error)
|
||
if _is_casdoor_password_error(str(first_error)):
|
||
_raise_incorrect_current_password()
|
||
try:
|
||
_casdoor_set_password(user_owner, username, '', new_password)
|
||
except RuntimeError:
|
||
raise first_error
|
||
|
||
def _cleanup_wecom_state_cache():
|
||
now = datetime.utcnow()
|
||
expired = [k for k, v in _WECOM_STATE_CACHE.items() if not v or v < now]
|
||
for k in expired:
|
||
_WECOM_STATE_CACHE.pop(k, None)
|
||
|
||
def _issue_wecom_state():
|
||
_cleanup_wecom_state_cache()
|
||
state = f'hxops_wecom_{uuid.uuid4().hex}'
|
||
_WECOM_STATE_CACHE[state] = datetime.utcnow() + timedelta(minutes=10)
|
||
return state
|
||
|
||
def _consume_wecom_state(state: str):
|
||
if not state:
|
||
return False
|
||
_cleanup_wecom_state_cache()
|
||
exp = _WECOM_STATE_CACHE.pop(state, None)
|
||
return bool(exp and exp > datetime.utcnow())
|
||
|
||
def _cleanup_wecom_bind_session_cache():
|
||
now = datetime.utcnow()
|
||
expired = [key for key, item in _WECOM_BIND_SESSION_CACHE.items() if not isinstance(item, dict) or not item.get('expires_at') or item['expires_at'] < now]
|
||
for key in expired:
|
||
_WECOM_BIND_SESSION_CACHE.pop(key, None)
|
||
|
||
def _issue_wecom_bind_session(identity: dict):
|
||
_cleanup_wecom_bind_session_cache()
|
||
token = f'hxops_wecom_bind_{uuid.uuid4().hex}'
|
||
_WECOM_BIND_SESSION_CACHE[token] = {'expires_at': datetime.utcnow() + timedelta(minutes=10), 'identity': dict(identity or {})}
|
||
return token
|
||
|
||
def _get_wecom_bind_session(token: str):
|
||
if not token:
|
||
return None
|
||
_cleanup_wecom_bind_session_cache()
|
||
item = _WECOM_BIND_SESSION_CACHE.get(token)
|
||
if not isinstance(item, dict):
|
||
return None
|
||
expires_at = item.get('expires_at')
|
||
if not expires_at or expires_at < datetime.utcnow():
|
||
_WECOM_BIND_SESSION_CACHE.pop(token, None)
|
||
return None
|
||
identity = item.get('identity')
|
||
return identity if isinstance(identity, dict) else None
|
||
|
||
def _consume_wecom_bind_session(token: str):
|
||
identity = _get_wecom_bind_session(token)
|
||
if identity is None:
|
||
return None
|
||
_WECOM_BIND_SESSION_CACHE.pop(token, None)
|
||
return identity
|
||
|
||
def _parse_wecom_field_list(raw_value, default_fields: list[str]):
|
||
return _wecom_svc.parse_field_list(raw_value, default_fields)
|
||
|
||
def _verify_wecom_msg_signature(msg_signature: str, token: str, timestamp: str, nonce: str, encrypt: str) -> bool:
|
||
if not msg_signature or not token or (not encrypt):
|
||
return False
|
||
expected = sha1_hex([token, str(timestamp or ''), str(nonce or ''), encrypt])
|
||
return expected == msg_signature
|
||
|
||
def _extract_xml_field(xml_text: str, tag: str):
|
||
if not xml_text:
|
||
return None
|
||
m = re.search(f'<{tag}><!\\[CDATA\\[(.*?)\\]\\]></{tag}>', xml_text, re.DOTALL)
|
||
if m:
|
||
return m.group(1).strip()
|
||
m2 = re.search(f'<{tag}>(.*?)</{tag}>', xml_text, re.DOTALL)
|
||
if m2:
|
||
return m2.group(1).strip()
|
||
return None
|
||
|
||
def _persist_wecom_callback_audit(*, msg_signature, timestamp, nonce, encrypt_raw, decrypted_xml=None, msg_type=None, event=None, from_user=None, agent_id=None, msg_id=None, error_message=None):
|
||
try:
|
||
row = WecomCallbackAudit(msg_signature=msg_signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_raw, decrypted_xml=decrypted_xml, msg_type=msg_type, event=event, from_user=from_user, agent_id=agent_id, msg_id=msg_id, error_message=error_message)
|
||
db.session.add(row)
|
||
db.session.commit()
|
||
except Exception:
|
||
db.session.rollback()
|
||
|
||
def _get_wecom_access_token():
|
||
return _wecom_svc.get_access_token()
|
||
|
||
def _build_login_payload(user: User, source: str='password', bind_status: str=None):
|
||
payload = {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'source': source, 'access_token': issue_local_access_token(user), 'token_type': 'Bearer'}
|
||
if bind_status:
|
||
payload['bind_status'] = bind_status
|
||
return payload
|
||
|
||
def _clean_str(value):
|
||
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_leave_int_flag(value, field_label: str):
|
||
if value in (0, 1):
|
||
return int(value)
|
||
text = _clean_str(value)
|
||
if text in ('0', '1'):
|
||
return int(text)
|
||
raise OALeaveWorkflowError(f'{field_label} 取值无效,应为 0 或 1。')
|
||
|
||
def _normalize_mobile(mobile: str):
|
||
mobile = _clean_str(mobile)
|
||
if not mobile:
|
||
return None
|
||
digits = re.sub('\\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_wecom_extattr_value(wecom_user: dict, key: str):
|
||
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_wecom_match_config():
|
||
return _wecom_svc.get_match_config()
|
||
|
||
def _get_wecom_first_login_bind_mode():
|
||
return _wecom_svc.get_first_login_bind_mode()
|
||
|
||
def _get_wecom_first_login_input_fields():
|
||
return _wecom_svc.get_first_login_input_fields()
|
||
|
||
def _extract_wecom_identity(wecom_user: dict):
|
||
return _wecom_svc.extract_identity(wecom_user)
|
||
|
||
def _mobile_candidates(identity: dict):
|
||
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_WECOM_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):
|
||
return _wecom_svc.find_users_by_match_rules(identity, rules, operator)
|
||
|
||
def _assert_wecom_binding_not_occupied(user: User, identity: dict):
|
||
wecom_userid = identity.get('wecom_userid')
|
||
wecom_unionid = identity.get('wecom_unionid')
|
||
if wecom_userid:
|
||
dup = db.session.query(User).filter(User.wecom_userid == wecom_userid, User.id != user.id).first()
|
||
if dup:
|
||
raise WeComLoginError(error=f'Current WeCom account has been bound to user: {dup.username}', error_code='WECOM_BIND_CONFLICT', status_code=409, reason='bind_conflict')
|
||
if wecom_unionid:
|
||
dup_union = db.session.query(User).filter(User.wecom_unionid == wecom_unionid, User.id != user.id).first()
|
||
if dup_union:
|
||
raise WeComLoginError(error=f'Current WeCom unionid has been bound to user: {dup_union.username}', error_code='WECOM_BIND_CONFLICT', status_code=409, reason='bind_conflict')
|
||
|
||
def _sync_user_from_wecom_identity(user: User, identity: dict):
|
||
_assert_wecom_binding_not_occupied(user, identity)
|
||
if identity.get('wecom_userid'):
|
||
user.wecom_userid = identity['wecom_userid']
|
||
if identity.get('wecom_unionid') and (not user.wecom_unionid):
|
||
user.wecom_unionid = identity['wecom_unionid']
|
||
if identity.get('name') and (not user.real_name):
|
||
user.real_name = identity['name']
|
||
if identity.get('email') and (not user.email):
|
||
dup_email = db.session.query(User).filter(User.email == identity['email'], User.id != user.id).first()
|
||
if not dup_email:
|
||
user.email = identity['email']
|
||
if identity.get('mobile') and (not user.phone_number):
|
||
candidates = _mobile_candidates(identity)
|
||
dup_mobile = db.session.query(User).filter(User.phone_number.in_(candidates), User.id != user.id).first()
|
||
if not dup_mobile:
|
||
user.phone_number = identity['mobile']
|
||
if identity.get('employee_id') and (not user.employee_id):
|
||
dup_employee = db.session.query(User).filter(User.employee_id == identity['employee_id'], User.id != user.id).first()
|
||
if not dup_employee:
|
||
user.employee_id = identity['employee_id']
|
||
|
||
def _create_user_from_wecom_identity(identity: dict) -> User:
|
||
base_username = (identity.get('wecom_userid') or identity.get('email') or identity.get('mobile') or f'wecom_{uuid.uuid4().hex[:8]}').replace('@', '_')
|
||
candidate = base_username
|
||
suffix = 1
|
||
while db.session.query(User).filter_by(username=candidate).first():
|
||
candidate = f'{base_username}_{suffix}'
|
||
suffix += 1
|
||
safe_email = identity.get('email') or f'{candidate}@wecom.local'
|
||
if db.session.query(User).filter_by(email=safe_email).first():
|
||
safe_email = f'{candidate}_{uuid.uuid4().hex[:6]}@wecom.local'
|
||
employee_id = identity.get('employee_id')
|
||
if employee_id and db.session.query(User).filter_by(employee_id=employee_id).first():
|
||
employee_id = None
|
||
phone_number = identity.get('mobile')
|
||
if phone_number:
|
||
candidates = _mobile_candidates(identity)
|
||
dup_mobile = db.session.query(User).filter(User.phone_number.in_(candidates)).first()
|
||
if dup_mobile:
|
||
phone_number = None
|
||
user = User(username=candidate, email=safe_email, role='user', status='active', real_name=identity.get('name'), employee_id=employee_id, phone_number=phone_number, wecom_userid=identity.get('wecom_userid'), wecom_unionid=identity.get('wecom_unionid'))
|
||
user.set_password(uuid.uuid4().hex)
|
||
db.session.add(user)
|
||
return user
|
||
|
||
def _issue_wecom_input_bind_prompt(identity: dict):
|
||
allowed_fields = _get_wecom_first_login_input_fields()
|
||
binding_token = _issue_wecom_bind_session(identity)
|
||
raise WeComLoginError(error='First WeCom login requires verification input to bind a local account.', error_code='WECOM_BIND_INPUT_REQUIRED', status_code=409, reason='input_bind_required', extra={'binding_token': binding_token, 'allowed_fields': allowed_fields, 'wecom_name': identity.get('name'), 'wecom_userid': identity.get('wecom_userid')})
|
||
|
||
def _sync_or_create_user_from_wecom(wecom_user: dict):
|
||
identity = _extract_wecom_identity(wecom_user)
|
||
rules, operator = _get_wecom_match_config()
|
||
rule_info = {'operator': operator, 'fields': rules}
|
||
bind_mode = _get_wecom_first_login_bind_mode()
|
||
user = None
|
||
if identity.get('wecom_userid'):
|
||
user = db.session.query(User).filter_by(wecom_userid=identity['wecom_userid']).first()
|
||
if user:
|
||
_sync_user_from_wecom_identity(user, identity)
|
||
return (user, 'already_bound', rule_info)
|
||
if bind_mode == 'input_verify':
|
||
_issue_wecom_input_bind_prompt(identity)
|
||
matched_users, missing_fields = _find_users_by_match_rules(identity, rules, operator)
|
||
if missing_fields:
|
||
missing_field = missing_fields[0]
|
||
raise WeComLoginError(error=f'Required match attribute missing: {missing_field}', error_code='WECOM_MATCH_ATTR_MISSING', status_code=422, reason=f'missing_attr:{missing_field}', extra={'missing_field': missing_field, 'match_rules': rule_info})
|
||
if len(matched_users) == 1:
|
||
user = matched_users[0]
|
||
_sync_user_from_wecom_identity(user, identity)
|
||
return (user, 'matched_and_bound', rule_info)
|
||
if len(matched_users) > 1:
|
||
raise WeComLoginError(error='Multiple local users matched', error_code='WECOM_MATCH_AMBIGUOUS', status_code=409, reason='ambiguous_match', extra={'candidate_count': len(matched_users), 'match_rules': rule_info})
|
||
if not current_app.config.get('WECOM_AUTO_CREATE_USER', True):
|
||
raise WeComLoginError(error='No linked account found. Contact admin to bind WeCom account.', error_code='WECOM_BIND_REQUIRED', status_code=403, reason='bind_required', extra={'match_rules': rule_info})
|
||
user = _create_user_from_wecom_identity(identity)
|
||
return (user, 'auto_created', rule_info)
|
||
|
||
@user_bp.route('/register', methods=['POST'])
|
||
def register():
|
||
"""
|
||
User registration
|
||
"""
|
||
data = request.get_json() or {}
|
||
required_fields = ['username', 'password', 'email', 'real_name', 'employee_id', 'phone_number']
|
||
for field in required_fields:
|
||
if not data.get(field):
|
||
raise ValidationError(f'{field} is required')
|
||
if db.session.query(User).filter_by(username=data['username']).first():
|
||
raise ValidationError('Username already exists')
|
||
if db.session.query(User).filter_by(email=data['email']).first():
|
||
raise ValidationError('Email already exists')
|
||
if db.session.query(User).filter_by(employee_id=data['employee_id']).first():
|
||
raise ValidationError('Employee ID already exists')
|
||
try:
|
||
user = User(username=data['username'], email=data['email'], real_name=data['real_name'], employee_id=data['employee_id'], phone_number=data['phone_number'], department=data.get('department'), role='user', status='active')
|
||
user.set_password(data['password'])
|
||
db.session.add(user)
|
||
db.session.commit()
|
||
return (jsonify({'message': 'Registration successful', 'id': user.id}), 201)
|
||
except Exception as e:
|
||
db.session.rollback()
|
||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
|
||
|
||
@user_bp.route('/login', methods=['POST'])
|
||
def login():
|
||
"""
|
||
Username/password login (kept for compatibility).
|
||
|
||
Request:
|
||
POST /api/user/login
|
||
{
|
||
"username": "<local username>",
|
||
"password": "<local password>"
|
||
}
|
||
|
||
Response 200:
|
||
local user profile + local HS256 access_token
|
||
|
||
Notes:
|
||
Can be disabled via AUTH_ALLOW_LOCAL_PASSWORD_LOGIN=false.
|
||
"""
|
||
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_PASSWORD_LOGIN', True)):
|
||
raise AppError(
|
||
code='AUTH.PASSWORD_LOGIN_DISABLED',
|
||
message='Password login is disabled. Please use Casdoor login.',
|
||
http_status=403,
|
||
)
|
||
|
||
def _attempt_login():
|
||
data = request.get_json() or {}
|
||
username = data.get('username')
|
||
password = data.get('password')
|
||
if not username or not password:
|
||
_write_login_audit('password', 'failed', username=username, reason='missing_credentials')
|
||
raise ValidationError('Username and password are required')
|
||
user = db.session.query(User).filter_by(username=username).first()
|
||
if not user:
|
||
_write_login_audit('password', 'failed', username=username, reason='user_not_found')
|
||
db.session.commit()
|
||
raise AppError(code='AUTH.USER_NOT_FOUND', message='User not found', http_status=404)
|
||
if not user.check_password(password):
|
||
_write_login_audit('password', 'failed', user=user, reason='incorrect_password')
|
||
db.session.commit()
|
||
raise AppError(code='AUTH.INCORRECT_PASSWORD', message='Incorrect password', http_status=401)
|
||
if user.status != 'active':
|
||
_write_login_audit('password', 'failed', user=user, reason='account_disabled')
|
||
db.session.commit()
|
||
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
|
||
_write_login_audit('password', 'success', user=user)
|
||
db.session.commit()
|
||
return jsonify(_build_login_payload(user, 'password'))
|
||
try:
|
||
return _attempt_login()
|
||
except OperationalError as e:
|
||
db.session.rollback()
|
||
db.session.remove()
|
||
try:
|
||
return _attempt_login()
|
||
except (OperationalError, DatabaseError) as retry_exc:
|
||
current_app.logger.warning('Password login retry failed: %s', retry_exc)
|
||
raise ServiceUnavailableError('Database connection failed')
|
||
except DatabaseError as e:
|
||
db.session.rollback()
|
||
db.session.remove()
|
||
try:
|
||
return _attempt_login()
|
||
except (OperationalError, DatabaseError) as retry_exc:
|
||
current_app.logger.warning('Password login retry failed: %s', retry_exc)
|
||
raise ServiceUnavailableError('Database connection failed')
|
||
except AppError:
|
||
raise
|
||
except Exception as e:
|
||
db.session.rollback()
|
||
current_app.logger.exception('Login error: %s', e)
|
||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Internal server error', http_status=500)
|
||
|
||
@user_bp.route('/casdoor/password-login', methods=['POST'])
|
||
def casdoor_password_login():
|
||
"""
|
||
Direct login with username/password against Casdoor (no browser redirect).
|
||
"""
|
||
if (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() != 'casdoor':
|
||
raise AppError(
|
||
code='AUTH.CASDOOR_PASSWORD_LOGIN_DISABLED',
|
||
message='Casdoor password login is disabled by AUTH_LOGIN_MODE',
|
||
http_status=403,
|
||
)
|
||
data = request.get_json() or {}
|
||
username = _clean_str(data.get('username'))
|
||
password = data.get('password') or ''
|
||
if not username or not password:
|
||
raise ValidationError('Username and password are required')
|
||
try:
|
||
token_data = _casdoor_password_login(username, password)
|
||
access_token = token_data.get('access_token')
|
||
refresh_token = token_data.get('refresh_token')
|
||
id_token = token_data.get('id_token')
|
||
expires_in = int(token_data.get('expires_in') or 3600)
|
||
claims = None
|
||
if id_token:
|
||
try:
|
||
claims = _decode_jwt(id_token)
|
||
except Exception:
|
||
claims = None
|
||
if claims is None:
|
||
claims = _casdoor_userinfo(access_token)
|
||
user = _resolve_user_from_casdoor_claims(claims)
|
||
_write_login_audit('casdoor', 'success', user=user)
|
||
db.session.commit()
|
||
api_bearer_token = id_token or access_token
|
||
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
|
||
except WeComLoginError:
|
||
db.session.rollback()
|
||
raise
|
||
except AppError:
|
||
db.session.rollback()
|
||
raise
|
||
except Exception as e:
|
||
db.session.rollback()
|
||
_raise_casdoor_auth_error(e, context='password')
|
||
|
||
@user_bp.route('/casdoor/authorize-url', methods=['GET'])
|
||
def casdoor_authorize_url():
|
||
"""
|
||
Build Casdoor OAuth authorize URL.
|
||
|
||
Request:
|
||
GET /api/user/casdoor/authorize-url
|
||
|
||
Optional query:
|
||
redirect_uri, provider_hint, default_provider=wecom (uses CASDOOR_WECOM_PROVIDER_HINT),
|
||
silent_signin=1 or CASDOOR_WECOM_SILENT_SIGNIN for silentSignin=1.
|
||
|
||
Response 200:
|
||
{
|
||
"url": "<authorization endpoint with state>",
|
||
"state": "<opaque state token>"
|
||
}
|
||
|
||
Error Codes:
|
||
500:
|
||
- Casdoor authorization endpoint missing
|
||
- Casdoor client config is incomplete
|
||
- 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})
|
||
except Exception as e:
|
||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'Failed to build Casdoor authorize url: {str(e)}', http_status=500)
|
||
|
||
@user_bp.route('/casdoor/login', methods=['POST'])
|
||
def casdoor_login():
|
||
"""
|
||
Exchange authorization code for Casdoor tokens and map to local user.
|
||
|
||
Request:
|
||
POST /api/user/casdoor/login
|
||
Content-Type: application/json
|
||
{
|
||
"code": "<oauth code>",
|
||
"state": "<state returned by authorize-url>"
|
||
}
|
||
|
||
Response 200:
|
||
{
|
||
"id": <local user id>,
|
||
"username": "<local username>",
|
||
"role": "<local role>",
|
||
"default_agent_id": <int|null>,
|
||
"source": "casdoor",
|
||
"access_token": "<casdoor access token>",
|
||
"refresh_token": "<casdoor refresh token>",
|
||
"id_token": "<casdoor id token|nullable>",
|
||
"token_type": "Bearer",
|
||
"expires_in": <seconds>
|
||
}
|
||
|
||
Error Codes:
|
||
400:
|
||
- code is required
|
||
- Invalid or expired Casdoor state
|
||
401:
|
||
- Casdoor login failed: <detail>
|
||
403:
|
||
- CASDOOR_USER_NOT_FOUND
|
||
- ACCOUNT_DISABLED
|
||
"""
|
||
data = request.get_json() or {}
|
||
code = _clean_str(data.get('code'))
|
||
state = _clean_str(data.get('state'))
|
||
if not code:
|
||
raise ValidationError('code is required')
|
||
current_app.logger.info('[casdoor_login] start code_len=%s state=%s', len(code), state[:24] if state else '')
|
||
redirect_uri = _consume_casdoor_state(state)
|
||
if not redirect_uri:
|
||
current_app.logger.warning('[casdoor_login] invalid_state state=%s', state[:24] if state else '')
|
||
raise ValidationError('Invalid or expired Casdoor state')
|
||
try:
|
||
token_data = _casdoor_exchange_code(code, redirect_uri)
|
||
access_token = token_data.get('access_token')
|
||
refresh_token = token_data.get('refresh_token')
|
||
id_token = token_data.get('id_token')
|
||
expires_in = int(token_data.get('expires_in') or 3600)
|
||
current_app.logger.info('[casdoor_login] token_exchange_ok redirect_uri=%s access=%s refresh=%s id=%s', redirect_uri, _token_brief(access_token), _token_brief(refresh_token), _token_brief(id_token))
|
||
claims = None
|
||
if id_token:
|
||
try:
|
||
claims = _decode_jwt(id_token)
|
||
except Exception:
|
||
claims = None
|
||
if claims is None:
|
||
claims = _casdoor_userinfo(access_token)
|
||
user = _resolve_user_from_casdoor_claims(claims)
|
||
current_app.logger.info('[casdoor_login] user_resolved username=%s id=%s', user.username, user.id)
|
||
_write_login_audit('casdoor', 'success', user=user)
|
||
db.session.commit()
|
||
api_bearer_token = id_token or access_token
|
||
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
|
||
except WeComLoginError:
|
||
db.session.rollback()
|
||
current_app.logger.warning('[casdoor_login] business_reject')
|
||
raise
|
||
except AppError:
|
||
db.session.rollback()
|
||
raise
|
||
except Exception as e:
|
||
db.session.rollback()
|
||
current_app.logger.exception('[casdoor_login] failed state=%s redirect_uri=%s', state[:24] if state else '', redirect_uri)
|
||
_raise_casdoor_auth_error(e, context='code')
|
||
|
||
@user_bp.route('/casdoor/refresh', methods=['POST'])
|
||
def casdoor_refresh():
|
||
"""
|
||
Refresh Casdoor access token using refresh_token.
|
||
|
||
Request:
|
||
POST /api/user/casdoor/refresh
|
||
Content-Type: application/json
|
||
{
|
||
"refresh_token": "<refresh token>"
|
||
}
|
||
|
||
Response 200:
|
||
{
|
||
"access_token": "<new access token>",
|
||
"refresh_token": "<possibly rotated refresh token>",
|
||
"id_token": "<optional id token>",
|
||
"token_type": "Bearer",
|
||
"expires_in": <seconds>
|
||
}
|
||
|
||
Error Codes:
|
||
400:
|
||
- refresh_token is required
|
||
401:
|
||
- Casdoor refresh failed: <detail>
|
||
"""
|
||
data = request.get_json() or {}
|
||
refresh_token = _clean_str(data.get('refresh_token'))
|
||
if not refresh_token:
|
||
raise ValidationError('refresh_token is required')
|
||
current_app.logger.info('[casdoor_refresh] start refresh=%s', _token_brief(refresh_token))
|
||
try:
|
||
token_data = _casdoor_refresh_token(refresh_token)
|
||
access_token = token_data.get('access_token')
|
||
id_token = token_data.get('id_token')
|
||
next_refresh = token_data.get('refresh_token') or refresh_token
|
||
expires_in = int(token_data.get('expires_in') or 3600)
|
||
current_app.logger.info('[casdoor_refresh] token_refresh_ok access=%s id=%s next_refresh=%s', _token_brief(access_token), _token_brief(id_token), _token_brief(next_refresh))
|
||
api_bearer_token = id_token or access_token
|
||
return jsonify({'access_token': api_bearer_token, 'refresh_token': next_refresh, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
|
||
except Exception as e:
|
||
message = str(e)
|
||
if 'unsupported_grant_type' in message or 'refresh_token is not supported' in message:
|
||
raise AppError(
|
||
code='AUTH.CASDOOR_REFRESH_UNSUPPORTED',
|
||
message='Casdoor refresh token is not supported by current application config',
|
||
http_status=400,
|
||
)
|
||
current_app.logger.exception('[casdoor_refresh] failed refresh=%s', _token_brief(refresh_token))
|
||
raise UnauthorizedError(f'Casdoor refresh failed: {str(e)}')
|
||
|
||
@user_bp.route('/wecom/authorize-url', methods=['GET'])
|
||
def wecom_authorize_url():
|
||
if not _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 = _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})
|
||
|
||
@user_bp.route('/wecom/login', methods=['POST'])
|
||
def wecom_login():
|
||
if not _is_wecom_configured():
|
||
raise ValidationError('WeCom login is not configured')
|
||
data = request.get_json() or {}
|
||
code = data.get('code')
|
||
state = data.get('state')
|
||
if not code:
|
||
_write_login_audit('wecom', 'failed', reason='missing_code')
|
||
db.session.commit()
|
||
raise ValidationError('code is required')
|
||
if not _consume_wecom_state(state):
|
||
_write_login_audit('wecom', 'failed', reason='invalid_state')
|
||
db.session.commit()
|
||
raise ValidationError('Invalid or expired WeCom state')
|
||
wecom_userid_for_audit = None
|
||
try:
|
||
access_token = _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)
|
||
info = info_resp.json()
|
||
wecom_userid_value = info.get('userid') or info.get('UserId')
|
||
wecom_openid_value = info.get('openid') or info.get('OpenId')
|
||
wecom_userid_for_audit = wecom_userid_value
|
||
if info.get('errcode') != 0:
|
||
_write_login_audit('wecom', 'failed', reason=f"auth_failed:{info.get('errmsg')}")
|
||
db.session.commit()
|
||
raise UnauthorizedError(f"WeCom auth failed: {info.get('errmsg', 'unknown error')}")
|
||
if not wecom_userid_value:
|
||
_write_login_audit('wecom', 'failed', reason=f"not_in_agent_scope:openid={wecom_openid_value or ''}", error_code='WECOM_NOT_IN_AGENT_SCOPE')
|
||
db.session.commit()
|
||
raise AppError(
|
||
code='WECOM_NOT_IN_AGENT_SCOPE',
|
||
message='当前企业微信账号未授权登录该应用:账号不在自建应用的可见范围内,或不是本企业成员。请管理员到「企业微信后台 → 应用管理 → 该应用 → 可见范围」中加入该成员所在的部门或个人。',
|
||
http_status=401,
|
||
)
|
||
user_resp = requests.get('https://qyapi.weixin.qq.com/cgi-bin/user/get', params={'access_token': access_token, 'userid': wecom_userid_value}, timeout=8)
|
||
wecom_user = user_resp.json()
|
||
wecom_userid_for_audit = wecom_user.get('userid') or wecom_userid_for_audit
|
||
if wecom_user.get('errcode') != 0:
|
||
_write_login_audit('wecom', 'failed', reason=f"user_fetch_failed:{wecom_user.get('errmsg')}", wecom_userid=wecom_userid_value)
|
||
db.session.commit()
|
||
raise UnauthorizedError(f"WeCom user fetch failed: {wecom_user.get('errmsg', 'unknown error')}")
|
||
user, bind_status, rule_info = _sync_or_create_user_from_wecom(wecom_user)
|
||
if user.status != 'active':
|
||
_write_login_audit('wecom', 'failed', user=user, reason='account_disabled', wecom_userid=wecom_user.get('userid'))
|
||
db.session.commit()
|
||
raise ForbiddenError('Account is disabled')
|
||
_write_login_audit('wecom', 'success', user=user, wecom_userid=wecom_user.get('userid'), match_rules=rule_info.get('fields'), match_operator=rule_info.get('operator'), match_result=bind_status)
|
||
db.session.commit()
|
||
return jsonify(_build_login_payload(user, 'wecom', bind_status=bind_status))
|
||
except WeComLoginError as e:
|
||
db.session.rollback()
|
||
_write_login_audit('wecom', 'failed', reason=e.reason or 'wecom_login_error', wecom_userid=wecom_userid_for_audit, error_code=e.error_code)
|
||
db.session.commit()
|
||
raise
|
||
except Exception as e:
|
||
db.session.rollback()
|
||
if _is_users_pk_sequence_error(e):
|
||
_write_login_audit('wecom', 'failed', reason='db_sequence_misconfig', wecom_userid=wecom_userid_for_audit, error_code='DB_SEQUENCE_MISCONFIG')
|
||
db.session.commit()
|
||
raise AppError(
|
||
code='SYSTEM.DB_SEQUENCE_MISCONFIG',
|
||
message='数据库主键自增配置异常,当前环境缺少 users.id 的自动序列。请执行数据库迁移后重试。',
|
||
http_status=500,
|
||
)
|
||
_write_login_audit('wecom', 'failed', reason=f'exception:{str(e)[:160]}')
|
||
db.session.commit()
|
||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'WeCom login failed: {str(e)}', http_status=500)
|
||
|
||
@user_bp.route('/wecom/complete-bind', methods=['POST'])
|
||
def wecom_complete_bind():
|
||
if not _is_wecom_configured():
|
||
raise ValidationError('WeCom login is not configured')
|
||
data = request.get_json() or {}
|
||
binding_token = _clean_str(data.get('binding_token'))
|
||
field = _clean_str(data.get('field'))
|
||
value = data.get('value')
|
||
identity = _get_wecom_bind_session(binding_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 = _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 = _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 len(matched_users) == 0:
|
||
_write_login_audit('wecom', 'failed', reason=f'input_bind_not_found:{field}', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_BIND_INPUT_NOT_FOUND', match_rules=[field], match_operator='AND')
|
||
db.session.commit()
|
||
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:
|
||
_write_login_audit('wecom', 'failed', reason=f'input_bind_ambiguous:{field}', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_BIND_INPUT_AMBIGUOUS', match_rules=[field], match_operator='AND')
|
||
db.session.commit()
|
||
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':
|
||
_write_login_audit('wecom', 'failed', user=user, reason='account_disabled', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_ACCOUNT_DISABLED', match_rules=[field], match_operator='AND')
|
||
db.session.commit()
|
||
raise ForbiddenError('Account is disabled')
|
||
try:
|
||
_sync_user_from_wecom_identity(user, identity)
|
||
_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()
|
||
_WECOM_BIND_SESSION_CACHE.pop(binding_token, None)
|
||
return jsonify(_build_login_payload(user, 'wecom', bind_status='input_verified_and_bound'))
|
||
except WeComLoginError as e:
|
||
db.session.rollback()
|
||
_write_login_audit('wecom', 'failed', user=user, reason=e.reason or 'wecom_input_bind_error', wecom_userid=identity.get('wecom_userid'), error_code=e.error_code, match_rules=[field], match_operator='AND')
|
||
db.session.commit()
|
||
raise
|
||
except Exception as e:
|
||
db.session.rollback()
|
||
_write_login_audit('wecom', 'failed', user=user, reason=f'exception:{str(e)[: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: {str(e)}', http_status=500)
|
||
|
||
@user_bp.route('/wecom/deeplink-opened', methods=['POST'])
|
||
def mark_wecom_deeplink_opened():
|
||
user = _get_current_user()
|
||
if not user:
|
||
raise UnauthorizedError('Unauthorized')
|
||
data = request.get_json() or {}
|
||
trace_id = _clean_str(data.get('trace_id'))
|
||
if not trace_id:
|
||
raise ValidationError('trace_id is required')
|
||
ok = mark_wecom_message_opened(trace_id)
|
||
if not ok:
|
||
raise NotFoundError('trace_id not found')
|
||
db.session.commit()
|
||
return jsonify({'status': 'ok'})
|
||
|
||
@user_bp.route('/wecom/task-complete', methods=['POST'])
|
||
def wecom_task_complete():
|
||
"""
|
||
Lightweight endpoint for sending task completion WeCom message.
|
||
Can be called by frontend after long-running task is done.
|
||
"""
|
||
user = _get_current_user()
|
||
if not user:
|
||
raise UnauthorizedError('Unauthorized')
|
||
data = request.get_json() or {}
|
||
title = _clean_str(data.get('title')) or 'AI 任务已完成'
|
||
content = _clean_str(data.get('content')) or '你发起的 AI 任务已完成,点击查看详情。'
|
||
agent_id = data.get('agent_id')
|
||
jump_path = '/workspace'
|
||
jump_params = {}
|
||
if agent_id:
|
||
jump_path = f'/chat/{int(agent_id)}'
|
||
result = send_wecom_event_message(event_type='task_completed', user=user, title=title, content=content, jump_path=jump_path, jump_params=jump_params)
|
||
db.session.commit()
|
||
return (jsonify(result), 200 if result.get('ok') else 202)
|
||
|
||
@user_bp.route('/leave-balance', methods=['GET'])
|
||
def get_leave_balance():
|
||
user = _get_current_user()
|
||
if not user:
|
||
raise UnauthorizedError('Unauthorized')
|
||
leave_type_code = _clean_str(request.args.get('leave_type'))
|
||
if leave_type_code not in ('010', '408'):
|
||
raise ValidationError('仅支持查询年假(010)和育儿假(408)的余额')
|
||
try:
|
||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||
employee_code = HRLeaveSQLServerService._get_employee_code(user)
|
||
now_year = datetime.now().year
|
||
if leave_type_code == '010':
|
||
_, record = HRLeaveSQLServerService._query_one(view_name='VIEW_D044', year_column='D044001', total_column='D044005', used_column='D044006', remaining_column='D044007', employee_code=employee_code, year=now_year)
|
||
label = '年假'
|
||
else:
|
||
_, record = HRLeaveSQLServerService._query_one(view_name='VIEW_D072', year_column='d072001', total_column='d072002', used_column='d072003', remaining_column='d072004', employee_code=employee_code, year=now_year)
|
||
label = '育儿假'
|
||
remaining = record.get('remaining_hours') if record else None
|
||
try:
|
||
has_balance = remaining is not None and float(remaining) > 0
|
||
except (TypeError, ValueError):
|
||
has_balance = False
|
||
return jsonify({'leave_type_code': leave_type_code, 'leave_type_label': label, 'year': record.get('leave_year', now_year) if record else now_year, 'total_hours': record.get('total_hours') if record else None, 'used_hours': record.get('used_hours') if record else None, 'remaining_hours': remaining, 'has_balance': has_balance})
|
||
except Exception as exc:
|
||
current_app.logger.exception('[leave-balance] query failed user_id=%s', getattr(user, 'id', None))
|
||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'假期余额查询失败:{exc}', http_status=500)
|
||
|
||
@user_bp.route('/leave-workflow/submit', methods=['POST'])
|
||
def submit_leave_workflow():
|
||
user = _get_current_user()
|
||
if not user:
|
||
raise UnauthorizedError('Unauthorized')
|
||
data = request.get_json() or {}
|
||
form_data = {'applicantName': _clean_str(data.get('applicantName')) or _clean_str(getattr(user, 'real_name', None)) or _clean_str(getattr(user, 'username', None)), 'employeeId': _clean_str(data.get('employeeId')) or _clean_str(getattr(user, 'employee_id', None)) or _clean_str(getattr(user, 'username', None)), 'applicantJobTitle': _clean_str(data.get('applicantJobTitle')), 'applicantDepartmentId': _clean_str(data.get('applicantDepartmentId')), 'applicantSubCompanyId1': _clean_str(data.get('applicantSubCompanyId1')), 'applyTime': _clean_str(data.get('applyTime')), 'fillerName': _clean_str(data.get('fillerName')) or _clean_str(getattr(user, 'real_name', None)) or _clean_str(getattr(user, 'username', None)), 'agentUid': _clean_str(data.get('agentUid')), 'agentEmployeeId': _clean_str(data.get('agentEmployeeId')), 'agentName': _clean_str(data.get('agentName')), 'agentJobTitle': _clean_str(data.get('agentJobTitle')), 'agentDepartmentId': _clean_str(data.get('agentDepartmentId')), 'agentSubCompanyId1': _clean_str(data.get('agentSubCompanyId1')), 'leaveType': _clean_str(data.get('leaveType')), 'startTime': _clean_str(data.get('startTime')), 'endTime': _clean_str(data.get('endTime')), 'durationHours': data.get('durationHours'), 'isOutOfOffice': _parse_leave_int_flag(data.get('isOutOfOffice'), '是否外出'), 'isWorkInjury': _parse_leave_int_flag(data.get('isWorkInjury'), '是否为工伤'), 'remark': _clean_str(data.get('remark')) or ''}
|
||
required_fields = {'applicantName': '请假人', 'employeeId': '工号', 'fillerName': '填单人', 'agentUid': '代理人UID', 'agentEmployeeId': '代理人工号', 'agentName': '代理人姓名', 'leaveType': '假别', 'startTime': '开始时间', 'endTime': '结束时间'}
|
||
for key, label in required_fields.items():
|
||
if not form_data.get(key):
|
||
raise ValidationError(f'{label}不能为空。')
|
||
try:
|
||
from app.services.oa_leave_workflow import OALeaveWorkflowService, OALeaveWorkflowError
|
||
result = OALeaveWorkflowService.submit_leave_request(form_data, user)
|
||
except OALeaveWorkflowError as exc:
|
||
current_app.logger.warning('[oa-leave] submit failed user_id=%s employee_id=%s err=%s', getattr(user, 'id', None), form_data.get('employeeId'), exc)
|
||
raise ValidationError(str(exc))
|
||
except Exception as exc:
|
||
current_app.logger.exception('[oa-leave] unexpected submit failure user_id=%s', getattr(user, 'id', None))
|
||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'OA 请假提交失败:{exc}', http_status=500)
|
||
current_app.logger.info('[oa-leave] submit success user_id=%s employee_id=%s request_id=%s workflow_id=%s', getattr(user, 'id', None), form_data.get('employeeId'), result.get('request_id'), result.get('workflow_id'))
|
||
return jsonify(result)
|
||
|
||
@user_bp.route('/wecom/callback', methods=['GET', 'POST'])
|
||
def wecom_callback():
|
||
"""
|
||
Enterprise WeCom callback endpoint.
|
||
Supports URL verification and basic signature check for incoming events.
|
||
"""
|
||
msg_signature = request.args.get('msg_signature') or request.args.get('signature')
|
||
timestamp = request.args.get('timestamp', '')
|
||
nonce = request.args.get('nonce', '')
|
||
token = current_app.config.get('WECOM_CALLBACK_TOKEN') or ''
|
||
aes_key = current_app.config.get('WECOM_ENCODING_AES_KEY') or ''
|
||
corp_id = current_app.config.get('WECOM_CORP_ID') or ''
|
||
if request.method == 'GET':
|
||
echostr = request.args.get('echostr', '') or ''
|
||
if not token:
|
||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='callback token not configured', http_status=500)
|
||
if aes_key:
|
||
if not _verify_wecom_msg_signature(msg_signature, token, timestamp, nonce, echostr):
|
||
raise ForbiddenError('invalid callback signature')
|
||
try:
|
||
plain = decrypt_wecom_aes(echostr, aes_key, corp_id)
|
||
except Exception as exc:
|
||
_persist_wecom_callback_audit(msg_signature=msg_signature, timestamp=timestamp, nonce=nonce, encrypt_raw=echostr, error_message=f'decrypt_failed:{str(exc)[:200]}')
|
||
raise ValidationError('decrypt failed')
|
||
_persist_wecom_callback_audit(msg_signature=msg_signature, timestamp=timestamp, nonce=nonce, encrypt_raw=echostr, decrypted_xml=plain, msg_type='url_verify')
|
||
return (plain, 200, {'Content-Type': 'text/plain; charset=utf-8'})
|
||
if not _verify_wecom_msg_signature(msg_signature, token, timestamp, nonce, echostr):
|
||
raise ForbiddenError('invalid callback signature')
|
||
_persist_wecom_callback_audit(msg_signature=msg_signature, timestamp=timestamp, nonce=nonce, encrypt_raw=echostr, decrypted_xml=echostr, msg_type='url_verify_plain')
|
||
return (echostr, 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 token:
|
||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='callback token not configured', http_status=500)
|
||
if not encrypt_field:
|
||
raise ValidationError('missing Encrypt field')
|
||
if not _verify_wecom_msg_signature(msg_signature, token, timestamp, nonce, encrypt_field):
|
||
_persist_wecom_callback_audit(msg_signature=msg_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:
|
||
_persist_wecom_callback_audit(msg_signature=msg_signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_field, error_message=f'decrypt_failed:{str(exc)[:200]}')
|
||
raise ValidationError('decrypt failed')
|
||
msg_type = _extract_xml_field(decrypted, 'MsgType') if decrypted else None
|
||
event = _extract_xml_field(decrypted, 'Event') if decrypted else None
|
||
from_user = _extract_xml_field(decrypted, 'FromUserName') if decrypted else None
|
||
agent_id = _extract_xml_field(decrypted, 'AgentID') if decrypted else None
|
||
msg_id = _extract_xml_field(decrypted, 'MsgId') if decrypted else None
|
||
_persist_wecom_callback_audit(msg_signature=msg_signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_field, decrypted_xml=decrypted, msg_type=msg_type, event=event, from_user=from_user, agent_id=agent_id, msg_id=msg_id)
|
||
return ('success', 200, {'Content-Type': 'text/plain; charset=utf-8'})
|
||
|
||
@user_bp.route('/wecom/binding', methods=['GET'])
|
||
def get_wecom_binding():
|
||
user = _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})
|
||
|
||
@user_bp.route('/wecom/unbind', methods=['POST'])
|
||
def unbind_wecom_self():
|
||
user = _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'})
|
||
|
||
@user_bp.route('/feedback', methods=['POST'])
|
||
def submit_general_feedback():
|
||
"""
|
||
通用意见反馈接口(与 /api/chat/feedback 的对话评分接口不同
|
||
"""
|
||
user = _get_current_user()
|
||
if not user:
|
||
raise UnauthorizedError('Unauthorized')
|
||
data = request.get_json() or {}
|
||
feedback_type = _clean_str(data.get('feedback_type'))
|
||
feedback_module = _clean_str(data.get('feedback_module'))
|
||
content = _clean_str(data.get('content'))
|
||
source_page = _clean_str(data.get('source_page'))
|
||
raw_chat_log_id = data.get('chat_log_id')
|
||
chat_log_id = None
|
||
if raw_chat_log_id not in (None, ''):
|
||
try:
|
||
chat_log_id = int(raw_chat_log_id)
|
||
except (TypeError, ValueError):
|
||
raise ValidationError('chat_log_id must be an integer')
|
||
if chat_log_id <= 0:
|
||
raise ValidationError('chat_log_id must be a positive integer')
|
||
if not feedback_type:
|
||
raise ValidationError('feedback_type is required')
|
||
if not feedback_module:
|
||
raise ValidationError('feedback_module is required')
|
||
if len(feedback_type) > 32:
|
||
raise ValidationError('feedback_type is too long')
|
||
if len(feedback_module) > 32:
|
||
raise ValidationError('feedback_module is too long')
|
||
if not content:
|
||
raise ValidationError('content is required')
|
||
if len(content) > 2000:
|
||
raise ValidationError('content is too long')
|
||
if source_page != 'chat':
|
||
chat_log_id = None
|
||
if chat_log_id is not None:
|
||
chat_log = db.session.get(ChatLog, chat_log_id)
|
||
if not chat_log:
|
||
raise ValidationError('chat_log_id not found')
|
||
if chat_log.user_id != user.id:
|
||
raise ForbiddenError('chat_log_id is not owned by current user')
|
||
row = GeneralFeedback(user_id=user.id, username=user.username, feedback_type=feedback_type, feedback_module=feedback_module, content=content, source_page=source_page, chat_log_id=chat_log_id)
|
||
db.session.add(row)
|
||
db.session.commit()
|
||
notify_result = send_feedback_group_notification(row, user)
|
||
if notify_result.get('ok'):
|
||
current_app.logger.info('[feedback] group notification sent feedback_id=%s', row.id)
|
||
elif not notify_result.get('skipped'):
|
||
current_app.logger.warning(
|
||
'[feedback] group notification failed feedback_id=%s reason=%s',
|
||
row.id,
|
||
notify_result.get('reason'),
|
||
)
|
||
return jsonify({'status': 'ok', 'id': row.id})
|
||
|
||
@user_bp.route('/home', methods=['GET'])
|
||
def home():
|
||
"""
|
||
Get user homepage data
|
||
"""
|
||
user = _get_current_user()
|
||
if not user:
|
||
raise UnauthorizedError('Unauthorized')
|
||
|
||
def _load_home_payload():
|
||
if user.role == 'admin':
|
||
agent_rows = db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url, Agent.extra_config).filter(Agent.is_active.is_(True)).all()
|
||
else:
|
||
agent_rows = [{'id': agent.id, 'name': agent.name, 'description': agent.description, 'icon_url': agent.icon_url, 'extra_config': agent.extra_config} for agent in user.agents if agent.is_active]
|
||
agent_rows = sort_agent_rows(agent_rows)
|
||
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
|
||
favorite_ids = [f.agent_id for f in favorites]
|
||
qqs = db.session.query(QuickQuestion).filter(
|
||
or_(
|
||
QuickQuestion.user_id == user.id,
|
||
and_(QuickQuestion.user_id.is_(None), QuickQuestion.is_enabled.is_(True)),
|
||
)
|
||
).all()
|
||
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
|
||
layout = layout_config.layout if layout_config else {}
|
||
embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
|
||
embedded_agents = []
|
||
for rel in embedded_rel:
|
||
agent = db.session.get(Agent, rel.agent_id)
|
||
if agent:
|
||
embedded_agents.append({'id': agent.id, 'name': agent.name, 'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None})
|
||
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
|
||
try:
|
||
return _run_db_with_retry(_load_home_payload, label='user.home')
|
||
except (OperationalError, DatabaseError) as exc:
|
||
current_app.logger.warning('user.home retry failed: %s', exc)
|
||
raise ServiceUnavailableError('Database connection failed')
|
||
|
||
@user_bp.route('/favorites/<int:agent_id>', methods=['POST', 'DELETE'])
|
||
def toggle_favorite(agent_id: int):
|
||
user = _get_current_user()
|
||
if not user:
|
||
raise UnauthorizedError('Unauthorized')
|
||
if request.method == 'POST':
|
||
exists = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id, agent_id=agent_id).first()
|
||
if not exists:
|
||
fav = UserFavoriteAgent(user_id=user.id, agent_id=agent_id)
|
||
db.session.add(fav)
|
||
else:
|
||
db.session.query(UserFavoriteAgent).filter_by(user_id=user.id, agent_id=agent_id).delete()
|
||
db.session.commit()
|
||
return jsonify({'status': 'ok'})
|
||
|
||
@user_bp.route('/quick-questions', methods=['POST'])
|
||
def add_quick_question():
|
||
user = _get_current_user()
|
||
if not user:
|
||
raise UnauthorizedError('Unauthorized')
|
||
data = request.get_json() or {}
|
||
if not data.get('title') or not data.get('question') or (not data.get('agent_id')):
|
||
raise ValidationError('Missing fields')
|
||
qq = QuickQuestion(user_id=user.id, title=data['title'], question=data['question'], agent_id=data['agent_id'])
|
||
db.session.add(qq)
|
||
db.session.commit()
|
||
return (jsonify({'message': 'Added', 'id': qq.id}), 201)
|
||
|
||
@user_bp.route('/quick-questions/<int:qq_id>', methods=['PUT', 'DELETE'])
|
||
def update_quick_question(qq_id: int):
|
||
user = _get_current_user()
|
||
if not user:
|
||
raise UnauthorizedError('Unauthorized')
|
||
qq = db.session.query(QuickQuestion).filter_by(id=qq_id, user_id=user.id).first()
|
||
if not qq:
|
||
raise NotFoundError('QuickQuestion not found or permission denied')
|
||
if request.method == 'DELETE':
|
||
db.session.delete(qq)
|
||
db.session.commit()
|
||
return jsonify({'status': 'ok'})
|
||
data = request.get_json() or {}
|
||
if 'title' in data:
|
||
qq.title = data['title']
|
||
if 'question' in data:
|
||
qq.question = data['question']
|
||
if 'agent_id' in data:
|
||
qq.agent_id = data['agent_id']
|
||
db.session.commit()
|
||
return jsonify({'status': 'ok'})
|
||
|
||
@user_bp.route('/homepage-layout', methods=['PUT'])
|
||
def update_layout():
|
||
user = _get_current_user()
|
||
if not user:
|
||
raise UnauthorizedError('Unauthorized')
|
||
data = request.get_json() or {}
|
||
layout = data.get('layout', {})
|
||
config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
|
||
if not config:
|
||
config = UserHomepageConfig(user_id=user.id, layout=layout)
|
||
db.session.add(config)
|
||
else:
|
||
config.layout = layout
|
||
db.session.commit()
|
||
return jsonify({'status': 'ok'})
|
||
|
||
@user_bp.route('/profile', methods=['GET', 'PUT'])
|
||
def user_profile():
|
||
"""
|
||
User profile management
|
||
GET: Get details
|
||
PUT: Update basic info
|
||
"""
|
||
user = _get_current_user()
|
||
if not user:
|
||
raise UnauthorizedError('Unauthorized')
|
||
if request.method == 'GET':
|
||
return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'language': user.language, 'theme_preference': user.theme_preference or 'system'})
|
||
data = request.get_json() or {}
|
||
|
||
def _update_profile():
|
||
if 'real_name' in data:
|
||
user.real_name = data['real_name']
|
||
if 'phone_number' in data:
|
||
user.phone_number = data['phone_number']
|
||
if 'language' in data:
|
||
user.language = data['language']
|
||
if 'theme_preference' in data:
|
||
if data['theme_preference'] not in ['light', 'dark', 'system']:
|
||
raise ValidationError('Invalid theme preference')
|
||
user.theme_preference = data['theme_preference']
|
||
if 'email' in data:
|
||
if data['email']:
|
||
existing = db.session.query(User).filter_by(email=data['email']).first()
|
||
if existing and existing.id != user.id:
|
||
raise ValidationError('Email already exists')
|
||
user.email = data['email']
|
||
if 'employee_id' in data:
|
||
if data['employee_id']:
|
||
existing = db.session.query(User).filter_by(employee_id=data['employee_id']).first()
|
||
if existing and existing.id != user.id:
|
||
raise ValidationError('Employee ID already exists')
|
||
user.employee_id = data['employee_id']
|
||
if 'department' in data:
|
||
user.department = data['department']
|
||
db.session.commit()
|
||
return jsonify({'message': 'Profile updated successfully'})
|
||
try:
|
||
return _run_db_with_retry(_update_profile, label='user.profile.update')
|
||
except (OperationalError, DatabaseError) as exc:
|
||
db.session.rollback()
|
||
current_app.logger.warning('user.profile.update retry failed: %s', exc)
|
||
raise ServiceUnavailableError('Database connection failed')
|
||
except Exception as e:
|
||
db.session.rollback()
|
||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
|
||
|
||
@user_bp.route('/change-password', methods=['POST'])
|
||
def change_password():
|
||
"""
|
||
Change password for the current user.
|
||
|
||
Verify current password against local DB and/or Casdoor, then update both stores
|
||
to keep them in sync regardless of AUTH_LOGIN_MODE or login method.
|
||
"""
|
||
user = _get_current_user()
|
||
if not user:
|
||
raise UnauthorizedError('Unauthorized')
|
||
data = request.get_json() or {}
|
||
current_password = data.get('current_password')
|
||
new_password = data.get('new_password')
|
||
if not current_password or not new_password:
|
||
raise ValidationError('Current and new password are required')
|
||
try:
|
||
_verify_current_password_for_change(user, current_password)
|
||
_sync_casdoor_password(user.username, current_password, new_password)
|
||
user.set_password(new_password)
|
||
db.session.commit()
|
||
return jsonify({'message': 'Password changed successfully'})
|
||
except AppError:
|
||
raise
|
||
except RuntimeError as e:
|
||
db.session.rollback()
|
||
message = str(e)
|
||
if _is_casdoor_password_error(message):
|
||
_raise_incorrect_current_password()
|
||
_raise_casdoor_set_password_error(e)
|
||
except Exception as e:
|
||
db.session.rollback()
|
||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
|
||
|
||
def _get_password_reset_public_base_url() -> str:
|
||
"""
|
||
解析密码重置外链基地址,优先公网入口配置。
|
||
核心逻辑:依次读取 WECOM_PUBLIC_BASE_URL / PUBLIC_BASE_URL / WECOM_NOTIFY_BASE_URL。
|
||
Returns:
|
||
去掉尾斜杠的基地址;均未配置时返回空字符串。
|
||
"""
|
||
for key in ('WECOM_PUBLIC_BASE_URL', 'PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'):
|
||
base = _clean_str(current_app.config.get(key))
|
||
if base:
|
||
return base.rstrip('/')
|
||
return ''
|
||
|
||
|
||
def _build_password_reset_url(token: str) -> str:
|
||
"""
|
||
构造带 token 的密码重置页 URL。
|
||
@param token: reset_token 明文
|
||
Returns:
|
||
完整重置链接
|
||
Raises:
|
||
RuntimeError: 公网基地址未配置
|
||
"""
|
||
base = _get_password_reset_public_base_url()
|
||
if not base:
|
||
raise RuntimeError('Password reset public base URL is not configured')
|
||
return f'{base}/reset-password?token={token}'
|
||
|
||
|
||
def _password_reset_rate_limit_state(key: str, *, window_seconds: int = 300) -> tuple[bool, int]:
|
||
"""
|
||
判断找回密码是否触发限流,并在允许时记录本次请求时间。
|
||
@param key: 限流键,通常为 employee_id + IP
|
||
@param window_seconds: 窗口秒数,默认 5 分钟
|
||
Returns:
|
||
(allowed, retry_after_seconds):allowed 为 False 时 retry_after_seconds 为剩余等待秒数
|
||
"""
|
||
now = datetime.utcnow()
|
||
last = _PASSWORD_RESET_RATE_CACHE.get(key)
|
||
if last:
|
||
elapsed = (now - last).total_seconds()
|
||
if elapsed < window_seconds:
|
||
return False, max(1, int(window_seconds - elapsed))
|
||
_PASSWORD_RESET_RATE_CACHE[key] = now
|
||
return True, 0
|
||
|
||
|
||
def _check_password_reset_rate_limit(key: str, *, window_seconds: int = 300) -> bool:
|
||
"""
|
||
简易内存限流,防止同工号/IP 频繁触发找回密码。
|
||
@param key: 限流键,通常为 employee_id + IP
|
||
@param window_seconds: 窗口秒数,默认 5 分钟
|
||
Returns:
|
||
True 表示允许继续;False 表示应拒绝
|
||
"""
|
||
allowed, _ = _password_reset_rate_limit_state(key, window_seconds=window_seconds)
|
||
return allowed
|
||
|
||
|
||
def _sync_casdoor_password_for_reset(user: User, new_password: str):
|
||
"""
|
||
Token 重置场景下将新密码同步至 Casdoor(无旧密码校验)。
|
||
核心逻辑:Casdoor 已配置时调用 set-password,oldPassword 传空串(与 change-password fallback 一致)。
|
||
@param user: 本地用户
|
||
@param new_password: 新密码明文
|
||
Raises:
|
||
AppError: Casdoor 策略或 IdP 同步失败
|
||
"""
|
||
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_casdoor_user_missing_error(str(exc)):
|
||
_raise_casdoor_user_not_in_idp(exc)
|
||
_raise_casdoor_set_password_error(exc)
|
||
|
||
|
||
def _password_reset_rate_key(employee_id: str) -> str:
|
||
"""
|
||
生成找回密码限流键。
|
||
@param employee_id: 工号
|
||
Returns:
|
||
employee_id 与客户端 IP 组合键
|
||
"""
|
||
client_ip = request.headers.get('X-Forwarded-For', request.remote_addr) or 'unknown'
|
||
return f'{employee_id}:{client_ip}'
|
||
|
||
|
||
@user_bp.route('/reset-password-by-wecom', methods=['POST'])
|
||
def reset_password_by_wecom():
|
||
"""
|
||
通过工号 + 用户名发起找回密码,并向已绑定 wecom_userid 发送 textcard 重置链接。
|
||
Request JSON: { "employee_id": "...", "username": "..." }
|
||
"""
|
||
if not _is_wecom_configured():
|
||
raise AppError(
|
||
code='WECOM.RESET_NOT_CONFIGURED',
|
||
message='WeCom password reset is not configured',
|
||
http_status=503,
|
||
details={'missing': _get_wecom_config_missing_fields()},
|
||
)
|
||
if not bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)):
|
||
raise AppError(
|
||
code='WECOM.NOTIFY_DISABLED',
|
||
message='WeCom notification is disabled',
|
||
http_status=503,
|
||
)
|
||
if not _get_password_reset_public_base_url():
|
||
raise AppError(
|
||
code='WECOM.RESET_URL_NOT_CONFIGURED',
|
||
message='Password reset public base URL is not configured',
|
||
http_status=503,
|
||
)
|
||
|
||
data = request.get_json() or {}
|
||
employee_id = _clean_str(data.get('employee_id'))
|
||
username = _clean_str(data.get('username'))
|
||
if not employee_id:
|
||
raise ValidationError('Employee ID is required')
|
||
if not username:
|
||
raise ValidationError('Username is required')
|
||
|
||
rate_key = _password_reset_rate_key(employee_id)
|
||
allowed, retry_after_seconds = _password_reset_rate_limit_state(rate_key)
|
||
if not allowed:
|
||
retry_minutes = max(1, (retry_after_seconds + 59) // 60)
|
||
current_app.logger.info(
|
||
'[password_reset] rejected reason=rate_limited employee_id=%s retry_after_seconds=%s',
|
||
employee_id,
|
||
retry_after_seconds,
|
||
)
|
||
raise AppError(
|
||
code='AUTH.PASSWORD_RESET_RATE_LIMITED',
|
||
message='Password reset requests are too frequent',
|
||
http_status=429,
|
||
details={
|
||
'retry_after_seconds': retry_after_seconds,
|
||
'retry_after_minutes': retry_minutes,
|
||
},
|
||
retryable=True,
|
||
)
|
||
|
||
user = db.session.query(User).filter(User.employee_id == employee_id).first()
|
||
if not user:
|
||
current_app.logger.info(
|
||
'[password_reset] noop reason=user_not_found employee_id=%s',
|
||
employee_id,
|
||
)
|
||
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
|
||
if user.username != username:
|
||
current_app.logger.info(
|
||
'[password_reset] noop reason=username_mismatch employee_id=%s user_id=%s',
|
||
employee_id,
|
||
user.id,
|
||
)
|
||
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
|
||
if user.status != 'active':
|
||
current_app.logger.info(
|
||
'[password_reset] noop reason=account_inactive employee_id=%s user_id=%s',
|
||
employee_id,
|
||
user.id,
|
||
)
|
||
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
|
||
if not user.wecom_userid:
|
||
current_app.logger.info(
|
||
'[password_reset] noop reason=wecom_unbound employee_id=%s user_id=%s',
|
||
employee_id,
|
||
user.id,
|
||
)
|
||
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
|
||
|
||
token = str(uuid.uuid4())
|
||
user.reset_token = token
|
||
user.reset_token_expiry = datetime.utcnow() + timedelta(hours=1)
|
||
db.session.flush()
|
||
|
||
title = '和信AI智能工作台 密码重置'
|
||
content = (
|
||
'您发起了和信AI智能工作台密码重置请求。\n'
|
||
'请在 1 小时内点击下方按钮设置新密码。\n'
|
||
'如非本人操作,请忽略本消息。'
|
||
)
|
||
try:
|
||
reset_jump_url = _build_password_reset_url(token)
|
||
result = send_wecom_event_message(
|
||
event_type='password_reset',
|
||
user=user,
|
||
title=title,
|
||
content=content,
|
||
jump_url=reset_jump_url,
|
||
)
|
||
if not result.get('ok'):
|
||
db.session.rollback()
|
||
current_app.logger.warning(
|
||
'[password_reset] wecom send failed user_id=%s employee_id=%s reason=%s trace_id=%s raw=%s',
|
||
user.id,
|
||
employee_id,
|
||
result.get('reason'),
|
||
result.get('trace_id'),
|
||
result.get('raw'),
|
||
)
|
||
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
|
||
|
||
db.session.commit()
|
||
current_app.logger.info(
|
||
'[password_reset] reset link sent user_id=%s employee_id=%s trace_id=%s',
|
||
user.id,
|
||
employee_id,
|
||
result.get('trace_id'),
|
||
)
|
||
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
|
||
except Exception as exc:
|
||
db.session.rollback()
|
||
current_app.logger.exception('[password_reset] unexpected failure user_id=%s: %s', user.id, exc)
|
||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Failed to request password reset', http_status=500)
|
||
|
||
|
||
@user_bp.route('/reset-password-by-email', methods=['POST'])
|
||
def reset_password_request():
|
||
"""
|
||
Request password reset via email
|
||
"""
|
||
data = request.get_json() or {}
|
||
email = data.get('email')
|
||
if not email:
|
||
raise ValidationError('Email is required')
|
||
user = db.session.query(User).filter_by(email=email).first()
|
||
if not user:
|
||
return jsonify({'message': 'If the email exists, a reset link has been sent.'})
|
||
token = str(uuid.uuid4())
|
||
user.reset_token = token
|
||
user.reset_token_expiry = datetime.utcnow() + timedelta(hours=1)
|
||
db.session.commit()
|
||
reset_link = f'http://localhost:5173/reset-password?token={token}'
|
||
print(f'============================================')
|
||
print(f'MOCK EMAIL TO: {email}')
|
||
print(f'SUBJECT: Password Reset Request')
|
||
print(f'LINK: {reset_link}')
|
||
print(f'============================================')
|
||
return jsonify({'message': 'If the email exists, a reset link has been sent.'})
|
||
|
||
@user_bp.route('/reset-password-confirm', methods=['POST'])
|
||
def reset_password_confirm():
|
||
"""
|
||
Reset password with token
|
||
"""
|
||
data = request.get_json() or {}
|
||
token = _clean_str(data.get('token'))
|
||
new_password = data.get('new_password')
|
||
if not token or not new_password:
|
||
raise ValidationError('Token and new password are required')
|
||
user = db.session.query(User).filter_by(reset_token=token).first()
|
||
if not user or not user.reset_token_expiry or user.reset_token_expiry < datetime.utcnow():
|
||
current_app.logger.info(
|
||
'[password_reset] confirm rejected reason=token_invalid token_prefix=%s found_user=%s',
|
||
token[:8] if token else '',
|
||
bool(user),
|
||
)
|
||
raise AppError(
|
||
code='AUTH.RESET_TOKEN_INVALID',
|
||
message='Invalid or expired token',
|
||
http_status=400,
|
||
)
|
||
try:
|
||
_sync_casdoor_password_for_reset(user, new_password)
|
||
user.set_password(new_password)
|
||
user.reset_token = None
|
||
user.reset_token_expiry = None
|
||
db.session.commit()
|
||
return jsonify({'message': 'Password has been reset successfully'})
|
||
except AppError:
|
||
db.session.rollback()
|
||
raise
|
||
except Exception as e:
|
||
db.session.rollback()
|
||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
|
||
|
||
@user_bp.route('/agents/<int:id>', methods=['GET'])
|
||
def get_agent_details(id):
|
||
"""
|
||
Get agent details with permission check
|
||
"""
|
||
user = _get_current_user()
|
||
if not user:
|
||
raise UnauthorizedError('Unauthorized')
|
||
agent = db.session.get(Agent, id)
|
||
if not agent:
|
||
raise NotFoundError('Not found')
|
||
if user.role != 'admin':
|
||
has_permission = agent in user.agents
|
||
if not has_permission:
|
||
raise ForbiddenError('Access denied')
|
||
extra_config = agent.extra_config or {}
|
||
if isinstance(extra_config, dict):
|
||
from app.services.file_check_tools.task_resolver import enrich_agent_extra_if_file_check
|
||
|
||
extra_config = enrich_agent_extra_if_file_check(agent)
|
||
dify_app_type = extra_config.get('dify_app_type') if isinstance(extra_config, dict) else None
|
||
|
||
dify_parameters = None
|
||
agent_type = str(getattr(agent, 'type', '') or '').strip().lower()
|
||
if agent_type == 'api' and getattr(agent, 'dify_api_key', None):
|
||
from app.services.dify import DifyService
|
||
|
||
try:
|
||
params = DifyService.get_app_parameters(agent)
|
||
if isinstance(params, dict):
|
||
dify_parameters = {
|
||
'file_upload': params.get('file_upload') if isinstance(params.get('file_upload'), dict) else {},
|
||
'system_parameters': params.get('system_parameters') if isinstance(params.get('system_parameters'), dict) else {},
|
||
}
|
||
except Exception as exc:
|
||
current_app.logger.warning('[user.agents] dify parameters fetch failed agent_id=%s err=%s', id, exc)
|
||
|
||
return jsonify({
|
||
'id': agent.id,
|
||
'name': agent.name,
|
||
'description': agent.description,
|
||
'type': agent.type,
|
||
'icon_url': agent.icon_url,
|
||
'extra_config': extra_config if isinstance(extra_config, dict) else {},
|
||
'dify_app_type': dify_app_type,
|
||
'welcome_message': extra_config.get('welcome_message') if isinstance(extra_config, dict) else None,
|
||
'suggested_questions': extra_config.get('suggested_questions', []) if isinstance(extra_config, dict) else [],
|
||
'dify_parameters': dify_parameters,
|
||
})
|
||
|
||
@user_bp.route('/db', methods=['GET'])
|
||
def get_db():
|
||
from app.models import User
|
||
from app import db
|
||
u = db.session.query(User).filter_by(username='26040006').first()
|
||
return jsonify({'db': current_app.config.get('SQLALCHEMY_DATABASE_URI'), 'user': u.username if u else None})
|