Merge branch 'dev' into runny0429

This commit is contained in:
sophie committed 2026-05-06 10:31:01 +08:00
commit 66b108f9d8
20 files changed
+1102 -274

No files matched your search

+9 -24
View File
@@ -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,
@@ -49,6 +50,7 @@ import * as XLSX from 'xlsx';
const { t, locale } = useI18n();
const { showMessageDialog } = useGlobalMessageDialog();
const EMAIL_PATTERN = /^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$/;
const sidebarItems = computed(() => {
const items = [
@@ -307,6 +309,12 @@ const saveUser = async () => {
showMessageDialog('warning', t('admin.user.msgs.usernameRequired'));
return;
}
const email = (editingUser.value.email || '').trim();
if (email && !EMAIL_PATTERN.test(email)) {
showMessageDialog('warning', t('admin.user.msgs.invalidEmail'));
return;
}
if (!editingUser.value.id && !editingUser.value.password) {
showMessageDialog('warning', t('admin.user.msgs.passwordRequired'));
@@ -748,29 +756,6 @@ const submitBatchPermission = async () => {
}
};
const getAuthHeaders = () => {
let stored = localStorage.getItem('hxops_user');
if (!stored) stored = sessionStorage.getItem('hxops_user');
if (!stored) return {};
try {
const data = JSON.parse(stored);
const user = data.user || data; // Handle both wrapped and unwrapped format
const headers: Record<string, string> = {
'X-Username': user.username,
'X-Role': user.role,
};
if (user.id) {
headers['X-User-Id'] = String(user.id);
}
return headers;
} catch (e) {
return {};
}
};
/**
* 加载 Agent 列表
* 核心逻辑:调用 GET /api/admin/agents
@@ -1327,7 +1312,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;
+1 -27
View File
@@ -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();
@@ -404,33 +405,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
+1 -19
View File
@@ -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 {
+101 -35
View File
@@ -20,6 +20,7 @@ import {
type WecomLoginDialogContent,
type WecomMatchField,
} from '../utils/wecom';
import { getAuthHeaders, getStoredAuthUser, saveAuthUser } 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,14 +382,7 @@ const loadAuthUser = () => {
};
const persistLoginUser = (user: any) => {
if (rememberMe.value) {
const expiry = new Date().getTime() + 30 * 24 * 60 * 60 * 1000;
localStorage.setItem('hxops_user', JSON.stringify({ user, expiry }));
sessionStorage.removeItem('hxops_user');
} else {
sessionStorage.setItem('hxops_user', JSON.stringify({ user }));
localStorage.removeItem('hxops_user');
}
saveAuthUser({ ...(user || {}) }, rememberMe.value);
};
const handleLogin = async () => {
@@ -464,6 +436,86 @@ const handleLogin = async () => {
}
};
const handleCasdoorLogin = async () => {
if (!config.auth?.casdoor?.enabled) return;
try {
// Ask backend to build a server-side-tracked authorize URL (includes state).
const api = config.auth.casdoor.authorizeApi || '/api/user/casdoor/authorize-url';
const callbackPath = config.auth.casdoor.callbackPath || '/casdoor-callback';
const redirectUri = `${window.location.origin}${callbackPath}`;
const res = await fetch(`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`);
const data = await res.json();
if (!res.ok || !data.url) {
showMessageDialog('error', data.error || t('login.requestFailed'));
return;
}
if (data.state) {
sessionStorage.setItem('hxops_casdoor_state', data.state);
}
window.location.href = data.url;
} catch (e) {
console.error(e);
showMessageDialog('error', t('login.requestFailed'));
}
};
const tryCasdoorCallbackLogin = async () => {
if (!config.auth?.casdoor?.enabled) return false;
const casdoorPath = config.auth.casdoor.callbackPath || '/casdoor-callback';
const path = window.location.pathname;
// Compatibility: allow temporary callback landing on /workspace during migration.
if (path !== casdoorPath && path !== '/workspace') return false;
const params = new URLSearchParams(window.location.search);
const code = params.get('code');
const state = params.get('state');
if (!code) return false;
const expectedState = sessionStorage.getItem('hxops_casdoor_state');
// Backward compatibility: old backend emitted random in-memory state
// (hxops_casdoor_*), while new backend emits signed stateless state.
// For new signed state, rely on backend signature verification instead of
// strict frontend equality check to avoid false negatives during rollout.
const shouldStrictCheck = !!expectedState && !!state && !String(state).startsWith('hxops_casdoor_v1.');
if (shouldStrictCheck && state !== expectedState) {
// Prevent CSRF/state mismatch replay.
showMessageDialog('error', 'Invalid or expired Casdoor state');
clearWecomCallbackQuery();
return true;
}
try {
const api = config.auth.casdoor.loginApi || '/api/user/casdoor/login';
const res = await fetch(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, state }),
});
const data = await res.json();
if (!res.ok) {
const code = String(data.error_code || '');
let msg = data.error || 'Casdoor login failed';
if (code === 'CASDOOR_USER_NOT_FOUND') {
msg = 'Casdoor 登录成功,但未匹配到本地账号。请让管理员在本地用户表创建同名 username 或相同 email 的账号。';
} else if (code === 'ACCOUNT_DISABLED') {
msg = '该本地账号已被禁用,请联系管理员启用后再登录。';
}
showMessageDialog('error', msg);
clearWecomCallbackQuery();
return true;
}
// Persist access+refresh tokens for API auth and silent refresh.
persistLoginUser(data);
sessionStorage.removeItem('hxops_casdoor_state');
window.history.replaceState({}, '', '/workspace');
await fetchHome();
return true;
} catch (e) {
console.error(e);
showMessageDialog('error', 'Casdoor login failed');
clearWecomCallbackQuery();
return true;
}
};
const handleWecomLogin = async () => {
if (!config.auth?.wecom?.enabled) return;
try {
@@ -566,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');
@@ -879,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;
@@ -1086,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"