Files
AIEC-new/AIEC-server/auth/components/auth-handler.js
2025-10-17 09:31:28 +08:00

404 lines
12 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 认证处理器 - 处理登录/注册页面的交互逻辑
*/
class AuthHandler {
constructor() {
this.countdownTimer = null;
this.countdownSeconds = 60;
this.init();
}
/**
* 初始化
*/
init() {
this.setupEventListeners();
this.setupFormValidation();
this.checkPageType();
}
/**
* 检查页面类型并设置相应逻辑
*/
checkPageType() {
const loginForm = document.getElementById('loginForm');
const registerForm = document.getElementById('registerForm');
if (loginForm) {
this.setupLoginForm();
}
if (registerForm) {
this.setupRegisterForm();
}
}
/**
* 设置事件监听器
*/
setupEventListeners() {
// 发送验证码按钮
const sendCodeBtn = document.getElementById('sendCodeBtn');
if (sendCodeBtn) {
sendCodeBtn.addEventListener('click', (e) => {
e.preventDefault();
this.handleSendCode();
});
}
// 页面加载时检查登录状态
this.checkAuthStatus();
}
/**
* 设置表单验证
*/
setupFormValidation() {
// 账号字段实时验证
FormValidator.setupRealTimeValidation('account', (value) => FormValidator.validateAccount(value));
// 验证码字段实时验证
FormValidator.setupRealTimeValidation('verifyCode', (value) => FormValidator.validateVerifyCode(value));
// 用户名字段实时验证(仅注册页面)
const usernameField = document.getElementById('username');
if (usernameField) {
FormValidator.setupRealTimeValidation('username', (value) => FormValidator.validateUsername(value));
}
}
/**
* 设置登录表单
*/
setupLoginForm() {
const loginForm = document.getElementById('loginForm');
loginForm.addEventListener('submit', async (e) => {
e.preventDefault();
await this.handleLogin();
});
}
/**
* 设置注册表单
*/
setupRegisterForm() {
const registerForm = document.getElementById('registerForm');
registerForm.addEventListener('submit', async (e) => {
e.preventDefault();
await this.handleRegister();
});
}
/**
* 处理发送验证码
*/
async handleSendCode() {
const accountField = document.getElementById('account');
const sendCodeBtn = document.getElementById('sendCodeBtn');
if (!accountField || !sendCodeBtn) return;
const account = accountField.value.trim();
// 验证账号格式
const accountValidation = FormValidator.validateAccount(account);
if (!accountValidation.valid) {
FormValidator.showError('account', accountValidation.message);
this.showStatus('error', accountValidation.message);
return;
}
// 清除账号错误信息
FormValidator.clearError('account');
// 禁用按钮并显示加载状态
sendCodeBtn.disabled = true;
sendCodeBtn.classList.add('loading');
sendCodeBtn.textContent = '发送中...';
try {
// 判断是登录还是注册页面
const isRegisterPage = window.location.pathname.includes('register');
const type = isRegisterPage ? 'register' : 'login';
const result = await AuthService.sendVerifyCode(account, type);
if (result.success) {
this.showStatus('success', result.message);
this.startCountdown();
} else {
this.showStatus('error', result.message);
// 恢复按钮状态
sendCodeBtn.disabled = false;
sendCodeBtn.classList.remove('loading');
sendCodeBtn.textContent = '发送验证码';
}
} catch (error) {
console.error('Send code error:', error);
this.showStatus('error', '发送失败,请稍后重试');
// 恢复按钮状态
sendCodeBtn.disabled = false;
sendCodeBtn.classList.remove('loading');
sendCodeBtn.textContent = '发送验证码';
}
}
/**
* 处理登录
*/
async handleLogin() {
const accountField = document.getElementById('account');
const codeField = document.getElementById('verifyCode');
const loginBtn = document.getElementById('loginBtn');
if (!accountField || !codeField || !loginBtn) return;
const account = accountField.value.trim();
const verifyCode = codeField.value.trim();
// 验证表单
const accountValidation = FormValidator.validateAccount(account);
const codeValidation = FormValidator.validateVerifyCode(verifyCode);
let hasError = false;
if (!accountValidation.valid) {
FormValidator.showError('account', accountValidation.message);
hasError = true;
} else {
FormValidator.clearError('account');
}
if (!codeValidation.valid) {
FormValidator.showError('verifyCode', codeValidation.message);
hasError = true;
} else {
FormValidator.clearError('verifyCode');
}
if (hasError) {
this.showStatus('error', '请检查输入信息');
return;
}
// 显示加载状态
loginBtn.disabled = true;
loginBtn.classList.add('loading');
loginBtn.textContent = '登录中...';
try {
const result = await AuthService.login(account, verifyCode);
if (result.success) {
this.showStatus('success', result.message);
// 登录成功,延迟跳转
setTimeout(() => {
this.redirectAfterLogin();
}, 1000);
} else {
this.showStatus('error', result.message);
// 恢复按钮状态
loginBtn.disabled = false;
loginBtn.classList.remove('loading');
loginBtn.textContent = '登录';
}
} catch (error) {
console.error('Login error:', error);
this.showStatus('error', '登录失败,请稍后重试');
// 恢复按钮状态
loginBtn.disabled = false;
loginBtn.classList.remove('loading');
loginBtn.textContent = '登录';
}
}
/**
* 处理注册
*/
async handleRegister() {
const usernameField = document.getElementById('username');
const accountField = document.getElementById('account');
const codeField = document.getElementById('verifyCode');
const registerBtn = document.getElementById('registerBtn');
if (!usernameField || !accountField || !codeField || !registerBtn) return;
const username = usernameField.value.trim();
const account = accountField.value.trim();
const verifyCode = codeField.value.trim();
// 验证表单
const usernameValidation = FormValidator.validateUsername(username);
const accountValidation = FormValidator.validateAccount(account);
const codeValidation = FormValidator.validateVerifyCode(verifyCode);
let hasError = false;
if (!usernameValidation.valid) {
FormValidator.showError('username', usernameValidation.message);
hasError = true;
} else {
FormValidator.clearError('username');
}
if (!accountValidation.valid) {
FormValidator.showError('account', accountValidation.message);
hasError = true;
} else {
FormValidator.clearError('account');
}
if (!codeValidation.valid) {
FormValidator.showError('verifyCode', codeValidation.message);
hasError = true;
} else {
FormValidator.clearError('verifyCode');
}
if (hasError) {
this.showStatus('error', '请检查输入信息');
return;
}
// 显示加载状态
registerBtn.disabled = true;
registerBtn.classList.add('loading');
registerBtn.textContent = '注册中...';
try {
const result = await AuthService.register(username, account, verifyCode);
if (result.success) {
this.showStatus('success', result.message);
// 注册成功,延迟跳转
setTimeout(() => {
this.redirectAfterLogin();
}, 1000);
} else {
this.showStatus('error', result.message);
// 恢复按钮状态
registerBtn.disabled = false;
registerBtn.classList.remove('loading');
registerBtn.textContent = '注册';
}
} catch (error) {
console.error('Register error:', error);
this.showStatus('error', '注册失败,请稍后重试');
// 恢复按钮状态
registerBtn.disabled = false;
registerBtn.classList.remove('loading');
registerBtn.textContent = '注册';
}
}
/**
* 开始倒计时
*/
startCountdown() {
const sendCodeBtn = document.getElementById('sendCodeBtn');
if (!sendCodeBtn) return;
let seconds = this.countdownSeconds;
const updateButton = () => {
sendCodeBtn.textContent = `${seconds}秒后重试`;
sendCodeBtn.disabled = true;
sendCodeBtn.classList.add('countdown');
};
updateButton();
this.countdownTimer = setInterval(() => {
seconds--;
if (seconds > 0) {
updateButton();
} else {
// 倒计时结束
clearInterval(this.countdownTimer);
sendCodeBtn.textContent = '发送验证码';
sendCodeBtn.disabled = false;
sendCodeBtn.classList.remove('loading', 'countdown');
}
}, 1000);
}
/**
* 显示状态消息
* @param {string} type - 消息类型success/error/info/warning
* @param {string} message - 消息内容
*/
showStatus(type, message) {
const statusElement = document.getElementById('statusMessage');
const statusText = document.getElementById('statusText');
if (!statusElement || !statusText) return;
// 清除之前的类
statusElement.className = 'mt-4 p-3 rounded-lg';
statusElement.classList.add(type);
statusText.textContent = message;
statusElement.classList.remove('hidden');
// 成功消息3秒后自动隐藏
if (type === 'success') {
setTimeout(() => {
statusElement.classList.add('hidden');
}, 3000);
}
}
/**
* 检查认证状态
*/
async checkAuthStatus() {
try {
const authStatus = await AuthService.checkAuthStatus();
if (authStatus.isAuthenticated) {
// 已登录,重定向到首页
this.redirectAfterLogin();
}
} catch (error) {
console.error('Check auth status error:', error);
}
}
/**
* 登录后重定向
*/
redirectAfterLogin() {
// 获取跳转目标,默认为首页
const urlParams = new URLSearchParams(window.location.search);
const redirectUrl = urlParams.get('redirect') || '../../index.html';
window.location.href = redirectUrl;
}
/**
* 销毁实例
*/
destroy() {
if (this.countdownTimer) {
clearInterval(this.countdownTimer);
}
}
}
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
window.authHandler = new AuthHandler();
});
// 页面卸载时清理
window.addEventListener('beforeunload', () => {
if (window.authHandler) {
window.authHandler.destroy();
}
});