2007 lines
71 KiB
Python
2007 lines
71 KiB
Python
from flask import Blueprint, request, jsonify, current_app
|
|
from app import db
|
|
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
|
|
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.auth_jwt import get_current_user as _auth_current_user
|
|
from app.auth_jwt import issue_local_access_token
|
|
from sqlalchemy.exc import 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
|
|
|
|
user_bp = Blueprint('user', __name__)
|
|
|
|
_WECOM_ACCESS_TOKEN_CACHE = {
|
|
'token': None,
|
|
'expires_at': None,
|
|
}
|
|
_WECOM_STATE_CACHE = {}
|
|
_WECOM_BIND_SESSION_CACHE = {}
|
|
_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(Exception):
|
|
def __init__(self, error: str, error_code: str, status_code: int, reason: str = None, extra: dict = None):
|
|
super().__init__(error)
|
|
self.error = error
|
|
self.error_code = error_code
|
|
self.status_code = status_code
|
|
self.reason = reason
|
|
self.extra = extra or {}
|
|
|
|
def to_response(self):
|
|
payload = {
|
|
'error': self.error,
|
|
'error_code': self.error_code,
|
|
}
|
|
if self.reason:
|
|
payload['reason'] = self.reason
|
|
payload.update(self.extra)
|
|
return payload, self.status_code
|
|
|
|
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:
|
|
# Do not break auth flow because of audit logging.
|
|
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 _is_wecom_configured():
|
|
return all([
|
|
current_app.config.get('WECOM_ENABLED'),
|
|
current_app.config.get('WECOM_CORP_ID'),
|
|
current_app.config.get('WECOM_AGENT_ID'),
|
|
current_app.config.get('WECOM_SECRET'),
|
|
])
|
|
|
|
|
|
def _issue_casdoor_state(redirect_uri: str):
|
|
# Stateless signed state for multi-process/multi-instance deployment.
|
|
# Why: in-memory state breaks when authorize/login hit different workers.
|
|
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('.')
|
|
# Format: hxops_casdoor_v1.<payload_b64>.<hmac_b64>
|
|
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('=')
|
|
# Constant-time compare to avoid timing side-channel on signature check.
|
|
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())
|
|
# Expiration check prevents long-lived replay.
|
|
if exp <= now_ts:
|
|
return None
|
|
return _clean_str(payload.get('redirect_uri'))
|
|
|
|
|
|
def _get_casdoor_oidc_metadata():
|
|
# Cache OIDC discovery payload to reduce metadata roundtrips.
|
|
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):
|
|
# We do not auto-provision in phase-2; user must exist in local ACL model.
|
|
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):
|
|
# Authorization code -> tokens (access/refresh/id token).
|
|
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 RuntimeError(f'Casdoor token exchange failed: {data}')
|
|
return data
|
|
|
|
|
|
def _casdoor_refresh_token(refresh_token: str):
|
|
# Refresh token -> new access token; refresh token may rotate.
|
|
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 RuntimeError(f'Casdoor refresh failed: {data}')
|
|
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 _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]):
|
|
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_WECOM_MATCH_FIELDS and piece not in result:
|
|
result.append(piece)
|
|
return result or list(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(rf'<{tag}><!\[CDATA\[(.*?)\]\]></{tag}>', xml_text, re.DOTALL)
|
|
if m:
|
|
return m.group(1).strip()
|
|
m2 = re.search(rf'<{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():
|
|
now = datetime.utcnow()
|
|
token = _WECOM_ACCESS_TOKEN_CACHE.get('token')
|
|
expires_at = _WECOM_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')
|
|
token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
|
|
resp = requests.get(token_url, 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}")
|
|
|
|
_WECOM_ACCESS_TOKEN_CACHE['token'] = data['access_token']
|
|
_WECOM_ACCESS_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60))
|
|
return data['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 _normalize_mobile(mobile: str):
|
|
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_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):
|
|
# Some WeCom payloads wrap values in nested shape.
|
|
raw = raw.get('text') or raw.get('web') or raw.get('value')
|
|
return _clean_str(raw)
|
|
return None
|
|
|
|
|
|
def _get_wecom_match_config():
|
|
raw_rules = current_app.config.get('WECOM_MATCH_RULES', 'employee_id,mobile')
|
|
rules = _parse_wecom_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_wecom_first_login_bind_mode():
|
|
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_wecom_first_login_input_fields():
|
|
raw_fields = current_app.config.get('WECOM_FIRST_LOGIN_INPUT_FIELDS', 'employee_id,mobile,email')
|
|
return _parse_wecom_field_list(raw_fields, ['employee_id', 'mobile', 'email'])
|
|
|
|
|
|
def _extract_wecom_identity(wecom_user: dict):
|
|
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_mobile = bool(current_app.config.get('WECOM_MOBILE_NORMALIZE', True))
|
|
mobile = _normalize_mobile(mobile_raw) if normalize_mobile 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_wecom_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):
|
|
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):
|
|
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, []
|
|
|
|
|
|
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):
|
|
return jsonify({'error': f'{field} is required'}), 400
|
|
|
|
if db.session.query(User).filter_by(username=data['username']).first():
|
|
return jsonify({'error': 'Username already exists'}), 400
|
|
if db.session.query(User).filter_by(email=data['email']).first():
|
|
return jsonify({'error': 'Email already exists'}), 400
|
|
if db.session.query(User).filter_by(employee_id=data['employee_id']).first():
|
|
return jsonify({'error': 'Employee ID already exists'}), 400
|
|
|
|
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()
|
|
return jsonify({'error': str(e)}), 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)):
|
|
return jsonify({
|
|
'error': 'Password login is disabled. Please use Casdoor login.',
|
|
'error_code': 'PASSWORD_LOGIN_DISABLED',
|
|
}), 403
|
|
|
|
try:
|
|
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')
|
|
return jsonify({'error': 'Username and password are required'}), 400
|
|
|
|
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()
|
|
return jsonify({'error': 'User not found'}), 404
|
|
|
|
if not user.check_password(password):
|
|
_write_login_audit('password', 'failed', user=user, reason='incorrect_password')
|
|
db.session.commit()
|
|
return jsonify({'error': 'Incorrect password'}), 401
|
|
|
|
if user.status != 'active':
|
|
_write_login_audit('password', 'failed', user=user, reason='account_disabled')
|
|
db.session.commit()
|
|
return jsonify({'error': 'Account is disabled'}), 403
|
|
|
|
_write_login_audit('password', 'success', user=user)
|
|
db.session.commit()
|
|
return jsonify(_build_login_payload(user, 'password'))
|
|
except OperationalError as e:
|
|
print(f"Database connection error: {e}")
|
|
return jsonify({'error': 'Database connection failed'}), 503
|
|
except Exception as e:
|
|
db.session.rollback()
|
|
print(f"Login error: {e}")
|
|
return jsonify({'error': 'Internal server error'}), 500
|
|
|
|
|
|
@user_bp.route('/casdoor/authorize-url', methods=['GET'])
|
|
def casdoor_authorize_url():
|
|
"""
|
|
Build Casdoor OAuth authorize URL.
|
|
|
|
Request:
|
|
GET /api/user/casdoor/authorize-url
|
|
|
|
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:
|
|
return jsonify({'error': 'Casdoor authorization endpoint missing'}), 500
|
|
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
|
|
# Allow frontend to pass current-origin callback so localhost/prod can coexist.
|
|
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:
|
|
return jsonify({'error': 'Casdoor client config is incomplete'}), 500
|
|
state = _issue_casdoor_state(redirect_uri)
|
|
url = (
|
|
f"{authorize_endpoint}?client_id={quote(client_id, safe='')}"
|
|
f"&response_type=code"
|
|
f"&redirect_uri={quote(redirect_uri, safe='')}"
|
|
f"&scope={quote(scope, safe='')}"
|
|
f"&state={quote(state, safe='')}"
|
|
)
|
|
return jsonify({'url': url, 'state': state, 'redirect_uri': redirect_uri})
|
|
except Exception as e:
|
|
return jsonify({'error': f'Failed to build Casdoor authorize url: {str(e)}'}), 500
|
|
|
|
|
|
@user_bp.route('/casdoor/login', methods=['POST'])
|
|
def casdoor_login():
|
|
# OAuth callback exchange entry: validate state, exchange code, map local user.
|
|
"""
|
|
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:
|
|
return jsonify({'error': 'code is required'}), 400
|
|
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 '')
|
|
return jsonify({'error': 'Invalid or expired Casdoor state'}), 400
|
|
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:
|
|
# Prefer validated ID token claims when available.
|
|
claims = _decode_jwt(id_token)
|
|
except Exception:
|
|
claims = None
|
|
if claims is None:
|
|
# Fallback when ID token is absent/unexpected.
|
|
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 layer uses JWT middleware. In OIDC, id_token is guaranteed JWT;
|
|
# access_token may be opaque, so prefer id_token for frontend Bearer usage.
|
|
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 as e:
|
|
db.session.rollback()
|
|
current_app.logger.warning(
|
|
'[casdoor_login] business_reject error_code=%s error=%s',
|
|
e.error_code,
|
|
e.error,
|
|
)
|
|
payload, status = e.to_response()
|
|
return jsonify(payload), status
|
|
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)
|
|
return jsonify({'error': f'Casdoor login failed: {str(e)}'}), 401
|
|
|
|
|
|
@user_bp.route('/casdoor/refresh', methods=['POST'])
|
|
def casdoor_refresh():
|
|
# Frontend silent-refresh endpoint used by global fetch interceptor.
|
|
"""
|
|
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:
|
|
return jsonify({'error': 'refresh_token is required'}), 400
|
|
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),
|
|
)
|
|
# Keep returned access_token aligned with JWT middleware expectations.
|
|
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:
|
|
return jsonify({
|
|
'error': 'Casdoor refresh token is not supported by current application config',
|
|
'error_code': 'CASDOOR_REFRESH_UNSUPPORTED',
|
|
}), 400
|
|
current_app.logger.exception('[casdoor_refresh] failed refresh=%s', _token_brief(refresh_token))
|
|
return jsonify({'error': f'Casdoor refresh failed: {str(e)}'}), 401
|
|
|
|
@user_bp.route('/wecom/authorize-url', methods=['GET'])
|
|
def wecom_authorize_url():
|
|
if not _is_wecom_configured():
|
|
return jsonify({'error': 'WeCom login is not configured'}), 400
|
|
|
|
redirect_uri = request.args.get('redirect_uri') or current_app.config.get('WECOM_REDIRECT_URI')
|
|
if not redirect_uri:
|
|
return jsonify({'error': 'redirect_uri is required'}), 400
|
|
|
|
state = _issue_wecom_state()
|
|
corp_id = current_app.config.get('WECOM_CORP_ID')
|
|
agent_id = current_app.config.get('WECOM_AGENT_ID')
|
|
|
|
url = (
|
|
"https://open.weixin.qq.com/connect/oauth2/authorize"
|
|
f"?appid={corp_id}"
|
|
f"&redirect_uri={quote(redirect_uri, safe='')}"
|
|
"&response_type=code"
|
|
f"&scope=snsapi_base&state={quote(state, safe='')}"
|
|
f"&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():
|
|
return jsonify({'error': 'WeCom login is not configured'}), 400
|
|
|
|
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()
|
|
return jsonify({'error': 'code is required'}), 400
|
|
if not _consume_wecom_state(state):
|
|
_write_login_audit('wecom', 'failed', reason='invalid_state')
|
|
db.session.commit()
|
|
return jsonify({'error': 'Invalid or expired WeCom state'}), 400
|
|
|
|
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()
|
|
# /cgi-bin/auth/getuserinfo 新接口返回小写 userid;为兼容历史 mock / 旧接口同时
|
|
# 兼容大写 UserId。企业成员返回 userid,外部联系人/非可见范围成员只返回 openid。
|
|
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()
|
|
return jsonify({'error': f"WeCom auth failed: {info.get('errmsg', 'unknown error')}"}), 401
|
|
if not wecom_userid_value:
|
|
# errcode=0 但没有 userid:登录者不在该自建应用「可见范围」内,
|
|
# 或不是本企业成员(外部联系人 / openid)。给出明确的可执行提示。
|
|
_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()
|
|
return jsonify({
|
|
'error': '当前企业微信账号未授权登录该应用:账号不在自建应用的可见范围内,或不是本企业成员。请管理员到「企业微信后台 → 应用管理 → 该应用 → 可见范围」中加入该成员所在的部门或个人。',
|
|
'error_code': 'WECOM_NOT_IN_AGENT_SCOPE',
|
|
}), 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()
|
|
return jsonify({'error': f"WeCom user fetch failed: {wecom_user.get('errmsg', 'unknown error')}"}), 401
|
|
|
|
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()
|
|
return jsonify({'error': 'Account is disabled'}), 403
|
|
_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()
|
|
payload, status_code = e.to_response()
|
|
return jsonify(payload), status_code
|
|
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()
|
|
return jsonify({
|
|
'error': '数据库主键自增配置异常,当前环境缺少 users.id 的自动序列。请执行数据库迁移后重试。',
|
|
'error_code': 'DB_SEQUENCE_MISCONFIG',
|
|
}), 500
|
|
_write_login_audit('wecom', 'failed', reason=f'exception:{str(e)[:160]}')
|
|
db.session.commit()
|
|
return jsonify({'error': f'WeCom login failed: {str(e)}'}), 500
|
|
|
|
|
|
@user_bp.route('/wecom/complete-bind', methods=['POST'])
|
|
def wecom_complete_bind():
|
|
if not _is_wecom_configured():
|
|
return jsonify({'error': 'WeCom login is not configured'}), 400
|
|
|
|
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:
|
|
return jsonify({
|
|
'error': 'WeCom binding session expired. Please restart WeCom login.',
|
|
'error_code': 'WECOM_BIND_SESSION_EXPIRED',
|
|
}), 400
|
|
|
|
allowed_fields = _get_wecom_first_login_input_fields()
|
|
if field not in allowed_fields:
|
|
return jsonify({
|
|
'error': 'Selected bind field is not allowed',
|
|
'error_code': 'WECOM_BIND_FIELD_NOT_ALLOWED',
|
|
'allowed_fields': allowed_fields,
|
|
}), 400
|
|
|
|
matched_users, missing_field = _find_users_by_input_field(field, value)
|
|
if missing_field:
|
|
return jsonify({
|
|
'error': f'{field} is required',
|
|
'error_code': 'WECOM_BIND_INPUT_VALUE_REQUIRED',
|
|
'field': field,
|
|
}), 400
|
|
|
|
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()
|
|
return jsonify({
|
|
'error': 'No local account matched the verification value.',
|
|
'error_code': 'WECOM_BIND_INPUT_NOT_FOUND',
|
|
'field': field,
|
|
}), 404
|
|
|
|
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()
|
|
return jsonify({
|
|
'error': 'Multiple local accounts matched the verification value.',
|
|
'error_code': 'WECOM_BIND_INPUT_AMBIGUOUS',
|
|
'field': field,
|
|
'candidate_count': len(matched_users),
|
|
}), 409
|
|
|
|
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()
|
|
return jsonify({'error': 'Account is disabled'}), 403
|
|
|
|
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()
|
|
payload, status_code = e.to_response()
|
|
return jsonify(payload), status_code
|
|
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()
|
|
return jsonify({'error': f'WeCom bind failed: {str(e)}'}), 500
|
|
|
|
|
|
@user_bp.route('/wecom/deeplink-opened', methods=['POST'])
|
|
def mark_wecom_deeplink_opened():
|
|
user = _get_current_user()
|
|
if not user:
|
|
return jsonify({'error': 'Unauthorized'}), 401
|
|
|
|
data = request.get_json() or {}
|
|
trace_id = _clean_str(data.get('trace_id'))
|
|
if not trace_id:
|
|
return jsonify({'error': 'trace_id is required'}), 400
|
|
|
|
ok = mark_wecom_message_opened(trace_id)
|
|
if not ok:
|
|
return jsonify({'error': 'trace_id not found'}), 404
|
|
|
|
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:
|
|
return jsonify({'error': 'Unauthorized'}), 401
|
|
|
|
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('/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:
|
|
return jsonify({'error': 'callback token not configured'}), 500
|
|
if aes_key:
|
|
if not _verify_wecom_msg_signature(msg_signature, token, timestamp, nonce, echostr):
|
|
return jsonify({'error': 'invalid callback signature'}), 403
|
|
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]}',
|
|
)
|
|
return jsonify({'error': 'decrypt failed'}), 400
|
|
_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):
|
|
return jsonify({'error': 'invalid callback signature'}), 403
|
|
_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:
|
|
return jsonify({'error': 'callback token not configured'}), 500
|
|
if not encrypt_field:
|
|
return jsonify({'error': 'missing Encrypt field'}), 400
|
|
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',
|
|
)
|
|
return jsonify({'error': 'invalid callback signature'}), 403
|
|
|
|
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]}',
|
|
)
|
|
return jsonify({'error': 'decrypt failed'}), 400
|
|
|
|
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:
|
|
return jsonify({'error': 'Unauthorized'}), 401
|
|
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:
|
|
return jsonify({'error': 'Unauthorized'}), 401
|
|
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:
|
|
return jsonify({'error': 'Unauthorized'}), 401
|
|
|
|
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):
|
|
return jsonify({'error': 'chat_log_id must be an integer'}), 400
|
|
if chat_log_id <= 0:
|
|
return jsonify({'error': 'chat_log_id must be a positive integer'}), 400
|
|
|
|
if not feedback_type:
|
|
return jsonify({'error': 'feedback_type is required'}), 400
|
|
if not feedback_module:
|
|
return jsonify({'error': 'feedback_module is required'}), 400
|
|
if len(feedback_type) > 32:
|
|
return jsonify({'error': 'feedback_type is too long'}), 400
|
|
if len(feedback_module) > 32:
|
|
return jsonify({'error': 'feedback_module is too long'}), 400
|
|
if not content:
|
|
return jsonify({'error': 'content is required'}), 400
|
|
if len(content) > 2000:
|
|
return jsonify({'error': 'content is too long'}), 400
|
|
|
|
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:
|
|
return jsonify({'error': 'chat_log_id not found'}), 400
|
|
if chat_log.user_id != user.id:
|
|
return jsonify({'error': 'chat_log_id is not owned by current user'}), 403
|
|
|
|
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()
|
|
|
|
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:
|
|
return jsonify({'error': 'Unauthorized'}), 401
|
|
|
|
# Get all agents available to user (including public ones)
|
|
if user.role == 'admin':
|
|
agents = db.session.query(Agent).filter_by(is_active=True).all()
|
|
else:
|
|
# User permissions
|
|
agents = user.agents
|
|
|
|
# Favorites
|
|
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
|
|
favorite_ids = [f.agent_id for f in favorites]
|
|
|
|
# Quick Questions (Global + User specific)
|
|
qqs = db.session.query(QuickQuestion).filter(
|
|
(QuickQuestion.user_id == user.id) | (QuickQuestion.user_id == None)
|
|
).all()
|
|
|
|
# Layout
|
|
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
|
|
layout = layout_config.layout if layout_config else {}
|
|
|
|
# Embedded agents
|
|
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': [{
|
|
'id': a.id,
|
|
'name': a.name,
|
|
'description': a.description,
|
|
'icon_url': a.icon_url
|
|
} for a in agents],
|
|
'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
|
|
})
|
|
|
|
@user_bp.route('/favorites/<int:agent_id>', methods=['POST', 'DELETE'])
|
|
def toggle_favorite(agent_id: int):
|
|
user = _get_current_user()
|
|
if not user:
|
|
return jsonify({'error': 'Unauthorized'}), 401
|
|
|
|
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:
|
|
return jsonify({'error': 'Unauthorized'}), 401
|
|
|
|
data = request.get_json() or {}
|
|
if not data.get('title') or not data.get('question') or not data.get('agent_id'):
|
|
return jsonify({'error': 'Missing fields'}), 400
|
|
|
|
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:
|
|
return jsonify({'error': 'Unauthorized'}), 401
|
|
|
|
qq = db.session.query(QuickQuestion).filter_by(id=qq_id, user_id=user.id).first()
|
|
if not qq:
|
|
return jsonify({"error": "QuickQuestion not found or permission denied"}), 404
|
|
|
|
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:
|
|
return jsonify({'error': 'Unauthorized'}), 401
|
|
|
|
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:
|
|
return jsonify({'error': 'Unauthorized'}), 401
|
|
|
|
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',
|
|
})
|
|
|
|
# PUT
|
|
data = request.get_json() or {}
|
|
|
|
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']:
|
|
return jsonify({'error': 'Invalid theme preference'}), 400
|
|
user.theme_preference = data['theme_preference']
|
|
|
|
# Allow editing email, employee_id, department
|
|
if 'email' in data:
|
|
# Check uniqueness
|
|
if data['email']:
|
|
existing = db.session.query(User).filter_by(email=data['email']).first()
|
|
if existing and existing.id != user.id:
|
|
return jsonify({'error': 'Email already exists'}), 400
|
|
user.email = data['email']
|
|
|
|
if 'employee_id' in data:
|
|
# Check uniqueness
|
|
if data['employee_id']:
|
|
existing = db.session.query(User).filter_by(employee_id=data['employee_id']).first()
|
|
if existing and existing.id != user.id:
|
|
return jsonify({'error': 'Employee ID already exists'}), 400
|
|
user.employee_id = data['employee_id']
|
|
|
|
if 'department' in data:
|
|
user.department = data['department']
|
|
|
|
try:
|
|
db.session.commit()
|
|
return jsonify({'message': 'Profile updated successfully'})
|
|
except Exception as e:
|
|
db.session.rollback()
|
|
return jsonify({'error': str(e)}), 500
|
|
|
|
@user_bp.route('/change-password', methods=['POST'])
|
|
def change_password():
|
|
"""
|
|
Change password
|
|
"""
|
|
user = _get_current_user()
|
|
if not user:
|
|
return jsonify({'error': 'Unauthorized'}), 401
|
|
|
|
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:
|
|
return jsonify({'error': 'Current and new password are required'}), 400
|
|
|
|
if not user.check_password(current_password):
|
|
return jsonify({'error': 'Incorrect current password'}), 403
|
|
|
|
try:
|
|
user.set_password(new_password)
|
|
db.session.commit()
|
|
return jsonify({'message': 'Password changed successfully'})
|
|
except Exception as e:
|
|
db.session.rollback()
|
|
return jsonify({'error': str(e)}), 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:
|
|
return jsonify({'error': 'Email is required'}), 400
|
|
|
|
user = db.session.query(User).filter_by(email=email).first()
|
|
if not user:
|
|
# For security, don't reveal if email exists
|
|
return jsonify({'message': 'If the email exists, a reset link has been sent.'})
|
|
|
|
# Generate token
|
|
token = str(uuid.uuid4())
|
|
user.reset_token = token
|
|
user.reset_token_expiry = datetime.utcnow() + timedelta(hours=1)
|
|
db.session.commit()
|
|
|
|
# Mock send email
|
|
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 = data.get('token')
|
|
new_password = data.get('new_password')
|
|
|
|
if not token or not new_password:
|
|
return jsonify({'error': 'Token and new password are required'}), 400
|
|
|
|
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():
|
|
return jsonify({'error': 'Invalid or expired token'}), 400
|
|
|
|
try:
|
|
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 Exception as e:
|
|
db.session.rollback()
|
|
return jsonify({'error': str(e)}), 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:
|
|
return jsonify({'error': 'Unauthorized'}), 401
|
|
|
|
agent = db.session.get(Agent, id)
|
|
if not agent:
|
|
return jsonify({'error': 'Not found'}), 404
|
|
|
|
# Check permission
|
|
# Admin can access all
|
|
if user.role != 'admin':
|
|
has_permission = agent in user.agents
|
|
if not has_permission:
|
|
return jsonify({'error': 'Access denied'}), 403
|
|
|
|
return jsonify({
|
|
'id': agent.id,
|
|
'name': agent.name,
|
|
'description': agent.description,
|
|
'icon_url': agent.extra_config.get('icon_url') if agent.extra_config else None,
|
|
'welcome_message': agent.extra_config.get('welcome_message') if agent.extra_config else None,
|
|
'suggested_questions': agent.extra_config.get('suggested_questions', []) if agent.extra_config else []
|
|
})
|
|
|
|
@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})
|
|
|
|
@user_bp.route('/announcements', methods=['GET'])
|
|
def get_announcements():
|
|
"""
|
|
Get active announcements (Public)
|
|
"""
|
|
try:
|
|
anns = db.session.query(Announcement).filter_by(is_active=True).order_by(Announcement.created_at.desc()).all()
|
|
return jsonify([{
|
|
'id': a.id,
|
|
'title': a.title,
|
|
'content': a.content,
|
|
'created_at': a.created_at.isoformat()
|
|
} for a in anns])
|
|
except Exception as e:
|
|
import traceback
|
|
return jsonify({'error': str(e), 'traceback': traceback.format_exc()}), 500
|
|
|
|
@user_bp.route('/announcements', methods=['POST'])
|
|
def create_announcement():
|
|
"""
|
|
Create announcement (Admin only)
|
|
"""
|
|
user = _get_current_user()
|
|
if not user or user.role != 'admin':
|
|
return jsonify({'error': 'Unauthorized'}), 403
|
|
|
|
data = request.get_json() or {}
|
|
if not data.get('title') or not data.get('content'):
|
|
return jsonify({'error': 'Missing fields'}), 400
|
|
|
|
ann = Announcement(
|
|
title=data['title'],
|
|
content=data['content'],
|
|
is_active=True
|
|
)
|
|
db.session.add(ann)
|
|
db.session.commit()
|
|
return jsonify({'message': 'Created', 'id': ann.id}), 201
|
|
|
|
@user_bp.route('/announcements/<int:id>', methods=['DELETE'])
|
|
def delete_announcement(id):
|
|
user = _get_current_user()
|
|
if not user or user.role != 'admin':
|
|
return jsonify({'error': 'Unauthorized'}), 403
|
|
|
|
ann = db.session.get(Announcement, id)
|
|
if ann:
|
|
db.session.delete(ann)
|
|
db.session.commit()
|
|
return jsonify({'message': 'Deleted'})
|