Merge branch 'dev' into runny0429
This commit is contained in:
commit
66b108f9d8
20 files changed
+1102
-274
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
|
||||
@@ -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():
|
||||
|
||||
@@ -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',
|
||||
)
|
||||
|
||||
# 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):
|
||||
DEBUG = True
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv(
|
||||
'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:123456@localhost:5432/hxops_db',
|
||||
#'postgresql://postgres:123456@localhost:5432/hxops_db',
|
||||
)
|
||||
|
||||
|
||||
|
||||
+14
-56
@@ -6,64 +6,16 @@ backend/app/decorators.py
|
||||
逻辑关系:为需要鉴权的 API 提供统一的用户获取、权限校验入口
|
||||
"""
|
||||
from functools import wraps
|
||||
from flask import request, jsonify, g
|
||||
from app import db
|
||||
from flask import request, jsonify, g, current_app
|
||||
from app.models import Agent, User
|
||||
from app.auth_jwt import get_current_user as _auth_current_user
|
||||
|
||||
|
||||
def _get_current_user() -> User:
|
||||
"""
|
||||
内部工具函数:获取当前登录用户
|
||||
支持从请求头识别用户并创建用户,读取 X-User-Id / X-Username / X-Role。
|
||||
"""
|
||||
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
|
||||
"""Resolve current user via JWT auth flow (legacy headers optional via config)."""
|
||||
user = _auth_current_user()
|
||||
if user:
|
||||
g.current_user = user
|
||||
return user
|
||||
|
||||
|
||||
@@ -92,8 +44,10 @@ def require_agent_permission(f):
|
||||
if not agent_id:
|
||||
return jsonify({'error': 'agent_id is required'}), 400
|
||||
|
||||
# 获取当前用户(此处固定为 admin 用户,用于演示)
|
||||
# 获取当前用户
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
return jsonify({'error': 'Unauthorized'}), 401
|
||||
|
||||
# 查询目标 Agent 是否存在
|
||||
agent = Agent.query.get(agent_id)
|
||||
@@ -127,8 +81,12 @@ def require_admin(f):
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
# 获取当前用户(自动创建 admin)
|
||||
# 获取当前用户
|
||||
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
|
||||
if user.role != 'admin':
|
||||
return jsonify({'error': 'Admin privilege required'}), 403
|
||||
|
||||
@@ -12,3 +12,5 @@ pydantic
|
||||
python-dotenv
|
||||
openpyxl
|
||||
pycryptodome
|
||||
PyJWT
|
||||
cryptography
|
||||
Reference in new issue
Block a user