Merge branch 'dev' into runny0429
This commit is contained in:
commit
66b108f9d8
20 files changed
+1102
-274
No files matched your search
+17
-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, clearAuthUser } 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,17 @@ watch(themePreference, (newTheme) => {
|
||||
updateThemePreference(newTheme);
|
||||
});
|
||||
|
||||
const onUnauthorized = () => {
|
||||
showMessageDialog('error', '认证已过期或无效,请重新登录');
|
||||
clearAuthUser();
|
||||
if (window.location.pathname !== '/') {
|
||||
window.location.href = '/';
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
window.addEventListener('hxops:unauthorized', onUnauthorized as EventListener);
|
||||
|
||||
initTheme();
|
||||
|
||||
const headers = getAuthHeaders();
|
||||
@@ -101,6 +87,10 @@ onMounted(async () => {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('hxops:unauthorized', onUnauthorized as EventListener);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -23,7 +23,7 @@ const props = withDefaults(defineProps<Props>(), {
|
||||
message: '',
|
||||
closeOnMask: true,
|
||||
closeOnEsc: true,
|
||||
autoCloseMs: 3000,
|
||||
autoCloseMs: 5000,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
|
||||
@@ -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 流式响应
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
export const config = {
|
||||
appTitle: 'AI工作台',
|
||||
auth: {
|
||||
casdoor: {
|
||||
enabled: true,
|
||||
authorizeApi: '/api/user/casdoor/authorize-url',
|
||||
loginApi: '/api/user/casdoor/login',
|
||||
refreshApi: '/api/user/casdoor/refresh',
|
||||
callbackPath: '/casdoor-callback',
|
||||
},
|
||||
wecom: {
|
||||
enabled: true,
|
||||
authorizeApi: '/api/user/wecom/authorize-url',
|
||||
|
||||
@@ -36,6 +36,7 @@ const messages = {
|
||||
announcements: 'Announcements',
|
||||
passwordResetEmailSent: '如果账号存在,重置链接已发送到您的邮箱。',
|
||||
passwordResetRequestFailed: '请求密码重置失败',
|
||||
casdoorLogin: 'Login with Casdoor',
|
||||
wecomLogin: 'Login with WeCom',
|
||||
wecomConnecting: 'Connecting to WeCom...',
|
||||
wecomStartFailed: 'Failed to start WeCom login',
|
||||
@@ -323,6 +324,7 @@ const messages = {
|
||||
msgs: {
|
||||
usernameRequired: 'Username is required',
|
||||
passwordRequired: 'Password is required for new users',
|
||||
invalidEmail: 'Invalid email format',
|
||||
created: 'User created successfully',
|
||||
updated: 'User updated successfully',
|
||||
deleted: 'User deleted successfully',
|
||||
@@ -922,6 +924,7 @@ const messages = {
|
||||
announcements: '公告',
|
||||
passwordResetEmailSent: '如果账号存在,重置链接已发送到您的邮箱。',
|
||||
passwordResetRequestFailed: '请求密码重置失败',
|
||||
casdoorLogin: 'Casdoor 登录',
|
||||
wecomLogin: '企业微信登录',
|
||||
wecomConnecting: '正在连接企业微信...',
|
||||
wecomStartFailed: '启动企业微信登录失败',
|
||||
@@ -1209,6 +1212,7 @@ const messages = {
|
||||
msgs: {
|
||||
usernameRequired: '用户名必填',
|
||||
passwordRequired: '新用户必须设置密码',
|
||||
invalidEmail: '邮箱格式不正确',
|
||||
created: '用户创建成功',
|
||||
updated: '用户更新成功',
|
||||
deleted: '用户删除成功',
|
||||
@@ -1776,6 +1780,7 @@ const messages = {
|
||||
announcements: '公告',
|
||||
forgotPasswordDesc: '輸入您的郵箱以重設密碼',
|
||||
findPassword: '找回密碼',
|
||||
casdoorLogin: 'Casdoor 登入',
|
||||
wecomLogin: '企業微信登錄',
|
||||
wecomConnecting: '正在連接企業微信...',
|
||||
wecomStartFailed: '啟動企業微信登錄失敗',
|
||||
@@ -2058,6 +2063,7 @@ const messages = {
|
||||
msgs: {
|
||||
usernameRequired: '用戶名必填',
|
||||
passwordRequired: '新用戶必須設置密碼',
|
||||
invalidEmail: '郵箱格式不正確',
|
||||
created: '用戶創建成功',
|
||||
updated: '用戶更新成功',
|
||||
deleted: '用戶刪除成功',
|
||||
@@ -2630,6 +2636,7 @@ const messages = {
|
||||
announcements: 'ประกาศ',
|
||||
forgotPasswordDesc: 'กรอกอีเมลเพื่อรีเซ็ตรหัสผ่าน',
|
||||
findPassword: 'ค้นหารหัสผ่าน',
|
||||
casdoorLogin: 'เข้าสู่ระบบด้วย Casdoor',
|
||||
wecomLogin: 'เข้าสู่ระบบด้วย WeCom',
|
||||
wecomConnecting: 'กำลังเชื่อมต่อ WeCom...',
|
||||
wecomStartFailed: 'เริ่มต้นการเข้าสู่ระบบด้วย WeCom ไม่สำเร็จ',
|
||||
@@ -2912,6 +2919,7 @@ const messages = {
|
||||
msgs: {
|
||||
usernameRequired: 'กรุณากรอกชื่อผู้ใช้',
|
||||
passwordRequired: 'ต้องระบุรหัสผ่านสำหรับผู้ใช้ใหม่',
|
||||
invalidEmail: 'รูปแบบอีเมลไม่ถูกต้อง',
|
||||
created: 'สร้างผู้ใช้สำเร็จ',
|
||||
updated: 'อัปเดตผู้ใช้สำเร็จ',
|
||||
deleted: 'ลบผู้ใช้สำเร็จ',
|
||||
|
||||
+36
-2
@@ -1,14 +1,48 @@
|
||||
|
||||
import { createApp } from 'vue'
|
||||
import { createApp } from 'vue'
|
||||
import './style.css'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import i18n from './i18n'
|
||||
import { config } from './config'
|
||||
import { refreshAccessToken, getAuthToken } from './utils/auth'
|
||||
|
||||
// Set document title from config
|
||||
document.title = config.appTitle || 'AI工作台';
|
||||
|
||||
// Global 401 interceptor for API calls.
|
||||
const _rawFetch = window.fetch.bind(window);
|
||||
window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
|
||||
// Keep original request closure so we can retry with a refreshed token.
|
||||
const runFetch = (nextInit?: RequestInit) => _rawFetch(input, nextInit);
|
||||
let reqInit = init;
|
||||
let res = await runFetch(reqInit);
|
||||
try {
|
||||
const url = typeof input === 'string'
|
||||
? input
|
||||
: (input instanceof URL ? input.toString() : input.url);
|
||||
const isApi = url.includes('/api/');
|
||||
const isRefreshApi = url.includes('/api/user/casdoor/refresh');
|
||||
if (res.status === 401 && isApi && !isRefreshApi) {
|
||||
// First unauthorized response: try silent refresh once.
|
||||
const refreshed = await refreshAccessToken();
|
||||
if (refreshed) {
|
||||
const mergedHeaders = new Headers((reqInit && reqInit.headers) || {});
|
||||
mergedHeaders.set('Authorization', `Bearer ${getAuthToken()}`);
|
||||
reqInit = { ...(reqInit || {}), headers: mergedHeaders };
|
||||
// Retry original request exactly once with the renewed access token.
|
||||
res = await runFetch(reqInit);
|
||||
}
|
||||
}
|
||||
if (res.status === 401 && isApi) {
|
||||
// Still unauthorized after retry (or no refresh token): force global logout UX.
|
||||
window.dispatchEvent(new CustomEvent('hxops:unauthorized', { detail: { url, status: res.status } }));
|
||||
}
|
||||
} catch {
|
||||
// no-op
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
createApp(App)
|
||||
.use(router)
|
||||
.use(i18n)
|
||||
|
||||
@@ -18,6 +18,11 @@ const routes = [
|
||||
name: 'Workspace',
|
||||
component: WorkspaceView
|
||||
},
|
||||
{
|
||||
path: '/casdoor-callback',
|
||||
name: 'CasdoorCallback',
|
||||
component: WorkspaceView
|
||||
},
|
||||
{
|
||||
path: '/profile',
|
||||
name: 'Profile',
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
export interface AuthUser {
|
||||
id?: number;
|
||||
username?: string;
|
||||
role?: string;
|
||||
token?: string;
|
||||
access_token?: string;
|
||||
refresh_token?: string;
|
||||
expires_in?: number;
|
||||
token_expires_at?: number;
|
||||
}
|
||||
|
||||
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}` };
|
||||
};
|
||||
|
||||
export const saveAuthUser = (user: AuthUser, remember = false): void => {
|
||||
const next = { ...user };
|
||||
if (next.expires_in && !next.token_expires_at) {
|
||||
// Pre-compute an absolute expiry timestamp for later proactive checks.
|
||||
next.token_expires_at = Date.now() + Number(next.expires_in) * 1000;
|
||||
}
|
||||
const payload = remember
|
||||
? { user: next, expiry: Date.now() + 30 * 24 * 60 * 60 * 1000 }
|
||||
: { user: next };
|
||||
if (remember) {
|
||||
localStorage.setItem('hxops_user', JSON.stringify(payload));
|
||||
sessionStorage.removeItem('hxops_user');
|
||||
} else {
|
||||
sessionStorage.setItem('hxops_user', JSON.stringify(payload));
|
||||
localStorage.removeItem('hxops_user');
|
||||
}
|
||||
};
|
||||
|
||||
export const clearAuthUser = (): void => {
|
||||
localStorage.removeItem('hxops_user');
|
||||
sessionStorage.removeItem('hxops_user');
|
||||
sessionStorage.removeItem('hxops_wecom_state');
|
||||
sessionStorage.removeItem('hxops_casdoor_state');
|
||||
};
|
||||
|
||||
let _refreshing: Promise<string | null> | null = null;
|
||||
|
||||
export const refreshAccessToken = async (): Promise<string | null> => {
|
||||
// Single-flight guard: concurrent 401s share one refresh request.
|
||||
const current = getStoredAuthUser();
|
||||
const refreshToken = current?.refresh_token;
|
||||
if (!refreshToken) return null;
|
||||
if (_refreshing) return _refreshing;
|
||||
_refreshing = (async () => {
|
||||
try {
|
||||
// Backend endpoint wraps Casdoor refresh flow.
|
||||
const res = await fetch('/api/user/casdoor/refresh', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ refresh_token: refreshToken }),
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
const data = await res.json();
|
||||
if (!data?.access_token) return null;
|
||||
// Preserve existing profile fields while replacing rotated token material.
|
||||
saveAuthUser({ ...(current || {}), ...data }, Boolean(localStorage.getItem('hxops_user')));
|
||||
return String(data.access_token);
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
_refreshing = null;
|
||||
}
|
||||
})();
|
||||
return _refreshing;
|
||||
};
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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, 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"
|
||||
|
||||
Reference in new issue
Block a user