Make moderation actions atomic and authorized
This commit is contained in:
Furrium Network authored and GitHub committed 2026-08-11 16:58:13 +08:00
commit 2e745b547d
4 files changed
+78 -21

No files matched your search

-6
View File
@@ -49,12 +49,6 @@ function renderAdminReports() {
const note = action === 'approve' ? '已删除违规帖子' : '举报不成立';
if (action === 'approve' && !confirm('确定要删除该帖子并标记举报为已处理吗?')) return;
API.updateReport(id, status, note).then(() => {
if (action === 'approve') {
const report = reports.find(r => r.id === id);
if (report && report.post_id) {
API.deletePost(report.post_id).catch(() => {});
}
}
renderAdminReports();
}).catch(err => alert('操作失败:' + err.message));
});
+1 -1
View File
@@ -123,7 +123,7 @@ async function renderPostDetail(postId) {
<img src="${rAvatar}" class="reply-avatar" />
<span class="reply-username" style="cursor:pointer;color:var(--primary);" onclick="switchPage('user','${rUsername}')">${rUsername}</span>
<span class="reply-time">${rTime}</span>
${currentUser && currentUser.id === r.user_id ? `<button class="btn-sm btn-danger reply-delete-btn" data-replyid="${r.id}">
${currentUser && (currentUser.id === r.user_id || currentUser.role === 'admin') ? `<button class="btn-sm btn-danger reply-delete-btn" data-replyid="${r.id}">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
删除
</button>` : ''}
+26 -1
View File
@@ -45,7 +45,7 @@ CREATE TABLE IF NOT EXISTS friendly_links (
-- 举报表
CREATE TABLE IF NOT EXISTS reports (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
post_id UUID NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
post_id UUID REFERENCES posts(id) ON DELETE SET NULL,
reporter_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
reason VARCHAR(100) NOT NULL,
status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected')),
@@ -55,6 +55,31 @@ CREATE TABLE IF NOT EXISTS reports (
handler_note TEXT
);
-- Preserve moderation history when a reported post is deleted. This also
-- upgrades databases created with the previous ON DELETE CASCADE constraint.
DO $$
DECLARE
constraint_name TEXT;
BEGIN
SELECT con.conname INTO constraint_name
FROM pg_constraint con
JOIN pg_class rel ON rel.oid = con.conrelid
JOIN pg_attribute attr ON attr.attrelid = rel.oid AND attr.attnum = ANY(con.conkey)
WHERE rel.relname = 'reports'
AND con.contype = 'f'
AND attr.attname = 'post_id'
LIMIT 1;
IF constraint_name IS NOT NULL THEN
EXECUTE format('ALTER TABLE reports DROP CONSTRAINT %I', constraint_name);
END IF;
ALTER TABLE reports ALTER COLUMN post_id DROP NOT NULL;
ALTER TABLE reports
ADD CONSTRAINT reports_post_id_fkey
FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE SET NULL;
END $$;
-- 事件日志表
CREATE TABLE IF NOT EXISTS event_logs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+51 -13
View File
@@ -802,34 +802,64 @@ app.post('/api/reports', auth, async (req, res) => {
app.put('/api/reports/:id', auth, admin, async (req, res) => {
const { status, note } = req.body;
if (!['pending', 'approved', 'rejected'].includes(status)) {
if (!['approved', 'rejected'].includes(status)) {
return res.status(400).json({ error: '无效的状态' });
}
let client;
try {
const report = await pool.query('SELECT reporter_id, post_id FROM reports WHERE id = $1', [req.params.id]);
client = await pool.connect();
await client.query('BEGIN');
const report = await client.query(
'SELECT reporter_id, post_id, status FROM reports WHERE id = $1 FOR UPDATE',
[req.params.id]
);
if (report.rows.length === 0) {
await client.query('ROLLBACK');
return res.status(404).json({ error: '举报不存在' });
}
if (report.rows[0].status !== 'pending') {
await client.query('ROLLBACK');
return res.status(409).json({ error: '该举报已处理' });
}
await pool.query(
await client.query(
`UPDATE reports
SET status = $1, handled_at = NOW(), handler_id = $2, handler_note = $3
WHERE id = $4`,
[status, req.user.id, note || '', req.params.id]
);
if (report.rows[0]) {
const statusText = status === 'approved' ? '已删除' : '已驳回';
await createNotification(
if (status === 'approved' && report.rows[0].post_id) {
await client.query('DELETE FROM posts WHERE id = $1', [report.rows[0].post_id]);
}
const statusText = status === 'approved' ? '已删除' : '已驳回';
await client.query(
`INSERT INTO notifications (user_id, type, title, content, link)
VALUES ($1, $2, $3, $4, $5)`,
[
report.rows[0].reporter_id,
'report_handled',
'你的举报已被处理',
`你举报的帖子已被管理员${statusText}`,
report.rows[0].post_id ? '/?post=' + report.rows[0].post_id : null
);
}
status === 'rejected' && report.rows[0].post_id ? '/?post=' + report.rows[0].post_id : null,
]
);
res.json({ success: true });
await client.query('COMMIT');
res.json({ success: true, post_deleted: status === 'approved' });
} catch (err) {
if (client) {
try {
await client.query('ROLLBACK');
} catch (rollbackError) {
console.error('回滚举报处理事务失败:', rollbackError);
}
}
res.status(500).json({ error: '操作失败,请稍后重试' });
} finally {
if (client) client.release();
}
});
@@ -1192,10 +1222,18 @@ app.post('/api/conversations/:id/messages', auth, async (req, res) => {
// 标记消息已读
app.put('/api/messages/:id/read', auth, async (req, res) => {
try {
await pool.query(`
UPDATE messages SET is_read = true
WHERE id = $1 AND sender_id != $2
const result = await pool.query(`
UPDATE messages AS m SET is_read = true
FROM conversations AS c
WHERE m.id = $1
AND m.sender_id != $2
AND c.id = m.conversation_id
AND (c.user1_id = $2 OR c.user2_id = $2)
RETURNING m.id
`, [req.params.id, req.user.id]);
if (result.rows.length === 0) {
return res.status(404).json({ error: '消息不存在或无权限' });
}
res.json({ success: true });
} catch (err) {
res.status(500).json({ error: '服务器错误' });