过渡版:本地验发token
This commit is contained in:
1 parent
fb71def840
commit
a5f0ec645d
14 files changed
+313
-220
No files matched your search
@@ -18,6 +18,7 @@ import io
|
||||
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__)
|
||||
|
||||
@@ -598,7 +599,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)
|
||||
|
||||
@@ -3,6 +3,8 @@ 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
|
||||
@@ -122,13 +124,8 @@ def _execute_login_audit_insert(payload: dict):
|
||||
raise
|
||||
|
||||
def _get_current_user():
|
||||
"""
|
||||
Helper to get current user from headers
|
||||
"""
|
||||
user_id = request.headers.get('X-User-Id')
|
||||
if not user_id:
|
||||
return None
|
||||
return db.session.get(User, int(user_id))
|
||||
"""Helper to resolve current user from JWT first, then optional legacy headers."""
|
||||
return _auth_current_user()
|
||||
|
||||
def _is_wecom_configured():
|
||||
return all([
|
||||
@@ -296,6 +293,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
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import time
|
||||
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 _extract_bearer_token() -> Optional[str]:
|
||||
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:
|
||||
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:
|
||||
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')
|
||||
if not kid:
|
||||
# local issued token fallback (HS256)
|
||||
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()
|
||||
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')
|
||||
|
||||
public_key = jwt.algorithms.RSAAlgorithm.from_jwk(jwk)
|
||||
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]:
|
||||
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)
|
||||
except Exception:
|
||||
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:
|
||||
now = datetime.now(timezone.utc)
|
||||
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=12)).timestamp()),
|
||||
'iss': 'hxops-backend',
|
||||
'aud': 'hxops-frontend',
|
||||
}
|
||||
secret = current_app.config.get('SECRET_KEY')
|
||||
return jwt.encode(payload, secret, algorithm='HS256')
|
||||
+15
-2
@@ -67,14 +67,27 @@ 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', 'false').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')
|
||||
|
||||
|
||||
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,4 @@ pydantic
|
||||
python-dotenv
|
||||
openpyxl
|
||||
pycryptodome
|
||||
PyJWT
|
||||
+19
-27
@@ -1,10 +1,11 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { watch, onMounted } from 'vue';
|
||||
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';
|
||||
|
||||
const { locale } = useI18n();
|
||||
const { themePreference, initTheme, setThemePreference } = useTheme();
|
||||
@@ -13,35 +14,10 @@ const {
|
||||
messageDialogLevel,
|
||||
messageDialogTitle,
|
||||
messageDialogContent,
|
||||
showMessageDialog,
|
||||
closeMessageDialog,
|
||||
} = useGlobalMessageDialog();
|
||||
|
||||
const getAuthHeaders = () => {
|
||||
const candidates = [
|
||||
sessionStorage.getItem('hxops_user'),
|
||||
localStorage.getItem('hxops_user'),
|
||||
];
|
||||
for (const stored of candidates) {
|
||||
if (!stored) continue;
|
||||
try {
|
||||
const data = JSON.parse(stored) as any;
|
||||
const user = data.user || data;
|
||||
if (!user?.username || !user?.role) continue;
|
||||
const headers: Record<string, string> = {
|
||||
'X-Username': user.username,
|
||||
'X-Role': user.role,
|
||||
};
|
||||
if (user.id) {
|
||||
headers['X-User-Id'] = String(user.id);
|
||||
}
|
||||
return headers;
|
||||
} catch (e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return {};
|
||||
};
|
||||
|
||||
const updateLanguagePreference = async (lang: string) => {
|
||||
const headers = getAuthHeaders();
|
||||
if (Object.keys(headers).length === 0) return; // Not logged in
|
||||
@@ -80,7 +56,19 @@ watch(themePreference, (newTheme) => {
|
||||
updateThemePreference(newTheme);
|
||||
});
|
||||
|
||||
const onUnauthorized = () => {
|
||||
showMessageDialog('error', '认证已过期或无效,请重新登录');
|
||||
localStorage.removeItem('hxops_user');
|
||||
sessionStorage.removeItem('hxops_user');
|
||||
sessionStorage.removeItem('hxops_wecom_state');
|
||||
if (window.location.pathname !== '/') {
|
||||
window.location.href = '/';
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
window.addEventListener('hxops:unauthorized', onUnauthorized as EventListener);
|
||||
|
||||
initTheme();
|
||||
|
||||
const headers = getAuthHeaders();
|
||||
@@ -101,6 +89,10 @@ onMounted(async () => {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('hxops:unauthorized', onUnauthorized as EventListener);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
* 逻辑关系:封装 Fetch API 处理流式响应,供 ChatView 组件使用
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { getAuthHeaders } from '../utils/auth';
|
||||
|
||||
interface RetrieverResource {
|
||||
// 知识库/检索来源的基础字段,具体键可能因后端返回而扩展
|
||||
@@ -119,32 +120,6 @@ export function useChat() {
|
||||
*/
|
||||
const conversationId = ref<string | null>(null);
|
||||
|
||||
const getAuthHeaders = () => {
|
||||
const candidates = [
|
||||
sessionStorage.getItem('hxops_user'),
|
||||
localStorage.getItem('hxops_user'),
|
||||
];
|
||||
for (const stored of candidates) {
|
||||
if (!stored) continue;
|
||||
try {
|
||||
const data = JSON.parse(stored) as any;
|
||||
const user = data.user || data;
|
||||
if (!user?.username || !user?.role) continue;
|
||||
const headers: Record<string, string> = {
|
||||
'X-Username': user.username,
|
||||
'X-Role': user.role,
|
||||
};
|
||||
if (user.id) {
|
||||
headers['X-User-Id'] = String(user.id);
|
||||
}
|
||||
return headers;
|
||||
} catch (e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return {};
|
||||
};
|
||||
|
||||
/**
|
||||
* sendMessage
|
||||
* 用途:发送消息并处理 SSE 流式响应
|
||||
|
||||
+18
-2
@@ -1,5 +1,4 @@
|
||||
|
||||
import { createApp } from 'vue'
|
||||
import { createApp } from 'vue'
|
||||
import './style.css'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
@@ -9,6 +8,23 @@ import { config } from './config'
|
||||
// Set document title from config
|
||||
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);
|
||||
try {
|
||||
const url = typeof input === 'string'
|
||||
? input
|
||||
: (input instanceof URL ? input.toString() : input.url);
|
||||
if (res.status === 401 && url.includes('/api/')) {
|
||||
window.dispatchEvent(new CustomEvent('hxops:unauthorized', { detail: { url, status: res.status } }));
|
||||
}
|
||||
} catch {
|
||||
// no-op
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
createApp(App)
|
||||
.use(router)
|
||||
.use(i18n)
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
export interface AuthUser {
|
||||
id?: number;
|
||||
username?: string;
|
||||
role?: string;
|
||||
token?: string;
|
||||
access_token?: string;
|
||||
}
|
||||
|
||||
export const getStoredAuthUser = (): AuthUser | null => {
|
||||
const candidates = [
|
||||
sessionStorage.getItem('hxops_user'),
|
||||
localStorage.getItem('hxops_user'),
|
||||
];
|
||||
for (const stored of candidates) {
|
||||
if (!stored) continue;
|
||||
try {
|
||||
const data = JSON.parse(stored);
|
||||
return (data.user || data) as AuthUser;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
export const getAuthToken = (): string => {
|
||||
const user = getStoredAuthUser();
|
||||
const token = user?.access_token || user?.token;
|
||||
return token ? String(token) : '';
|
||||
};
|
||||
|
||||
export const getAuthHeaders = (): Record<string, string> => {
|
||||
const token = getAuthToken();
|
||||
if (!token) return {};
|
||||
return { Authorization: `Bearer ${token}` };
|
||||
};
|
||||
@@ -19,6 +19,7 @@ import DeleteConfirmDialog from '../components/DeleteConfirmDialog.vue';
|
||||
import { loadReportLayoutPref, saveReportLayoutPref } from '../composables/useReportLayoutStorage';
|
||||
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
|
||||
import { buildWecomAuditMeta, formatWecomAuditReason } from '../utils/wecom';
|
||||
import { getAuthHeaders } from '../utils/auth';
|
||||
import {
|
||||
ArrowLeft,
|
||||
// Save,
|
||||
@@ -748,29 +749,6 @@ const submitBatchPermission = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
const getAuthHeaders = () => {
|
||||
let stored = localStorage.getItem('hxops_user');
|
||||
if (!stored) stored = sessionStorage.getItem('hxops_user');
|
||||
|
||||
if (!stored) return {};
|
||||
|
||||
try {
|
||||
const data = JSON.parse(stored);
|
||||
const user = data.user || data; // Handle both wrapped and unwrapped format
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'X-Username': user.username,
|
||||
'X-Role': user.role,
|
||||
};
|
||||
if (user.id) {
|
||||
headers['X-User-Id'] = String(user.id);
|
||||
}
|
||||
return headers;
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 加载 Agent 列表
|
||||
* 核心逻辑:调用 GET /api/admin/agents
|
||||
@@ -1327,7 +1305,7 @@ const resetQuestionForm = () => {
|
||||
// 组件挂载时加载初始数据
|
||||
onMounted(async () => {
|
||||
const headers = getAuthHeaders();
|
||||
if (!headers['X-User-Id'] && !headers['X-Username']) {
|
||||
if (!headers['Authorization']) {
|
||||
console.warn('No auth headers found, redirecting to login');
|
||||
router.push('/');
|
||||
return;
|
||||
|
||||
@@ -21,6 +21,7 @@ import FilePreviewModal from '../components/FilePreviewModal.vue';
|
||||
import ThemeToggleButton from '../components/ThemeToggleButton.vue';
|
||||
import GeneralFeedbackDialog from '../components/GeneralFeedbackDialog.vue';
|
||||
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
|
||||
import { getAuthHeaders } from '../utils/auth';
|
||||
|
||||
const { t, locale } = useI18n();
|
||||
const { showMessageDialog } = useGlobalMessageDialog();
|
||||
@@ -402,33 +403,6 @@ const presetQuestion = computed(() => {
|
||||
return typeof q === 'string' ? q : '';
|
||||
});
|
||||
|
||||
const getAuthHeaders = () => {
|
||||
const candidates = [
|
||||
sessionStorage.getItem('hxops_user'),
|
||||
localStorage.getItem('hxops_user'),
|
||||
];
|
||||
|
||||
for (const stored of candidates) {
|
||||
if (!stored) continue;
|
||||
try {
|
||||
const data = JSON.parse(stored);
|
||||
const user = data.user || data;
|
||||
if (!user?.username || !user?.role) continue;
|
||||
const headers: Record<string, string> = {
|
||||
'X-Username': user.username,
|
||||
'X-Role': user.role,
|
||||
};
|
||||
if (user.id) {
|
||||
headers['X-User-Id'] = String(user.id);
|
||||
}
|
||||
return headers;
|
||||
} catch (e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return {};
|
||||
};
|
||||
|
||||
/**
|
||||
* handleSend
|
||||
* 用途:将输入框内容发送给当前 Agent
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useTheme } from '../composables/useTheme';
|
||||
import type { ThemePreference } from '../composables/useTheme';
|
||||
import ThemeToggleButton from '../components/ThemeToggleButton.vue';
|
||||
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
|
||||
import { getAuthHeaders } from '../utils/auth';
|
||||
import {
|
||||
User,
|
||||
Mail,
|
||||
@@ -99,25 +100,6 @@ const cancelEditing = () => {
|
||||
};
|
||||
|
||||
// Methods
|
||||
const getAuthHeaders = (): Record<string, string> => {
|
||||
let stored = localStorage.getItem('hxops_user');
|
||||
if (!stored) stored = sessionStorage.getItem('hxops_user');
|
||||
|
||||
if (!stored) return {};
|
||||
|
||||
try {
|
||||
const data = JSON.parse(stored);
|
||||
const u = data.user || data;
|
||||
return {
|
||||
'X-Username': u.username,
|
||||
'X-Role': u.role,
|
||||
'X-User-Id': String(u.id)
|
||||
};
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
const fetchProfile = async () => {
|
||||
isLoading.value = true;
|
||||
try {
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
type WecomLoginDialogContent,
|
||||
type WecomMatchField,
|
||||
} from '../utils/wecom';
|
||||
import { getAuthHeaders, getStoredAuthUser } from '../utils/auth';
|
||||
import {
|
||||
Settings,
|
||||
LayoutGrid,
|
||||
@@ -233,33 +234,11 @@ const getSectionTitleKey = (sectionId: string) => {
|
||||
};
|
||||
|
||||
// Methods
|
||||
const getAuthHeaders = () => {
|
||||
let stored = localStorage.getItem('hxops_user');
|
||||
if (!stored) stored = sessionStorage.getItem('hxops_user');
|
||||
|
||||
if (!stored) return {};
|
||||
|
||||
try {
|
||||
const data = JSON.parse(stored);
|
||||
const user = data.user || data; // Handle both wrapped and unwrapped format
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'X-Username': user.username,
|
||||
'X-Role': user.role,
|
||||
};
|
||||
if (user.id) {
|
||||
headers['X-User-Id'] = String(user.id);
|
||||
}
|
||||
return headers;
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
const fetchHome = async () => {
|
||||
try {
|
||||
const res = await fetch('/api/user/home', { headers: getAuthHeaders() });
|
||||
if (res.status === 401) {
|
||||
showMessageDialog('error', t('login.loginRequired'));
|
||||
handleLogout();
|
||||
return;
|
||||
}
|
||||
@@ -389,12 +368,12 @@ const loadAuthUser = () => {
|
||||
if (!stored) return;
|
||||
|
||||
try {
|
||||
const data = JSON.parse(stored);
|
||||
const user = data.user || data; // Handle both wrapped and unwrapped format
|
||||
const user = getStoredAuthUser();
|
||||
if (!user) return;
|
||||
currentUser.value = {
|
||||
id: user.id || 0,
|
||||
username: user.username,
|
||||
role: user.role,
|
||||
username: user.username || '',
|
||||
role: user.role || 'user',
|
||||
};
|
||||
} catch (e) {
|
||||
localStorage.removeItem('hxops_user');
|
||||
@@ -403,12 +382,16 @@ 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, expiry }));
|
||||
localStorage.setItem('hxops_user', JSON.stringify({ user: nextUser, expiry }));
|
||||
sessionStorage.removeItem('hxops_user');
|
||||
} else {
|
||||
sessionStorage.setItem('hxops_user', JSON.stringify({ user }));
|
||||
sessionStorage.setItem('hxops_user', JSON.stringify({ user: nextUser }));
|
||||
localStorage.removeItem('hxops_user');
|
||||
}
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user