381 lines
14 KiB
TypeScript
381 lines
14 KiB
TypeScript
/**
|
|
* features/auth/composables/useLoginAuth.ts
|
|
* 登录表单、企微/Casdoor OAuth 回调、注册与找回密码逻辑。
|
|
*/
|
|
import { ref } from 'vue';
|
|
import { config } from '@/config';
|
|
import { resolveCasdoorErrorMessage } from '@/shared/utils/casdoor';
|
|
import {
|
|
buildWecomLoginDialogContent,
|
|
normalizeWecomMatchRules,
|
|
type WecomMatchField,
|
|
} from '@/shared/utils/wecom';
|
|
import { saveAuthUser } from '@/shared/utils/auth';
|
|
import { BusinessError, requestJson } from '@/shared/api/client';
|
|
import { DEFAULT_POST_LOGIN_AGENT_ID } from '@/features/workspace/types/workspace.types';
|
|
import type { WecomBindPromptState, WecomLoginDialogContent } from '@/features/workspace/types/workspace.types';
|
|
import type { LoginDeps } from './login.deps';
|
|
|
|
interface LoginAuthOptions {
|
|
completePasswordLogin: () => Promise<void>;
|
|
completeOAuthLogin: () => Promise<void>;
|
|
}
|
|
|
|
const LOGIN_CALLBACK_PATHS = ['/login', '/workspace'] as const;
|
|
|
|
function isLoginCallbackPath(path: string, extraPaths: string[] = []): boolean {
|
|
return LOGIN_CALLBACK_PATHS.includes(path as (typeof LOGIN_CALLBACK_PATHS)[number])
|
|
|| extraPaths.includes(path);
|
|
}
|
|
|
|
export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
|
|
const { t, msg } = deps;
|
|
const { completePasswordLogin, completeOAuthLogin } = options;
|
|
|
|
const loginUsername = ref('');
|
|
const loginPassword = ref('');
|
|
const rememberMe = ref(false);
|
|
const showRegisterModal = ref(false);
|
|
const showForgotPasswordModal = ref(false);
|
|
const registerForm = ref({
|
|
username: '',
|
|
password: '',
|
|
email: '',
|
|
real_name: '',
|
|
employee_id: '',
|
|
phone_number: '',
|
|
});
|
|
const forgotPasswordForm = ref({ email: '' });
|
|
const isWecomLoggingIn = ref(false);
|
|
const wecomLoginDialog = ref<WecomLoginDialogContent | null>(null);
|
|
const wecomBindPrompt = ref<WecomBindPromptState | null>(null);
|
|
|
|
const clearWecomCallbackQuery = () => {
|
|
const nextUrl = `${window.location.pathname}${window.location.hash || ''}`;
|
|
window.history.replaceState({}, '', nextUrl);
|
|
};
|
|
|
|
const persistLoginUser = (user: Record<string, unknown>) => {
|
|
saveAuthUser({ ...(user || {}) }, rememberMe.value);
|
|
};
|
|
|
|
const handleForgotPassword = async () => {
|
|
if (!forgotPasswordForm.value.email) {
|
|
msg.warning(t('register.emailRequired'));
|
|
return;
|
|
}
|
|
try {
|
|
await requestJson('/api/user/reset-password-by-email', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(forgotPasswordForm.value),
|
|
});
|
|
msg.success(t('login.passwordResetEmailSent'));
|
|
showForgotPasswordModal.value = false;
|
|
forgotPasswordForm.value = { email: '' };
|
|
} catch (e) {
|
|
console.error('Password reset error', e);
|
|
msg.error((e as Error)?.message || t('login.passwordResetRequestFailed'));
|
|
}
|
|
};
|
|
|
|
const handleLogin = async (event?: Event) => {
|
|
event?.preventDefault();
|
|
event?.stopPropagation();
|
|
|
|
if (!loginUsername.value.trim()) {
|
|
msg.warning(t('login.usernameRequired'));
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const loginMode = String(config.auth?.loginMode || 'casdoor').toLowerCase();
|
|
const isCasdoorMode = loginMode === 'casdoor';
|
|
const loginApi = isCasdoorMode
|
|
? (config.auth?.casdoor?.passwordLoginApi || '/api/user/casdoor/password-login')
|
|
: '/api/user/login';
|
|
const user = await requestJson<Record<string, unknown>>(loginApi, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
username: loginUsername.value.trim(),
|
|
password: loginPassword.value,
|
|
}),
|
|
});
|
|
|
|
persistLoginUser(user);
|
|
await completePasswordLogin();
|
|
} catch (e) {
|
|
const err = e as BusinessError;
|
|
const rawError = String(err.message || '');
|
|
let errorText = resolveCasdoorErrorMessage(err, t);
|
|
if (rawError === 'User not found') errorText = t('login.userNotFound');
|
|
if (rawError === 'Incorrect password') errorText = t('login.incorrectPassword');
|
|
if (rawError === 'Account is disabled') errorText = t('login.accountDisabled');
|
|
if (rawError === 'Database connection failed') errorText = t('login.dbConnectionFailed');
|
|
if (rawError === 'Internal server error') errorText = t('login.internalError');
|
|
console.error(e);
|
|
msg.error(errorText || 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;
|
|
if (!isLoginCallbackPath(path, [casdoorPath])) 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');
|
|
const shouldStrictCheck = !!expectedState && !!state && !String(state).startsWith('hxops_casdoor_v1.');
|
|
if (shouldStrictCheck && state !== expectedState) {
|
|
msg.error(t('login.casdoorErrors.stateExpired'));
|
|
clearWecomCallbackQuery();
|
|
return true;
|
|
}
|
|
try {
|
|
const api = config.auth.casdoor.loginApi || '/api/user/casdoor/login';
|
|
const data = await requestJson<Record<string, unknown>>(api, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ code, state }),
|
|
});
|
|
persistLoginUser(data);
|
|
sessionStorage.removeItem('hxops_casdoor_state');
|
|
await completeOAuthLogin();
|
|
return true;
|
|
} catch (e) {
|
|
const err = e as BusinessError;
|
|
console.error(e);
|
|
msg.error(resolveCasdoorErrorMessage(err, t));
|
|
clearWecomCallbackQuery();
|
|
return true;
|
|
}
|
|
};
|
|
|
|
const handleWecomLogin = async () => {
|
|
if (!config.auth?.wecom?.enabled) return;
|
|
const wecomCfg = config.auth.wecom as { loginViaCasdoor?: boolean; callbackPath?: string; authorizeApi?: string };
|
|
const viaCasdoor = Boolean(wecomCfg?.loginViaCasdoor);
|
|
try {
|
|
if (viaCasdoor) {
|
|
if (!config.auth?.casdoor?.enabled) {
|
|
msg.error(t('login.wecomStartFailed'));
|
|
return;
|
|
}
|
|
const callbackPath = config.auth.casdoor.callbackPath || '/casdoor-callback';
|
|
const redirectUri = `${window.location.origin}${callbackPath}`;
|
|
const api = config.auth.casdoor.authorizeApi || '/api/user/casdoor/authorize-url';
|
|
const qs = new URLSearchParams({ redirect_uri: redirectUri, default_provider: 'wecom' });
|
|
const hint = (config.auth.casdoor as { wecomProviderHint?: string }).wecomProviderHint?.trim();
|
|
if (hint) qs.set('provider_hint', hint);
|
|
const data = await requestJson<{ url?: string; state?: string }>(`${api}?${qs.toString()}`);
|
|
if (!data?.url) {
|
|
msg.error(t('login.wecomStartFailed'));
|
|
return;
|
|
}
|
|
if (data.state) sessionStorage.setItem('hxops_casdoor_state', data.state);
|
|
window.location.href = data.url;
|
|
return;
|
|
}
|
|
|
|
const callbackPath = wecomCfg.callbackPath || '/login';
|
|
const redirectUri = `${window.location.origin}${callbackPath}`;
|
|
const api = wecomCfg.authorizeApi || '/api/user/wecom/authorize-url';
|
|
const data = await requestJson<{ url?: string; state?: string }>(
|
|
`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`,
|
|
);
|
|
if (!data?.url) {
|
|
msg.error(t('login.wecomStartFailed'));
|
|
return;
|
|
}
|
|
if (data.state) sessionStorage.setItem('hxops_wecom_state', data.state);
|
|
window.location.href = data.url;
|
|
} catch (e) {
|
|
console.error(e);
|
|
msg.error((e as Error)?.message || t('login.wecomStartFailed'));
|
|
}
|
|
};
|
|
|
|
const openWecomLoginDialog = (payload: Record<string, unknown>) => {
|
|
wecomLoginDialog.value = buildWecomLoginDialogContent(payload, t);
|
|
};
|
|
|
|
const openWecomBindPrompt = (payload: Record<string, unknown>) => {
|
|
const allowedFields = normalizeWecomMatchRules(payload.allowed_fields).fields;
|
|
const fallbackFields: WecomMatchField[] = ['employee_id', 'mobile', 'email'];
|
|
const fields: WecomMatchField[] = allowedFields.length ? allowedFields : fallbackFields;
|
|
wecomBindPrompt.value = {
|
|
binding_token: String(payload.binding_token || ''),
|
|
allowed_fields: fields,
|
|
wecom_name: String(payload.wecom_name || ''),
|
|
field: fields[0] || 'employee_id',
|
|
value: '',
|
|
submitting: false,
|
|
error: '',
|
|
};
|
|
};
|
|
|
|
const formatWecomBindPromptError = (payload: Record<string, unknown>) => {
|
|
const errorCode = String(payload.error_code || '');
|
|
if (errorCode === 'WECOM_BIND_INPUT_NOT_FOUND') return t('login.wecomBindInputNotFound');
|
|
if (errorCode === 'WECOM_BIND_INPUT_AMBIGUOUS') return t('login.wecomBindInputAmbiguous');
|
|
if (errorCode === 'WECOM_BIND_SESSION_EXPIRED') return t('login.wecomBindSessionExpired');
|
|
if (errorCode === 'WECOM_BIND_CONFLICT') return t('login.wecomBindConflict');
|
|
if (errorCode === 'WECOM_BIND_FIELD_NOT_ALLOWED') return t('login.wecomBindFieldNotAllowed');
|
|
if (errorCode === 'WECOM_BIND_INPUT_VALUE_REQUIRED') return t('login.wecomBindValueRequired');
|
|
if (String(payload.error || '').includes('Account is disabled')) return t('login.wecomAccountDisabled');
|
|
return String(payload.error || t('login.wecomLoginFailed'));
|
|
};
|
|
|
|
const submitWecomCompleteBind = async () => {
|
|
if (!wecomBindPrompt.value) return;
|
|
if (!wecomBindPrompt.value.value.trim()) {
|
|
wecomBindPrompt.value.error = t('login.wecomBindValueRequired');
|
|
return;
|
|
}
|
|
wecomBindPrompt.value.submitting = true;
|
|
wecomBindPrompt.value.error = '';
|
|
try {
|
|
const api = config.auth.wecom.completeBindApi || '/api/user/wecom/complete-bind';
|
|
const data = await requestJson<Record<string, unknown>>(api, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
binding_token: wecomBindPrompt.value.binding_token,
|
|
field: wecomBindPrompt.value.field,
|
|
value: wecomBindPrompt.value.value.trim(),
|
|
}),
|
|
});
|
|
wecomLoginDialog.value = null;
|
|
persistLoginUser(data);
|
|
sessionStorage.removeItem('hxops_wecom_state');
|
|
wecomBindPrompt.value = null;
|
|
await completeOAuthLogin();
|
|
} catch (e) {
|
|
const err = e as BusinessError;
|
|
if (wecomBindPrompt.value) {
|
|
const errorPayload = { error: err.message, error_code: err.code };
|
|
wecomBindPrompt.value.error = formatWecomBindPromptError(errorPayload);
|
|
if (String(err.code || '') === 'WECOM_BIND_SESSION_EXPIRED') {
|
|
openWecomLoginDialog(errorPayload);
|
|
wecomBindPrompt.value = null;
|
|
}
|
|
}
|
|
console.error(e);
|
|
} finally {
|
|
if (wecomBindPrompt.value) wecomBindPrompt.value.submitting = false;
|
|
}
|
|
};
|
|
|
|
const tryWecomCallbackLogin = async () => {
|
|
if (!config.auth?.wecom?.enabled) return false;
|
|
if ((config.auth.wecom as { loginViaCasdoor?: boolean }).loginViaCasdoor) return false;
|
|
const wecomPath = config.auth.wecom.callbackPath || '/login';
|
|
const path = window.location.pathname;
|
|
if (path !== wecomPath && !isLoginCallbackPath(path)) 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_wecom_state');
|
|
if (expectedState && state && state !== expectedState) {
|
|
msg.error(t('login.wecomInvalidState'));
|
|
openWecomLoginDialog({ error: 'Invalid or expired WeCom state' });
|
|
clearWecomCallbackQuery();
|
|
return true;
|
|
}
|
|
|
|
isWecomLoggingIn.value = true;
|
|
try {
|
|
const api = config.auth.wecom.loginApi || '/api/user/wecom/login';
|
|
const data = await requestJson<Record<string, unknown>>(api, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ code, state }),
|
|
});
|
|
wecomLoginDialog.value = null;
|
|
persistLoginUser(data);
|
|
sessionStorage.removeItem('hxops_wecom_state');
|
|
await completeOAuthLogin();
|
|
return true;
|
|
} catch (e) {
|
|
const err = e as BusinessError;
|
|
const rawError = String(err.message || '');
|
|
const errorCode = String(err.code || '');
|
|
let friendly = rawError || t('login.wecomLoginFailed');
|
|
if (rawError.includes('Invalid or expired WeCom state')) friendly = t('login.wecomStateExpired');
|
|
else if (rawError.includes('bind WeCom account') || rawError.includes('No linked account found')) {
|
|
friendly = t('login.wecomBindRequired');
|
|
} else if (rawError.includes('Account is disabled')) friendly = t('login.wecomAccountDisabled');
|
|
console.error(e);
|
|
msg.error(friendly);
|
|
sessionStorage.removeItem('hxops_wecom_state');
|
|
if (errorCode === 'WECOM_BIND_INPUT_REQUIRED') {
|
|
openWecomBindPrompt({ error: rawError, error_code: errorCode });
|
|
} else {
|
|
openWecomLoginDialog({ error: rawError || t('login.wecomLoginFailed'), error_code: errorCode });
|
|
}
|
|
clearWecomCallbackQuery();
|
|
return true;
|
|
} finally {
|
|
isWecomLoggingIn.value = false;
|
|
}
|
|
};
|
|
|
|
const handleRegister = async () => {
|
|
const form = registerForm.value;
|
|
if (!form.username || !form.password || !form.real_name || !form.employee_id || !form.phone_number) {
|
|
msg.warning(t('register.inputError'));
|
|
return;
|
|
}
|
|
try {
|
|
await requestJson('/api/user/register', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(form),
|
|
});
|
|
msg.success(t('register.success'));
|
|
showRegisterModal.value = false;
|
|
registerForm.value = {
|
|
username: '',
|
|
password: '',
|
|
email: '',
|
|
real_name: '',
|
|
employee_id: '',
|
|
phone_number: '',
|
|
};
|
|
} catch (e) {
|
|
console.error('Register error:', e);
|
|
msg.error((e as Error)?.message || t('register.requestFailed'));
|
|
}
|
|
};
|
|
|
|
return {
|
|
loginUsername,
|
|
loginPassword,
|
|
rememberMe,
|
|
showRegisterModal,
|
|
showForgotPasswordModal,
|
|
registerForm,
|
|
forgotPasswordForm,
|
|
isWecomLoggingIn,
|
|
wecomLoginDialog,
|
|
wecomBindPrompt,
|
|
clearWecomCallbackQuery,
|
|
handleForgotPassword,
|
|
handleLogin,
|
|
tryCasdoorCallbackLogin,
|
|
handleWecomLogin,
|
|
submitWecomCompleteBind,
|
|
tryWecomCallbackLogin,
|
|
handleRegister,
|
|
DEFAULT_POST_LOGIN_AGENT_ID,
|
|
};
|
|
}
|