81 lines
2.5 KiB
JavaScript
81 lines
2.5 KiB
JavaScript
window.onload = function() {
|
||
autoLogin();
|
||
};
|
||
|
||
var checkInfo = {};
|
||
|
||
checkInfo.checkUsername = function() {
|
||
let username = document.getElementById('username').value;
|
||
if (username.length < 1) {
|
||
document.getElementById('usernameError').textContent = '用户名不能为空';
|
||
return false;
|
||
}
|
||
document.getElementById('usernameError').textContent = '';
|
||
return true;
|
||
}
|
||
|
||
checkInfo.checkPassword = function() {
|
||
let password = document.getElementById('password').value;
|
||
let regexPassword = /^[A-Za-z0-9\W_]{6,20}$/;
|
||
if (!regexPassword.test(password)) {
|
||
document.getElementById('loginError').textContent = "密码须为长度为6-20位字母、数字或符号";
|
||
return false;
|
||
}
|
||
document.getElementById('loginError').textContent = '';
|
||
return true;
|
||
}
|
||
|
||
function submitForm() {
|
||
if (checkInfo.checkUsername() && checkInfo.checkPassword()) {
|
||
document.getElementById('encryptedPassword').value = md5(
|
||
document.getElementById('password').value
|
||
);
|
||
login();
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
// 登录函数
|
||
async function login() {
|
||
const username = document.getElementById('username').value;
|
||
const encryptedPassword = document.getElementById('encryptedPassword').value;
|
||
try {
|
||
const response = await fetch('/login', {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json'
|
||
},
|
||
body: JSON.stringify({ username: username, password: encryptedPassword }),
|
||
credentials: 'include' // 确保请求包含凭据(cookies)
|
||
});
|
||
const data = await response.json();
|
||
if (response.ok) {
|
||
alert('登录成功');
|
||
// 自动跳转到主页
|
||
window.location.href = data.redirect;
|
||
} else {
|
||
document.getElementById('loginError').textContent = data.message;
|
||
}
|
||
} catch (error) {
|
||
alert('数据库错误,请稍后再试');
|
||
}
|
||
}
|
||
|
||
// 自动登录函数
|
||
async function autoLogin() {
|
||
const token = localStorage.getItem('token');
|
||
if (token) {
|
||
const response = await fetch('/index', {
|
||
headers: {
|
||
'Authorization': 'Bearer ' + token
|
||
}
|
||
});
|
||
if (response.ok) {
|
||
document.getElementById('content').innerText = '已自动登录';
|
||
} else {
|
||
document.getElementById('content').innerText = '自动登录失败';
|
||
}
|
||
}
|
||
}
|