feat: follow lite forum updates
This commit is contained in:
1 parent
f59739e36f
commit
b42944b687
38 files changed
+1433
-71
No files matched your search
@@ -0,0 +1,20 @@
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, requireAdmin } from '@/lib/auth';
|
||||
import { loadSmtpConfig, isConfigComplete } from '@/lib/mailer';
|
||||
|
||||
export async function PUT(req) {
|
||||
const forbidden = await requireAdmin(getUser(req));
|
||||
if (forbidden) return forbidden;
|
||||
const body = await req.json().catch(() => ({}));
|
||||
if (typeof body.required !== 'boolean') return Response.json({ error: '参数无效' }, { status: 400 });
|
||||
try {
|
||||
if (body.required && !isConfigComplete(await loadSmtpConfig())) {
|
||||
return Response.json({ error: '请先完成 SMTP 配置' }, { status: 400 });
|
||||
}
|
||||
await pool.query(`INSERT INTO settings (key, value) VALUES ('email_verify_required', $1)
|
||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`, [String(body.required)]);
|
||||
return Response.json({ success: true, email_verify_required: body.required });
|
||||
} catch {
|
||||
return Response.json({ error: '保存失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, requireAdmin } from '@/lib/auth';
|
||||
|
||||
export async function DELETE(req) {
|
||||
const forbidden = await requireAdmin(getUser(req));
|
||||
if (forbidden) return forbidden;
|
||||
try {
|
||||
await pool.query(`INSERT INTO settings (key, value) VALUES ('smtp_password', '')
|
||||
ON CONFLICT (key) DO UPDATE SET value = '', updated_at = now()`);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '清除失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, requireAdmin } from '@/lib/auth';
|
||||
import { loadSmtpConfig, isConfigComplete } from '@/lib/mailer';
|
||||
import { normalizeEmail } from '@/lib/email-verification';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function GET(req) {
|
||||
const forbidden = await requireAdmin(getUser(req));
|
||||
if (forbidden) return forbidden;
|
||||
try {
|
||||
const config = await loadSmtpConfig();
|
||||
return Response.json({
|
||||
enabled: config.enabled,
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
secure: config.secure,
|
||||
user: config.user,
|
||||
from_name: config.fromName,
|
||||
from_email: config.fromEmail,
|
||||
allow_self_signed: config.allowSelfSigned,
|
||||
password_set: Boolean(config.password),
|
||||
configured: isConfigComplete(config),
|
||||
}, { headers: { 'Cache-Control': 'private, no-store' } });
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(req) {
|
||||
const forbidden = await requireAdmin(getUser(req));
|
||||
if (forbidden) return forbidden;
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const port = Number(body.port);
|
||||
const host = typeof body.host === 'string' ? body.host.trim() : '';
|
||||
const user = typeof body.user === 'string' ? body.user.trim() : '';
|
||||
const fromName = typeof body.from_name === 'string' ? body.from_name.trim() : '';
|
||||
const fromEmail = typeof body.from_email === 'string' ? body.from_email.trim() : '';
|
||||
if (typeof body.enabled !== 'boolean' || typeof body.secure !== 'boolean' ||
|
||||
!Number.isInteger(port) || port < 1 || port > 65535 ||
|
||||
host.length > 255 || user.length > 255 || fromName.length > 100 ||
|
||||
(fromEmail && !normalizeEmail(fromEmail)) ||
|
||||
(body.password !== undefined && (typeof body.password !== 'string' || body.password.length > 255))) {
|
||||
return Response.json({ error: 'SMTP 配置无效' }, { status: 400 });
|
||||
}
|
||||
const previous = await loadSmtpConfig();
|
||||
if (body.enabled && (!host || !fromEmail || (user && !body.password && !previous.password))) {
|
||||
return Response.json({ error: '启用 SMTP 前请填写服务器、发件邮箱和认证信息' }, { status: 400 });
|
||||
}
|
||||
const entries = [
|
||||
['smtp_enabled', String(body.enabled)], ['smtp_host', host], ['smtp_port', String(port)],
|
||||
['smtp_secure', String(body.secure)], ['smtp_user', user], ['smtp_from_name', fromName],
|
||||
['smtp_from_email', fromEmail], ['smtp_allow_self_signed', String(body.allow_self_signed === true)],
|
||||
];
|
||||
if (body.password) entries.push(['smtp_password', body.password]);
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
for (const [key, value] of entries) {
|
||||
await client.query(`INSERT INTO settings (key, value) VALUES ($1, $2)
|
||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`, [key, value]);
|
||||
}
|
||||
if (!body.enabled) {
|
||||
await client.query(`INSERT INTO settings (key, value) VALUES ('email_verify_required', 'false')
|
||||
ON CONFLICT (key) DO UPDATE SET value = 'false', updated_at = now()`);
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
return Response.json({ error: '保存失败,请稍后重试' }, { status: 500 });
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, requireAdmin } from '@/lib/auth';
|
||||
import { loadSmtpConfig, isConfigComplete, sendMail, describeSmtpError } from '@/lib/mailer';
|
||||
import { normalizeEmail } from '@/lib/email-verification';
|
||||
|
||||
export async function POST(req) {
|
||||
const user = getUser(req);
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
const body = await req.json().catch(() => ({}));
|
||||
if (body.to && !normalizeEmail(body.to)) return Response.json({ error: '收件人邮箱格式无效' }, { status: 400 });
|
||||
try {
|
||||
const config = await loadSmtpConfig();
|
||||
if (!isConfigComplete(config)) return Response.json({ error: 'SMTP 尚未配置完成' }, { status: 400 });
|
||||
const me = await pool.query('SELECT email FROM users WHERE id = $1', [user.id]);
|
||||
const to = body.to ? normalizeEmail(body.to) : me.rows[0]?.email;
|
||||
if (!to) return Response.json({ error: '请指定收件人邮箱' }, { status: 400 });
|
||||
await sendMail(config, {
|
||||
to,
|
||||
subject: 'Forumlify SMTP 测试邮件',
|
||||
text: `这是一封来自 Forumlify 的测试邮件。\n\n发送时间:${new Date().toISOString()}`,
|
||||
});
|
||||
return Response.json({ success: true, to });
|
||||
} catch (error) {
|
||||
return Response.json({ error: describeSmtpError(error) }, { status: 400 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import pool from '@/lib/db';
|
||||
import { loadSmtpConfig, isConfigComplete, sendMail, describeSmtpError } from '@/lib/mailer';
|
||||
import { normalizeEmail, saveEmailCode, invalidateEmailCode } from '@/lib/email-verification';
|
||||
|
||||
export async function POST(req) {
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const email = normalizeEmail(body.email);
|
||||
if (!email) return Response.json({ error: '请输入有效邮箱' }, { status: 400 });
|
||||
try {
|
||||
const config = await loadSmtpConfig();
|
||||
if (!isConfigComplete(config)) return Response.json({ error: '站点尚未配置邮件服务' }, { status: 503 });
|
||||
const user = await pool.query('SELECT id FROM users WHERE LOWER(email) = $1', [email]);
|
||||
if (user.rowCount) {
|
||||
const code = await saveEmailCode(email, 'reset');
|
||||
if (!code) return Response.json({ error: '请 60 秒后再获取验证码' }, { status: 429 });
|
||||
try {
|
||||
await sendMail(config, {
|
||||
to: email,
|
||||
subject: 'Forumlify 密码重置验证码',
|
||||
text: `你的密码重置验证码是:${code}\n\n有效期 10 分钟。如果这不是你本人的操作,请忽略本邮件。`,
|
||||
});
|
||||
} catch (error) {
|
||||
await invalidateEmailCode(email, 'reset');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return Response.json({ success: true, message: '如果该邮箱已注册,重置码已发送' });
|
||||
} catch (error) {
|
||||
return Response.json({ error: describeSmtpError(error) }, { status: 400 });
|
||||
}
|
||||
}
|
||||
@@ -3,20 +3,27 @@ import bcrypt from 'bcryptjs';
|
||||
import pool from '@/lib/db';
|
||||
import { verifyCaptcha } from '@/lib/captcha';
|
||||
import { logAudit } from '@/lib/audit';
|
||||
import { normalizeEmail, isEmailVerificationRequired, withEmailCode, CODE_ERRORS, ensureEmailVerificationSchema } from '@/lib/email-verification';
|
||||
|
||||
export async function POST(req) {
|
||||
const { email, password, username, captcha_id, captcha_answer, captcha_sig } = await req.json();
|
||||
if (!email || !password || !username) {
|
||||
const { email, password, username, email_code, captcha_id, captcha_answer, captcha_sig } = await req.json();
|
||||
const normalizedEmail = normalizeEmail(email);
|
||||
if (!normalizedEmail || !password || !username) {
|
||||
return Response.json({ error: '请填写完整信息' }, { status: 400 });
|
||||
}
|
||||
if (password.length < 6) {
|
||||
return Response.json({ error: '密码至少6位' }, { status: 400 });
|
||||
if (typeof password !== 'string' || password.length < 6 || password.length > 128 ||
|
||||
typeof username !== 'string' || !username.trim() || username.length > 50) {
|
||||
return Response.json({ error: '用户名或密码长度无效' }, { status: 400 });
|
||||
}
|
||||
// 服务端验证码校验(ENABLE_CAPTCHA 关闭时跳过)
|
||||
if (process.env.ENABLE_CAPTCHA !== 'false' && !verifyCaptcha(captcha_id, captcha_answer, captcha_sig)) {
|
||||
return Response.json({ error: '验证码错误,请重新计算' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const verificationRequired = await isEmailVerificationRequired();
|
||||
if (verificationRequired && !/^\d{6}$/.test(email_code || '')) {
|
||||
return Response.json({ error: '请输入邮箱验证码' }, { status: 400 });
|
||||
}
|
||||
const countResult = await pool.query('SELECT COUNT(*) FROM users');
|
||||
const isFirstUser = parseInt(countResult.rows[0].count) === 0;
|
||||
|
||||
@@ -24,12 +31,21 @@ export async function POST(req) {
|
||||
const avatar = 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) + '&background=6366f1&color=fff&size=64';
|
||||
const role = isFirstUser ? 'admin' : 'user';
|
||||
|
||||
const r = await pool.query(
|
||||
`INSERT INTO users (email, password_hash, username, avatar_url, role)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
const insert = (client) => client.query(
|
||||
`INSERT INTO users (email, password_hash, username, avatar_url, role, email_verified)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING id, username, avatar_url, role, created_at`,
|
||||
[email, hash, username, avatar, role]
|
||||
[normalizedEmail, hash, username.trim(), avatar, role, verificationRequired]
|
||||
);
|
||||
let r;
|
||||
if (verificationRequired) {
|
||||
const result = await withEmailCode(normalizedEmail, 'register', email_code, insert);
|
||||
if (result.failure) return Response.json({ error: CODE_ERRORS[result.failure] }, { status: 400 });
|
||||
r = result.value;
|
||||
} else {
|
||||
await ensureEmailVerificationSchema();
|
||||
r = await insert(pool);
|
||||
}
|
||||
|
||||
// 服务端审计:注册成功
|
||||
await logAudit(req, 'register', r.rows[0].id);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { normalizeEmail, withEmailCode, CODE_ERRORS } from '@/lib/email-verification';
|
||||
|
||||
export async function POST(req) {
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const email = normalizeEmail(body.email);
|
||||
if (!email || !/^\d{6}$/.test(body.code || '') ||
|
||||
typeof body.newPassword !== 'string' || body.newPassword.length < 6 || body.newPassword.length > 128) {
|
||||
return Response.json({ error: '请填写有效的邮箱、验证码和新密码' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const hash = await bcrypt.hash(body.newPassword, 10);
|
||||
const result = await withEmailCode(email, 'reset', body.code, async (client) => {
|
||||
const updated = await client.query('UPDATE users SET password_hash = $1 WHERE LOWER(email) = $2 RETURNING id', [hash, email]);
|
||||
if (!updated.rowCount) throw new Error('账号不存在');
|
||||
return updated.rows[0];
|
||||
});
|
||||
if (result.failure) return Response.json({ error: CODE_ERRORS[result.failure] }, { status: 400 });
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '重置失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import pool from '@/lib/db';
|
||||
import { loadSmtpConfig, isConfigComplete, sendMail, describeSmtpError } from '@/lib/mailer';
|
||||
import { normalizeEmail, isEmailVerificationRequired, saveEmailCode, invalidateEmailCode } from '@/lib/email-verification';
|
||||
|
||||
export async function POST(req) {
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const email = normalizeEmail(body.email);
|
||||
if (!email) return Response.json({ error: '请输入有效邮箱' }, { status: 400 });
|
||||
try {
|
||||
if (!await isEmailVerificationRequired()) {
|
||||
return Response.json({ error: '本站未开启邮箱验证' }, { status: 400 });
|
||||
}
|
||||
const config = await loadSmtpConfig();
|
||||
if (!isConfigComplete(config)) return Response.json({ error: '站点尚未配置邮件服务' }, { status: 503 });
|
||||
const existing = await pool.query('SELECT 1 FROM users WHERE LOWER(email) = $1', [email]);
|
||||
if (existing.rowCount) return Response.json({ error: '该邮箱已被注册' }, { status: 409 });
|
||||
const code = await saveEmailCode(email, 'register');
|
||||
if (!code) return Response.json({ error: '请 60 秒后再获取验证码' }, { status: 429 });
|
||||
try {
|
||||
await sendMail(config, {
|
||||
to: email,
|
||||
subject: 'Forumlify 注册验证码',
|
||||
text: `你的注册验证码是:${code}\n\n有效期 10 分钟,请勿转发给他人。`,
|
||||
});
|
||||
} catch (error) {
|
||||
await invalidateEmailCode(email, 'register');
|
||||
throw error;
|
||||
}
|
||||
return Response.json({ success: true });
|
||||
} catch (error) {
|
||||
return Response.json({ error: describeSmtpError(error) }, { status: 400 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
import { ensureUserBlocksSchema } from '@/lib/user-blocks';
|
||||
|
||||
export async function GET(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
try {
|
||||
await ensureUserBlocksSchema();
|
||||
const result = await pool.query(`
|
||||
SELECT u.id, u.username, u.avatar_url, b.created_at
|
||||
FROM user_blocks b JOIN users u ON u.id = b.blocked_id
|
||||
WHERE b.blocker_id = $1 ORDER BY b.created_at DESC
|
||||
`, [user.id]);
|
||||
return Response.json({ data: result.rows }, { headers: { 'Cache-Control': 'private, no-store' } });
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
// GET /api/conversations/[id]/messages, POST /api/conversations/[id]/messages
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
import { ensureUserBlocksSchema } from '@/lib/user-blocks';
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
@@ -49,30 +50,60 @@ export async function POST(req, { params }) {
|
||||
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
|
||||
}
|
||||
const { content } = await req.json();
|
||||
if (!content || content.trim().length === 0) {
|
||||
return Response.json({ error: '请填写消息内容' }, { status: 400 });
|
||||
if (typeof content !== 'string' || !content.trim() || content.length > 10000) {
|
||||
return Response.json({ error: '消息长度应为1到10000个字符' }, { status: 400 });
|
||||
}
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
const check = await pool.query(`
|
||||
SELECT id FROM conversations
|
||||
await ensureUserBlocksSchema();
|
||||
await client.query('BEGIN');
|
||||
const check = await client.query(`
|
||||
SELECT id, user1_id, user2_id FROM conversations
|
||||
WHERE id = $1 AND (user1_id = $2 OR user2_id = $2)
|
||||
FOR UPDATE
|
||||
`, [(await params).id, user.id]);
|
||||
if (check.rows.length === 0) {
|
||||
await client.query('ROLLBACK');
|
||||
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
|
||||
}
|
||||
const r = await pool.query(`
|
||||
const conversation = check.rows[0];
|
||||
const otherId = conversation.user1_id === user.id ? conversation.user2_id : conversation.user1_id;
|
||||
const blocked = await client.query(`
|
||||
SELECT 1 FROM user_blocks
|
||||
WHERE (blocker_id = $1 AND blocked_id = $2)
|
||||
OR (blocker_id = $2 AND blocked_id = $1)
|
||||
LIMIT 1
|
||||
`, [otherId, user.id]);
|
||||
if (blocked.rowCount) {
|
||||
await client.query('ROLLBACK');
|
||||
return Response.json({ error: '无法向该用户发送消息' }, { status: 403 });
|
||||
}
|
||||
const stats = await client.query(`
|
||||
SELECT COUNT(*) FILTER (WHERE sender_id = $2) AS mine,
|
||||
COUNT(*) FILTER (WHERE sender_id = $3) AS theirs
|
||||
FROM messages WHERE conversation_id = $1
|
||||
`, [(await params).id, user.id, otherId]);
|
||||
if (Number(stats.rows[0].theirs) === 0 && Number(stats.rows[0].mine) >= 3) {
|
||||
await client.query('ROLLBACK');
|
||||
return Response.json({ error: '对方回复前最多发送 3 条消息,请等待对方回复', limit_reached: true, limit: 3 }, { status: 429 });
|
||||
}
|
||||
const r = await client.query(`
|
||||
INSERT INTO messages (conversation_id, sender_id, content)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING *
|
||||
`, [(await params).id, user.id, content]);
|
||||
await pool.query('UPDATE conversations SET last_message_at = NOW() WHERE id = $1', [(await params).id]);
|
||||
const userInfo = await pool.query('SELECT username, avatar_url FROM users WHERE id = $1', [user.id]);
|
||||
`, [(await params).id, user.id, content.trim()]);
|
||||
await client.query('UPDATE conversations SET last_message_at = NOW() WHERE id = $1', [(await params).id]);
|
||||
const userInfo = await client.query('SELECT username, avatar_url FROM users WHERE id = $1', [user.id]);
|
||||
await client.query('COMMIT');
|
||||
return Response.json({
|
||||
...r.rows[0],
|
||||
sender_username: userInfo.rows[0].username,
|
||||
sender_avatar_url: userInfo.rows[0].avatar_url,
|
||||
});
|
||||
} catch {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
return Response.json({ error: '发送失败,请稍后重试' }, { status: 500 });
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
// GET /api/conversations, POST /api/conversations
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
import { ensureUserBlocksSchema, hasBlocked, UUID_RE } from '@/lib/user-blocks';
|
||||
|
||||
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
|
||||
export const dynamic = 'force-dynamic';
|
||||
@@ -42,17 +43,21 @@ export async function POST(req) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
const { other_user_id } = await req.json();
|
||||
if (!other_user_id) {
|
||||
return Response.json({ error: '缺少对方用户ID' }, { status: 400 });
|
||||
if (!UUID_RE.test(other_user_id || '')) {
|
||||
return Response.json({ error: '对方用户ID无效' }, { status: 400 });
|
||||
}
|
||||
if (other_user_id === user.id) {
|
||||
return Response.json({ error: '不能与自己私信' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
await ensureUserBlocksSchema();
|
||||
const userCheck = await pool.query('SELECT id FROM users WHERE id = $1', [other_user_id]);
|
||||
if (userCheck.rows.length === 0) {
|
||||
return Response.json({ error: '用户不存在' }, { status: 404 });
|
||||
}
|
||||
if (await hasBlocked(other_user_id, user.id) || await hasBlocked(user.id, other_user_id)) {
|
||||
return Response.json({ error: '无法向该用户发起私信' }, { status: 403 });
|
||||
}
|
||||
const existing = await pool.query(`
|
||||
SELECT id FROM conversations
|
||||
WHERE (user1_id = $1 AND user2_id = $2) OR (user1_id = $2 AND user2_id = $1)
|
||||
@@ -62,7 +67,9 @@ export async function POST(req) {
|
||||
}
|
||||
const r = await pool.query(`
|
||||
INSERT INTO conversations (user1_id, user2_id)
|
||||
VALUES ($1, $2)
|
||||
VALUES (LEAST($1::uuid, $2::uuid), GREATEST($1::uuid, $2::uuid))
|
||||
ON CONFLICT (user1_id, user2_id)
|
||||
DO UPDATE SET user1_id = EXCLUDED.user1_id
|
||||
RETURNING id
|
||||
`, [user.id, other_user_id]);
|
||||
return Response.json({ id: r.rows[0].id });
|
||||
|
||||
@@ -6,8 +6,12 @@ import { verifyCaptcha } from '@/lib/captcha';
|
||||
import { logAudit } from '@/lib/audit';
|
||||
import { getReplySchemaCapabilities } from '@/lib/reply-schema';
|
||||
import { resolvePostReference } from '@/lib/post-reference';
|
||||
import { ensureUserBlocksSchema } from '@/lib/user-blocks';
|
||||
|
||||
function repliesSelectSql(capabilities) {
|
||||
function repliesSelectSql(capabilities, viewer) {
|
||||
const visible = viewer ? ` AND NOT EXISTS (
|
||||
SELECT 1 FROM user_blocks b WHERE b.blocker_id = $2 AND b.blocked_id = r.user_id
|
||||
)` : '';
|
||||
if (capabilities.replyToId) {
|
||||
return `SELECT r.id, r.post_id, r.user_id, r.content, r.created_at,
|
||||
r.reply_to_id, u.username, u.avatar_url,
|
||||
@@ -16,7 +20,7 @@ function repliesSelectSql(capabilities) {
|
||||
JOIN users u ON r.user_id = u.id
|
||||
LEFT JOIN replies rt ON r.reply_to_id = rt.id
|
||||
LEFT JOIN users ru ON rt.user_id = ru.id
|
||||
WHERE r.post_id = $1
|
||||
WHERE r.post_id = $1${visible}
|
||||
ORDER BY r.created_at ASC`;
|
||||
}
|
||||
|
||||
@@ -27,7 +31,7 @@ function repliesSelectSql(capabilities) {
|
||||
r.reply_to_username
|
||||
FROM replies r
|
||||
JOIN users u ON r.user_id = u.id
|
||||
WHERE r.post_id = $1
|
||||
WHERE r.post_id = $1${visible}
|
||||
ORDER BY r.created_at ASC`;
|
||||
}
|
||||
|
||||
@@ -37,7 +41,7 @@ function repliesSelectSql(capabilities) {
|
||||
u.username, u.avatar_url
|
||||
FROM replies r
|
||||
JOIN users u ON r.user_id = u.id
|
||||
WHERE r.post_id = $1
|
||||
WHERE r.post_id = $1${visible}
|
||||
ORDER BY r.created_at ASC`;
|
||||
}
|
||||
|
||||
@@ -45,9 +49,13 @@ export async function GET(req, { params }) {
|
||||
try {
|
||||
const reference = await resolvePostReference((await params).id);
|
||||
if (!reference) return Response.json({ error: '帖子不存在' }, { status: 404 });
|
||||
const viewer = getUser(req);
|
||||
if (viewer) await ensureUserBlocksSchema();
|
||||
const capabilities = await getReplySchemaCapabilities();
|
||||
const r = await pool.query(repliesSelectSql(capabilities), [reference.id]);
|
||||
return jsonWithEtag(req, r.rows);
|
||||
const r = await pool.query(repliesSelectSql(capabilities, viewer), viewer ? [reference.id, viewer.id] : [reference.id]);
|
||||
return viewer
|
||||
? Response.json(r.rows, { headers: { 'Cache-Control': 'private, no-store' } })
|
||||
: jsonWithEtag(req, r.rows);
|
||||
} catch (error) {
|
||||
console.error('[replies] list failed:', error?.code || error?.message);
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
|
||||
@@ -3,6 +3,7 @@ import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
import { jsonWithEtag } from '@/lib/http-cache';
|
||||
import { resolvePostReference } from '@/lib/post-reference';
|
||||
import { ensureUserBlocksSchema } from '@/lib/user-blocks';
|
||||
|
||||
function invalidId() {
|
||||
return Response.json({ error: '帖子不存在' }, { status: 404 });
|
||||
@@ -10,19 +11,25 @@ function invalidId() {
|
||||
|
||||
export async function GET(req, { params }) {
|
||||
try {
|
||||
const viewer = getUser(req);
|
||||
const reference = await resolvePostReference((await params).id);
|
||||
if (!reference) return invalidId();
|
||||
if (viewer) await ensureUserBlocksSchema();
|
||||
const r = await pool.query(
|
||||
`SELECT p.*, u.username, u.avatar_url, u.signature
|
||||
FROM posts p
|
||||
JOIN users u ON p.user_id = u.id
|
||||
WHERE p.id = $1`,
|
||||
[reference.id]
|
||||
WHERE p.id = $1${viewer ? ` AND NOT EXISTS (
|
||||
SELECT 1 FROM user_blocks b WHERE b.blocker_id = $2 AND b.blocked_id = p.user_id
|
||||
)` : ''}`,
|
||||
viewer ? [reference.id, viewer.id] : [reference.id]
|
||||
);
|
||||
if (r.rows.length === 0) {
|
||||
return invalidId();
|
||||
}
|
||||
return jsonWithEtag(req, r.rows[0]);
|
||||
return viewer
|
||||
? Response.json(r.rows[0], { headers: { 'Cache-Control': 'private, no-store' } })
|
||||
: jsonWithEtag(req, r.rows[0]);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
|
||||
+19
-6
@@ -5,6 +5,7 @@ import { jsonWithEtag } from '@/lib/http-cache';
|
||||
import { verifyCaptcha } from '@/lib/captcha';
|
||||
import { logAudit } from '@/lib/audit';
|
||||
import { ensurePostNumberSchema } from '@/lib/post-reference';
|
||||
import { ensureUserBlocksSchema } from '@/lib/user-blocks';
|
||||
|
||||
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
|
||||
export const dynamic = 'force-dynamic';
|
||||
@@ -14,6 +15,7 @@ export async function GET(req) {
|
||||
const url = new URL(req.url);
|
||||
const sort = url.searchParams.get('sort') === 'hot' ? 'updated_at' : 'created_at';
|
||||
const userId = url.searchParams.get('user_id');
|
||||
const viewer = getUser(req);
|
||||
const page = Math.max(1, parseInt(url.searchParams.get('page')) || 1);
|
||||
// 分页边界:limit 封顶 50,page 封顶 10000(防深分页 DoS)
|
||||
const limit = Math.min(50, Math.max(1, parseInt(url.searchParams.get('limit')) || 20));
|
||||
@@ -24,11 +26,19 @@ export async function GET(req) {
|
||||
try {
|
||||
await ensurePostNumberSchema();
|
||||
const params = [];
|
||||
let where = '';
|
||||
const conditions = [];
|
||||
if (userId) {
|
||||
where = ' WHERE p.user_id = $1';
|
||||
(await params).push(userId);
|
||||
params.push(userId);
|
||||
conditions.push(`p.user_id = $${params.length}`);
|
||||
}
|
||||
if (viewer) {
|
||||
await ensureUserBlocksSchema();
|
||||
params.push(viewer.id);
|
||||
conditions.push(`NOT EXISTS (
|
||||
SELECT 1 FROM user_blocks b WHERE b.blocker_id = $${params.length} AND b.blocked_id = p.user_id
|
||||
)`);
|
||||
}
|
||||
const where = conditions.length ? ` WHERE ${conditions.join(' AND ')}` : '';
|
||||
|
||||
const countResult = await pool.query(`SELECT COUNT(*) as total FROM posts p${where}`, params);
|
||||
const total = parseInt(countResult.rows[0]?.total || 0);
|
||||
@@ -44,13 +54,16 @@ export async function GET(req) {
|
||||
JOIN users u ON p.user_id = u.id
|
||||
${where}
|
||||
ORDER BY is_pinned DESC, pinned_at DESC NULLS LAST, ${sort} DESC
|
||||
LIMIT $${(await params).length + 1} OFFSET $${(await params).length + 2}
|
||||
LIMIT $${params.length + 1} OFFSET $${params.length + 2}
|
||||
`, [...params, limit, offset]);
|
||||
|
||||
return jsonWithEtag(req, {
|
||||
const payload = {
|
||||
data: r.rows,
|
||||
pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
|
||||
});
|
||||
};
|
||||
return viewer
|
||||
? Response.json(payload, { headers: { 'Cache-Control': 'private, no-store' } })
|
||||
: jsonWithEtag(req, payload);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
import { ensurePostNumberSchema } from '@/lib/post-reference';
|
||||
import { ensureUserBlocksSchema } from '@/lib/user-blocks';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
function escapeLike(value) {
|
||||
return value.replace(/[\\%_]/g, (character) => `\\${character}`);
|
||||
}
|
||||
|
||||
export async function GET(req) {
|
||||
const url = new URL(req.url);
|
||||
const keyword = (url.searchParams.get('q') || '').trim();
|
||||
if (!keyword) return Response.json({ error: '请输入搜索关键词' }, { status: 400 });
|
||||
if (keyword.length > 100) return Response.json({ error: '搜索关键词过长(最多 100 字)' }, { status: 400 });
|
||||
|
||||
const limit = Math.min(50, Math.max(1, parseInt(url.searchParams.get('limit'), 10) || 20));
|
||||
const page = Math.min(10000, Math.max(1, parseInt(url.searchParams.get('page'), 10) || 1));
|
||||
const user = getUser(req);
|
||||
const values = [`%${escapeLike(keyword)}%`];
|
||||
let where = '(p.title ILIKE $1 OR p.content ILIKE $1)';
|
||||
|
||||
try {
|
||||
if (user) {
|
||||
await ensureUserBlocksSchema();
|
||||
values.push(user.id);
|
||||
where += ` AND NOT EXISTS (
|
||||
SELECT 1 FROM user_blocks b WHERE b.blocker_id = $2 AND b.blocked_id = p.user_id
|
||||
)`;
|
||||
}
|
||||
await ensurePostNumberSchema();
|
||||
const count = await pool.query(`SELECT COUNT(*) AS total FROM posts p WHERE ${where}`, values);
|
||||
const total = Number(count.rows[0].total);
|
||||
const rows = await pool.query(`
|
||||
SELECT p.*, u.username, u.avatar_url, u.signature,
|
||||
(SELECT COUNT(*) FROM replies WHERE post_id = p.id) AS reply_count
|
||||
FROM posts p JOIN users u ON u.id = p.user_id
|
||||
WHERE ${where}
|
||||
ORDER BY p.created_at DESC
|
||||
LIMIT $${values.length + 1} OFFSET $${values.length + 2}
|
||||
`, [...values, limit, (page - 1) * limit]);
|
||||
return Response.json({
|
||||
data: rows.rows,
|
||||
query: keyword,
|
||||
pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
|
||||
}, { headers: { 'Cache-Control': 'private, no-store' } });
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, requireAdmin } from '@/lib/auth';
|
||||
import { jsonWithEtag } from '@/lib/http-cache';
|
||||
import { loadSmtpConfig, isConfigComplete } from '@/lib/mailer';
|
||||
|
||||
const VERSION_COMMIT = (process.env.FORUMLIFY_COMMIT || 'unknown').slice(0, 7);
|
||||
|
||||
@@ -15,10 +16,14 @@ export async function GET(req) {
|
||||
`INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify')
|
||||
ON CONFLICT (key) DO NOTHING`
|
||||
);
|
||||
const r = await pool.query('SELECT key, value FROM settings ORDER BY key');
|
||||
const r = await pool.query(`SELECT key, value FROM settings
|
||||
WHERE key = ANY($1::text[]) ORDER BY key`,
|
||||
[['forum_name', 'favicon_url', 'favicon_version', 'custom_css_enabled', 'email_verify_required']]);
|
||||
const settings = {};
|
||||
r.rows.forEach((row) => { settings[row.key] = row.value; });
|
||||
delete settings.favicon_object;
|
||||
const config = await loadSmtpConfig();
|
||||
settings.smtp_ready = isConfigComplete(config);
|
||||
settings.email_verify_required = settings.email_verify_required === 'true' && settings.smtp_ready;
|
||||
// 兜底:即使插入失败也保证返回 forum_name
|
||||
if (!settings.forum_name) settings.forum_name = 'Forumlify';
|
||||
settings.version_commit = VERSION_COMMIT;
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
import { ensureUserBlocksSchema, UUID_RE } from '@/lib/user-blocks';
|
||||
|
||||
export async function GET(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
const targetId = (await params).id;
|
||||
if (!UUID_RE.test(targetId)) return Response.json({ error: '用户不存在' }, { status: 404 });
|
||||
if (targetId === user.id) return Response.json({ blocked_by_me: false, blocked_me: false, self: true });
|
||||
try {
|
||||
await ensureUserBlocksSchema();
|
||||
const result = await pool.query(`
|
||||
SELECT
|
||||
EXISTS(SELECT 1 FROM user_blocks WHERE blocker_id = $1 AND blocked_id = $2) AS blocked_by_me,
|
||||
EXISTS(SELECT 1 FROM user_blocks WHERE blocker_id = $2 AND blocked_id = $1) AS blocked_me
|
||||
`, [user.id, targetId]);
|
||||
return Response.json(result.rows[0], { headers: { 'Cache-Control': 'private, no-store' } });
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
import { ensureUserBlocksSchema, UUID_RE } from '@/lib/user-blocks';
|
||||
|
||||
export async function POST(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
const targetId = (await params).id;
|
||||
if (!UUID_RE.test(targetId) || targetId === user.id) {
|
||||
return Response.json({ error: '不能屏蔽该用户' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
await ensureUserBlocksSchema();
|
||||
const result = await pool.query(`
|
||||
INSERT INTO user_blocks (blocker_id, blocked_id)
|
||||
SELECT $1, id FROM users WHERE id = $2
|
||||
ON CONFLICT (blocker_id, blocked_id) DO NOTHING RETURNING id
|
||||
`, [user.id, targetId]);
|
||||
if (!result.rowCount) {
|
||||
const target = await pool.query('SELECT id FROM users WHERE id = $1', [targetId]);
|
||||
if (!target.rowCount) return Response.json({ error: '用户不存在' }, { status: 404 });
|
||||
}
|
||||
return Response.json({ success: true, blocked: true });
|
||||
} catch {
|
||||
return Response.json({ error: '操作失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
const targetId = (await params).id;
|
||||
if (!UUID_RE.test(targetId)) return Response.json({ error: '用户不存在' }, { status: 404 });
|
||||
try {
|
||||
await ensureUserBlocksSchema();
|
||||
await pool.query('DELETE FROM user_blocks WHERE blocker_id = $1 AND blocked_id = $2', [user.id, targetId]);
|
||||
return Response.json({ success: true, blocked: false });
|
||||
} catch {
|
||||
return Response.json({ error: '操作失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
import { ensureUserBlocksSchema } from '@/lib/user-blocks';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function GET(req) {
|
||||
const url = new URL(req.url);
|
||||
const keyword = (url.searchParams.get('q') || '').trim();
|
||||
if (!keyword) return Response.json({ error: '请输入搜索关键词' }, { status: 400 });
|
||||
if (keyword.length > 50) return Response.json({ error: '搜索关键词过长(最多 50 字)' }, { status: 400 });
|
||||
|
||||
const limit = Math.min(20, Math.max(1, parseInt(url.searchParams.get('limit'), 10) || 10));
|
||||
const user = getUser(req);
|
||||
try {
|
||||
const values = [`%${keyword.replace(/[\\%_]/g, (character) => `\\${character}`)}%`,
|
||||
`${keyword.replace(/[\\%_]/g, (character) => `\\${character}`)}%`];
|
||||
let filter = '';
|
||||
if (user) {
|
||||
await ensureUserBlocksSchema();
|
||||
values.push(user.id);
|
||||
filter = ` AND u.id <> $3 AND NOT EXISTS (
|
||||
SELECT 1 FROM user_blocks b WHERE b.blocker_id = $3 AND b.blocked_id = u.id
|
||||
)`;
|
||||
}
|
||||
values.push(limit);
|
||||
const result = await pool.query(`
|
||||
SELECT u.id, u.username, u.avatar_url, u.role, u.signature
|
||||
FROM users u WHERE u.username ILIKE $1${filter}
|
||||
ORDER BY CASE WHEN u.username ILIKE $2 THEN 0 ELSE 1 END,
|
||||
LENGTH(u.username), u.username
|
||||
LIMIT $${values.length}
|
||||
`, values);
|
||||
return Response.json({ data: result.rows, query: keyword }, { headers: { 'Cache-Control': 'private, no-store' } });
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user