第二版:casdoor登录,保留用户密码登录
This commit is contained in:
1 parent
a5f0ec645d
commit
61fa96d686
13 files changed
+701
-39
No files matched your search
@@ -1,2 +1,26 @@
|
||||
INTEGRATION_API_BASE=http://192.168.100.230:8891
|
||||
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
|
||||
+415
-7
@@ -11,6 +11,10 @@ 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__)
|
||||
@@ -23,6 +27,15 @@ _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:
|
||||
@@ -124,7 +137,14 @@ def _execute_login_audit_insert(payload: dict):
|
||||
raise
|
||||
|
||||
def _get_current_user():
|
||||
"""Helper to resolve current user from JWT first, then optional legacy 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.
|
||||
"""
|
||||
return _auth_current_user()
|
||||
|
||||
def _is_wecom_configured():
|
||||
@@ -135,6 +155,159 @@ def _is_wecom_configured():
|
||||
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]
|
||||
@@ -673,33 +846,52 @@ def register():
|
||||
@user_bp.route('/login', methods=['POST'])
|
||||
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:
|
||||
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'))
|
||||
@@ -711,6 +903,222 @@ def login():
|
||||
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():
|
||||
|
||||
+56
-8
@@ -1,4 +1,5 @@
|
||||
import time
|
||||
import json
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
@@ -15,8 +16,17 @@ _JWKS_CACHE: dict[str, Any] = {
|
||||
'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
|
||||
@@ -28,6 +38,7 @@ def _extract_bearer_token() -> Optional[str]:
|
||||
|
||||
|
||||
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
|
||||
@@ -54,6 +65,7 @@ def _get_jwks_keys(jwks_url: str) -> dict:
|
||||
|
||||
|
||||
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()
|
||||
@@ -62,13 +74,20 @@ def _decode_jwt(token: str) -> dict:
|
||||
|
||||
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:
|
||||
# local issued token fallback (HS256)
|
||||
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('JWT header missing kid')
|
||||
local_audience = (current_app.config.get('AUTH_JWT_LOCAL_AUDIENCE') or 'hxops-frontend').strip()
|
||||
local_issuer = (current_app.config.get('AUTH_JWT_LOCAL_ISSUER') or 'hxops-backend').strip()
|
||||
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,
|
||||
@@ -88,7 +107,25 @@ def _decode_jwt(token: str) -> dict:
|
||||
if not jwk:
|
||||
raise ValueError('No matching JWKS key for token')
|
||||
|
||||
public_key = jwt.algorithms.RSAAlgorithm.from_jwk(jwk)
|
||||
# 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,
|
||||
@@ -100,6 +137,7 @@ def _decode_jwt(token: str) -> dict:
|
||||
|
||||
|
||||
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:
|
||||
@@ -149,7 +187,15 @@ def get_current_user() -> Optional[User]:
|
||||
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:
|
||||
@@ -167,7 +213,9 @@ def get_current_user() -> Optional[User]:
|
||||
|
||||
|
||||
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,
|
||||
@@ -176,9 +224,9 @@ def issue_local_access_token(user: User) -> str:
|
||||
'role': user.role,
|
||||
'email': user.email,
|
||||
'iat': int(now.timestamp()),
|
||||
'exp': int((now + timedelta(hours=12)).timestamp()),
|
||||
'iss': 'hxops-backend',
|
||||
'aud': 'hxops-frontend',
|
||||
'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')
|
||||
+11
-4
@@ -69,16 +69,23 @@ class Config:
|
||||
|
||||
# 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', 'false').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')
|
||||
# 本地签发 JWT(过渡模式)时使用的 iss/aud(需与 auth_jwt.py 中签发保持一致)
|
||||
AUTH_JWT_LOCAL_ISSUER = os.getenv('AUTH_JWT_LOCAL_ISSUER', 'hxops-backend')
|
||||
AUTH_JWT_LOCAL_AUDIENCE = os.getenv('AUTH_JWT_LOCAL_AUDIENCE', 'hxops-frontend')
|
||||
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):
|
||||
|
||||
@@ -13,3 +13,4 @@ python-dotenv
|
||||
openpyxl
|
||||
pycryptodome
|
||||
PyJWT
|
||||
cryptography
|
||||
@@ -5,7 +5,7 @@ import { watch, onMounted, onBeforeUnmount } from 'vue';
|
||||
import { useTheme } from './composables/useTheme';
|
||||
import LevelMessageDialog from './components/LevelMessageDialog.vue';
|
||||
import { useGlobalMessageDialog } from './composables/useGlobalMessageDialog';
|
||||
import { getAuthHeaders } from './utils/auth';
|
||||
import { getAuthHeaders, clearAuthUser } from './utils/auth';
|
||||
|
||||
const { locale } = useI18n();
|
||||
const { themePreference, initTheme, setThemePreference } = useTheme();
|
||||
@@ -58,9 +58,7 @@ watch(themePreference, (newTheme) => {
|
||||
|
||||
const onUnauthorized = () => {
|
||||
showMessageDialog('error', '认证已过期或无效,请重新登录');
|
||||
localStorage.removeItem('hxops_user');
|
||||
sessionStorage.removeItem('hxops_user');
|
||||
sessionStorage.removeItem('hxops_wecom_state');
|
||||
clearAuthUser();
|
||||
if (window.location.pathname !== '/') {
|
||||
window.location.href = '/';
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ const props = withDefaults(defineProps<Props>(), {
|
||||
message: '',
|
||||
closeOnMask: true,
|
||||
closeOnEsc: true,
|
||||
autoCloseMs: 3000,
|
||||
autoCloseMs: 5000,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
export const config = {
|
||||
appTitle: 'AI工作台',
|
||||
auth: {
|
||||
casdoor: {
|
||||
enabled: true,
|
||||
authorizeApi: '/api/user/casdoor/authorize-url',
|
||||
loginApi: '/api/user/casdoor/login',
|
||||
refreshApi: '/api/user/casdoor/refresh',
|
||||
callbackPath: '/casdoor-callback',
|
||||
},
|
||||
wecom: {
|
||||
enabled: true,
|
||||
authorizeApi: '/api/user/wecom/authorize-url',
|
||||
|
||||
@@ -36,6 +36,7 @@ const messages = {
|
||||
announcements: 'Announcements',
|
||||
passwordResetEmailSent: '如果账号存在,重置链接已发送到您的邮箱。',
|
||||
passwordResetRequestFailed: '请求密码重置失败',
|
||||
casdoorLogin: 'Login with Casdoor',
|
||||
wecomLogin: 'Login with WeCom',
|
||||
wecomConnecting: 'Connecting to WeCom...',
|
||||
wecomStartFailed: 'Failed to start WeCom login',
|
||||
@@ -922,6 +923,7 @@ const messages = {
|
||||
announcements: '公告',
|
||||
passwordResetEmailSent: '如果账号存在,重置链接已发送到您的邮箱。',
|
||||
passwordResetRequestFailed: '请求密码重置失败',
|
||||
casdoorLogin: 'Casdoor 登录',
|
||||
wecomLogin: '企业微信登录',
|
||||
wecomConnecting: '正在连接企业微信...',
|
||||
wecomStartFailed: '启动企业微信登录失败',
|
||||
@@ -1776,6 +1778,7 @@ const messages = {
|
||||
announcements: '公告',
|
||||
forgotPasswordDesc: '輸入您的郵箱以重設密碼',
|
||||
findPassword: '找回密碼',
|
||||
casdoorLogin: 'Casdoor 登入',
|
||||
wecomLogin: '企業微信登錄',
|
||||
wecomConnecting: '正在連接企業微信...',
|
||||
wecomStartFailed: '啟動企業微信登錄失敗',
|
||||
@@ -2630,6 +2633,7 @@ const messages = {
|
||||
announcements: 'ประกาศ',
|
||||
forgotPasswordDesc: 'กรอกอีเมลเพื่อรีเซ็ตรหัสผ่าน',
|
||||
findPassword: 'ค้นหารหัสผ่าน',
|
||||
casdoorLogin: 'เข้าสู่ระบบด้วย Casdoor',
|
||||
wecomLogin: 'เข้าสู่ระบบด้วย WeCom',
|
||||
wecomConnecting: 'กำลังเชื่อมต่อ WeCom...',
|
||||
wecomStartFailed: 'เริ่มต้นการเข้าสู่ระบบด้วย WeCom ไม่สำเร็จ',
|
||||
|
||||
+20
-2
@@ -4,6 +4,7 @@ import App from './App.vue'
|
||||
import router from './router'
|
||||
import i18n from './i18n'
|
||||
import { config } from './config'
|
||||
import { refreshAccessToken, getAuthToken } from './utils/auth'
|
||||
|
||||
// Set document title from config
|
||||
document.title = config.appTitle || 'AI工作台';
|
||||
@@ -11,12 +12,29 @@ 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> => {
|
||||
const res = await _rawFetch(input, init);
|
||||
// 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);
|
||||
if (res.status === 401 && url.includes('/api/')) {
|
||||
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 {
|
||||
|
||||
@@ -18,6 +18,11 @@ const routes = [
|
||||
name: 'Workspace',
|
||||
component: WorkspaceView
|
||||
},
|
||||
{
|
||||
path: '/casdoor-callback',
|
||||
name: 'CasdoorCallback',
|
||||
component: WorkspaceView
|
||||
},
|
||||
{
|
||||
path: '/profile',
|
||||
name: 'Profile',
|
||||
|
||||
@@ -4,6 +4,9 @@ export interface AuthUser {
|
||||
role?: string;
|
||||
token?: string;
|
||||
access_token?: string;
|
||||
refresh_token?: string;
|
||||
expires_in?: number;
|
||||
token_expires_at?: number;
|
||||
}
|
||||
|
||||
export const getStoredAuthUser = (): AuthUser | null => {
|
||||
@@ -34,3 +37,59 @@ export const getAuthHeaders = (): Record<string, string> => {
|
||||
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;
|
||||
};
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
type WecomLoginDialogContent,
|
||||
type WecomMatchField,
|
||||
} from '../utils/wecom';
|
||||
import { getAuthHeaders, getStoredAuthUser } from '../utils/auth';
|
||||
import { getAuthHeaders, getStoredAuthUser, saveAuthUser } from '../utils/auth';
|
||||
import {
|
||||
Settings,
|
||||
LayoutGrid,
|
||||
@@ -382,18 +382,7 @@ const loadAuthUser = () => {
|
||||
};
|
||||
|
||||
const persistLoginUser = (user: any) => {
|
||||
const nextUser = { ...user };
|
||||
if (user?.access_token && !user?.token) {
|
||||
nextUser.token = user.access_token;
|
||||
}
|
||||
if (rememberMe.value) {
|
||||
const expiry = new Date().getTime() + 30 * 24 * 60 * 60 * 1000;
|
||||
localStorage.setItem('hxops_user', JSON.stringify({ user: nextUser, expiry }));
|
||||
sessionStorage.removeItem('hxops_user');
|
||||
} else {
|
||||
sessionStorage.setItem('hxops_user', JSON.stringify({ user: nextUser }));
|
||||
localStorage.removeItem('hxops_user');
|
||||
}
|
||||
saveAuthUser({ ...(user || {}) }, rememberMe.value);
|
||||
};
|
||||
|
||||
const handleLogin = async () => {
|
||||
@@ -447,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 () => {
|
||||
if (!config.auth?.wecom?.enabled) return;
|
||||
try {
|
||||
@@ -549,6 +618,8 @@ const submitWecomCompleteBind = async () => {
|
||||
|
||||
const tryWecomCallbackLogin = async () => {
|
||||
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 code = params.get('code');
|
||||
@@ -862,6 +933,10 @@ onMounted(async () => {
|
||||
document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true });
|
||||
loadLanguagePreference();
|
||||
fetchAnnouncements();
|
||||
const handledCasdoor = await tryCasdoorCallbackLogin();
|
||||
if (handledCasdoor && currentUser.value && currentUser.value.role !== 'guest') {
|
||||
return;
|
||||
}
|
||||
const handledWecom = await tryWecomCallbackLogin();
|
||||
if (handledWecom && currentUser.value && currentUser.value.role !== 'guest') {
|
||||
return;
|
||||
@@ -1069,6 +1144,14 @@ onBeforeUnmount(() => {
|
||||
{{ $t('login.submit') }}
|
||||
</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
|
||||
v-if="config.auth?.wecom?.enabled"
|
||||
@click="handleWecomLogin"
|
||||
|
||||
Reference in new issue
Block a user