65 lines
2.8 KiB
JavaScript
65 lines
2.8 KiB
JavaScript
import { apiClient } from '/static/portal/common/api-client.js?v=20260913';
|
|
import {
|
|
clearAuthSession,
|
|
setAuthSession,
|
|
staffHomeForRoles,
|
|
startAuthSync,
|
|
} from '/static/portal/common/auth.js';
|
|
|
|
const REASON_MESSAGES = Object.freeze({
|
|
'account-switched': '当前浏览器中的账号已切换,请重新登录后继续。',
|
|
'signed-out': '您已安全退出登录。',
|
|
'session-expired': '登录已过期或长时间未操作,请重新登录。',
|
|
});
|
|
|
|
export function setupLogin({ mode }) {
|
|
startAuthSync();
|
|
const form = document.querySelector('[data-login-form]');
|
|
const alert = document.querySelector('[data-login-alert]');
|
|
const submit = form.querySelector('[type="submit"]');
|
|
const allowedRoles = mode === 'customer'
|
|
? ['customer']
|
|
: ['risk_operator', 'operator', 'advisor', 'admin', 'super_admin'];
|
|
const reason = new URLSearchParams(window.location.search).get('reason');
|
|
if (REASON_MESSAGES[reason]) {
|
|
alert.textContent = REASON_MESSAGES[reason];
|
|
alert.classList.add('form-alert--visible', 'form-alert--info');
|
|
}
|
|
|
|
form.addEventListener('submit', async (event) => {
|
|
event.preventDefault();
|
|
alert.classList.remove('form-alert--visible', 'form-alert--info');
|
|
submit.disabled = true;
|
|
const formData = new FormData(form);
|
|
const username = String(formData.get('username') || '').trim();
|
|
const password = String(formData.get('password') || '');
|
|
try {
|
|
const response = await apiClient.post('A034', { username, password });
|
|
const roles = Array.isArray(response.data.roles) ? response.data.roles : [];
|
|
if (!roles.some((role) => allowedRoles.includes(role))) {
|
|
clearAuthSession();
|
|
throw new Error(mode === 'customer' ? '该账号不是客户账号,请使用后台登录入口。' : '该账号没有后台访问权限。');
|
|
}
|
|
setAuthSession(response.data, username);
|
|
apiClient.track('login_result', { mode, succeeded: true, roles });
|
|
const next = new URLSearchParams(window.location.search).get('next');
|
|
let fallback = mode === 'customer' ? '/portal/customer/dashboard/' : staffHomeForRoles(roles);
|
|
let onboardingRequired = false;
|
|
if (mode === 'customer') {
|
|
const onboarding = await apiClient.get('ONB001');
|
|
onboardingRequired = Boolean(onboarding.data?.required);
|
|
if (onboardingRequired) fallback = '/portal/customer/risk-questionnaire/';
|
|
}
|
|
const target = !onboardingRequired && next?.startsWith('/portal/') ? next : fallback;
|
|
window.location.assign(target);
|
|
} catch (error) {
|
|
apiClient.reportError(error);
|
|
apiClient.track('login_result', { mode, succeeded: false, errorCode: error.code || 'ROLE_MISMATCH' });
|
|
alert.textContent = error.message || '登录未完成';
|
|
alert.classList.add('form-alert--visible');
|
|
} finally {
|
|
submit.disabled = false;
|
|
}
|
|
});
|
|
}
|