第二版:casdoor登录,保留用户密码登录
This commit is contained in:
1 parent
a5f0ec645d
commit
61fa96d686
13 files changed
+701
-39
No files matched your search
@@ -5,7 +5,7 @@ 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';
|
||||
import { getAuthHeaders, clearAuthUser } from './utils/auth';
|
||||
|
||||
const { locale } = useI18n();
|
||||
const { themePreference, initTheme, setThemePreference } = useTheme();
|
||||
@@ -58,9 +58,7 @@ watch(themePreference, (newTheme) => {
|
||||
|
||||
const onUnauthorized = () => {
|
||||
showMessageDialog('error', '认证已过期或无效,请重新登录');
|
||||
localStorage.removeItem('hxops_user');
|
||||
sessionStorage.removeItem('hxops_user');
|
||||
sessionStorage.removeItem('hxops_wecom_state');
|
||||
clearAuthUser();
|
||||
if (window.location.pathname !== '/') {
|
||||
window.location.href = '/';
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ const props = withDefaults(defineProps<Props>(), {
|
||||
message: '',
|
||||
closeOnMask: true,
|
||||
closeOnEsc: true,
|
||||
autoCloseMs: 3000,
|
||||
autoCloseMs: 5000,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
|
||||
@@ -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',
|
||||
@@ -922,6 +923,7 @@ const messages = {
|
||||
announcements: '公告',
|
||||
passwordResetEmailSent: '如果账号存在,重置链接已发送到您的邮箱。',
|
||||
passwordResetRequestFailed: '请求密码重置失败',
|
||||
casdoorLogin: 'Casdoor 登录',
|
||||
wecomLogin: '企业微信登录',
|
||||
wecomConnecting: '正在连接企业微信...',
|
||||
wecomStartFailed: '启动企业微信登录失败',
|
||||
@@ -1776,6 +1778,7 @@ const messages = {
|
||||
announcements: '公告',
|
||||
forgotPasswordDesc: '輸入您的郵箱以重設密碼',
|
||||
findPassword: '找回密碼',
|
||||
casdoorLogin: 'Casdoor 登入',
|
||||
wecomLogin: '企業微信登錄',
|
||||
wecomConnecting: '正在連接企業微信...',
|
||||
wecomStartFailed: '啟動企業微信登錄失敗',
|
||||
@@ -2630,6 +2633,7 @@ const messages = {
|
||||
announcements: 'ประกาศ',
|
||||
forgotPasswordDesc: 'กรอกอีเมลเพื่อรีเซ็ตรหัสผ่าน',
|
||||
findPassword: 'ค้นหารหัสผ่าน',
|
||||
casdoorLogin: 'เข้าสู่ระบบด้วย Casdoor',
|
||||
wecomLogin: 'เข้าสู่ระบบด้วย WeCom',
|
||||
wecomConnecting: 'กำลังเชื่อมต่อ WeCom...',
|
||||
wecomStartFailed: 'เริ่มต้นการเข้าสู่ระบบด้วย WeCom ไม่สำเร็จ',
|
||||
|
||||
+20
-2
@@ -4,6 +4,7 @@ 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工作台';
|
||||
@@ -11,12 +12,29 @@ 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);
|
||||
// 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);
|
||||
if (res.status === 401 && url.includes('/api/')) {
|
||||
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 {
|
||||
|
||||
@@ -18,6 +18,11 @@ const routes = [
|
||||
name: 'Workspace',
|
||||
component: WorkspaceView
|
||||
},
|
||||
{
|
||||
path: '/casdoor-callback',
|
||||
name: 'CasdoorCallback',
|
||||
component: WorkspaceView
|
||||
},
|
||||
{
|
||||
path: '/profile',
|
||||
name: 'Profile',
|
||||
|
||||
@@ -4,6 +4,9 @@ export interface AuthUser {
|
||||
role?: string;
|
||||
token?: string;
|
||||
access_token?: string;
|
||||
refresh_token?: string;
|
||||
expires_in?: number;
|
||||
token_expires_at?: number;
|
||||
}
|
||||
|
||||
export const getStoredAuthUser = (): AuthUser | null => {
|
||||
@@ -34,3 +37,59 @@ export const getAuthHeaders = (): Record<string, string> => {
|
||||
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;
|
||||
};
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
type WecomLoginDialogContent,
|
||||
type WecomMatchField,
|
||||
} from '../utils/wecom';
|
||||
import { getAuthHeaders, getStoredAuthUser } from '../utils/auth';
|
||||
import { getAuthHeaders, getStoredAuthUser, saveAuthUser } from '../utils/auth';
|
||||
import {
|
||||
Settings,
|
||||
LayoutGrid,
|
||||
@@ -382,18 +382,7 @@ 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: nextUser, expiry }));
|
||||
sessionStorage.removeItem('hxops_user');
|
||||
} else {
|
||||
sessionStorage.setItem('hxops_user', JSON.stringify({ user: nextUser }));
|
||||
localStorage.removeItem('hxops_user');
|
||||
}
|
||||
saveAuthUser({ ...(user || {}) }, rememberMe.value);
|
||||
};
|
||||
|
||||
const handleLogin = async () => {
|
||||
@@ -447,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 {
|
||||
@@ -549,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');
|
||||
@@ -862,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;
|
||||
@@ -1069,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