Merge branch 'dev' into runny0429
This commit is contained in:
commit
66b108f9d8
20 files changed
+1102
-274
No files matched your search
@@ -15,13 +15,34 @@ from sqlalchemy.exc import IntegrityError
|
||||
from datetime import datetime, timedelta
|
||||
import csv
|
||||
import io
|
||||
import re
|
||||
import requests
|
||||
import uuid
|
||||
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__)
|
||||
|
||||
|
||||
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():
|
||||
return {
|
||||
'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():
|
||||
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(
|
||||
username=data['username'],
|
||||
email=data.get('email'),
|
||||
department=data.get('department'),
|
||||
email=email,
|
||||
department=_empty_to_none(data.get('department')),
|
||||
role=data.get('role', 'user'),
|
||||
status=data.get('status', 'active'),
|
||||
real_name=data.get('real_name'),
|
||||
employee_id=data.get('employee_id'),
|
||||
phone_number=data.get('phone_number')
|
||||
real_name=_empty_to_none(data.get('real_name')),
|
||||
employee_id=_empty_to_none(data.get('employee_id')),
|
||||
phone_number=_empty_to_none(data.get('phone_number'))
|
||||
)
|
||||
if data.get('password'): user.set_password(data['password'])
|
||||
|
||||
@@ -564,7 +589,18 @@ def create_user():
|
||||
user.agents = agents
|
||||
|
||||
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
|
||||
|
||||
@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
|
||||
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']:
|
||||
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'])
|
||||
|
||||
@@ -583,7 +628,18 @@ def update_user(id):
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
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'})
|
||||
|
||||
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
|
||||
@@ -598,7 +654,8 @@ def cleanup_rejected_users():
|
||||
def batch_delete_users():
|
||||
data = request.get_json() or {}
|
||||
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)]
|
||||
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)
|
||||
|
||||
+418
-11
@@ -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.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
||||
from app.auth_jwt import get_current_user as _auth_current_user
|
||||
from app.auth_jwt import issue_local_access_token
|
||||
from sqlalchemy.exc import IntegrityError, OperationalError
|
||||
from sqlalchemy import and_, or_, inspect, insert
|
||||
from datetime import datetime, timedelta
|
||||
import uuid
|
||||
import requests
|
||||
from urllib.parse import quote
|
||||
import hashlib
|
||||
import hmac
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
|
||||
user_bp = Blueprint('user', __name__)
|
||||
@@ -21,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:
|
||||
@@ -123,12 +138,14 @@ def _execute_login_audit_insert(payload: dict):
|
||||
|
||||
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')
|
||||
if not user_id:
|
||||
return None
|
||||
return db.session.get(User, int(user_id))
|
||||
return _auth_current_user()
|
||||
|
||||
def _is_wecom_configured():
|
||||
return all([
|
||||
@@ -138,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]
|
||||
@@ -296,6 +466,8 @@ def _build_login_payload(user: User, source: str = 'password', bind_status: str
|
||||
'role': user.role,
|
||||
'default_agent_id': user.default_agent_id,
|
||||
'source': source,
|
||||
'access_token': issue_local_access_token(user),
|
||||
'token_type': 'Bearer',
|
||||
}
|
||||
if bind_status:
|
||||
payload['bind_status'] = bind_status
|
||||
@@ -674,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'))
|
||||
@@ -712,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():
|
||||
|
||||
Reference in new issue
Block a user