refactor: CSP nonce替代unsafe-inline, HSTS始终启用, router/api拆分, 管理后台+用户设置页拆分, DB健康降级, 时区配置, UID统一解析, CI接入
Some checks failed
CI / Lint + Build (push) Has been cancelled

审计修复:
- CSP: unsafe-inline移除, nonce替代; unsafe-eval保留供Vditor使用
- HSTS: 始终启用(不再依赖release模式)
- Controller Exp: common.GetGinExp包装, 不再直接读context
- UID解析: common.ParseUIDParam统一, follow/admin controller改用

重构:
- router/api.go(198行)拆为7个域文件: auth/settings/posts/comments/reactions/social/studio
- 管理后台站点设置: 单页拆为4个子页(brand/security/registration/content)+子菜单
- 前台用户设置页: 1201行拆为6个独立模板+6个独立JS文件

新增:
- DB健康检测中间件(middleware/db_health.go): 5s ping+降级页面
- 时区配置: config.yaml server.timezone→time.Local初始化
- .gitea/workflows/ci.yml: strict模式CI流水线
This commit is contained in:
2026-06-22 03:06:24 +08:00
parent e7185f58fb
commit 2449a27eb5
43 changed files with 2157 additions and 226 deletions

View File

@ -0,0 +1,413 @@
(function(){'use strict';
<script nonce="{{.CSPNonce}}">
(function () {
'use strict';
var toastEl = document.getElementById('settingsToast');
var toastTimer = null;
function showSettingsToast(msg, isError) {
if (!toastEl) return;
clearTimeout(toastTimer);
toastEl.textContent = msg;
toastEl.className = 'settings-toast' + (isError ? ' error' : '');
void toastEl.offsetWidth;
toastEl.classList.add('show');
toastTimer = setTimeout(function () {
toastEl.classList.remove('show');
}, 5000);
}
// ===== 个人资料 Tab =====
(function () {
var usernameInput = document.getElementById('usernameInput');
var bioInput = document.getElementById('bioInput');
var btn = document.getElementById('saveProfileBtn');
if (!usernameInput || !bioInput || !btn) return;
// ---- 字符计数器 ----
var usernameCounter = document.getElementById('usernameCounter');
var bioCounterEl = document.getElementById('bioCounter');
function updateCounters() {
if (usernameCounter) {
usernameCounter.textContent = usernameInput.value.length + '/16';
}
if (bioCounterEl) {
bioCounterEl.textContent = bioInput.value.length + '/128';
}
}
usernameInput.addEventListener('input', updateCounters);
bioInput.addEventListener('input', updateCounters);
updateCounters();
// ---- 原始值(用于判断是否变更) ----
var origUsername = usernameInput.value.trim();
var origBio = bioInput.value;
var hasCompletedRename = usernameInput.getAttribute('data-has-completed-rename') === 'true';
// 与后端一致的合法字符集:中文、英文大小写、数字、下划线、连字符
var usernameRe = /^[\u4e00-\u9fffa-zA-Z0-9_-]+$/;
btn.addEventListener('click', function () {
var username = usernameInput.value.trim();
var bio = bioInput.value;
// 用户名校验
if (!username) {
showSettingsToast('用户名不能为空', true);
return;
}
if (username.length > 16) {
showSettingsToast('用户名不能超过 16 个字符', true);
return;
}
if (!usernameRe.test(username)) {
showSettingsToast('用户名仅支持中英文、数字、下划线、连字符', true);
return;
}
// 个性签名校验
if (bio.length > 128) {
showSettingsToast('个性签名不能超过 128 个字符', true);
return;
}
// 无变更判断
if (username === origUsername && bio === origBio) {
showSettingsToast('内容未变更,无需保存');
return;
}
// 用户名有变更时弹出消耗确认
if (username !== origUsername) {
var confirmMsg = hasCompletedRename
? '确认修改用户名?\n\n本次将消耗 6 域能,是否继续?'
: '确认修改用户名?\n\n首次更名无需消耗域能。';
showConfirm('修改用户名', confirmMsg).then(function(ok) {
if (ok) doSave(username, bio);
});
return;
}
doSave(username, bio);
});
function doSave(username, bio) {
btn.disabled = true;
btn.textContent = '保存中...';
var xhr = new XMLHttpRequest();
xhr.open('PUT', '/api/settings/profile', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;
btn.disabled = false;
btn.textContent = '保存';
try {
var res = JSON.parse(xhr.responseText);
if (res.success) {
showSettingsToast(res.message || '个人资料已更新');
origUsername = username;
origBio = bio;
} else {
showSettingsToast(res.message || '保存失败', true);
}
} catch (e) {
showSettingsToast('保存失败', true);
}
};
xhr.send(JSON.stringify({ username: username, bio: bio }));
}
// ---- 头像裁切上传 ----
var avatarWrap = document.getElementById('avatarWrap');
var avatarInput = document.getElementById('avatarInput');
var avatarPreview = document.getElementById('avatarPreview');
var cropOverlay = document.getElementById('cropOverlay');
var cropStage = document.getElementById('cropStage');
var cropImageEl = document.getElementById('cropImageEl');
var cropFrame = document.getElementById('cropFrame');
var cropMask = document.getElementById('cropMask');
var cropCancelBtn = document.getElementById('cropCancelBtn');
var cropConfirmBtn = document.getElementById('cropConfirmBtn');
var pendingFile = null;
var imgNW, imgNH; // 原图像素尺寸
var imgDW, imgDH; // 图片缩放后显示尺寸zoom=1 基准)
var zoom = 1; // 图片缩放系数
var minZoom = 1; // 最小缩放系数(超大图限制选区不超过 3840px
var panX = 0, panY = 0; // 图片平移偏移量
var fSize, fLeft, fTop; // 裁切框的固定屏幕像素:边长、左、顶
var CROP_MAX_PX = 3840; // 选区最大像素限制
// 更新裁切框固定参数(图片加载时计算一次,之后不变)
function initFrame() {
var sw = cropStage.clientWidth, sh = cropStage.clientHeight;
fSize = Math.min(imgDW, imgDH); // 短边长度填满可见区域
fLeft = Math.round((sw - fSize) / 2);
fTop = Math.round((sh - fSize) / 2);
}
// 约束 panX/panY确保裁切框始终在图片范围内
function clampPan() {
var sw = cropStage.clientWidth, sh = cropStage.clientHeight;
var iw = imgDW * zoom, ih = imgDH * zoom;
var cx = Math.round((sw - iw) / 2); // 图片居中时的基准偏移
var cy = Math.round((sh - ih) / 2);
panX = Math.max(fLeft + fSize - cx - iw, Math.min(panX, fLeft - cx));
panY = Math.max(fTop + fSize - cy - ih, Math.min(panY, fTop - cy));
}
function renderCrop() {
var sw = cropStage.clientWidth, sh = cropStage.clientHeight;
var iw = imgDW * zoom, ih = imgDH * zoom;
var ox = Math.round((sw - iw) / 2) + panX;
var oy = Math.round((sh - ih) / 2) + panY;
cropImageEl.style.width = iw + 'px';
cropImageEl.style.height = ih + 'px';
cropImageEl.style.left = ox + 'px';
cropImageEl.style.top = oy + 'px';
cropFrame.style.left = fLeft + 'px';
cropFrame.style.top = fTop + 'px';
cropFrame.style.width = fSize + 'px';
cropFrame.style.height = fSize + 'px';
cropMask.style.left = fLeft + 'px';
cropMask.style.top = fTop + 'px';
cropMask.style.width = fSize + 'px';
cropMask.style.height = fSize + 'px';
// 实时显示选区像素尺寸
var p = getCropParams();
var infoEl = document.getElementById('cropInfo');
if (infoEl) infoEl.textContent = p.size + ' × ' + p.size + ' px';
}
function openCrop(file) {
var reader = new FileReader();
reader.onload = function (e) {
cropImageEl.src = e.target.result;
cropImageEl.onload = function () {
imgNW = cropImageEl.naturalWidth;
imgNH = cropImageEl.naturalHeight;
var sw = cropStage.clientWidth, sh = cropStage.clientHeight;
var fit = Math.min(sw / imgNW, sh / imgNH);
imgDW = Math.round(imgNW * fit);
imgDH = Math.round(imgNH * fit);
// 限制选框最大像素:原图短边超过 3840 时,抬高最小缩放
minZoom = Math.min(imgNW, imgNH) > CROP_MAX_PX
? Math.min(imgNW, imgNH) / CROP_MAX_PX
: 1;
zoom = minZoom;
panX = 0;
panY = 0;
initFrame();
renderCrop();
};
};
reader.readAsDataURL(file);
cropOverlay.classList.add('active');
}
function closeCrop() {
cropOverlay.classList.remove('active');
avatarInput.value = '';
pendingFile = null;
}
function getCropParams() {
var sw = cropStage.clientWidth, sh = cropStage.clientHeight;
var iw = imgDW * zoom, ih = imgDH * zoom;
var ox = Math.round((sw - iw) / 2) + panX;
var oy = Math.round((sh - ih) / 2) + panY;
var cx = (fLeft + fSize / 2 - ox) / zoom;
var cy = (fTop + fSize / 2 - oy) / zoom;
var cs = fSize / zoom;
var sx = imgNW / imgDW, sy = imgNH / imgDH;
return {
x: Math.round((cx - cs / 2) * sx),
y: Math.round((cy - cs / 2) * sy),
size: Math.round(cs * sx)
};
}
// ---- 图片平移 ----
var panning = false, panStartX = 0, panStartY = 0, panInitX = 0, panInitY = 0;
function startPan(clientX, clientY) {
panning = true;
panStartX = clientX;
panStartY = clientY;
panInitX = panX;
panInitY = panY;
cropStage.style.cursor = 'grabbing';
}
function movePan(clientX, clientY) {
panX = panInitX + (clientX - panStartX);
panY = panInitY + (clientY - panStartY);
clampPan();
renderCrop();
}
cropStage.addEventListener('mousedown', function (e) {
e.preventDefault();
startPan(e.clientX, e.clientY);
});
document.addEventListener('mousemove', function (e) {
if (!panning) return;
movePan(e.clientX, e.clientY);
});
document.addEventListener('mouseup', function () {
panning = false;
cropStage.style.cursor = 'grab';
});
cropStage.addEventListener('touchstart', function (e) {
e.preventDefault();
var t = e.touches[0];
startPan(t.clientX, t.clientY);
});
document.addEventListener('touchmove', function (e) {
if (!panning) return;
var t = e.touches[0];
movePan(t.clientX, t.clientY);
}, { passive: true });
document.addEventListener('touchend', function () {
panning = false;
cropStage.style.cursor = 'grab';
});
cropStage.addEventListener('wheel', function (e) {
e.preventDefault();
if (panning) return;
var newZoom = Math.max(minZoom, Math.min(zoom * (e.deltaY < 0 ? 1.1 : 1 / 1.1), 3));
if (newZoom === zoom) return;
zoom = newZoom;
clampPan();
renderCrop();
}, { passive: false });
cropCancelBtn.addEventListener('click', closeCrop);
cropOverlay.addEventListener('click', function (e) {
if (e.target === cropOverlay) closeCrop();
});
// 客户端裁剪 + 压缩Canvas 裁出选区并一步到位缩放到 512px上传体积最小
function cropOnClient(file, x, y, size) {
return new Promise(function (resolve) {
var url = URL.createObjectURL(file);
var img = new Image();
img.onload = function () {
URL.revokeObjectURL(url);
var out = 512; // 直接缩放到服务端目标输出尺寸
var canvas = document.createElement('canvas');
canvas.width = out;
canvas.height = out;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, x, y, size, size, 0, 0, out, out);
canvas.toBlob(function (blob) {
resolve({
file: new File([blob], 'avatar.jpg', { type: blob.type || 'image/jpeg' }),
cropX: 0,
cropY: 0,
cropSize: out
});
}, 'image/jpeg', 0.88);
};
img.onerror = function () {
URL.revokeObjectURL(url);
// Canvas 处理失败时回退:直接上传原文件 + 原坐标
resolve({ file: file, cropX: x, cropY: y, cropSize: size });
};
img.src = url;
});
}
cropConfirmBtn.addEventListener('click', function () {
if (!pendingFile) return;
var params = getCropParams();
cropConfirmBtn.disabled = true;
cropConfirmBtn.textContent = '处理中...';
showSettingsToast('上传中...');
cropOnClient(pendingFile, params.x, params.y, params.size).then(function (result) {
var formData = new FormData();
formData.append('avatar', result.file, result.file.name);
formData.append('crop_x', result.cropX);
formData.append('crop_y', result.cropY);
formData.append('crop_size', result.cropSize);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/api/settings/avatar', true);
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;
cropConfirmBtn.disabled = false;
cropConfirmBtn.textContent = '确认';
closeCrop();
try {
var res = JSON.parse(xhr.responseText);
if (res.success) {
showSettingsToast(res.message || '头像已更新');
var newAvatarUrl = res.data && res.data.url && (res.data.url + '?t=' + Date.now());
if (newAvatarUrl && avatarPreview.tagName === 'IMG') {
avatarPreview.src = newAvatarUrl;
}
// 同步更新 NAV 头像
if (newAvatarUrl) {
var navLink = document.querySelector('.nav-avatar-link');
if (navLink) {
var navImg = navLink.querySelector('img.nav-avatar');
if (navImg) {
navImg.src = newAvatarUrl;
navImg.style.display = '';
var fb = navLink.querySelector('.nav-avatar-default');
if (fb) fb.style.display = 'none';
} else {
var fb2 = navLink.querySelector('.nav-avatar-default');
if (fb2) {
var img = document.createElement('img');
img.src = newAvatarUrl;
img.alt = '';
img.className = 'nav-avatar';
img.onerror = function() { this.style.display = 'none'; this.nextElementSibling.style.display = 'flex'; };
navLink.insertBefore(img, fb2);
fb2.style.display = 'none';
}
}
}
}
} else {
showSettingsToast(res.message || '上传失败', true);
}
} catch (err) {
showSettingsToast('上传失败', true);
}
};
xhr.send(formData);
}).catch(function () {
cropConfirmBtn.disabled = false;
cropConfirmBtn.textContent = '确认';
showSettingsToast('处理失败,请重试', true);
});
});
if (avatarWrap && avatarInput) {
avatarWrap.addEventListener('click', function () {
avatarInput.click();
});
avatarInput.addEventListener('change', function () {
var file = avatarInput.files[0];
if (!file) return;
pendingFile = file;
openCrop(file);
});
}
})(); // 结束个人资料 Tab 子 IIFE
})();