5 Commits
v3.0.0 ... main

Author SHA1 Message Date
dqzboy
d5758885bc docs: README.md 2026-01-05 09:33:38 +08:00
dqzboy
e817fc85e2 feat: optimize document management UI and error handling 2025-12-31 14:25:33 +08:00
dqzboy
f181c7a135 feat: Update the styling of the user center interface and the administrator pages 2025-12-31 12:36:54 +08:00
dqzboy
da2111e998 feat: Add user password reset and username modification features 2025-12-31 12:29:38 +08:00
dqzboy
da0950b0c4 docs: update README 2025-11-12 15:31:53 +08:00
15 changed files with 3854 additions and 1194 deletions

1
.gitignore vendored
View File

@@ -161,3 +161,4 @@ cython_debug/
node_modules
.DS_Store
hubcmdui/package-lock.json
hubcmdui/data/app.db

View File

@@ -173,6 +173,8 @@ docker logs -f [容器ID或名称]
> HubCMD-UI 手动安装教程:[点击查看教程](hubcmdui/README.md)
> HubCMD-UI 演示环境 [点击查看](https://ufxsgwxleywi.ap-southeast-1.clawcloudrun.com/)
<br/>
<table>
<tr>
@@ -236,7 +238,7 @@ docker logs -f [容器ID或名称]
</tbody>
</table>
##### *Telegram Bot: [点击联系](https://t.me/WiseAidBot) E-Mail: support@dqzboy.com*
##### *Telegram Bot: [点击联系](https://t.me/RelayHubBot) E-Mail: support@dqzboy.com*
**仅接受长期稳定运营,信誉良好的商家*

View File

@@ -73,7 +73,12 @@ app.use('/api', (req, res, next) => {
'/api/config',
'/api/monitoring-config',
'/api/documentation',
'/api/documentation/file'
'/api/documentation/file',
'/api/captcha',
'/api/auth/captcha',
'/api/auth/request-reset-token',
'/api/auth/reset-password',
'/api/auth/validate-reset-token'
];
// 如果是公共API或用户已登录则继续

View File

@@ -82,6 +82,31 @@ router.post('/change-password', requireLogin, async (req, res) => {
}
});
// 修改用户名
router.post('/change-username', requireLogin, async (req, res) => {
const { newUsername, password } = req.body;
// 用户名格式校验
const usernameRegex = /^[a-zA-Z0-9_]{3,20}$/;
if (!usernameRegex.test(newUsername)) {
return res.status(400).json({ error: '用户名格式不正确3-20位只能包含字母、数字和下划线' });
}
try {
const currentUsername = req.session.user.username;
const result = await userServiceDB.changeUsername(currentUsername, newUsername, password);
// 更新session中的用户名
req.session.user.username = newUsername;
logger.info(`用户 ${currentUsername} 已修改用户名为 ${newUsername}`);
res.json({ success: true, newUsername });
} catch (error) {
logger.error('修改用户名失败:', error);
res.status(400).json({ error: error.message || '修改用户名失败' });
}
});
// 获取用户信息
router.get('/user-info', requireLogin, async (req, res) => {
try {
@@ -138,6 +163,79 @@ router.get('/check-session', (req, res) => {
});
});
// 请求密码重置令牌(需要用户名验证)
router.post('/request-reset-token', async (req, res) => {
const { username, captcha } = req.body;
// 验证码检查
if (req.session.captcha !== parseInt(captcha)) {
logger.warn(`重置密码验证码验证失败: ${username}`);
return res.status(401).json({ error: '验证码错误' });
}
try {
// 验证用户是否存在
const user = await userServiceDB.getUserByUsername(username);
if (!user) {
logger.warn(`密码重置请求失败,用户不存在: ${username}`);
return res.status(404).json({ error: '用户不存在' });
}
// 生成重置令牌
const token = userServiceDB.generateResetToken(username);
logger.info(`用户 ${username} 请求了密码重置令牌`);
// 返回令牌(在生产环境中,这应该通过邮件发送)
res.json({
success: true,
token,
message: '重置令牌已生成有效期10分钟',
expiresIn: '10分钟'
});
} catch (error) {
logger.error('生成重置令牌失败:', error);
res.status(500).json({ error: '生成重置令牌失败', details: error.message });
}
});
// 使用令牌重置密码
router.post('/reset-password', async (req, res) => {
const { token, newPassword, confirmPassword } = req.body;
// 验证密码是否匹配
if (newPassword !== confirmPassword) {
return res.status(400).json({ error: '两次输入的密码不一致' });
}
// 密码复杂度校验
const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[.,\-_+=()[\]{}|\\;:'"<>?/@$!%*#?&])[A-Za-z\d.,\-_+=()[\]{}|\\;:'"<>?/@$!%*#?&]{8,16}$/;
if (!passwordRegex.test(newPassword)) {
return res.status(400).json({ error: '密码需要8-16位包含至少一个字母、一个数字和一个特殊字符' });
}
try {
const result = await userServiceDB.resetPasswordWithToken(token, newPassword);
logger.info(`用户 ${result.username} 通过重置令牌成功修改了密码`);
res.json({ success: true, message: '密码重置成功,请使用新密码登录' });
} catch (error) {
logger.error('重置密码失败:', error);
res.status(400).json({ error: error.message || '重置密码失败' });
}
});
// 验证重置令牌是否有效
router.post('/validate-reset-token', (req, res) => {
const { token } = req.body;
const username = userServiceDB.validateResetToken(token);
if (username) {
res.json({ valid: true, username });
} else {
res.status(400).json({ valid: false, error: '令牌无效或已过期' });
}
});
logger.success('✓ 认证路由已加载');
// 导出路由

View File

@@ -60,7 +60,7 @@ class DocumentationServiceDB {
);
if (!document) {
throw new Error(`文档 ${docId} 不存在`);
return null;
}
return {

View File

@@ -155,6 +155,57 @@ class UserServiceDB {
}
}
/**
* 修改用户名
*/
async changeUsername(currentUsername, newUsername, password) {
try {
const user = await this.getUserByUsername(currentUsername);
if (!user) {
throw new Error('用户不存在');
}
// 验证密码
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
throw new Error('密码不正确');
}
// 验证新用户名格式
if (!this.isUsernameValid(newUsername)) {
throw new Error('用户名格式不正确3-20位只能包含字母、数字和下划线');
}
// 检查新用户名是否已存在
const existingUser = await this.getUserByUsername(newUsername);
if (existingUser) {
throw new Error('该用户名已被使用');
}
// 更新用户名
await database.run(
'UPDATE users SET username = ?, updated_at = ? WHERE username = ?',
[newUsername, new Date().toISOString(), currentUsername]
);
logger.info(`用户 ${currentUsername} 已成功修改用户名为 ${newUsername}`);
return { success: true, newUsername };
} catch (error) {
logger.error('修改用户名失败:', error);
throw error;
}
}
/**
* 验证用户名格式
*/
isUsernameValid(username) {
// 3-20位只能包含字母、数字和下划线
const usernameRegex = /^[a-zA-Z0-9_]{3,20}$/;
return usernameRegex.test(username);
}
/**
* 验证密码复杂度
*/
@@ -185,6 +236,132 @@ class UserServiceDB {
throw error;
}
}
/**
* 生成密码重置令牌
* 返回一个临时令牌存储在内存中有效期10分钟
*/
generateResetToken(username) {
const crypto = require('crypto');
const token = crypto.randomBytes(32).toString('hex');
const expiry = Date.now() + 10 * 60 * 1000; // 10分钟有效期
// 存储在内存中(简单实现)
if (!this.resetTokens) {
this.resetTokens = {};
}
this.resetTokens[token] = {
username,
expiry
};
// 清理过期令牌
this.cleanExpiredTokens();
logger.info(`为用户 ${username} 生成了密码重置令牌`);
return token;
}
/**
* 清理过期的重置令牌
*/
cleanExpiredTokens() {
if (!this.resetTokens) return;
const now = Date.now();
for (const token in this.resetTokens) {
if (this.resetTokens[token].expiry < now) {
delete this.resetTokens[token];
}
}
}
/**
* 验证重置令牌
*/
validateResetToken(token) {
if (!this.resetTokens || !this.resetTokens[token]) {
return null;
}
const tokenData = this.resetTokens[token];
if (tokenData.expiry < Date.now()) {
delete this.resetTokens[token];
return null;
}
return tokenData.username;
}
/**
* 使用令牌重置密码
*/
async resetPasswordWithToken(token, newPassword) {
try {
const username = this.validateResetToken(token);
if (!username) {
throw new Error('重置令牌无效或已过期');
}
// 验证新密码复杂度
if (!this.isPasswordComplex(newPassword)) {
throw new Error('新密码不符合复杂度要求需要8-16位包含字母、数字和特殊字符');
}
const user = await this.getUserByUsername(username);
if (!user) {
throw new Error('用户不存在');
}
// 更新密码
const hashedNewPassword = await bcrypt.hash(newPassword, 10);
await database.run(
'UPDATE users SET password = ?, updated_at = ? WHERE username = ?',
[hashedNewPassword, new Date().toISOString(), username]
);
// 删除使用过的令牌
delete this.resetTokens[token];
logger.info(`用户 ${username} 密码已通过重置令牌成功修改`);
return { success: true, username };
} catch (error) {
logger.error('重置密码失败:', error);
throw error;
}
}
/**
* 直接重置用户密码(管理员功能,无需旧密码)
* 用于忘记密码时,通过验证用户名来重置
*/
async forceResetPassword(username, newPassword) {
try {
const user = await this.getUserByUsername(username);
if (!user) {
throw new Error('用户不存在');
}
// 验证新密码复杂度
if (!this.isPasswordComplex(newPassword)) {
throw new Error('新密码不符合复杂度要求需要8-16位包含字母、数字和特殊字符');
}
// 更新密码
const hashedNewPassword = await bcrypt.hash(newPassword, 10);
await database.run(
'UPDATE users SET password = ?, updated_at = ? WHERE username = ?',
[hashedNewPassword, new Date().toISOString(), username]
);
logger.info(`用户 ${username} 密码已被强制重置`);
return { success: true };
} catch (error) {
logger.error('强制重置密码失败:', error);
throw error;
}
}
}
module.exports = new UserServiceDB();

