Merge branch 'test' into prod
This commit is contained in:
commit
6e5ef8f6c0
19 files changed
+1056
-235
No files matched your search
@@ -1,2 +1,26 @@
|
|||||||
INTEGRATION_API_BASE=http://192.168.100.230:8891
|
INTEGRATION_API_BASE=http://192.168.100.230:8891
|
||||||
INTEGRATION_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
INTEGRATION_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||||
|
|
||||||
|
|
||||||
|
# 是否启用 JWT 认证
|
||||||
|
AUTH_JWT_REQUIRED=true
|
||||||
|
|
||||||
|
# Casdoor JWT 验签三件套
|
||||||
|
AUTH_JWT_ISSUER=http://192.168.100.230:8088
|
||||||
|
AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
|
||||||
|
AUTH_JWT_JWKS_URL=http://192.168.100.230:8088/.well-known/jwks
|
||||||
|
|
||||||
|
# Casdoor OAuth
|
||||||
|
CASDOOR_BASE_URL=http://192.168.100.230:8088
|
||||||
|
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
|
||||||
|
CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab
|
||||||
|
# CASDOOR_REDIRECT_URI=http://localhost:8881/casdoor-callback
|
||||||
|
CASDOOR_REDIRECT_URI=http://192.168.100.230:8881/casdoor-callback
|
||||||
|
CASDOOR_SCOPE=openid profile email
|
||||||
|
|
||||||
|
# 是否保留本地密码登录/本地JWT兼容(按你当前需求建议保留)
|
||||||
|
AUTH_ALLOW_LOCAL_PASSWORD_LOGIN=true
|
||||||
|
AUTH_ALLOW_LOCAL_JWT=true
|
||||||
|
AUTH_LOCAL_JWT_ISSUER=hxops-backend
|
||||||
|
AUTH_LOCAL_JWT_AUDIENCE=hxops-frontend
|
||||||
|
AUTH_LOCAL_JWT_EXPIRES_HOURS=12
|
||||||
@@ -15,13 +15,34 @@ from sqlalchemy.exc import IntegrityError
|
|||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
import csv
|
import csv
|
||||||
import io
|
import io
|
||||||
|
import re
|
||||||
import requests
|
import requests
|
||||||
import uuid
|
import uuid
|
||||||
from app.services.wecom_notify import send_wecom_event_message
|
from app.services.wecom_notify import send_wecom_event_message
|
||||||
|
from app.auth_jwt import get_current_user as _get_auth_user
|
||||||
|
|
||||||
admin_bp = Blueprint('admin', __name__)
|
admin_bp = Blueprint('admin', __name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _empty_to_none(value):
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
if isinstance(value, str) and value.strip() == '':
|
||||||
|
return None
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _is_valid_email(email: str) -> bool:
|
||||||
|
# Practical validation: local@domain.tld (avoid over-strict RFC parsing)
|
||||||
|
if not isinstance(email, str):
|
||||||
|
return False
|
||||||
|
email = email.strip()
|
||||||
|
if len(email) > 254:
|
||||||
|
return False
|
||||||
|
pattern = r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$"
|
||||||
|
return re.match(pattern, email) is not None
|
||||||
|
|
||||||
|
|
||||||
def _serialize_wecom_notify_settings():
|
def _serialize_wecom_notify_settings():
|
||||||
return {
|
return {
|
||||||
'enabled': bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)),
|
'enabled': bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)),
|
||||||
@@ -547,15 +568,19 @@ def create_user():
|
|||||||
if db.session.query(User).filter_by(username=data['username']).first():
|
if db.session.query(User).filter_by(username=data['username']).first():
|
||||||
return jsonify({'error': 'Username exists'}), 400
|
return jsonify({'error': 'Username exists'}), 400
|
||||||
|
|
||||||
|
email = _empty_to_none(data.get('email'))
|
||||||
|
if email is not None and not _is_valid_email(email):
|
||||||
|
return jsonify({'error': 'Invalid email format'}), 400
|
||||||
|
|
||||||
user = User(
|
user = User(
|
||||||
username=data['username'],
|
username=data['username'],
|
||||||
email=data.get('email'),
|
email=email,
|
||||||
department=data.get('department'),
|
department=_empty_to_none(data.get('department')),
|
||||||
role=data.get('role', 'user'),
|
role=data.get('role', 'user'),
|
||||||
status=data.get('status', 'active'),
|
status=data.get('status', 'active'),
|
||||||
real_name=data.get('real_name'),
|
real_name=_empty_to_none(data.get('real_name')),
|
||||||
employee_id=data.get('employee_id'),
|
employee_id=_empty_to_none(data.get('employee_id')),
|
||||||
phone_number=data.get('phone_number')
|
phone_number=_empty_to_none(data.get('phone_number'))
|
||||||
)
|
)
|
||||||
if data.get('password'): user.set_password(data['password'])
|
if data.get('password'): user.set_password(data['password'])
|
||||||
|
|
||||||
@@ -564,7 +589,18 @@ def create_user():
|
|||||||
user.agents = agents
|
user.agents = agents
|
||||||
|
|
||||||
db.session.add(user)
|
db.session.add(user)
|
||||||
db.session.commit()
|
try:
|
||||||
|
db.session.commit()
|
||||||
|
except IntegrityError as e:
|
||||||
|
db.session.rollback()
|
||||||
|
message = str(getattr(e, 'orig', e))
|
||||||
|
if 'users_email_key' in message:
|
||||||
|
return jsonify({'error': 'Email exists'}), 400
|
||||||
|
if 'users_employee_id_key' in message:
|
||||||
|
return jsonify({'error': 'Employee ID exists'}), 400
|
||||||
|
if 'users_phone_number_key' in message:
|
||||||
|
return jsonify({'error': 'Phone number exists'}), 400
|
||||||
|
return jsonify({'error': 'Data uniqueness conflict'}), 400
|
||||||
return jsonify({'id': user.id}), 201
|
return jsonify({'id': user.id}), 201
|
||||||
|
|
||||||
@admin_bp.route('/users/<int:id>', methods=['PUT'])
|
@admin_bp.route('/users/<int:id>', methods=['PUT'])
|
||||||
@@ -574,8 +610,17 @@ def update_user(id):
|
|||||||
if not user: return jsonify({'error': 'Not found'}), 404
|
if not user: return jsonify({'error': 'Not found'}), 404
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
|
|
||||||
|
if 'email' in data:
|
||||||
|
email = _empty_to_none(data.get('email'))
|
||||||
|
if email is not None and not _is_valid_email(email):
|
||||||
|
return jsonify({'error': 'Invalid email format'}), 400
|
||||||
|
|
||||||
for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
||||||
if k in data: setattr(user, k, data[k])
|
if k in data:
|
||||||
|
if k in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||||||
|
setattr(user, k, _empty_to_none(data[k]))
|
||||||
|
else:
|
||||||
|
setattr(user, k, data[k])
|
||||||
|
|
||||||
if data.get('password'): user.set_password(data['password'])
|
if data.get('password'): user.set_password(data['password'])
|
||||||
|
|
||||||
@@ -583,7 +628,18 @@ def update_user(id):
|
|||||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||||
user.agents = agents
|
user.agents = agents
|
||||||
|
|
||||||
db.session.commit()
|
try:
|
||||||
|
db.session.commit()
|
||||||
|
except IntegrityError as e:
|
||||||
|
db.session.rollback()
|
||||||
|
message = str(getattr(e, 'orig', e))
|
||||||
|
if 'users_email_key' in message:
|
||||||
|
return jsonify({'error': 'Email exists'}), 400
|
||||||
|
if 'users_employee_id_key' in message:
|
||||||
|
return jsonify({'error': 'Employee ID exists'}), 400
|
||||||
|
if 'users_phone_number_key' in message:
|
||||||
|
return jsonify({'error': 'Phone number exists'}), 400
|
||||||
|
return jsonify({'error': 'Data uniqueness conflict'}), 400
|
||||||
return jsonify({'status': 'ok'})
|
return jsonify({'status': 'ok'})
|
||||||
|
|
||||||
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
|
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
|
||||||
@@ -598,7 +654,8 @@ def cleanup_rejected_users():
|
|||||||
def batch_delete_users():
|
def batch_delete_users():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
ids = data.get('user_ids', [])
|
ids = data.get('user_ids', [])
|
||||||
current_user_id = request.headers.get('X-User-Id')
|
current_user = _get_auth_user()
|
||||||
|
current_user_id = current_user.id if current_user else None
|
||||||
target_ids = [uid for uid in ids if str(uid) != str(current_user_id)]
|
target_ids = [uid for uid in ids if str(uid) != str(current_user_id)]
|
||||||
if not target_ids: return jsonify({'error': 'No valid users'}), 400
|
if not target_ids: return jsonify({'error': 'No valid users'}), 400
|
||||||
cnt = db.session.query(User).filter(User.id.in_(target_ids)).delete(synchronize_session=False)
|
cnt = db.session.query(User).filter(User.id.in_(target_ids)).delete(synchronize_session=False)
|
||||||
|
|||||||
+414
-7
@@ -3,12 +3,18 @@ from app import db
|
|||||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
|
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_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.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.exc import IntegrityError, OperationalError
|
||||||
from sqlalchemy import and_, or_, inspect, insert
|
from sqlalchemy import and_, or_, inspect, insert
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
import uuid
|
import uuid
|
||||||
import requests
|
import requests
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
import re
|
import re
|
||||||
|
|
||||||
user_bp = Blueprint('user', __name__)
|
user_bp = Blueprint('user', __name__)
|
||||||
@@ -21,6 +27,15 @@ _WECOM_STATE_CACHE = {}
|
|||||||
_WECOM_BIND_SESSION_CACHE = {}
|
_WECOM_BIND_SESSION_CACHE = {}
|
||||||
_ALLOWED_WECOM_MATCH_FIELDS = {'employee_id', 'mobile', 'email'}
|
_ALLOWED_WECOM_MATCH_FIELDS = {'employee_id', 'mobile', 'email'}
|
||||||
_LOGIN_AUDIT_COLUMNS_CACHE = None
|
_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:
|
def _is_users_pk_sequence_error(exc: Exception) -> bool:
|
||||||
@@ -123,12 +138,14 @@ def _execute_login_audit_insert(payload: dict):
|
|||||||
|
|
||||||
def _get_current_user():
|
def _get_current_user():
|
||||||
"""
|
"""
|
||||||
Helper to get current user from headers
|
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.
|
||||||
"""
|
"""
|
||||||
user_id = request.headers.get('X-User-Id')
|
return _auth_current_user()
|
||||||
if not user_id:
|
|
||||||
return None
|
|
||||||
return db.session.get(User, int(user_id))
|
|
||||||
|
|
||||||
def _is_wecom_configured():
|
def _is_wecom_configured():
|
||||||
return all([
|
return all([
|
||||||
@@ -138,6 +155,159 @@ def _is_wecom_configured():
|
|||||||
current_app.config.get('WECOM_SECRET'),
|
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():
|
def _cleanup_wecom_state_cache():
|
||||||
now = datetime.utcnow()
|
now = datetime.utcnow()
|
||||||
expired = [k for k, v in _WECOM_STATE_CACHE.items() if not v or v < now]
|
expired = [k for k, v in _WECOM_STATE_CACHE.items() if not v or v < now]
|
||||||
@@ -296,6 +466,8 @@ def _build_login_payload(user: User, source: str = 'password', bind_status: str
|
|||||||
'role': user.role,
|
'role': user.role,
|
||||||
'default_agent_id': user.default_agent_id,
|
'default_agent_id': user.default_agent_id,
|
||||||
'source': source,
|
'source': source,
|
||||||
|
'access_token': issue_local_access_token(user),
|
||||||
|
'token_type': 'Bearer',
|
||||||
}
|
}
|
||||||
if bind_status:
|
if bind_status:
|
||||||
payload['bind_status'] = bind_status
|
payload['bind_status'] = bind_status
|
||||||
@@ -674,8 +846,27 @@ def register():
|
|||||||
@user_bp.route('/login', methods=['POST'])
|
@user_bp.route('/login', methods=['POST'])
|
||||||
def login():
|
def login():
|
||||||
"""
|
"""
|
||||||
User login with detailed error messages
|
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:
|
try:
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
username = data.get('username')
|
username = data.get('username')
|
||||||
@@ -686,7 +877,6 @@ def login():
|
|||||||
return jsonify({'error': 'Username and password are required'}), 400
|
return jsonify({'error': 'Username and password are required'}), 400
|
||||||
|
|
||||||
user = db.session.query(User).filter_by(username=username).first()
|
user = db.session.query(User).filter_by(username=username).first()
|
||||||
|
|
||||||
if not user:
|
if not user:
|
||||||
_write_login_audit('password', 'failed', username=username, reason='user_not_found')
|
_write_login_audit('password', 'failed', username=username, reason='user_not_found')
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
@@ -701,6 +891,7 @@ def login():
|
|||||||
_write_login_audit('password', 'failed', user=user, reason='account_disabled')
|
_write_login_audit('password', 'failed', user=user, reason='account_disabled')
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return jsonify({'error': 'Account is disabled'}), 403
|
return jsonify({'error': 'Account is disabled'}), 403
|
||||||
|
|
||||||
_write_login_audit('password', 'success', user=user)
|
_write_login_audit('password', 'success', user=user)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return jsonify(_build_login_payload(user, 'password'))
|
return jsonify(_build_login_payload(user, 'password'))
|
||||||
@@ -712,6 +903,222 @@ def login():
|
|||||||
print(f"Login error: {e}")
|
print(f"Login error: {e}")
|
||||||
return jsonify({'error': 'Internal server error'}), 500
|
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'])
|
@user_bp.route('/wecom/authorize-url', methods=['GET'])
|
||||||
def wecom_authorize_url():
|
def wecom_authorize_url():
|
||||||
if not _is_wecom_configured():
|
if not _is_wecom_configured():
|
||||||
|
|||||||
@@ -0,0 +1,232 @@
|
|||||||
|
import time
|
||||||
|
import json
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
import jwt
|
||||||
|
import requests
|
||||||
|
from flask import current_app, g, request
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.models import User
|
||||||
|
|
||||||
|
_JWKS_CACHE: dict[str, Any] = {
|
||||||
|
'url': None,
|
||||||
|
'keys': None,
|
||||||
|
'expires_at': 0.0,
|
||||||
|
}
|
||||||
|
|
||||||
|
def _token_brief(token: Optional[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 _extract_bearer_token() -> Optional[str]:
|
||||||
|
# Only trust standard Bearer token; reject all non-Bearer auth schemes.
|
||||||
|
auth = request.headers.get('Authorization', '')
|
||||||
|
if not auth:
|
||||||
|
return None
|
||||||
|
parts = auth.split(' ', 1)
|
||||||
|
if len(parts) != 2 or parts[0].lower() != 'bearer':
|
||||||
|
return None
|
||||||
|
token = parts[1].strip()
|
||||||
|
return token or None
|
||||||
|
|
||||||
|
|
||||||
|
def _get_jwks_keys(jwks_url: str) -> dict:
|
||||||
|
# Keep a short in-memory JWKS cache to avoid hitting Casdoor for every request.
|
||||||
|
now = time.time()
|
||||||
|
if (
|
||||||
|
_JWKS_CACHE.get('url') == jwks_url
|
||||||
|
and isinstance(_JWKS_CACHE.get('keys'), dict)
|
||||||
|
and now < float(_JWKS_CACHE.get('expires_at') or 0.0)
|
||||||
|
):
|
||||||
|
return _JWKS_CACHE['keys']
|
||||||
|
|
||||||
|
resp = requests.get(jwks_url, timeout=5)
|
||||||
|
resp.raise_for_status()
|
||||||
|
data = resp.json() or {}
|
||||||
|
keys = {}
|
||||||
|
for item in data.get('keys', []):
|
||||||
|
kid = item.get('kid')
|
||||||
|
if kid:
|
||||||
|
keys[kid] = item
|
||||||
|
if not keys:
|
||||||
|
raise ValueError('No JWKS keys found')
|
||||||
|
|
||||||
|
_JWKS_CACHE['url'] = jwks_url
|
||||||
|
_JWKS_CACHE['keys'] = keys
|
||||||
|
_JWKS_CACHE['expires_at'] = now + 300
|
||||||
|
return keys
|
||||||
|
|
||||||
|
|
||||||
|
def _decode_jwt(token: str) -> dict:
|
||||||
|
# Strictly validate iss/aud/exp/iat against Casdoor metadata-derived settings.
|
||||||
|
issuer = (current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
|
||||||
|
audience = (current_app.config.get('AUTH_JWT_AUDIENCE') or '').strip()
|
||||||
|
jwks_url = (current_app.config.get('AUTH_JWT_JWKS_URL') or '').strip()
|
||||||
|
if not issuer or not audience or not jwks_url:
|
||||||
|
raise ValueError('JWT auth is not fully configured')
|
||||||
|
|
||||||
|
header = jwt.get_unverified_header(token)
|
||||||
|
kid = header.get('kid')
|
||||||
|
current_app.logger.info(
|
||||||
|
'[auth_jwt] decode start kid=%s alg=%s token=%s',
|
||||||
|
kid,
|
||||||
|
header.get('alg'),
|
||||||
|
_token_brief(token),
|
||||||
|
)
|
||||||
|
if not kid:
|
||||||
|
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_JWT', True)):
|
||||||
|
raise ValueError('JWT header missing kid')
|
||||||
|
secret = current_app.config.get('SECRET_KEY')
|
||||||
|
if not secret:
|
||||||
|
raise ValueError('Local JWT secret is missing')
|
||||||
|
local_issuer = (current_app.config.get('AUTH_LOCAL_JWT_ISSUER') or 'hxops-backend').strip()
|
||||||
|
local_audience = (current_app.config.get('AUTH_LOCAL_JWT_AUDIENCE') or 'hxops-frontend').strip()
|
||||||
|
return jwt.decode(
|
||||||
|
token,
|
||||||
|
key=secret,
|
||||||
|
algorithms=['HS256'],
|
||||||
|
audience=local_audience,
|
||||||
|
issuer=local_issuer,
|
||||||
|
options={'require': ['exp', 'iat']},
|
||||||
|
)
|
||||||
|
|
||||||
|
keys = _get_jwks_keys(jwks_url)
|
||||||
|
jwk = keys.get(kid)
|
||||||
|
if not jwk:
|
||||||
|
# stale cache fallback
|
||||||
|
_JWKS_CACHE['expires_at'] = 0.0
|
||||||
|
keys = _get_jwks_keys(jwks_url)
|
||||||
|
jwk = keys.get(kid)
|
||||||
|
if not jwk:
|
||||||
|
raise ValueError('No matching JWKS key for token')
|
||||||
|
|
||||||
|
# Different jwt packages/versions expose JWK->public-key helpers differently.
|
||||||
|
# Try multiple compatible paths to avoid hard dependency on one symbol name.
|
||||||
|
public_key = None
|
||||||
|
pyjwk = getattr(jwt, 'PyJWK', None)
|
||||||
|
if pyjwk and hasattr(pyjwk, 'from_dict'):
|
||||||
|
public_key = pyjwk.from_dict(jwk).key
|
||||||
|
if public_key is None:
|
||||||
|
rsa_alg = getattr(getattr(jwt, 'algorithms', None), 'RSAAlgorithm', None)
|
||||||
|
if rsa_alg and hasattr(rsa_alg, 'from_jwk'):
|
||||||
|
public_key = rsa_alg.from_jwk(json.dumps(jwk))
|
||||||
|
if public_key is None:
|
||||||
|
get_algs = getattr(getattr(jwt, 'algorithms', None), 'get_default_algorithms', None)
|
||||||
|
if callable(get_algs):
|
||||||
|
rs256 = (get_algs() or {}).get('RS256')
|
||||||
|
if rs256 and hasattr(rs256, 'from_jwk'):
|
||||||
|
public_key = rs256.from_jwk(json.dumps(jwk))
|
||||||
|
if public_key is None:
|
||||||
|
raise ValueError('Cannot build RSA public key from JWK; check installed jwt package')
|
||||||
|
|
||||||
|
return jwt.decode(
|
||||||
|
token,
|
||||||
|
key=public_key,
|
||||||
|
algorithms=['RS256', 'RS384', 'RS512'],
|
||||||
|
audience=audience,
|
||||||
|
issuer=issuer,
|
||||||
|
options={'require': ['exp', 'iat']},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_user_from_claims(claims: dict) -> Optional[User]:
|
||||||
|
# Resolution order keeps compatibility with different token claim conventions.
|
||||||
|
user_id = claims.get('user_id') or claims.get('id')
|
||||||
|
if user_id is not None:
|
||||||
|
try:
|
||||||
|
user = db.session.get(User, int(user_id))
|
||||||
|
if user:
|
||||||
|
return user
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
username = claims.get('preferred_username') or claims.get('username') or claims.get('name')
|
||||||
|
if username:
|
||||||
|
user = db.session.query(User).filter_by(username=str(username)).first()
|
||||||
|
if user:
|
||||||
|
return user
|
||||||
|
|
||||||
|
email = claims.get('email')
|
||||||
|
if email:
|
||||||
|
user = db.session.query(User).filter_by(email=str(email)).first()
|
||||||
|
if user:
|
||||||
|
return user
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _legacy_header_user() -> Optional[User]:
|
||||||
|
user_id = request.headers.get('X-User-Id')
|
||||||
|
if user_id:
|
||||||
|
try:
|
||||||
|
user = db.session.get(User, int(user_id))
|
||||||
|
if user:
|
||||||
|
return user
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
username = request.headers.get('X-Username')
|
||||||
|
if username:
|
||||||
|
return db.session.query(User).filter_by(username=username).first()
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def get_current_user() -> Optional[User]:
|
||||||
|
cached = getattr(g, 'current_user', None)
|
||||||
|
if cached is not None:
|
||||||
|
return cached
|
||||||
|
|
||||||
|
token = _extract_bearer_token()
|
||||||
|
if token:
|
||||||
|
try:
|
||||||
|
claims = _decode_jwt(token)
|
||||||
|
user = _resolve_user_from_claims(claims)
|
||||||
|
current_app.logger.info(
|
||||||
|
'[auth_jwt] decode ok sub=%s username=%s resolved_user=%s',
|
||||||
|
claims.get('sub'),
|
||||||
|
claims.get('preferred_username') or claims.get('username') or claims.get('name'),
|
||||||
|
getattr(user, 'username', None),
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
# Any decode/lookup failure should behave as unauthenticated.
|
||||||
|
current_app.logger.exception('[auth_jwt] decode failed token=%s path=%s', _token_brief(token), request.path)
|
||||||
|
user = None
|
||||||
|
claims = None
|
||||||
|
if user:
|
||||||
|
g.jwt_claims = claims
|
||||||
|
g.current_user = user
|
||||||
|
return user
|
||||||
|
|
||||||
|
if bool(current_app.config.get('AUTH_LEGACY_HEADER_ENABLED', True)):
|
||||||
|
user = _legacy_header_user()
|
||||||
|
if user:
|
||||||
|
g.current_user = user
|
||||||
|
return user
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def issue_local_access_token(user: User) -> str:
|
||||||
|
"""Issue local HS256 JWT for password-login flow compatibility."""
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
exp_hours = int(current_app.config.get('AUTH_LOCAL_JWT_EXPIRES_HOURS') or 12)
|
||||||
|
payload = {
|
||||||
|
'sub': str(user.id),
|
||||||
|
'id': user.id,
|
||||||
|
'user_id': user.id,
|
||||||
|
'username': user.username,
|
||||||
|
'role': user.role,
|
||||||
|
'email': user.email,
|
||||||
|
'iat': int(now.timestamp()),
|
||||||
|
'exp': int((now + timedelta(hours=max(1, exp_hours))).timestamp()),
|
||||||
|
'iss': (current_app.config.get('AUTH_LOCAL_JWT_ISSUER') or 'hxops-backend'),
|
||||||
|
'aud': (current_app.config.get('AUTH_LOCAL_JWT_AUDIENCE') or 'hxops-frontend'),
|
||||||
|
}
|
||||||
|
secret = current_app.config.get('SECRET_KEY')
|
||||||
|
return jwt.encode(payload, secret, algorithm='HS256')
|
||||||
+22
-2
@@ -67,14 +67,34 @@ class Config:
|
|||||||
'permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed',
|
'permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# JWT/Casdoor auth configuration (phase-1 compatible rollout)
|
||||||
|
AUTH_LEGACY_HEADER_ENABLED = os.getenv('AUTH_LEGACY_HEADER_ENABLED', 'true').lower() == 'true'
|
||||||
|
AUTH_JWT_REQUIRED = os.getenv('AUTH_JWT_REQUIRED', 'true').lower() == 'true'
|
||||||
|
AUTH_ALLOW_LOCAL_PASSWORD_LOGIN = os.getenv('AUTH_ALLOW_LOCAL_PASSWORD_LOGIN', 'true').lower() == 'true'
|
||||||
|
AUTH_ALLOW_LOCAL_JWT = os.getenv('AUTH_ALLOW_LOCAL_JWT', 'true').lower() == 'true'
|
||||||
|
# JWT 的签发者(iss)校验值,后端用它确认“这个 token 是谁发的”
|
||||||
|
AUTH_JWT_ISSUER = os.getenv('AUTH_JWT_ISSUER', 'http://192.168.100.230:8088')
|
||||||
|
# JWT 的受众(aud)校验值,后端用它确认“这个 token 是发给哪个应用的”
|
||||||
|
AUTH_JWT_AUDIENCE = os.getenv('AUTH_JWT_AUDIENCE', '758be5fcba2df784fdb4')
|
||||||
|
# 公钥集合地址(JWKS),后端从这里拉公钥来验签 JWT
|
||||||
|
AUTH_JWT_JWKS_URL = os.getenv('AUTH_JWT_JWKS_URL', 'http://192.168.100.230:8088/.well-known/jwks')
|
||||||
|
CASDOOR_BASE_URL = os.getenv('CASDOOR_BASE_URL', 'http://192.168.100.230:8088')
|
||||||
|
CASDOOR_CLIENT_ID = os.getenv('CASDOOR_CLIENT_ID', '758be5fcba2df784fdb4')
|
||||||
|
CASDOOR_CLIENT_SECRET = os.getenv('CASDOOR_CLIENT_SECRET', '')
|
||||||
|
CASDOOR_REDIRECT_URI = os.getenv('CASDOOR_REDIRECT_URI', 'http://localhost:8881/casdoor-callback')
|
||||||
|
CASDOOR_SCOPE = os.getenv('CASDOOR_SCOPE', 'openid profile email')
|
||||||
|
AUTH_LOCAL_JWT_ISSUER = os.getenv('AUTH_LOCAL_JWT_ISSUER', 'hxops-backend')
|
||||||
|
AUTH_LOCAL_JWT_AUDIENCE = os.getenv('AUTH_LOCAL_JWT_AUDIENCE', 'hxops-frontend')
|
||||||
|
AUTH_LOCAL_JWT_EXPIRES_HOURS = int(os.getenv('AUTH_LOCAL_JWT_EXPIRES_HOURS', '12'))
|
||||||
|
|
||||||
|
|
||||||
class DevelopmentConfig(Config):
|
class DevelopmentConfig(Config):
|
||||||
DEBUG = True
|
DEBUG = True
|
||||||
SQLALCHEMY_DATABASE_URI = os.getenv(
|
SQLALCHEMY_DATABASE_URI = os.getenv(
|
||||||
'DATABASE_URL',
|
'DATABASE_URL',
|
||||||
#'postgresql://postgres:123456@8.152.207.171:5432/hxops_db',
|
'postgresql://postgres:123456@8.152.207.171:5432/hxops_db',
|
||||||
#'postgresql://postgres:difyai123456@localhost:5432/hxops_db',
|
#'postgresql://postgres:difyai123456@localhost:5432/hxops_db',
|
||||||
'postgresql://postgres:123456@localhost:5432/hxops_db',
|
#'postgresql://postgres:123456@localhost:5432/hxops_db',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+14
-56
@@ -6,64 +6,16 @@ backend/app/decorators.py
|
|||||||
逻辑关系:为需要鉴权的 API 提供统一的用户获取、权限校验入口
|
逻辑关系:为需要鉴权的 API 提供统一的用户获取、权限校验入口
|
||||||
"""
|
"""
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
from flask import request, jsonify, g
|
from flask import request, jsonify, g, current_app
|
||||||
from app import db
|
|
||||||
from app.models import Agent, User
|
from app.models import Agent, User
|
||||||
|
from app.auth_jwt import get_current_user as _auth_current_user
|
||||||
|
|
||||||
|
|
||||||
def _get_current_user() -> User:
|
def _get_current_user() -> User:
|
||||||
"""
|
"""Resolve current user via JWT auth flow (legacy headers optional via config)."""
|
||||||
内部工具函数:获取当前登录用户
|
user = _auth_current_user()
|
||||||
支持从请求头识别用户并创建用户,读取 X-User-Id / X-Username / X-Role。
|
if user:
|
||||||
"""
|
g.current_user = user
|
||||||
user_id = request.headers.get('X-User-Id')
|
|
||||||
username = request.headers.get('X-Username')
|
|
||||||
role = request.headers.get('X-Role', 'user')
|
|
||||||
|
|
||||||
user = None
|
|
||||||
if user_id:
|
|
||||||
try:
|
|
||||||
user = User.query.get(int(user_id))
|
|
||||||
except ValueError:
|
|
||||||
user = None
|
|
||||||
if user is None and username:
|
|
||||||
user = User.query.filter_by(username=username).first()
|
|
||||||
if not user:
|
|
||||||
if user_id:
|
|
||||||
safe_id = int(user_id)
|
|
||||||
user = User(
|
|
||||||
id=safe_id,
|
|
||||||
username=username or f'user_{safe_id}',
|
|
||||||
email=f'{username or f"user_{safe_id}"}@example.com',
|
|
||||||
department='IT',
|
|
||||||
role=role,
|
|
||||||
)
|
|
||||||
db.session.add(user)
|
|
||||||
db.session.commit()
|
|
||||||
elif username:
|
|
||||||
user = User(
|
|
||||||
username=username,
|
|
||||||
email=f'{username}@example.com',
|
|
||||||
department='IT',
|
|
||||||
role=role,
|
|
||||||
)
|
|
||||||
db.session.add(user)
|
|
||||||
db.session.commit()
|
|
||||||
else:
|
|
||||||
# Check if guest user exists
|
|
||||||
user = User.query.filter_by(username='guest').first()
|
|
||||||
if not user:
|
|
||||||
user = User(
|
|
||||||
username='guest',
|
|
||||||
email='guest@example.com',
|
|
||||||
department='',
|
|
||||||
role='guest',
|
|
||||||
)
|
|
||||||
db.session.add(user)
|
|
||||||
db.session.commit()
|
|
||||||
|
|
||||||
|
|
||||||
g.current_user = user
|
|
||||||
return user
|
return user
|
||||||
|
|
||||||
|
|
||||||
@@ -92,8 +44,10 @@ def require_agent_permission(f):
|
|||||||
if not agent_id:
|
if not agent_id:
|
||||||
return jsonify({'error': 'agent_id is required'}), 400
|
return jsonify({'error': 'agent_id is required'}), 400
|
||||||
|
|
||||||
# 获取当前用户(此处固定为 admin 用户,用于演示)
|
# 获取当前用户
|
||||||
user = _get_current_user()
|
user = _get_current_user()
|
||||||
|
if not user:
|
||||||
|
return jsonify({'error': 'Unauthorized'}), 401
|
||||||
|
|
||||||
# 查询目标 Agent 是否存在
|
# 查询目标 Agent 是否存在
|
||||||
agent = Agent.query.get(agent_id)
|
agent = Agent.query.get(agent_id)
|
||||||
@@ -127,8 +81,12 @@ def require_admin(f):
|
|||||||
|
|
||||||
@wraps(f)
|
@wraps(f)
|
||||||
def decorated_function(*args, **kwargs):
|
def decorated_function(*args, **kwargs):
|
||||||
# 获取当前用户(自动创建 admin)
|
# 获取当前用户
|
||||||
user = _get_current_user()
|
user = _get_current_user()
|
||||||
|
if not user:
|
||||||
|
return jsonify({'error': 'Unauthorized'}), 401
|
||||||
|
if bool(current_app.config.get('AUTH_JWT_REQUIRED', False)) and not request.headers.get('Authorization'):
|
||||||
|
return jsonify({'error': 'JWT token is required'}), 401
|
||||||
# 如果不是管理员,则返回 403
|
# 如果不是管理员,则返回 403
|
||||||
if user.role != 'admin':
|
if user.role != 'admin':
|
||||||
return jsonify({'error': 'Admin privilege required'}), 403
|
return jsonify({'error': 'Admin privilege required'}), 403
|
||||||
|
|||||||
@@ -12,3 +12,5 @@ pydantic
|
|||||||
python-dotenv
|
python-dotenv
|
||||||
openpyxl
|
openpyxl
|
||||||
pycryptodome
|
pycryptodome
|
||||||
|
PyJWT
|
||||||
|
cryptography
|
||||||
+17
-27
@@ -1,10 +1,11 @@
|
|||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { watch, onMounted } from 'vue';
|
import { watch, onMounted, onBeforeUnmount } from 'vue';
|
||||||
import { useTheme } from './composables/useTheme';
|
import { useTheme } from './composables/useTheme';
|
||||||
import LevelMessageDialog from './components/LevelMessageDialog.vue';
|
import LevelMessageDialog from './components/LevelMessageDialog.vue';
|
||||||
import { useGlobalMessageDialog } from './composables/useGlobalMessageDialog';
|
import { useGlobalMessageDialog } from './composables/useGlobalMessageDialog';
|
||||||
|
import { getAuthHeaders, clearAuthUser } from './utils/auth';
|
||||||
|
|
||||||
const { locale } = useI18n();
|
const { locale } = useI18n();
|
||||||
const { themePreference, initTheme, setThemePreference } = useTheme();
|
const { themePreference, initTheme, setThemePreference } = useTheme();
|
||||||
@@ -13,35 +14,10 @@ const {
|
|||||||
messageDialogLevel,
|
messageDialogLevel,
|
||||||
messageDialogTitle,
|
messageDialogTitle,
|
||||||
messageDialogContent,
|
messageDialogContent,
|
||||||
|
showMessageDialog,
|
||||||
closeMessageDialog,
|
closeMessageDialog,
|
||||||
} = useGlobalMessageDialog();
|
} = useGlobalMessageDialog();
|
||||||
|
|
||||||
const getAuthHeaders = () => {
|
|
||||||
const candidates = [
|
|
||||||
sessionStorage.getItem('hxops_user'),
|
|
||||||
localStorage.getItem('hxops_user'),
|
|
||||||
];
|
|
||||||
for (const stored of candidates) {
|
|
||||||
if (!stored) continue;
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(stored) as any;
|
|
||||||
const user = data.user || data;
|
|
||||||
if (!user?.username || !user?.role) continue;
|
|
||||||
const headers: Record<string, string> = {
|
|
||||||
'X-Username': user.username,
|
|
||||||
'X-Role': user.role,
|
|
||||||
};
|
|
||||||
if (user.id) {
|
|
||||||
headers['X-User-Id'] = String(user.id);
|
|
||||||
}
|
|
||||||
return headers;
|
|
||||||
} catch (e) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return {};
|
|
||||||
};
|
|
||||||
|
|
||||||
const updateLanguagePreference = async (lang: string) => {
|
const updateLanguagePreference = async (lang: string) => {
|
||||||
const headers = getAuthHeaders();
|
const headers = getAuthHeaders();
|
||||||
if (Object.keys(headers).length === 0) return; // Not logged in
|
if (Object.keys(headers).length === 0) return; // Not logged in
|
||||||
@@ -80,7 +56,17 @@ watch(themePreference, (newTheme) => {
|
|||||||
updateThemePreference(newTheme);
|
updateThemePreference(newTheme);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const onUnauthorized = () => {
|
||||||
|
showMessageDialog('error', '认证已过期或无效,请重新登录');
|
||||||
|
clearAuthUser();
|
||||||
|
if (window.location.pathname !== '/') {
|
||||||
|
window.location.href = '/';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
|
window.addEventListener('hxops:unauthorized', onUnauthorized as EventListener);
|
||||||
|
|
||||||
initTheme();
|
initTheme();
|
||||||
|
|
||||||
const headers = getAuthHeaders();
|
const headers = getAuthHeaders();
|
||||||
@@ -101,6 +87,10 @@ onMounted(async () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
window.removeEventListener('hxops:unauthorized', onUnauthorized as EventListener);
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ const props = withDefaults(defineProps<Props>(), {
|
|||||||
message: '',
|
message: '',
|
||||||
closeOnMask: true,
|
closeOnMask: true,
|
||||||
closeOnEsc: true,
|
closeOnEsc: true,
|
||||||
autoCloseMs: 3000,
|
autoCloseMs: 5000,
|
||||||
});
|
});
|
||||||
|
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
* 逻辑关系:封装 Fetch API 处理流式响应,供 ChatView 组件使用
|
* 逻辑关系:封装 Fetch API 处理流式响应,供 ChatView 组件使用
|
||||||
*/
|
*/
|
||||||
import { ref } from 'vue';
|
import { ref } from 'vue';
|
||||||
|
import { getAuthHeaders } from '../utils/auth';
|
||||||
|
|
||||||
interface RetrieverResource {
|
interface RetrieverResource {
|
||||||
// 知识库/检索来源的基础字段,具体键可能因后端返回而扩展
|
// 知识库/检索来源的基础字段,具体键可能因后端返回而扩展
|
||||||
@@ -119,32 +120,6 @@ export function useChat() {
|
|||||||
*/
|
*/
|
||||||
const conversationId = ref<string | null>(null);
|
const conversationId = ref<string | null>(null);
|
||||||
|
|
||||||
const getAuthHeaders = () => {
|
|
||||||
const candidates = [
|
|
||||||
sessionStorage.getItem('hxops_user'),
|
|
||||||
localStorage.getItem('hxops_user'),
|
|
||||||
];
|
|
||||||
for (const stored of candidates) {
|
|
||||||
if (!stored) continue;
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(stored) as any;
|
|
||||||
const user = data.user || data;
|
|
||||||
if (!user?.username || !user?.role) continue;
|
|
||||||
const headers: Record<string, string> = {
|
|
||||||
'X-Username': user.username,
|
|
||||||
'X-Role': user.role,
|
|
||||||
};
|
|
||||||
if (user.id) {
|
|
||||||
headers['X-User-Id'] = String(user.id);
|
|
||||||
}
|
|
||||||
return headers;
|
|
||||||
} catch (e) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return {};
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* sendMessage
|
* sendMessage
|
||||||
* 用途:发送消息并处理 SSE 流式响应
|
* 用途:发送消息并处理 SSE 流式响应
|
||||||
|
|||||||
@@ -1,6 +1,13 @@
|
|||||||
export const config = {
|
export const config = {
|
||||||
appTitle: 'AI工作台',
|
appTitle: 'AI工作台',
|
||||||
auth: {
|
auth: {
|
||||||
|
casdoor: {
|
||||||
|
enabled: true,
|
||||||
|
authorizeApi: '/api/user/casdoor/authorize-url',
|
||||||
|
loginApi: '/api/user/casdoor/login',
|
||||||
|
refreshApi: '/api/user/casdoor/refresh',
|
||||||
|
callbackPath: '/casdoor-callback',
|
||||||
|
},
|
||||||
wecom: {
|
wecom: {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
authorizeApi: '/api/user/wecom/authorize-url',
|
authorizeApi: '/api/user/wecom/authorize-url',
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ const messages = {
|
|||||||
announcements: 'Announcements',
|
announcements: 'Announcements',
|
||||||
passwordResetEmailSent: '如果账号存在,重置链接已发送到您的邮箱。',
|
passwordResetEmailSent: '如果账号存在,重置链接已发送到您的邮箱。',
|
||||||
passwordResetRequestFailed: '请求密码重置失败',
|
passwordResetRequestFailed: '请求密码重置失败',
|
||||||
|
casdoorLogin: 'Login with Casdoor',
|
||||||
wecomLogin: 'Login with WeCom',
|
wecomLogin: 'Login with WeCom',
|
||||||
wecomConnecting: 'Connecting to WeCom...',
|
wecomConnecting: 'Connecting to WeCom...',
|
||||||
wecomStartFailed: 'Failed to start WeCom login',
|
wecomStartFailed: 'Failed to start WeCom login',
|
||||||
@@ -323,6 +324,7 @@ const messages = {
|
|||||||
msgs: {
|
msgs: {
|
||||||
usernameRequired: 'Username is required',
|
usernameRequired: 'Username is required',
|
||||||
passwordRequired: 'Password is required for new users',
|
passwordRequired: 'Password is required for new users',
|
||||||
|
invalidEmail: 'Invalid email format',
|
||||||
created: 'User created successfully',
|
created: 'User created successfully',
|
||||||
updated: 'User updated successfully',
|
updated: 'User updated successfully',
|
||||||
deleted: 'User deleted successfully',
|
deleted: 'User deleted successfully',
|
||||||
@@ -922,6 +924,7 @@ const messages = {
|
|||||||
announcements: '公告',
|
announcements: '公告',
|
||||||
passwordResetEmailSent: '如果账号存在,重置链接已发送到您的邮箱。',
|
passwordResetEmailSent: '如果账号存在,重置链接已发送到您的邮箱。',
|
||||||
passwordResetRequestFailed: '请求密码重置失败',
|
passwordResetRequestFailed: '请求密码重置失败',
|
||||||
|
casdoorLogin: 'Casdoor 登录',
|
||||||
wecomLogin: '企业微信登录',
|
wecomLogin: '企业微信登录',
|
||||||
wecomConnecting: '正在连接企业微信...',
|
wecomConnecting: '正在连接企业微信...',
|
||||||
wecomStartFailed: '启动企业微信登录失败',
|
wecomStartFailed: '启动企业微信登录失败',
|
||||||
@@ -1209,6 +1212,7 @@ const messages = {
|
|||||||
msgs: {
|
msgs: {
|
||||||
usernameRequired: '用户名必填',
|
usernameRequired: '用户名必填',
|
||||||
passwordRequired: '新用户必须设置密码',
|
passwordRequired: '新用户必须设置密码',
|
||||||
|
invalidEmail: '邮箱格式不正确',
|
||||||
created: '用户创建成功',
|
created: '用户创建成功',
|
||||||
updated: '用户更新成功',
|
updated: '用户更新成功',
|
||||||
deleted: '用户删除成功',
|
deleted: '用户删除成功',
|
||||||
@@ -1776,6 +1780,7 @@ const messages = {
|
|||||||
announcements: '公告',
|
announcements: '公告',
|
||||||
forgotPasswordDesc: '輸入您的郵箱以重設密碼',
|
forgotPasswordDesc: '輸入您的郵箱以重設密碼',
|
||||||
findPassword: '找回密碼',
|
findPassword: '找回密碼',
|
||||||
|
casdoorLogin: 'Casdoor 登入',
|
||||||
wecomLogin: '企業微信登錄',
|
wecomLogin: '企業微信登錄',
|
||||||
wecomConnecting: '正在連接企業微信...',
|
wecomConnecting: '正在連接企業微信...',
|
||||||
wecomStartFailed: '啟動企業微信登錄失敗',
|
wecomStartFailed: '啟動企業微信登錄失敗',
|
||||||
@@ -2058,6 +2063,7 @@ const messages = {
|
|||||||
msgs: {
|
msgs: {
|
||||||
usernameRequired: '用戶名必填',
|
usernameRequired: '用戶名必填',
|
||||||
passwordRequired: '新用戶必須設置密碼',
|
passwordRequired: '新用戶必須設置密碼',
|
||||||
|
invalidEmail: '郵箱格式不正確',
|
||||||
created: '用戶創建成功',
|
created: '用戶創建成功',
|
||||||
updated: '用戶更新成功',
|
updated: '用戶更新成功',
|
||||||
deleted: '用戶刪除成功',
|
deleted: '用戶刪除成功',
|
||||||
@@ -2630,6 +2636,7 @@ const messages = {
|
|||||||
announcements: 'ประกาศ',
|
announcements: 'ประกาศ',
|
||||||
forgotPasswordDesc: 'กรอกอีเมลเพื่อรีเซ็ตรหัสผ่าน',
|
forgotPasswordDesc: 'กรอกอีเมลเพื่อรีเซ็ตรหัสผ่าน',
|
||||||
findPassword: 'ค้นหารหัสผ่าน',
|
findPassword: 'ค้นหารหัสผ่าน',
|
||||||
|
casdoorLogin: 'เข้าสู่ระบบด้วย Casdoor',
|
||||||
wecomLogin: 'เข้าสู่ระบบด้วย WeCom',
|
wecomLogin: 'เข้าสู่ระบบด้วย WeCom',
|
||||||
wecomConnecting: 'กำลังเชื่อมต่อ WeCom...',
|
wecomConnecting: 'กำลังเชื่อมต่อ WeCom...',
|
||||||
wecomStartFailed: 'เริ่มต้นการเข้าสู่ระบบด้วย WeCom ไม่สำเร็จ',
|
wecomStartFailed: 'เริ่มต้นการเข้าสู่ระบบด้วย WeCom ไม่สำเร็จ',
|
||||||
@@ -2912,6 +2919,7 @@ const messages = {
|
|||||||
msgs: {
|
msgs: {
|
||||||
usernameRequired: 'กรุณากรอกชื่อผู้ใช้',
|
usernameRequired: 'กรุณากรอกชื่อผู้ใช้',
|
||||||
passwordRequired: 'ต้องระบุรหัสผ่านสำหรับผู้ใช้ใหม่',
|
passwordRequired: 'ต้องระบุรหัสผ่านสำหรับผู้ใช้ใหม่',
|
||||||
|
invalidEmail: 'รูปแบบอีเมลไม่ถูกต้อง',
|
||||||
created: 'สร้างผู้ใช้สำเร็จ',
|
created: 'สร้างผู้ใช้สำเร็จ',
|
||||||
updated: 'อัปเดตผู้ใช้สำเร็จ',
|
updated: 'อัปเดตผู้ใช้สำเร็จ',
|
||||||
deleted: 'ลบผู้ใช้สำเร็จ',
|
deleted: 'ลบผู้ใช้สำเร็จ',
|
||||||
|
|||||||
+36
-2
@@ -1,14 +1,48 @@
|
|||||||
|
import { createApp } from 'vue'
|
||||||
import { createApp } from 'vue'
|
|
||||||
import './style.css'
|
import './style.css'
|
||||||
import App from './App.vue'
|
import App from './App.vue'
|
||||||
import router from './router'
|
import router from './router'
|
||||||
import i18n from './i18n'
|
import i18n from './i18n'
|
||||||
import { config } from './config'
|
import { config } from './config'
|
||||||
|
import { refreshAccessToken, getAuthToken } from './utils/auth'
|
||||||
|
|
||||||
// Set document title from config
|
// Set document title from config
|
||||||
document.title = config.appTitle || 'AI工作台';
|
document.title = config.appTitle || 'AI工作台';
|
||||||
|
|
||||||
|
// Global 401 interceptor for API calls.
|
||||||
|
const _rawFetch = window.fetch.bind(window);
|
||||||
|
window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
|
||||||
|
// Keep original request closure so we can retry with a refreshed token.
|
||||||
|
const runFetch = (nextInit?: RequestInit) => _rawFetch(input, nextInit);
|
||||||
|
let reqInit = init;
|
||||||
|
let res = await runFetch(reqInit);
|
||||||
|
try {
|
||||||
|
const url = typeof input === 'string'
|
||||||
|
? input
|
||||||
|
: (input instanceof URL ? input.toString() : input.url);
|
||||||
|
const isApi = url.includes('/api/');
|
||||||
|
const isRefreshApi = url.includes('/api/user/casdoor/refresh');
|
||||||
|
if (res.status === 401 && isApi && !isRefreshApi) {
|
||||||
|
// First unauthorized response: try silent refresh once.
|
||||||
|
const refreshed = await refreshAccessToken();
|
||||||
|
if (refreshed) {
|
||||||
|
const mergedHeaders = new Headers((reqInit && reqInit.headers) || {});
|
||||||
|
mergedHeaders.set('Authorization', `Bearer ${getAuthToken()}`);
|
||||||
|
reqInit = { ...(reqInit || {}), headers: mergedHeaders };
|
||||||
|
// Retry original request exactly once with the renewed access token.
|
||||||
|
res = await runFetch(reqInit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (res.status === 401 && isApi) {
|
||||||
|
// Still unauthorized after retry (or no refresh token): force global logout UX.
|
||||||
|
window.dispatchEvent(new CustomEvent('hxops:unauthorized', { detail: { url, status: res.status } }));
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// no-op
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
|
||||||
createApp(App)
|
createApp(App)
|
||||||
.use(router)
|
.use(router)
|
||||||
.use(i18n)
|
.use(i18n)
|
||||||
|
|||||||
@@ -18,6 +18,11 @@ const routes = [
|
|||||||
name: 'Workspace',
|
name: 'Workspace',
|
||||||
component: WorkspaceView
|
component: WorkspaceView
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: '/casdoor-callback',
|
||||||
|
name: 'CasdoorCallback',
|
||||||
|
component: WorkspaceView
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: '/profile',
|
path: '/profile',
|
||||||
name: 'Profile',
|
name: 'Profile',
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
export interface AuthUser {
|
||||||
|
id?: number;
|
||||||
|
username?: string;
|
||||||
|
role?: string;
|
||||||
|
token?: string;
|
||||||
|
access_token?: string;
|
||||||
|
refresh_token?: string;
|
||||||
|
expires_in?: number;
|
||||||
|
token_expires_at?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getStoredAuthUser = (): AuthUser | null => {
|
||||||
|
const candidates = [
|
||||||
|
sessionStorage.getItem('hxops_user'),
|
||||||
|
localStorage.getItem('hxops_user'),
|
||||||
|
];
|
||||||
|
for (const stored of candidates) {
|
||||||
|
if (!stored) continue;
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(stored);
|
||||||
|
return (data.user || data) as AuthUser;
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getAuthToken = (): string => {
|
||||||
|
const user = getStoredAuthUser();
|
||||||
|
const token = user?.access_token || user?.token;
|
||||||
|
return token ? String(token) : '';
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getAuthHeaders = (): Record<string, string> => {
|
||||||
|
const token = getAuthToken();
|
||||||
|
if (!token) return {};
|
||||||
|
return { Authorization: `Bearer ${token}` };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const saveAuthUser = (user: AuthUser, remember = false): void => {
|
||||||
|
const next = { ...user };
|
||||||
|
if (next.expires_in && !next.token_expires_at) {
|
||||||
|
// Pre-compute an absolute expiry timestamp for later proactive checks.
|
||||||
|
next.token_expires_at = Date.now() + Number(next.expires_in) * 1000;
|
||||||
|
}
|
||||||
|
const payload = remember
|
||||||
|
? { user: next, expiry: Date.now() + 30 * 24 * 60 * 60 * 1000 }
|
||||||
|
: { user: next };
|
||||||
|
if (remember) {
|
||||||
|
localStorage.setItem('hxops_user', JSON.stringify(payload));
|
||||||
|
sessionStorage.removeItem('hxops_user');
|
||||||
|
} else {
|
||||||
|
sessionStorage.setItem('hxops_user', JSON.stringify(payload));
|
||||||
|
localStorage.removeItem('hxops_user');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const clearAuthUser = (): void => {
|
||||||
|
localStorage.removeItem('hxops_user');
|
||||||
|
sessionStorage.removeItem('hxops_user');
|
||||||
|
sessionStorage.removeItem('hxops_wecom_state');
|
||||||
|
sessionStorage.removeItem('hxops_casdoor_state');
|
||||||
|
};
|
||||||
|
|
||||||
|
let _refreshing: Promise<string | null> | null = null;
|
||||||
|
|
||||||
|
export const refreshAccessToken = async (): Promise<string | null> => {
|
||||||
|
// Single-flight guard: concurrent 401s share one refresh request.
|
||||||
|
const current = getStoredAuthUser();
|
||||||
|
const refreshToken = current?.refresh_token;
|
||||||
|
if (!refreshToken) return null;
|
||||||
|
if (_refreshing) return _refreshing;
|
||||||
|
_refreshing = (async () => {
|
||||||
|
try {
|
||||||
|
// Backend endpoint wraps Casdoor refresh flow.
|
||||||
|
const res = await fetch('/api/user/casdoor/refresh', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ refresh_token: refreshToken }),
|
||||||
|
});
|
||||||
|
if (!res.ok) return null;
|
||||||
|
const data = await res.json();
|
||||||
|
if (!data?.access_token) return null;
|
||||||
|
// Preserve existing profile fields while replacing rotated token material.
|
||||||
|
saveAuthUser({ ...(current || {}), ...data }, Boolean(localStorage.getItem('hxops_user')));
|
||||||
|
return String(data.access_token);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
_refreshing = null;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return _refreshing;
|
||||||
|
};
|
||||||
@@ -19,6 +19,7 @@ import DeleteConfirmDialog from '../components/DeleteConfirmDialog.vue';
|
|||||||
import { loadReportLayoutPref, saveReportLayoutPref } from '../composables/useReportLayoutStorage';
|
import { loadReportLayoutPref, saveReportLayoutPref } from '../composables/useReportLayoutStorage';
|
||||||
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
|
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
|
||||||
import { buildWecomAuditMeta, formatWecomAuditReason } from '../utils/wecom';
|
import { buildWecomAuditMeta, formatWecomAuditReason } from '../utils/wecom';
|
||||||
|
import { getAuthHeaders } from '../utils/auth';
|
||||||
import {
|
import {
|
||||||
ArrowLeft,
|
ArrowLeft,
|
||||||
// Save,
|
// Save,
|
||||||
@@ -49,6 +50,7 @@ import * as XLSX from 'xlsx';
|
|||||||
|
|
||||||
const { t, locale } = useI18n();
|
const { t, locale } = useI18n();
|
||||||
const { showMessageDialog } = useGlobalMessageDialog();
|
const { showMessageDialog } = useGlobalMessageDialog();
|
||||||
|
const EMAIL_PATTERN = /^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$/;
|
||||||
|
|
||||||
const sidebarItems = computed(() => {
|
const sidebarItems = computed(() => {
|
||||||
const items = [
|
const items = [
|
||||||
@@ -308,6 +310,12 @@ const saveUser = async () => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const email = (editingUser.value.email || '').trim();
|
||||||
|
if (email && !EMAIL_PATTERN.test(email)) {
|
||||||
|
showMessageDialog('warning', t('admin.user.msgs.invalidEmail'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!editingUser.value.id && !editingUser.value.password) {
|
if (!editingUser.value.id && !editingUser.value.password) {
|
||||||
showMessageDialog('warning', t('admin.user.msgs.passwordRequired'));
|
showMessageDialog('warning', t('admin.user.msgs.passwordRequired'));
|
||||||
return;
|
return;
|
||||||
@@ -748,29 +756,6 @@ const submitBatchPermission = async () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const getAuthHeaders = () => {
|
|
||||||
let stored = localStorage.getItem('hxops_user');
|
|
||||||
if (!stored) stored = sessionStorage.getItem('hxops_user');
|
|
||||||
|
|
||||||
if (!stored) return {};
|
|
||||||
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(stored);
|
|
||||||
const user = data.user || data; // Handle both wrapped and unwrapped format
|
|
||||||
|
|
||||||
const headers: Record<string, string> = {
|
|
||||||
'X-Username': user.username,
|
|
||||||
'X-Role': user.role,
|
|
||||||
};
|
|
||||||
if (user.id) {
|
|
||||||
headers['X-User-Id'] = String(user.id);
|
|
||||||
}
|
|
||||||
return headers;
|
|
||||||
} catch (e) {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 加载 Agent 列表
|
* 加载 Agent 列表
|
||||||
* 核心逻辑:调用 GET /api/admin/agents
|
* 核心逻辑:调用 GET /api/admin/agents
|
||||||
@@ -1327,7 +1312,7 @@ const resetQuestionForm = () => {
|
|||||||
// 组件挂载时加载初始数据
|
// 组件挂载时加载初始数据
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
const headers = getAuthHeaders();
|
const headers = getAuthHeaders();
|
||||||
if (!headers['X-User-Id'] && !headers['X-Username']) {
|
if (!headers['Authorization']) {
|
||||||
console.warn('No auth headers found, redirecting to login');
|
console.warn('No auth headers found, redirecting to login');
|
||||||
router.push('/');
|
router.push('/');
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import FilePreviewModal from '../components/FilePreviewModal.vue';
|
|||||||
import ThemeToggleButton from '../components/ThemeToggleButton.vue';
|
import ThemeToggleButton from '../components/ThemeToggleButton.vue';
|
||||||
import GeneralFeedbackDialog from '../components/GeneralFeedbackDialog.vue';
|
import GeneralFeedbackDialog from '../components/GeneralFeedbackDialog.vue';
|
||||||
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
|
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
|
||||||
|
import { getAuthHeaders } from '../utils/auth';
|
||||||
|
|
||||||
const { t, locale } = useI18n();
|
const { t, locale } = useI18n();
|
||||||
const { showMessageDialog } = useGlobalMessageDialog();
|
const { showMessageDialog } = useGlobalMessageDialog();
|
||||||
@@ -402,33 +403,6 @@ const presetQuestion = computed(() => {
|
|||||||
return typeof q === 'string' ? q : '';
|
return typeof q === 'string' ? q : '';
|
||||||
});
|
});
|
||||||
|
|
||||||
const getAuthHeaders = () => {
|
|
||||||
const candidates = [
|
|
||||||
sessionStorage.getItem('hxops_user'),
|
|
||||||
localStorage.getItem('hxops_user'),
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const stored of candidates) {
|
|
||||||
if (!stored) continue;
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(stored);
|
|
||||||
const user = data.user || data;
|
|
||||||
if (!user?.username || !user?.role) continue;
|
|
||||||
const headers: Record<string, string> = {
|
|
||||||
'X-Username': user.username,
|
|
||||||
'X-Role': user.role,
|
|
||||||
};
|
|
||||||
if (user.id) {
|
|
||||||
headers['X-User-Id'] = String(user.id);
|
|
||||||
}
|
|
||||||
return headers;
|
|
||||||
} catch (e) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return {};
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* handleSend
|
* handleSend
|
||||||
* 用途:将输入框内容发送给当前 Agent
|
* 用途:将输入框内容发送给当前 Agent
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { useTheme } from '../composables/useTheme';
|
|||||||
import type { ThemePreference } from '../composables/useTheme';
|
import type { ThemePreference } from '../composables/useTheme';
|
||||||
import ThemeToggleButton from '../components/ThemeToggleButton.vue';
|
import ThemeToggleButton from '../components/ThemeToggleButton.vue';
|
||||||
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
|
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
|
||||||
|
import { getAuthHeaders } from '../utils/auth';
|
||||||
import {
|
import {
|
||||||
User,
|
User,
|
||||||
Mail,
|
Mail,
|
||||||
@@ -99,25 +100,6 @@ const cancelEditing = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Methods
|
// Methods
|
||||||
const getAuthHeaders = (): Record<string, string> => {
|
|
||||||
let stored = localStorage.getItem('hxops_user');
|
|
||||||
if (!stored) stored = sessionStorage.getItem('hxops_user');
|
|
||||||
|
|
||||||
if (!stored) return {};
|
|
||||||
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(stored);
|
|
||||||
const u = data.user || data;
|
|
||||||
return {
|
|
||||||
'X-Username': u.username,
|
|
||||||
'X-Role': u.role,
|
|
||||||
'X-User-Id': String(u.id)
|
|
||||||
};
|
|
||||||
} catch (e) {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchProfile = async () => {
|
const fetchProfile = async () => {
|
||||||
isLoading.value = true;
|
isLoading.value = true;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import {
|
|||||||
type WecomLoginDialogContent,
|
type WecomLoginDialogContent,
|
||||||
type WecomMatchField,
|
type WecomMatchField,
|
||||||
} from '../utils/wecom';
|
} from '../utils/wecom';
|
||||||
|
import { getAuthHeaders, getStoredAuthUser, saveAuthUser } from '../utils/auth';
|
||||||
import {
|
import {
|
||||||
Settings,
|
Settings,
|
||||||
LayoutGrid,
|
LayoutGrid,
|
||||||
@@ -233,33 +234,11 @@ const getSectionTitleKey = (sectionId: string) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Methods
|
// Methods
|
||||||
const getAuthHeaders = () => {
|
|
||||||
let stored = localStorage.getItem('hxops_user');
|
|
||||||
if (!stored) stored = sessionStorage.getItem('hxops_user');
|
|
||||||
|
|
||||||
if (!stored) return {};
|
|
||||||
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(stored);
|
|
||||||
const user = data.user || data; // Handle both wrapped and unwrapped format
|
|
||||||
|
|
||||||
const headers: Record<string, string> = {
|
|
||||||
'X-Username': user.username,
|
|
||||||
'X-Role': user.role,
|
|
||||||
};
|
|
||||||
if (user.id) {
|
|
||||||
headers['X-User-Id'] = String(user.id);
|
|
||||||
}
|
|
||||||
return headers;
|
|
||||||
} catch (e) {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchHome = async () => {
|
const fetchHome = async () => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/user/home', { headers: getAuthHeaders() });
|
const res = await fetch('/api/user/home', { headers: getAuthHeaders() });
|
||||||
if (res.status === 401) {
|
if (res.status === 401) {
|
||||||
|
showMessageDialog('error', t('login.loginRequired'));
|
||||||
handleLogout();
|
handleLogout();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -389,12 +368,12 @@ const loadAuthUser = () => {
|
|||||||
if (!stored) return;
|
if (!stored) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const data = JSON.parse(stored);
|
const user = getStoredAuthUser();
|
||||||
const user = data.user || data; // Handle both wrapped and unwrapped format
|
if (!user) return;
|
||||||
currentUser.value = {
|
currentUser.value = {
|
||||||
id: user.id || 0,
|
id: user.id || 0,
|
||||||
username: user.username,
|
username: user.username || '',
|
||||||
role: user.role,
|
role: user.role || 'user',
|
||||||
};
|
};
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
localStorage.removeItem('hxops_user');
|
localStorage.removeItem('hxops_user');
|
||||||
@@ -403,14 +382,7 @@ const loadAuthUser = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const persistLoginUser = (user: any) => {
|
const persistLoginUser = (user: any) => {
|
||||||
if (rememberMe.value) {
|
saveAuthUser({ ...(user || {}) }, rememberMe.value);
|
||||||
const expiry = new Date().getTime() + 30 * 24 * 60 * 60 * 1000;
|
|
||||||
localStorage.setItem('hxops_user', JSON.stringify({ user, expiry }));
|
|
||||||
sessionStorage.removeItem('hxops_user');
|
|
||||||
} else {
|
|
||||||
sessionStorage.setItem('hxops_user', JSON.stringify({ user }));
|
|
||||||
localStorage.removeItem('hxops_user');
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleLogin = async () => {
|
const handleLogin = async () => {
|
||||||
@@ -464,6 +436,86 @@ const handleLogin = async () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleCasdoorLogin = async () => {
|
||||||
|
if (!config.auth?.casdoor?.enabled) return;
|
||||||
|
try {
|
||||||
|
// Ask backend to build a server-side-tracked authorize URL (includes state).
|
||||||
|
const api = config.auth.casdoor.authorizeApi || '/api/user/casdoor/authorize-url';
|
||||||
|
const callbackPath = config.auth.casdoor.callbackPath || '/casdoor-callback';
|
||||||
|
const redirectUri = `${window.location.origin}${callbackPath}`;
|
||||||
|
const res = await fetch(`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`);
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok || !data.url) {
|
||||||
|
showMessageDialog('error', data.error || t('login.requestFailed'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (data.state) {
|
||||||
|
sessionStorage.setItem('hxops_casdoor_state', data.state);
|
||||||
|
}
|
||||||
|
window.location.href = data.url;
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
showMessageDialog('error', t('login.requestFailed'));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const tryCasdoorCallbackLogin = async () => {
|
||||||
|
if (!config.auth?.casdoor?.enabled) return false;
|
||||||
|
const casdoorPath = config.auth.casdoor.callbackPath || '/casdoor-callback';
|
||||||
|
const path = window.location.pathname;
|
||||||
|
// Compatibility: allow temporary callback landing on /workspace during migration.
|
||||||
|
if (path !== casdoorPath && path !== '/workspace') return false;
|
||||||
|
const params = new URLSearchParams(window.location.search);
|
||||||
|
const code = params.get('code');
|
||||||
|
const state = params.get('state');
|
||||||
|
if (!code) return false;
|
||||||
|
|
||||||
|
const expectedState = sessionStorage.getItem('hxops_casdoor_state');
|
||||||
|
// Backward compatibility: old backend emitted random in-memory state
|
||||||
|
// (hxops_casdoor_*), while new backend emits signed stateless state.
|
||||||
|
// For new signed state, rely on backend signature verification instead of
|
||||||
|
// strict frontend equality check to avoid false negatives during rollout.
|
||||||
|
const shouldStrictCheck = !!expectedState && !!state && !String(state).startsWith('hxops_casdoor_v1.');
|
||||||
|
if (shouldStrictCheck && state !== expectedState) {
|
||||||
|
// Prevent CSRF/state mismatch replay.
|
||||||
|
showMessageDialog('error', 'Invalid or expired Casdoor state');
|
||||||
|
clearWecomCallbackQuery();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const api = config.auth.casdoor.loginApi || '/api/user/casdoor/login';
|
||||||
|
const res = await fetch(api, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ code, state }),
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) {
|
||||||
|
const code = String(data.error_code || '');
|
||||||
|
let msg = data.error || 'Casdoor login failed';
|
||||||
|
if (code === 'CASDOOR_USER_NOT_FOUND') {
|
||||||
|
msg = 'Casdoor 登录成功,但未匹配到本地账号。请让管理员在本地用户表创建同名 username 或相同 email 的账号。';
|
||||||
|
} else if (code === 'ACCOUNT_DISABLED') {
|
||||||
|
msg = '该本地账号已被禁用,请联系管理员启用后再登录。';
|
||||||
|
}
|
||||||
|
showMessageDialog('error', msg);
|
||||||
|
clearWecomCallbackQuery();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// Persist access+refresh tokens for API auth and silent refresh.
|
||||||
|
persistLoginUser(data);
|
||||||
|
sessionStorage.removeItem('hxops_casdoor_state');
|
||||||
|
window.history.replaceState({}, '', '/workspace');
|
||||||
|
await fetchHome();
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
showMessageDialog('error', 'Casdoor login failed');
|
||||||
|
clearWecomCallbackQuery();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const handleWecomLogin = async () => {
|
const handleWecomLogin = async () => {
|
||||||
if (!config.auth?.wecom?.enabled) return;
|
if (!config.auth?.wecom?.enabled) return;
|
||||||
try {
|
try {
|
||||||
@@ -566,6 +618,8 @@ const submitWecomCompleteBind = async () => {
|
|||||||
|
|
||||||
const tryWecomCallbackLogin = async () => {
|
const tryWecomCallbackLogin = async () => {
|
||||||
if (!config.auth?.wecom?.enabled) return false;
|
if (!config.auth?.wecom?.enabled) return false;
|
||||||
|
const wecomPath = config.auth.wecom.callbackPath || '/workspace';
|
||||||
|
if (window.location.pathname !== wecomPath) return false;
|
||||||
|
|
||||||
const params = new URLSearchParams(window.location.search);
|
const params = new URLSearchParams(window.location.search);
|
||||||
const code = params.get('code');
|
const code = params.get('code');
|
||||||
@@ -879,6 +933,10 @@ onMounted(async () => {
|
|||||||
document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true });
|
document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true });
|
||||||
loadLanguagePreference();
|
loadLanguagePreference();
|
||||||
fetchAnnouncements();
|
fetchAnnouncements();
|
||||||
|
const handledCasdoor = await tryCasdoorCallbackLogin();
|
||||||
|
if (handledCasdoor && currentUser.value && currentUser.value.role !== 'guest') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
const handledWecom = await tryWecomCallbackLogin();
|
const handledWecom = await tryWecomCallbackLogin();
|
||||||
if (handledWecom && currentUser.value && currentUser.value.role !== 'guest') {
|
if (handledWecom && currentUser.value && currentUser.value.role !== 'guest') {
|
||||||
return;
|
return;
|
||||||
@@ -1086,6 +1144,14 @@ onBeforeUnmount(() => {
|
|||||||
{{ $t('login.submit') }}
|
{{ $t('login.submit') }}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
v-if="config.auth?.casdoor?.enabled"
|
||||||
|
@click="handleCasdoorLogin"
|
||||||
|
class="btn-secondary w-full py-3 text-base mt-3"
|
||||||
|
>
|
||||||
|
{{ $t('login.casdoorLogin') }}
|
||||||
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
v-if="config.auth?.wecom?.enabled"
|
v-if="config.auth?.wecom?.enabled"
|
||||||
@click="handleWecomLogin"
|
@click="handleWecomLogin"
|
||||||
|
|||||||
Reference in new issue
Block a user