File diff suppressed because it is too large Load Diff

View File

@@ -365,7 +365,7 @@
async function loadDocument(id) {
try {
const response = await fetch(`/api/documents/${id}`, {
const response = await fetch(`/api/documentation/documents/${id}`, {
credentials: 'same-origin'
});
@@ -426,7 +426,7 @@
document.getElementById('loadingOverlay').style.display = 'flex';
try {
const url = currentDocId ? `/api/documents/${currentDocId}` : '/api/documents';
const url = currentDocId ? `/api/documentation/documents/${currentDocId}` : '/api/documentation/documents';
const method = currentDocId ? 'PUT' : 'POST';
const response = await fetch(url, {

View File

@@ -815,14 +815,12 @@
// 根据标签数量判断是否显示警告
let warningMessage = '';
let loadAllBtnDisabled = false;
if (tagCount > 1000) {
warningMessage = `<div class="tag-count-warning">
<i class="fas fa-exclamation-triangle"></i>
<p>该镜像包含 <strong>${tagCount}</strong> 个标签,加载全部可能会很慢。建议使用分页浏览或利用搜索功能查找特定标签。</p>
</div>`;
loadAllBtnDisabled = true;
} else if (tagCount > 500) {
warningMessage = `<div class="tag-count-warning moderate">
<i class="fas fa-info-circle"></i>
@@ -851,7 +849,7 @@
<div class="tag-search-container">
<input type="text" id="tagSearchInput" placeholder="搜索TAG..." onkeyup="filterTags()">
</div>
<button id="loadAllTagsBtn" class="load-all-btn" onclick="loadAllTags()" ${loadAllBtnDisabled ? 'disabled' : ''}>
<button id="loadAllTagsBtn" class="load-all-btn" onclick="loadAllTags()">
<i class="fas fa-cloud-download-alt"></i> 加载全部TAG
</button>
</div>
@@ -1530,12 +1528,6 @@
// 显示指定的文档
function showDocument(index) {
// 清理之前的返回顶部按钮
const existingBackToTopBtn = document.querySelector('.back-to-top-btn');
if (existingBackToTopBtn) {
existingBackToTopBtn.remove();
}
if (!window.documentationData || !Array.isArray(window.documentationData)) {
console.error('文档数据不可用');
return;
@@ -1793,42 +1785,26 @@
}
container.appendChild(docMetaDiv);
// 添加返回顶部按钮(如果内容很长)
if (docContentDiv.scrollHeight > 1000) {
const backToTopBtn = document.createElement('button');
// 添加返回顶部按钮
let backToTopBtn = document.querySelector('.back-to-top-btn');
if (!backToTopBtn) {
backToTopBtn = document.createElement('button');
backToTopBtn.className = 'back-to-top-btn';
backToTopBtn.innerHTML = '<i class="fas fa-arrow-up"></i>';
backToTopBtn.style.cssText = `
position: fixed;
bottom: 2rem;
right: 2rem;
width: 3rem;
height: 3rem;
border-radius: 50%;
background: var(--primary-color);
color: white;
border: none;
cursor: pointer;
box-shadow: 0 4px 12px rgba(61, 124, 244, 0.3);
z-index: 1000;
opacity: 0.8;
transition: all 0.3s ease;
`;
backToTopBtn.title = '返回顶部';
backToTopBtn.onclick = () => {
container.scrollIntoView({ behavior: 'smooth' });
};
backToTopBtn.onmouseenter = () => {
backToTopBtn.style.opacity = '1';
backToTopBtn.style.transform = 'scale(1.1)';
};
backToTopBtn.onmouseleave = () => {
backToTopBtn.style.opacity = '0.8';
backToTopBtn.style.transform = 'scale(1)';
window.scrollTo({ top: 0, behavior: 'smooth' });
};
document.body.appendChild(backToTopBtn);
// 当切换文档时清理按钮
container.setAttribute('data-back-to-top', 'true');
// 监听滚动事件
window.addEventListener('scroll', () => {
if (window.scrollY > 300) {
backToTopBtn.classList.add('visible');
} else {
backToTopBtn.classList.remove('visible');
}
});
}
} catch (error) {

View File

@@ -432,7 +432,13 @@ function refreshStoppedContainers() {
tbody.innerHTML = '';
if (containers.length === 0) {
tbody.innerHTML = '<tr><td colspan="4" style="text-align: center;">没有已停止的容器</td></tr>';
tbody.innerHTML = `
<tr>
<td colspan="4" class="stopped-containers-empty">
<i class="fas fa-check-circle"></i>
<p>所有容器运行正常,没有已停止的容器</p>
</td>
</tr>`;
return;
}
@@ -444,10 +450,10 @@ function refreshStoppedContainers() {
const row = `
<tr>
<td>${container.id}</td>
<td>${container.name}</td>
<td>${container.image ? container.image : '未知'}</td>
<td>${container.status}</td>
<td><code class="container-id-cell">${container.id}</code></td>
<td><span class="container-name-cell">${container.name}</span></td>
<td><span class="container-image-cell">${container.image ? container.image : '未知'}</span></td>
<td><span class="container-status-badge stopped"><i class="fas fa-stop-circle"></i> ${container.status}</span></td>
</tr>
`;
tbody.innerHTML += row;
@@ -455,8 +461,13 @@ function refreshStoppedContainers() {
})
.catch(error => {
console.error('获取已停止容器列表失败:', error);
document.getElementById('stoppedContainersBody').innerHTML =
'<tr><td colspan="4" style="text-align: center; color: red;">获取已停止容器列表失败</td></tr>';
document.getElementById('stoppedContainersBody').innerHTML = `
<tr>
<td colspan="4" class="table-empty-state">
<i class="fas fa-exclamation-triangle"></i>
<p>获取容器列表失败,请检查 Docker 服务状态</p>
</td>
</tr>`;
});
}

View File

@@ -1,5 +1,8 @@
// 用户认证相关功能
// 存储重置令牌
let currentResetToken = null;
// 登录函数
async function login() {
const username = document.getElementById('username').value;
@@ -82,10 +85,28 @@ async function refreshCaptcha() {
throw new Error(`验证码获取失败: ${response.status}`);
}
const data = await response.json();
document.getElementById('captchaText').textContent = data.captcha;
// 更新登录表单验证码
const captchaText = document.getElementById('captchaText');
if (captchaText) {
captchaText.textContent = data.captcha;
}
// 更新忘记密码表单验证码
const resetCaptchaText = document.getElementById('resetCaptchaText');
if (resetCaptchaText) {
resetCaptchaText.textContent = data.captcha;
}
} catch (error) {
// console.error('刷新验证码失败:', error);
document.getElementById('captchaText').textContent = '验证码加载失败,点击重试';
const captchaText = document.getElementById('captchaText');
if (captchaText) {
captchaText.textContent = '验证码加载失败,点击重试';
}
const resetCaptchaText = document.getElementById('resetCaptchaText');
if (resetCaptchaText) {
resetCaptchaText.textContent = '验证码加载失败,点击重试';
}
}
}
@@ -104,20 +125,171 @@ function showLoginModal() {
}
document.getElementById('loginModal').style.display = 'flex';
showLoginForm(); // 确保显示登录表单
refreshCaptcha();
}
// 显示登录表单
function showLoginForm() {
document.getElementById('loginTitle').textContent = '管理员登录';
document.getElementById('loginForm').style.display = 'block';
document.getElementById('forgotPasswordForm').style.display = 'none';
document.getElementById('resetPasswordForm').style.display = 'none';
currentResetToken = null;
refreshCaptcha();
}
// 显示忘记密码表单
function showForgotPassword() {
document.getElementById('loginTitle').textContent = '忘记密码';
document.getElementById('loginForm').style.display = 'none';
document.getElementById('forgotPasswordForm').style.display = 'block';
document.getElementById('resetPasswordForm').style.display = 'none';
refreshCaptcha();
}
// 显示重置密码表单
function showResetPasswordForm(token) {
document.getElementById('loginTitle').textContent = '重置密码';
document.getElementById('loginForm').style.display = 'none';
document.getElementById('forgotPasswordForm').style.display = 'none';
document.getElementById('resetPasswordForm').style.display = 'block';
if (token) {
currentResetToken = token;
document.getElementById('tokenValue').textContent = token;
document.getElementById('resetTokenDisplay').style.display = 'block';
}
}
// 请求重置令牌
async function requestResetToken() {
const username = document.getElementById('resetUsername').value;
const captcha = document.getElementById('resetCaptcha').value;
if (!username) {
core.showAlert('请输入用户名', 'error');
return;
}
if (!captcha) {
core.showAlert('请输入验证码', 'error');
return;
}
try {
core.showLoading();
const response = await fetch('/api/auth/request-reset-token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, captcha })
});
const data = await response.json();
if (response.ok) {
core.showAlert('重置令牌已生成有效期10分钟', 'success');
showResetPasswordForm(data.token);
} else {
core.showAlert(data.error || '获取重置令牌失败', 'error');
refreshCaptcha();
}
} catch (error) {
core.showAlert('获取重置令牌失败: ' + error.message, 'error');
refreshCaptcha();
} finally {
core.hideLoading();
}
}
// 重置密码
async function resetPassword() {
const newPassword = document.getElementById('resetNewPassword').value;
const confirmPassword = document.getElementById('resetConfirmPassword').value;
if (!newPassword || !confirmPassword) {
core.showAlert('请填写所有密码字段', 'error');
return;
}
if (newPassword !== confirmPassword) {
core.showAlert('两次输入的密码不一致', 'error');
return;
}
// 密码复杂度验证
const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[.,\-_+=()[\]{}|\\;:'"<>?/@$!%*#?&])[A-Za-z\d.,\-_+=()[\]{}|\\;:'"<>?/@$!%*#?&]{8,16}$/;
if (!passwordRegex.test(newPassword)) {
core.showAlert('密码需要8-16位包含至少一个字母、一个数字和一个特殊字符', 'error');
return;
}
if (!currentResetToken) {
core.showAlert('重置令牌无效,请重新获取', 'error');
showForgotPassword();
return;
}
try {
core.showLoading();
const response = await fetch('/api/auth/reset-password', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
token: currentResetToken,
newPassword,
confirmPassword
})
});
const data = await response.json();
if (response.ok) {
core.showAlert('密码重置成功!请使用新密码登录', 'success');
currentResetToken = null;
showLoginForm();
} else {
core.showAlert(data.error || '重置密码失败', 'error');
}
} catch (error) {
core.showAlert('重置密码失败: ' + error.message, 'error');
} finally {
core.hideLoading();
}
}
// 导出模块
const auth = {
init: function() {
// console.log('初始化认证模块...');
// 在这里可以添加认证模块初始化的相关代码
// 初始化忘记密码表单事件
const forgotPasswordForm = document.getElementById('forgotPasswordForm');
if (forgotPasswordForm) {
forgotPasswordForm.addEventListener('submit', function(e) {
e.preventDefault();
requestResetToken();
});
}
const resetPasswordForm = document.getElementById('resetPasswordForm');
if (resetPasswordForm) {
resetPasswordForm.addEventListener('submit', function(e) {
e.preventDefault();
resetPassword();
});
}
return Promise.resolve(); // 返回一个已解决的 Promise保持与其他模块一致
},
login,
logout,
refreshCaptcha,
showLoginModal
showLoginModal,
showLoginForm,
showForgotPassword,
showResetPasswordForm,
requestResetToken,
resetPassword
};
// 全局公开认证模块

View File

@@ -39,10 +39,10 @@ const documentManager = {
// 设置表头内容 (包含 ID 列)
thead.innerHTML = `
<tr>
<th style="width: 5%">#</th>
<th style="width: 25%">标题</th>
<th style="width: 20%">创建时间</th>
<th style="width: 20%">更新时间</th>
<th style="width: 6%">#</th>
<th style="width: 28%">文档标题</th>
<th style="width: 18%">创建时间</th>
<th style="width: 18%">更新时间</th>
<th style="width: 10%">状态</th>
<th style="width: 20%">操作</th>
</tr>
@@ -187,7 +187,13 @@ const documentManager = {
tbody.innerHTML = '';
if (documents.length === 0) {
tbody.innerHTML = '<tr><td colspan="6" style="text-align: center;">没有找到文档</td></tr>';
tbody.innerHTML = `
<tr>
<td colspan="6" class="table-empty-state">
<i class="fas fa-file-alt"></i>
<p>暂无文档,点击"新建文档"开始创建</p>
</td>
</tr>`;
return;
}
@@ -239,21 +245,21 @@ const documentManager = {
// console.warn(`解析文档时间失败:`, error, doc);
}
const statusClasses = doc.published ? 'status-badge status-running' : 'status-badge status-stopped';
const statusText = doc.published ? '已发布' : '未发布';
const statusClasses = doc.published ? 'doc-status-badge published' : 'doc-status-badge draft';
const statusText = doc.published ? '已发布' : '草稿';
const row = document.createElement('tr');
row.innerHTML = `
<td>${index + 1}</td>
<td>${doc.title || '无标题文档'}</td>
<td>${createdAt}</td>
<td>${updatedAt}</td>
<td><span class="table-row-num">${index + 1}</span></td>
<td><span class="doc-title-display">${doc.title || '无标题文档'}</span></td>
<td><span class="doc-date">${createdAt}</span></td>
<td><span class="doc-date">${updatedAt}</span></td>
<td><span class="${statusClasses}">${statusText}</span></td>
<td class="action-buttons">
<button class="action-btn edit-btn" title="编辑文档" onclick="documentManager.editDocument('${doc.id}')">
<i class="fas fa-edit"></i>
</button>
<button class="action-btn ${doc.published ? 'unpublish-btn' : 'publish-btn'}"
<button class="action-btn ${doc.published ? 'view-btn' : 'publish-btn'}"
title="${doc.published ? '取消发布' : '发布文档'}"
onclick="documentManager.togglePublish('${doc.id}')">
<i class="fas ${doc.published ? 'fa-toggle-off' : 'fa-toggle-on'}"></i>

View File

@@ -24,11 +24,11 @@ const menuManager = {
const thead = menuTable.querySelector('thead') || document.createElement('thead');
thead.innerHTML = `
<tr>
<th style="width: 5%">#</th>
<th style="width: 25%">文本 (Text)</th>
<th style="width: 40%">链接 (Link)</th>
<th style="width: 10%">新标签页 (New Tab)</th>
<th style="width: 20%">操作</th>
<th style="width: 6%">#</th>
<th style="width: 22%">菜单文本</th>
<th style="width: 38%">链接地址</th>
<th style="width: 12%">新标签页</th>
<th style="width: 22%">操作</th>
</tr>
`;
@@ -84,7 +84,24 @@ const menuManager = {
if (!Array.isArray(configMenuItems)) {
// console.error("configMenuItems 不是一个数组:", configMenuItems);
menuTableBody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: #ff4d4f;">菜单数据格式错误</td></tr>';
menuTableBody.innerHTML = `
<tr>
<td colspan="5" class="table-empty-state">
<i class="fas fa-exclamation-triangle"></i>
<p>菜单数据格式错误</p>
</td>
</tr>`;
return;
}
if (configMenuItems.length === 0) {
menuTableBody.innerHTML = `
<tr>
<td colspan="5" class="table-empty-state">
<i class="fas fa-list-ul"></i>
<p>暂无菜单项,点击"添加菜单项"开始创建</p>
</td>
</tr>`;
return;
}
@@ -92,10 +109,10 @@ const menuManager = {
const row = document.createElement('tr');
// 使用 index 作为临时 ID 进行操作
row.innerHTML = `
<td>${index + 1}</td>
<td>${item.text || ''}</td>
<td>${item.link || ''}</td>
<td>${item.newTab ? '是' : '否'}</td>
<td><span class="table-row-num">${index + 1}</span></td>
<td><span class="menu-text-display">${item.text || ''}</span></td>
<td><code class="menu-link-display">${item.link || ''}</code></td>
<td><span class="menu-newtab-badge ${item.newTab ? 'yes' : 'no'}">${item.newTab ? '是' : '否'}</span></td>
<td class="action-buttons">
<button class="action-btn edit-btn" title="编辑菜单" onclick="menuManager.editMenuItem(${index})">
<i class="fas fa-edit"></i>
@@ -114,6 +131,12 @@ const menuManager = {
const menuTableBody = document.getElementById('menuTableBody');
if (!menuTableBody) return;
// 移除空状态行(如果存在)
const emptyState = menuTableBody.querySelector('.table-empty-state');
if (emptyState) {
emptyState.closest('tr').remove();
}
// 如果已存在新行,则不重复添加
if (document.getElementById('new-menu-item-row')) {
document.getElementById('new-text').focus();
@@ -207,248 +230,324 @@ const menuManager = {
}
Swal.fire({
title: '<div class="edit-title"><i class="fas fa-edit"></i> 编辑菜单项</div>',
title: '',
html: `
<div class="edit-menu-form">
<div class="form-group">
<label for="edit-text">
<i class="fas fa-font"></i> 菜单文本
</label>
<div class="input-wrapper">
<input type="text" id="edit-text" class="modern-input" value="${item.text || ''}" placeholder="请输入菜单文本">
<span class="input-icon"><i class="fas fa-heading"></i></span>
<div class="swal-edit-container">
<div class="swal-edit-header">
<div class="swal-edit-icon">
<i class="fas fa-edit"></i>
</div>
<small class="form-hint">菜单项显示的文本,保持简洁明了</small>
<h2 class="swal-edit-title">编辑菜单项</h2>
<p class="swal-edit-subtitle">修改菜单显示文本和链接配置</p>
</div>
<div class="form-group">
<label for="edit-link">
<i class="fas fa-link"></i> 链接地址
</label>
<div class="input-wrapper">
<input type="text" id="edit-link" class="modern-input" value="${item.link || ''}" placeholder="请输入链接地址">
<span class="input-icon"><i class="fas fa-globe"></i></span>
<div class="swal-edit-form">
<div class="swal-form-group">
<label for="edit-text" class="swal-form-label">
<i class="fas fa-font"></i> 菜单文本
</label>
<div class="swal-input-wrapper">
<input type="text" id="edit-text" class="swal-modern-input" value="${item.text || ''}" placeholder="输入菜单显示文本">
</div>
<p class="swal-form-hint">用户在导航中看到的文字</p>
</div>
<small class="form-hint">完整URL路径例如: https://example.com或相对路径例如: /docs</small>
</div>
<div class="form-group toggle-switch">
<label for="edit-newTab" class="toggle-label-text">
<i class="fas fa-external-link-alt"></i> 在新标签页打开
</label>
<div class="toggle-switch-container">
<input type="checkbox" id="edit-newTab" class="toggle-input" ${item.newTab ? 'checked' : ''}>
<label for="edit-newTab" class="toggle-label"></label>
<span class="toggle-status">${item.newTab ? '是' : '否'}</span>
<div class="swal-form-group">
<label for="edit-link" class="swal-form-label">
<i class="fas fa-link"></i> 链接地址
</label>
<div class="swal-input-wrapper">
<input type="text" id="edit-link" class="swal-modern-input" value="${item.link || ''}" placeholder="https://example.com 或 /page">
</div>
<p class="swal-form-hint">点击菜单后跳转的URL</p>
</div>
</div>
<div class="form-preview">
<div class="preview-title"><i class="fas fa-eye"></i> 预览</div>
<div class="preview-content">
<a href="${item.link || '#'}" class="preview-link" target="${item.newTab ? '_blank' : '_self'}">
<span class="preview-text">${item.text || '菜单项'}</span>
${item.newTab ? '<i class="fas fa-external-link-alt preview-icon"></i>' : ''}
</a>
<div class="swal-form-group swal-toggle-group">
<div class="swal-toggle-left">
<label class="swal-form-label">
<i class="fas fa-external-link-alt"></i> 新标签页打开
</label>
<p class="swal-form-hint">是否在新窗口中打开链接</p>
</div>
<div class="swal-toggle-right">
<label class="swal-toggle-switch">
<input type="checkbox" id="edit-newTab" ${item.newTab ? 'checked' : ''}>
<span class="swal-toggle-slider"></span>
</label>
</div>
</div>
<div class="swal-preview-box">
<div class="swal-preview-label">
<i class="fas fa-eye"></i> 效果预览
</div>
<div class="swal-preview-content">
<a href="javascript:void(0)" class="swal-preview-link" id="preview-link-el">
<span id="preview-text-el">${item.text || '菜单项'}</span>
<i class="fas fa-external-link-alt swal-preview-external" id="preview-external-icon" style="${item.newTab ? '' : 'display:none'}"></i>
</a>
</div>
</div>
</div>
</div>
<style>
.edit-title {
.swal2-popup.swal2-modal {
border-radius: 20px !important;
padding: 0 !important;
overflow: hidden;
}
.swal-edit-container {
padding: 0;
}
.swal-edit-header {
background: linear-gradient(135deg, #3d7cfa 0%, #6366f1 100%);
padding: 2rem 2rem 1.75rem;
text-align: center;
position: relative;
}
.swal-edit-icon {
width: 56px;
height: 56px;
background: rgba(255,255,255,0.2);
border-radius: 16px;
display: inline-flex;
align-items: center;
justify-content: center;
margin-bottom: 1rem;
backdrop-filter: blur(10px);
}
.swal-edit-icon i {
font-size: 1.5rem;
color: #3085d6;
margin-bottom: 10px;
color: white;
}
.edit-menu-form {
text-align: left;
padding: 0 15px;
.swal-edit-title {
color: white;
font-size: 1.4rem;
font-weight: 700;
margin: 0 0 0.35rem 0;
}
.form-group {
margin-bottom: 20px;
position: relative;
.swal-edit-subtitle {
color: rgba(255,255,255,0.85);
font-size: 0.9rem;
margin: 0;
font-weight: 400;
}
.form-group label {
display: block;
margin-bottom: 8px;
.swal-edit-form {
padding: 1.75rem 2rem 1.5rem;
}
.swal-form-group {
margin-bottom: 1.35rem;
}
.swal-form-label {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.9rem;
font-weight: 600;
color: #444;
font-size: 0.95rem;
color: #334155;
margin-bottom: 0.6rem;
}
.input-wrapper {
.swal-form-label i {
color: #3d7cfa;
font-size: 0.85rem;
}
.swal-input-wrapper {
position: relative;
}
.modern-input {
.swal-modern-input {
width: 100%;
padding: 12px 40px 12px 15px;
border: 1px solid #ddd;
border-radius: 8px;
font-size: 1rem;
transition: all 0.3s ease;
box-shadow: 0 2px 5px rgba(0,0,0,0.05);
padding: 0.85rem 1rem;
border: 2px solid #e2e8f0;
border-radius: 12px;
font-size: 0.95rem;
transition: all 0.25s ease;
background: #f8fafc;
color: #1e293b;
box-sizing: border-box;
}
.modern-input:focus {
border-color: #3085d6;
box-shadow: 0 0 0 3px rgba(48, 133, 214, 0.2);
.swal-modern-input::placeholder {
color: #94a3b8;
}
.swal-modern-input:focus {
border-color: #3d7cfa;
background: white;
box-shadow: 0 0 0 4px rgba(61, 124, 250, 0.12);
outline: none;
}
.input-icon {
position: absolute;
right: 12px;
top: 50%;
transform: translateY(-50%);
color: #aaa;
.swal-form-hint {
font-size: 0.78rem;
color: #94a3b8;
margin: 0.4rem 0 0 0;
}
.form-hint {
display: block;
font-size: 0.8rem;
color: #888;
margin-top: 5px;
font-style: italic;
}
.toggle-switch {
.swal-toggle-group {
display: flex;
align-items: center;
justify-content: space-between;
align-items: center;
padding: 5px 0;
background: linear-gradient(135deg, #f1f5f9, #f8fafc);
padding: 1rem 1.25rem;
border-radius: 12px;
border: 1px solid #e2e8f0;
}
.toggle-label-text {
margin-bottom: 0 !important;
.swal-toggle-left {
flex: 1;
}
.toggle-switch-container {
display: flex;
align-items: center;
.swal-toggle-left .swal-form-label {
margin-bottom: 0.25rem;
}
.toggle-input {
display: none;
.swal-toggle-left .swal-form-hint {
margin: 0;
}
.toggle-label {
display: block;
width: 52px;
height: 26px;
background: #e6e6e6;
border-radius: 13px;
.swal-toggle-switch {
position: relative;
cursor: pointer;
transition: background 0.3s ease;
box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
display: inline-block;
width: 52px;
height: 28px;
}
.toggle-label:after {
content: '';
.swal-toggle-switch input {
opacity: 0;
width: 0;
height: 0;
}
.swal-toggle-slider {
position: absolute;
top: 3px;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: #cbd5e1;
transition: 0.3s;
border-radius: 28px;
}
.swal-toggle-slider:before {
position: absolute;
content: "";
height: 22px;
width: 22px;
left: 3px;
width: 20px;
height: 20px;
bottom: 3px;
background: white;
transition: 0.3s;
border-radius: 50%;
transition: transform 0.3s ease, box-shadow 0.3s ease;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
box-shadow: 0 2px 6px rgba(0,0,0,0.15);
}
.toggle-input:checked + .toggle-label {
background: #3085d6;
.swal-toggle-switch input:checked + .swal-toggle-slider {
background: linear-gradient(135deg, #10b981, #34d399);
}
.toggle-input:checked + .toggle-label:after {
transform: translateX(26px);
.swal-toggle-switch input:checked + .swal-toggle-slider:before {
transform: translateX(24px);
}
.toggle-status {
margin-left: 10px;
font-size: 0.9rem;
color: #666;
min-width: 20px;
.swal-preview-box {
margin-top: 1.5rem;
border: 2px dashed #e2e8f0;
border-radius: 12px;
padding: 1rem;
background: linear-gradient(135deg, #fafbfc, #f5f7fa);
}
.form-preview {
margin-top: 25px;
border: 1px dashed #ccc;
border-radius: 8px;
padding: 15px;
background-color: #f9f9f9;
}
.preview-title {
font-size: 0.9rem;
color: #666;
margin-bottom: 10px;
.swal-preview-label {
text-align: center;
font-size: 0.8rem;
color: #94a3b8;
margin-bottom: 0.75rem;
font-weight: 500;
}
.preview-content {
.swal-preview-label i {
margin-right: 0.35rem;
}
.swal-preview-content {
display: flex;
justify-content: center;
padding: 10px;
padding: 0.75rem;
background: white;
border-radius: 6px;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.preview-link {
display: flex;
.swal-preview-link {
display: inline-flex;
align-items: center;
color: #3085d6;
gap: 0.4rem;
color: #3d7cfa;
text-decoration: none;
font-weight: 500;
padding: 5px 10px;
border-radius: 4px;
transition: background 0.2s ease;
font-weight: 600;
font-size: 1rem;
padding: 0.5rem 1rem;
border-radius: 8px;
transition: all 0.2s ease;
}
.preview-link:hover {
background: #f0f7ff;
.swal-preview-link:hover {
background: rgba(61, 124, 250, 0.08);
}
.preview-text {
margin-right: 5px;
}
.preview-icon {
font-size: 0.8rem;
.swal-preview-external {
font-size: 0.75rem;
opacity: 0.7;
}
.swal2-actions {
padding: 0 2rem 1.75rem !important;
gap: 0.75rem !important;
margin: 0 !important;
}
.swal2-confirm {
background: linear-gradient(135deg, #3d7cfa, #6366f1) !important;
border-radius: 10px !important;
padding: 0.75rem 1.5rem !important;
font-weight: 600 !important;
font-size: 0.95rem !important;
box-shadow: 0 4px 14px rgba(61, 124, 250, 0.35) !important;
border: none !important;
}
.swal2-confirm:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(61, 124, 250, 0.45) !important;
}
.swal2-cancel {
background: #f1f5f9 !important;
color: #64748b !important;
border-radius: 10px !important;
padding: 0.75rem 1.5rem !important;
font-weight: 600 !important;
font-size: 0.95rem !important;
border: none !important;
}
.swal2-cancel:hover {
background: #e2e8f0 !important;
}
.swal2-validation-message {
background: #fef2f2 !important;
color: #dc2626 !important;
border-radius: 8px !important;
margin: 0 2rem 1rem !important;
padding: 0.75rem 1rem !important;
font-size: 0.9rem !important;
}
</style>
`,
showCancelButton: true,
confirmButtonText: '<i class="fas fa-save"></i> 保存',
cancelButtonText: '<i class="fas fa-times"></i> 取消',
confirmButtonColor: '#3085d6',
cancelButtonColor: '#6c757d',
width: '550px',
confirmButtonText: '<i class="fas fa-check"></i> 保存更改',
cancelButtonText: '取消',
width: '480px',
focusConfirm: false,
customClass: {
container: 'menu-edit-container',
popup: 'menu-edit-popup',
title: 'menu-edit-title',
confirmButton: 'menu-edit-confirm',
cancelButton: 'menu-edit-cancel'
showClass: {
popup: 'animate__animated animate__fadeInUp animate__faster'
},
hideClass: {
popup: 'animate__animated animate__fadeOutDown animate__faster'
},
didOpen: () => {
// 添加输入监听,更新预览
const textInput = document.getElementById('edit-text');
const linkInput = document.getElementById('edit-link');
const newTabToggle = document.getElementById('edit-newTab');
const toggleStatus = document.querySelector('.toggle-status');
const previewText = document.querySelector('.preview-text');
const previewLink = document.querySelector('.preview-link');
const previewIcon = document.querySelector('.preview-icon') || document.createElement('i');
if (!previewIcon.classList.contains('fas')) {
previewIcon.className = 'fas fa-external-link-alt preview-icon';
}
const previewTextEl = document.getElementById('preview-text-el');
const previewExternalIcon = document.getElementById('preview-external-icon');
const updatePreview = () => {
previewText.textContent = textInput.value || '菜单项';
previewLink.href = linkInput.value || '#';
previewLink.target = newTabToggle.checked ? '_blank' : '_self';
if (newTabToggle.checked) {
if (!previewLink.contains(previewIcon)) {
previewLink.appendChild(previewIcon);
}
} else {
if (previewLink.contains(previewIcon)) {
previewLink.removeChild(previewIcon);
}
}
previewTextEl.textContent = textInput.value || '菜单项';
previewExternalIcon.style.display = newTabToggle.checked ? '' : 'none';
};
textInput.addEventListener('input', updatePreview);
linkInput.addEventListener('input', updatePreview);
newTabToggle.addEventListener('change', () => {
toggleStatus.textContent = newTabToggle.checked ? '是' : '否';
updatePreview();
});
newTabToggle.addEventListener('change', updatePreview);
},
preConfirm: () => {
const text = document.getElementById('edit-text').value.trim();
@@ -456,12 +555,12 @@ const menuManager = {
const newTab = document.getElementById('edit-newTab').checked;
if (!text) {
Swal.showValidationMessage('<i class="fas fa-exclamation-circle"></i> 菜单文本不能为空');
Swal.showValidationMessage('菜单文本不能为空');
return false;
}
if (!link) {
Swal.showValidationMessage('<i class="fas fa-exclamation-circle"></i> 链接地址不能为空');
Swal.showValidationMessage('链接地址不能为空');
return false;
}

View File

@@ -163,22 +163,118 @@ function isPasswordComplex(password) {
return passwordRegex.test(password);
}
// 验证用户名格式
function isUsernameValid(username) {
// 3-20位只能包含字母、数字和下划线
const usernameRegex = /^[a-zA-Z0-9_]{3,20}$/;
return usernameRegex.test(username);
}
// 修改用户名
async function changeUsername(event) {
if (event) {
event.preventDefault();
}
const form = document.getElementById('changeUsernameForm');
const newUsername = form.querySelector('#ucNewUsername').value;
const password = form.querySelector('#ucUsernamePassword').value;
// 验证表单
if (!newUsername || !password) {
return core.showAlert('所有字段都不能为空', 'error');
}
// 用户名格式检查
if (!isUsernameValid(newUsername)) {
return core.showAlert('用户名格式不正确3-20位只能包含字母、数字和下划线', 'error');
}
// 显示加载状态
const submitButton = form.querySelector('button[type="submit"]');
const originalButtonText = submitButton.innerHTML;
submitButton.disabled = true;
submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 提交中...';
try {
const response = await fetch('/api/auth/change-username', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
newUsername,
password
})
});
// 无论成功与否,去除加载状态
submitButton.disabled = false;
submitButton.innerHTML = originalButtonText;
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || '修改用户名失败');
}
const data = await response.json();
// 清空表单
form.reset();
// 设置倒计时并显示
let countDown = 5;
Swal.fire({
title: '用户名修改成功',
html: `您的用户名已成功修改为 <b>${data.newUsername}</b>,系统将在 <b>${countDown}</b> 秒后自动退出,请使用新用户名重新登录。`,
icon: 'success',
timer: countDown * 1000,
timerProgressBar: true,
didOpen: () => {
const content = Swal.getHtmlContainer();
const timerInterval = setInterval(() => {
countDown--;
if (content) {
const b = content.querySelectorAll('b')[1]; // 获取第二个b标签倒计时
if (b) {
b.textContent = countDown > 0 ? countDown : 0;
}
}
if (countDown <= 0) clearInterval(timerInterval);
}, 1000);
},
allowOutsideClick: false,
showConfirmButton: true,
confirmButtonText: '确定'
}).then((result) => {
if (result.dismiss === Swal.DismissReason.timer || result.isConfirmed) {
auth.logout();
}
});
} catch (error) {
core.showAlert('修改用户名失败: ' + error.message, 'error');
}
}
// 检查密码强度
function checkUcPasswordStrength() {
const password = document.getElementById('ucNewPassword').value;
const strengthSpan = document.getElementById('ucPasswordStrength');
const strengthBar = document.getElementById('strengthBar');
const strengthIndicator = document.getElementById('strengthIndicator');
if (!password) {
strengthSpan.textContent = '';
if (strengthBar) strengthBar.style.width = '0%';
if (strengthSpan) strengthSpan.textContent = '';
if (strengthIndicator) {
strengthIndicator.className = 'strength-indicator';
strengthIndicator.style.width = '0';
}
return;
}
let strength = 0;
let strengthText = '';
let strengthColor = '';
let strengthWidth = '0%';
let strengthClass = '';
// 长度检查
if (password.length >= 8) strength++;
@@ -193,59 +289,55 @@ function checkUcPasswordStrength() {
// 包含特殊字符
if (/[.,\-_+=()[\]{}|\\;:'"<>?/@$!%*#?&]/.test(password)) strength++;
// 根据强度设置文本和颜色
switch(strength) {
case 0:
case 1:
strengthText = '密码强度:非常弱';
strengthColor = '#FF4136';
strengthWidth = '20%';
break;
case 2:
strengthText = '密码强度:弱';
strengthColor = '#FF851B';
strengthWidth = '40%';
break;
case 3:
strengthText = '密码强度:中';
strengthColor = '#FFDC00';
strengthWidth = '60%';
break;
case 4:
strengthText = '密码强度:强';
strengthColor = '#2ECC40';
strengthWidth = '80%';
break;
case 5:
strengthText = '密码强度:非常强';
strengthColor = '#3D9970';
strengthWidth = '100%';
break;
// 根据强度设置文本和样式类
if (strength <= 2) {
strengthText = '密码强度:弱';
strengthClass = 'weak';
} else if (strength <= 3) {
strengthText = '密码强度:中';
strengthClass = 'medium';
} else {
strengthText = '密码强度:强';
strengthClass = 'strong';
}
// 用span元素包裹文本并设置为不换行
strengthSpan.innerHTML = `<span style="white-space: nowrap;">${strengthText}</span>`;
strengthSpan.style.color = strengthColor;
// 更新UI
if (strengthSpan) {
strengthSpan.textContent = strengthText;
strengthSpan.className = `password-strength-text ${strengthClass}`;
}
if (strengthBar) {
strengthBar.style.width = strengthWidth;
strengthBar.style.backgroundColor = strengthColor;
if (strengthIndicator) {
strengthIndicator.className = `strength-indicator ${strengthClass}`;
}
}
// 切换密码可见性
function togglePasswordVisibility(inputId) {
function togglePasswordVisibility(inputId, btnElement) {
const passwordInput = document.getElementById(inputId);
const toggleBtn = passwordInput.nextElementSibling.querySelector('i');
if (!passwordInput) return;
// 获取图标元素
let toggleIcon;
if (btnElement) {
toggleIcon = btnElement.querySelector('i');
} else {
const nextSibling = passwordInput.nextElementSibling;
toggleIcon = nextSibling ? nextSibling.querySelector('i') : null;
}
if (passwordInput.type === 'password') {
passwordInput.type = 'text';
toggleBtn.classList.remove('fa-eye');
toggleBtn.classList.add('fa-eye-slash');
if (toggleIcon) {
toggleIcon.classList.remove('fa-eye');
toggleIcon.classList.add('fa-eye-slash');
}
} else {
passwordInput.type = 'password';
toggleBtn.classList.remove('fa-eye-slash');
toggleBtn.classList.add('fa-eye');
if (toggleIcon) {
toggleIcon.classList.remove('fa-eye-slash');
toggleIcon.classList.add('fa-eye');
}
}
}
@@ -312,11 +404,20 @@ function loadUserStats() {
const userCenter = {
init: function() {
// console.log('初始化用户中心模块...');
// 可以在这里调用初始化逻辑,也可以延迟到需要时调用
// 初始化修改用户名表单事件
const changeUsernameForm = document.getElementById('changeUsernameForm');
if (changeUsernameForm) {
changeUsernameForm.addEventListener('submit', function(e) {
e.preventDefault();
changeUsername();
});
}
return Promise.resolve(); // 返回一个已解决的 Promise保持与其他模块一致
},
getUserInfo,
changePassword,
changeUsername,
isUsernameValid,
checkUcPasswordStrength,
initUserCenter,
loadUserStats,

File diff suppressed because it is too large Load Diff