Compare commits
6
Commits
| Author | SHA1 | Date | ||
|---|---|---|---|---|
| ||||
|
|
b42944b687 | |||
| ||||
|
|
f59739e36f | |||
| ||||
|
|
fea9ad1c48 | |||
| ||||
|
|
6a0b6adf61 | |||
| ||||
|
|
56352167b4 | |||
|
|
fff303a46e | |||
No files matched your search
@@ -4,7 +4,8 @@
|
|||||||
|
|
||||||
> 一个简洁、优雅的现代社区系统。5 分钟 Docker 一键部署。
|
> 一个简洁、优雅的现代社区系统。5 分钟 Docker 一键部署。
|
||||||
|
|
||||||
官方演示地址:[Forumlify NEXT](https://next.forumlify.org)
|
官方演示地址:【维护中】
|
||||||
|
|
||||||
|
|
||||||
## ✨ 特性
|
## ✨ 特性
|
||||||
|
|
||||||
|
|||||||
@@ -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 pool from '@/lib/db';
|
||||||
import { verifyCaptcha } from '@/lib/captcha';
|
import { verifyCaptcha } from '@/lib/captcha';
|
||||||
import { logAudit } from '@/lib/audit';
|
import { logAudit } from '@/lib/audit';
|
||||||
|
import { normalizeEmail, isEmailVerificationRequired, withEmailCode, CODE_ERRORS, ensureEmailVerificationSchema } from '@/lib/email-verification';
|
||||||
|
|
||||||
export async function POST(req) {
|
export async function POST(req) {
|
||||||
const { email, password, username, captcha_id, captcha_answer, captcha_sig } = await req.json();
|
const { email, password, username, email_code, captcha_id, captcha_answer, captcha_sig } = await req.json();
|
||||||
if (!email || !password || !username) {
|
const normalizedEmail = normalizeEmail(email);
|
||||||
|
if (!normalizedEmail || !password || !username) {
|
||||||
return Response.json({ error: '请填写完整信息' }, { status: 400 });
|
return Response.json({ error: '请填写完整信息' }, { status: 400 });
|
||||||
}
|
}
|
||||||
if (password.length < 6) {
|
if (typeof password !== 'string' || password.length < 6 || password.length > 128 ||
|
||||||
return Response.json({ error: '密码至少6位' }, { status: 400 });
|
typeof username !== 'string' || !username.trim() || username.length > 50) {
|
||||||
|
return Response.json({ error: '用户名或密码长度无效' }, { status: 400 });
|
||||||
}
|
}
|
||||||
// 服务端验证码校验(ENABLE_CAPTCHA 关闭时跳过)
|
// 服务端验证码校验(ENABLE_CAPTCHA 关闭时跳过)
|
||||||
if (process.env.ENABLE_CAPTCHA !== 'false' && !verifyCaptcha(captcha_id, captcha_answer, captcha_sig)) {
|
if (process.env.ENABLE_CAPTCHA !== 'false' && !verifyCaptcha(captcha_id, captcha_answer, captcha_sig)) {
|
||||||
return Response.json({ error: '验证码错误,请重新计算' }, { status: 400 });
|
return Response.json({ error: '验证码错误,请重新计算' }, { status: 400 });
|
||||||
}
|
}
|
||||||
try {
|
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 countResult = await pool.query('SELECT COUNT(*) FROM users');
|
||||||
const isFirstUser = parseInt(countResult.rows[0].count) === 0;
|
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 avatar = 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) + '&background=6366f1&color=fff&size=64';
|
||||||
const role = isFirstUser ? 'admin' : 'user';
|
const role = isFirstUser ? 'admin' : 'user';
|
||||||
|
|
||||||
const r = await pool.query(
|
const insert = (client) => client.query(
|
||||||
`INSERT INTO users (email, password_hash, username, avatar_url, role)
|
`INSERT INTO users (email, password_hash, username, avatar_url, role, email_verified)
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
VALUES ($1, $2, $3, $4, $5, $6)
|
||||||
RETURNING id, username, avatar_url, role, created_at`,
|
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);
|
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
|
// GET /api/conversations/[id]/messages, POST /api/conversations/[id]/messages
|
||||||
import pool from '@/lib/db';
|
import pool from '@/lib/db';
|
||||||
import { getUser } from '@/lib/auth';
|
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;
|
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 });
|
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
|
||||||
}
|
}
|
||||||
const { content } = await req.json();
|
const { content } = await req.json();
|
||||||
if (!content || content.trim().length === 0) {
|
if (typeof content !== 'string' || !content.trim() || content.length > 10000) {
|
||||||
return Response.json({ error: '请填写消息内容' }, { status: 400 });
|
return Response.json({ error: '消息长度应为1到10000个字符' }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
const client = await pool.connect();
|
||||||
try {
|
try {
|
||||||
const check = await pool.query(`
|
await ensureUserBlocksSchema();
|
||||||
SELECT id FROM conversations
|
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)
|
WHERE id = $1 AND (user1_id = $2 OR user2_id = $2)
|
||||||
|
FOR UPDATE
|
||||||
`, [(await params).id, user.id]);
|
`, [(await params).id, user.id]);
|
||||||
if (check.rows.length === 0) {
|
if (check.rows.length === 0) {
|
||||||
|
await client.query('ROLLBACK');
|
||||||
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
|
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)
|
INSERT INTO messages (conversation_id, sender_id, content)
|
||||||
VALUES ($1, $2, $3)
|
VALUES ($1, $2, $3)
|
||||||
RETURNING *
|
RETURNING *
|
||||||
`, [(await params).id, user.id, content]);
|
`, [(await params).id, user.id, content.trim()]);
|
||||||
await pool.query('UPDATE conversations SET last_message_at = NOW() WHERE id = $1', [(await params).id]);
|
await client.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]);
|
const userInfo = await client.query('SELECT username, avatar_url FROM users WHERE id = $1', [user.id]);
|
||||||
|
await client.query('COMMIT');
|
||||||
return Response.json({
|
return Response.json({
|
||||||
...r.rows[0],
|
...r.rows[0],
|
||||||
sender_username: userInfo.rows[0].username,
|
sender_username: userInfo.rows[0].username,
|
||||||
sender_avatar_url: userInfo.rows[0].avatar_url,
|
sender_avatar_url: userInfo.rows[0].avatar_url,
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
|
await client.query('ROLLBACK').catch(() => {});
|
||||||
return Response.json({ error: '发送失败,请稍后重试' }, { status: 500 });
|
return Response.json({ error: '发送失败,请稍后重试' }, { status: 500 });
|
||||||
|
} finally {
|
||||||
|
client.release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
// GET /api/conversations, POST /api/conversations
|
// GET /api/conversations, POST /api/conversations
|
||||||
import pool from '@/lib/db';
|
import pool from '@/lib/db';
|
||||||
import { getUser } from '@/lib/auth';
|
import { getUser } from '@/lib/auth';
|
||||||
|
import { ensureUserBlocksSchema, hasBlocked, UUID_RE } from '@/lib/user-blocks';
|
||||||
|
|
||||||
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
|
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
|
||||||
export const dynamic = 'force-dynamic';
|
export const dynamic = 'force-dynamic';
|
||||||
@@ -42,17 +43,21 @@ export async function POST(req) {
|
|||||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||||
}
|
}
|
||||||
const { other_user_id } = await req.json();
|
const { other_user_id } = await req.json();
|
||||||
if (!other_user_id) {
|
if (!UUID_RE.test(other_user_id || '')) {
|
||||||
return Response.json({ error: '缺少对方用户ID' }, { status: 400 });
|
return Response.json({ error: '对方用户ID无效' }, { status: 400 });
|
||||||
}
|
}
|
||||||
if (other_user_id === user.id) {
|
if (other_user_id === user.id) {
|
||||||
return Response.json({ error: '不能与自己私信' }, { status: 400 });
|
return Response.json({ error: '不能与自己私信' }, { status: 400 });
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
|
await ensureUserBlocksSchema();
|
||||||
const userCheck = await pool.query('SELECT id FROM users WHERE id = $1', [other_user_id]);
|
const userCheck = await pool.query('SELECT id FROM users WHERE id = $1', [other_user_id]);
|
||||||
if (userCheck.rows.length === 0) {
|
if (userCheck.rows.length === 0) {
|
||||||
return Response.json({ error: '用户不存在' }, { status: 404 });
|
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(`
|
const existing = await pool.query(`
|
||||||
SELECT id FROM conversations
|
SELECT id FROM conversations
|
||||||
WHERE (user1_id = $1 AND user2_id = $2) OR (user1_id = $2 AND user2_id = $1)
|
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(`
|
const r = await pool.query(`
|
||||||
INSERT INTO conversations (user1_id, user2_id)
|
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
|
RETURNING id
|
||||||
`, [user.id, other_user_id]);
|
`, [user.id, other_user_id]);
|
||||||
return Response.json({ id: r.rows[0].id });
|
return Response.json({ id: r.rows[0].id });
|
||||||
|
|||||||
@@ -6,8 +6,12 @@ import { verifyCaptcha } from '@/lib/captcha';
|
|||||||
import { logAudit } from '@/lib/audit';
|
import { logAudit } from '@/lib/audit';
|
||||||
import { getReplySchemaCapabilities } from '@/lib/reply-schema';
|
import { getReplySchemaCapabilities } from '@/lib/reply-schema';
|
||||||
import { resolvePostReference } from '@/lib/post-reference';
|
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) {
|
if (capabilities.replyToId) {
|
||||||
return `SELECT r.id, r.post_id, r.user_id, r.content, r.created_at,
|
return `SELECT r.id, r.post_id, r.user_id, r.content, r.created_at,
|
||||||
r.reply_to_id, u.username, u.avatar_url,
|
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
|
JOIN users u ON r.user_id = u.id
|
||||||
LEFT JOIN replies rt ON r.reply_to_id = rt.id
|
LEFT JOIN replies rt ON r.reply_to_id = rt.id
|
||||||
LEFT JOIN users ru ON rt.user_id = ru.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`;
|
ORDER BY r.created_at ASC`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -27,7 +31,7 @@ function repliesSelectSql(capabilities) {
|
|||||||
r.reply_to_username
|
r.reply_to_username
|
||||||
FROM replies r
|
FROM replies r
|
||||||
JOIN users u ON r.user_id = u.id
|
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`;
|
ORDER BY r.created_at ASC`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,7 +41,7 @@ function repliesSelectSql(capabilities) {
|
|||||||
u.username, u.avatar_url
|
u.username, u.avatar_url
|
||||||
FROM replies r
|
FROM replies r
|
||||||
JOIN users u ON r.user_id = u.id
|
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`;
|
ORDER BY r.created_at ASC`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,9 +49,13 @@ export async function GET(req, { params }) {
|
|||||||
try {
|
try {
|
||||||
const reference = await resolvePostReference((await params).id);
|
const reference = await resolvePostReference((await params).id);
|
||||||
if (!reference) return Response.json({ error: '帖子不存在' }, { status: 404 });
|
if (!reference) return Response.json({ error: '帖子不存在' }, { status: 404 });
|
||||||
|
const viewer = getUser(req);
|
||||||
|
if (viewer) await ensureUserBlocksSchema();
|
||||||
const capabilities = await getReplySchemaCapabilities();
|
const capabilities = await getReplySchemaCapabilities();
|
||||||
const r = await pool.query(repliesSelectSql(capabilities), [reference.id]);
|
const r = await pool.query(repliesSelectSql(capabilities, viewer), viewer ? [reference.id, viewer.id] : [reference.id]);
|
||||||
return jsonWithEtag(req, r.rows);
|
return viewer
|
||||||
|
? Response.json(r.rows, { headers: { 'Cache-Control': 'private, no-store' } })
|
||||||
|
: jsonWithEtag(req, r.rows);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('[replies] list failed:', error?.code || error?.message);
|
console.error('[replies] list failed:', error?.code || error?.message);
|
||||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import pool from '@/lib/db';
|
|||||||
import { getUser } from '@/lib/auth';
|
import { getUser } from '@/lib/auth';
|
||||||
import { jsonWithEtag } from '@/lib/http-cache';
|
import { jsonWithEtag } from '@/lib/http-cache';
|
||||||
import { resolvePostReference } from '@/lib/post-reference';
|
import { resolvePostReference } from '@/lib/post-reference';
|
||||||
|
import { ensureUserBlocksSchema } from '@/lib/user-blocks';
|
||||||
|
|
||||||
function invalidId() {
|
function invalidId() {
|
||||||
return Response.json({ error: '帖子不存在' }, { status: 404 });
|
return Response.json({ error: '帖子不存在' }, { status: 404 });
|
||||||
@@ -10,19 +11,25 @@ function invalidId() {
|
|||||||
|
|
||||||
export async function GET(req, { params }) {
|
export async function GET(req, { params }) {
|
||||||
try {
|
try {
|
||||||
|
const viewer = getUser(req);
|
||||||
const reference = await resolvePostReference((await params).id);
|
const reference = await resolvePostReference((await params).id);
|
||||||
if (!reference) return invalidId();
|
if (!reference) return invalidId();
|
||||||
|
if (viewer) await ensureUserBlocksSchema();
|
||||||
const r = await pool.query(
|
const r = await pool.query(
|
||||||
`SELECT p.*, u.username, u.avatar_url, u.signature
|
`SELECT p.*, u.username, u.avatar_url, u.signature
|
||||||
FROM posts p
|
FROM posts p
|
||||||
JOIN users u ON p.user_id = u.id
|
JOIN users u ON p.user_id = u.id
|
||||||
WHERE p.id = $1`,
|
WHERE p.id = $1${viewer ? ` AND NOT EXISTS (
|
||||||
[reference.id]
|
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) {
|
if (r.rows.length === 0) {
|
||||||
return invalidId();
|
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 {
|
} catch {
|
||||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||||
}
|
}
|
||||||
|
|||||||
+19
-6
@@ -5,6 +5,7 @@ import { jsonWithEtag } from '@/lib/http-cache';
|
|||||||
import { verifyCaptcha } from '@/lib/captcha';
|
import { verifyCaptcha } from '@/lib/captcha';
|
||||||
import { logAudit } from '@/lib/audit';
|
import { logAudit } from '@/lib/audit';
|
||||||
import { ensurePostNumberSchema } from '@/lib/post-reference';
|
import { ensurePostNumberSchema } from '@/lib/post-reference';
|
||||||
|
import { ensureUserBlocksSchema } from '@/lib/user-blocks';
|
||||||
|
|
||||||
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
|
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
|
||||||
export const dynamic = 'force-dynamic';
|
export const dynamic = 'force-dynamic';
|
||||||
@@ -14,6 +15,7 @@ export async function GET(req) {
|
|||||||
const url = new URL(req.url);
|
const url = new URL(req.url);
|
||||||
const sort = url.searchParams.get('sort') === 'hot' ? 'updated_at' : 'created_at';
|
const sort = url.searchParams.get('sort') === 'hot' ? 'updated_at' : 'created_at';
|
||||||
const userId = url.searchParams.get('user_id');
|
const userId = url.searchParams.get('user_id');
|
||||||
|
const viewer = getUser(req);
|
||||||
const page = Math.max(1, parseInt(url.searchParams.get('page')) || 1);
|
const page = Math.max(1, parseInt(url.searchParams.get('page')) || 1);
|
||||||
// 分页边界:limit 封顶 50,page 封顶 10000(防深分页 DoS)
|
// 分页边界:limit 封顶 50,page 封顶 10000(防深分页 DoS)
|
||||||
const limit = Math.min(50, Math.max(1, parseInt(url.searchParams.get('limit')) || 20));
|
const limit = Math.min(50, Math.max(1, parseInt(url.searchParams.get('limit')) || 20));
|
||||||
@@ -24,11 +26,19 @@ export async function GET(req) {
|
|||||||
try {
|
try {
|
||||||
await ensurePostNumberSchema();
|
await ensurePostNumberSchema();
|
||||||
const params = [];
|
const params = [];
|
||||||
let where = '';
|
const conditions = [];
|
||||||
if (userId) {
|
if (userId) {
|
||||||
where = ' WHERE p.user_id = $1';
|
params.push(userId);
|
||||||
(await 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 countResult = await pool.query(`SELECT COUNT(*) as total FROM posts p${where}`, params);
|
||||||
const total = parseInt(countResult.rows[0]?.total || 0);
|
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
|
JOIN users u ON p.user_id = u.id
|
||||||
${where}
|
${where}
|
||||||
ORDER BY is_pinned DESC, pinned_at DESC NULLS LAST, ${sort} DESC
|
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]);
|
`, [...params, limit, offset]);
|
||||||
|
|
||||||
return jsonWithEtag(req, {
|
const payload = {
|
||||||
data: r.rows,
|
data: r.rows,
|
||||||
pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
|
pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
|
||||||
});
|
};
|
||||||
|
return viewer
|
||||||
|
? Response.json(payload, { headers: { 'Cache-Control': 'private, no-store' } })
|
||||||
|
: jsonWithEtag(req, payload);
|
||||||
} catch {
|
} catch {
|
||||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
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 pool from '@/lib/db';
|
||||||
import { getUser, requireAdmin } from '@/lib/auth';
|
import { getUser, requireAdmin } from '@/lib/auth';
|
||||||
import { jsonWithEtag } from '@/lib/http-cache';
|
import { jsonWithEtag } from '@/lib/http-cache';
|
||||||
|
import { loadSmtpConfig, isConfigComplete } from '@/lib/mailer';
|
||||||
|
|
||||||
const VERSION_COMMIT = (process.env.FORUMLIFY_COMMIT || 'unknown').slice(0, 7);
|
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')
|
`INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify')
|
||||||
ON CONFLICT (key) DO NOTHING`
|
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 = {};
|
const settings = {};
|
||||||
r.rows.forEach((row) => { settings[row.key] = row.value; });
|
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
|
// 兜底:即使插入失败也保证返回 forum_name
|
||||||
if (!settings.forum_name) settings.forum_name = 'Forumlify';
|
if (!settings.forum_name) settings.forum_name = 'Forumlify';
|
||||||
settings.version_commit = VERSION_COMMIT;
|
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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
+272
-4
@@ -514,6 +514,119 @@ svg {
|
|||||||
margin-right: 6px;
|
margin-right: 6px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.feed-search {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
width: 100%;
|
||||||
|
min-height: 44px;
|
||||||
|
padding: 0 14px;
|
||||||
|
margin: 0 0 18px;
|
||||||
|
border: 1px solid var(--glass-border);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
background: var(--glass-bg);
|
||||||
|
color: var(--glass-text-secondary);
|
||||||
|
backdrop-filter: blur(12px);
|
||||||
|
-webkit-backdrop-filter: blur(12px);
|
||||||
|
}
|
||||||
|
.feed-search:focus-within { border-color: var(--primary); }
|
||||||
|
.feed-search input {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
border: 0;
|
||||||
|
outline: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--glass-text);
|
||||||
|
font: inherit;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
.feed-search input::-webkit-search-cancel-button { display: none; }
|
||||||
|
.feed-search button {
|
||||||
|
border: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: inherit;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.search-empty {
|
||||||
|
padding: 60px 16px;
|
||||||
|
text-align: center;
|
||||||
|
color: var(--glass-text-secondary);
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.chat-user-search {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px 16px;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
.chat-user-search input {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
border: 0;
|
||||||
|
outline: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--text);
|
||||||
|
font: inherit;
|
||||||
|
}
|
||||||
|
.chat-user-result {
|
||||||
|
width: 100%;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 10px 16px;
|
||||||
|
border: 0;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
background: transparent;
|
||||||
|
color: var(--text);
|
||||||
|
text-align: left;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.chat-user-result:hover { background: var(--glass-bg); }
|
||||||
|
.chat-user-result img { width: 36px; height: 36px; border-radius: 50%; object-fit: cover; }
|
||||||
|
.chat-search-state { padding: 32px 16px; text-align: center; color: var(--text-secondary); }
|
||||||
|
.user-profile-actions { display: flex; justify-content: center; gap: 10px; flex-wrap: wrap; margin-top: 12px; }
|
||||||
|
.user-profile-actions button { padding: 8px 20px; }
|
||||||
|
.blocked-user-hint { margin-top: 10px; font-size: 12px; color: var(--text-secondary); }
|
||||||
|
.chat-limit-hint { padding: 8px 16px; font-size: 12px; color: var(--text-secondary); text-align: center; }
|
||||||
|
.smtp-settings { max-width: 860px; overflow-wrap: anywhere; }
|
||||||
|
.smtp-settings h3 { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
|
||||||
|
.smtp-settings label { display: block; font-size: 14px; font-weight: 600; color: var(--text); }
|
||||||
|
.smtp-settings input:not([type="checkbox"]) {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
|
margin: 6px 0 14px;
|
||||||
|
padding: 9px 12px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 6px;
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
font: inherit;
|
||||||
|
}
|
||||||
|
.smtp-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0 16px; }
|
||||||
|
.smtp-settings .smtp-check { display: flex; align-items: center; gap: 8px; margin: 10px 0; font-weight: 500; }
|
||||||
|
.smtp-actions { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 14px; }
|
||||||
|
.smtp-actions button { padding: 9px 18px; }
|
||||||
|
@media (max-width: 600px) { .smtp-grid { grid-template-columns: minmax(0, 1fr); } }
|
||||||
|
.auth-email-code-row { display: flex; align-items: stretch; gap: 8px; }
|
||||||
|
.auth-email-code-row input { min-width: 0; flex: 1; }
|
||||||
|
.auth-email-code-row button, .auth-send-code {
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 6px;
|
||||||
|
background: var(--surface);
|
||||||
|
color: var(--text);
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 8px 12px;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.auth-email-code-row button { align-self: flex-start; }
|
||||||
|
.auth-send-code { margin-bottom: 10px; }
|
||||||
|
.auth-reset-methods { display: flex; gap: 8px; margin-bottom: 12px; }
|
||||||
|
.auth-reset-methods button { flex: 1; padding: 8px; border: 1px solid var(--border); border-radius: 6px; background: var(--surface); color: var(--text-secondary); cursor: pointer; }
|
||||||
|
.auth-reset-methods button.active { border-color: var(--primary); color: var(--primary); }
|
||||||
|
|
||||||
.new-post-launch-label,
|
.new-post-launch-label,
|
||||||
.new-post-title-label {
|
.new-post-title-label {
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
@@ -580,6 +693,152 @@ svg {
|
|||||||
background: var(--feed-card-hover-bg);
|
background: var(--feed-card-hover-bg);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Lite 版主题列表的视觉语言:更清晰的层级、元信息和回复数胶囊,
|
||||||
|
保留 Next 版正文、图片和操作能力。 */
|
||||||
|
#feed .post-card {
|
||||||
|
padding: 16px 20px;
|
||||||
|
border-color: color-mix(in srgb, var(--glass-border) 72%, var(--primary) 28%);
|
||||||
|
box-shadow: 0 5px 20px rgba(25, 45, 65, 0.07);
|
||||||
|
}
|
||||||
|
|
||||||
|
#feed .post-card:hover {
|
||||||
|
transform: translateY(-2px);
|
||||||
|
box-shadow: 0 12px 28px rgba(25, 45, 65, 0.12);
|
||||||
|
}
|
||||||
|
|
||||||
|
#feed .topic-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 14px;
|
||||||
|
padding: 14px 18px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
#feed .topic-main {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#feed .topic-title-line {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#feed .topic-title-line .post-title {
|
||||||
|
min-width: 0;
|
||||||
|
margin: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
#feed .topic-meta {
|
||||||
|
margin: 5px 0 0;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#feed .topic-preview {
|
||||||
|
display: -webkit-box;
|
||||||
|
-webkit-box-orient: vertical;
|
||||||
|
-webkit-line-clamp: 1;
|
||||||
|
overflow: hidden;
|
||||||
|
margin-top: 4px;
|
||||||
|
color: var(--glass-text-light);
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
|
||||||
|
#feed .topic-replies {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
min-width: 38px;
|
||||||
|
padding: 4px 10px;
|
||||||
|
border: 1px solid var(--glass-border);
|
||||||
|
border-radius: 999px;
|
||||||
|
background: color-mix(in srgb, var(--glass-bg) 78%, var(--primary) 22%);
|
||||||
|
color: var(--glass-text-secondary);
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
#feed .topic-actions {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
#feed .post-header {
|
||||||
|
gap: 8px;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#feed .post-title {
|
||||||
|
margin: 4px 0 6px;
|
||||||
|
font-size: 16px;
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
|
||||||
|
#feed .post-content {
|
||||||
|
display: -webkit-box;
|
||||||
|
-webkit-box-orient: vertical;
|
||||||
|
-webkit-line-clamp: 3;
|
||||||
|
overflow: hidden;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
#feed .post-actions {
|
||||||
|
gap: 10px;
|
||||||
|
padding-top: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#feed .post-replies {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
min-width: 42px;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 3px 10px;
|
||||||
|
border: 1px solid var(--glass-border);
|
||||||
|
border-radius: 999px;
|
||||||
|
background: color-mix(in srgb, var(--glass-bg) 76%, var(--primary) 24%);
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--glass-text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
#feed .post-pin-state {
|
||||||
|
padding: 3px 8px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: color-mix(in srgb, var(--primary-bg) 70%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
#feed .post-card {
|
||||||
|
padding: 14px 16px;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
#feed .topic-row {
|
||||||
|
gap: 10px;
|
||||||
|
padding: 13px 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#feed .topic-title-line .post-title {
|
||||||
|
white-space: normal;
|
||||||
|
display: -webkit-box;
|
||||||
|
-webkit-box-orient: vertical;
|
||||||
|
-webkit-line-clamp: 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
#feed .post-time {
|
||||||
|
max-width: 42%;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.post-header {
|
.post-header {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@@ -1498,6 +1757,7 @@ html.post-view-transition::view-transition-group(post-expand),
|
|||||||
html.home-view-transition.returning-home::view-transition-group(post-expand) {
|
html.home-view-transition.returning-home::view-transition-group(post-expand) {
|
||||||
animation-duration: 1.1s;
|
animation-duration: 1.1s;
|
||||||
animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1);
|
animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1);
|
||||||
|
background: var(--glass-bg);
|
||||||
border-radius: var(--radius);
|
border-radius: var(--radius);
|
||||||
overflow: clip;
|
overflow: clip;
|
||||||
}
|
}
|
||||||
@@ -1658,17 +1918,25 @@ html.post-view-transition::view-transition-old(post-feed-actions) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
html.post-view-transition::view-transition-old(post-body) {
|
html.post-view-transition::view-transition-old(post-body) {
|
||||||
animation: none;
|
animation: postBodyPreviewOut 0.96s linear both;
|
||||||
opacity: 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
html.post-view-transition::view-transition-new(post-body) {
|
html.post-view-transition::view-transition-new(post-body) {
|
||||||
animation: none;
|
animation: postBodyDetailIn 0.96s linear both;
|
||||||
opacity: 1;
|
|
||||||
object-fit: none;
|
object-fit: none;
|
||||||
object-position: left top;
|
object-position: left top;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@keyframes postBodyPreviewOut {
|
||||||
|
0%, 62% { opacity: 1; }
|
||||||
|
78%, 100% { opacity: 0; }
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes postBodyDetailIn {
|
||||||
|
0%, 62% { opacity: 0; }
|
||||||
|
78%, 100% { opacity: 1; }
|
||||||
|
}
|
||||||
|
|
||||||
html.post-view-transition::view-transition-new(post-detail-controls),
|
html.post-view-transition::view-transition-new(post-detail-controls),
|
||||||
html.post-view-transition::view-transition-new(post-detail-signature) {
|
html.post-view-transition::view-transition-new(post-detail-signature) {
|
||||||
animation: detailOnlyPartIn 0.22s 0.62s ease-out both;
|
animation: detailOnlyPartIn 0.22s 0.62s ease-out both;
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import AdminLinks from './admin/AdminLinks';
|
|||||||
import AdminForumSettings from './admin/AdminForumSettings';
|
import AdminForumSettings from './admin/AdminForumSettings';
|
||||||
import AdminCustomPages from './admin/AdminCustomPages';
|
import AdminCustomPages from './admin/AdminCustomPages';
|
||||||
import AdminCustomCss from './admin/AdminCustomCss';
|
import AdminCustomCss from './admin/AdminCustomCss';
|
||||||
|
import AdminMailSettings from './admin/AdminMailSettings';
|
||||||
|
|
||||||
const NAV = [
|
const NAV = [
|
||||||
{ key: 'reports', labelKey: 'admin.reports', icon: 'shieldAlert' },
|
{ key: 'reports', labelKey: 'admin.reports', icon: 'shieldAlert' },
|
||||||
@@ -18,6 +19,7 @@ const NAV = [
|
|||||||
{ key: 'logs', labelKey: 'admin.logs', icon: 'file' },
|
{ key: 'logs', labelKey: 'admin.logs', icon: 'file' },
|
||||||
{ key: 'links', labelKey: 'admin.links', icon: 'link' },
|
{ key: 'links', labelKey: 'admin.links', icon: 'link' },
|
||||||
{ key: 'settings', labelKey: 'admin.forumSettings', icon: 'settings' },
|
{ key: 'settings', labelKey: 'admin.forumSettings', icon: 'settings' },
|
||||||
|
{ key: 'mail', labelKey: 'admin.mail', icon: 'message' },
|
||||||
{ key: 'custom', labelKey: 'admin.customPages', icon: 'file' },
|
{ key: 'custom', labelKey: 'admin.customPages', icon: 'file' },
|
||||||
{ key: 'css', labelKey: 'admin.customCss', icon: 'file' },
|
{ key: 'css', labelKey: 'admin.customCss', icon: 'file' },
|
||||||
];
|
];
|
||||||
@@ -123,6 +125,7 @@ export default function AdminPage() {
|
|||||||
if (tab === 'links') return <AdminLinks />;
|
if (tab === 'links') return <AdminLinks />;
|
||||||
if (tab === 'custom') return <AdminCustomPages />;
|
if (tab === 'custom') return <AdminCustomPages />;
|
||||||
if (tab === 'css') return <AdminCustomCss />;
|
if (tab === 'css') return <AdminCustomCss />;
|
||||||
|
if (tab === 'mail') return <AdminMailSettings />;
|
||||||
return <AdminForumSettings />;
|
return <AdminForumSettings />;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ const POST_TRANSITION_PARTS = [
|
|||||||
['.post-username', 'post-author'],
|
['.post-username', 'post-author'],
|
||||||
['.post-title', 'post-heading'],
|
['.post-title', 'post-heading'],
|
||||||
['.post-time', 'post-time'],
|
['.post-time', 'post-time'],
|
||||||
['.post-content', 'post-body'],
|
['.post-content, .topic-preview', 'post-body'],
|
||||||
['.post-images', 'post-media'],
|
['.post-images', 'post-media'],
|
||||||
['.post-pin-state', 'post-pin-state'],
|
['.post-pin-state', 'post-pin-state'],
|
||||||
['.post-edited-label', 'post-edited-label'],
|
['.post-edited-label', 'post-edited-label'],
|
||||||
@@ -937,8 +937,8 @@ export default function AppProvider({ children, cachedName = '' }) {
|
|||||||
return result;
|
return result;
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const register = useCallback(async (email, password, username, captcha) => {
|
const register = useCallback(async (email, password, username, captcha, emailCode = '') => {
|
||||||
const result = await API.register(email, password, username, captcha);
|
const result = await API.register(email, password, username, captcha, emailCode);
|
||||||
const loginResult = await API.login(email, password);
|
const loginResult = await API.login(email, password);
|
||||||
if (loginResult.user) {
|
if (loginResult.user) {
|
||||||
setCurrentUser(loginResult.user);
|
setCurrentUser(loginResult.user);
|
||||||
|
|||||||
+83
-15
@@ -17,7 +17,7 @@ function avatar(username) {
|
|||||||
|
|
||||||
export default function Feed({ onOpenModal, onReport }) {
|
export default function Feed({ onOpenModal, onReport }) {
|
||||||
const { currentUser, sort, setSort, openPost, openUser, navigate, refreshKey } = useApp();
|
const { currentUser, sort, setSort, openPost, openUser, navigate, refreshKey } = useApp();
|
||||||
const { t } = useTranslation();
|
const { t, i18n } = useTranslation();
|
||||||
const { toast, confirmAction } = useToast();
|
const { toast, confirmAction } = useToast();
|
||||||
const [posts, setPosts] = useState(null);
|
const [posts, setPosts] = useState(null);
|
||||||
const [error, setError] = useState(null);
|
const [error, setError] = useState(null);
|
||||||
@@ -26,24 +26,33 @@ export default function Feed({ onOpenModal, onReport }) {
|
|||||||
const [totalPages, setTotalPages] = useState(1);
|
const [totalPages, setTotalPages] = useState(1);
|
||||||
const [viewerSrc, setViewerSrc] = useState(null);
|
const [viewerSrc, setViewerSrc] = useState(null);
|
||||||
const [selectedSort, setSelectedSort] = useState(sort);
|
const [selectedSort, setSelectedSort] = useState(sort);
|
||||||
|
const [searchInput, setSearchInput] = useState(() => typeof window === 'undefined' ? '' : new URLSearchParams(window.location.search).get('q') || '');
|
||||||
|
const [searchQuery, setSearchQuery] = useState(() => typeof window === 'undefined' ? '' : new URLSearchParams(window.location.search).get('q') || '');
|
||||||
const [drawerPhase, setDrawerPhase] = useState('closed');
|
const [drawerPhase, setDrawerPhase] = useState('closed');
|
||||||
const postListRef = useRef(null);
|
const postListRef = useRef(null);
|
||||||
const sortTimerRef = useRef(null);
|
const sortTimerRef = useRef(null);
|
||||||
const pendingSortRef = useRef(null);
|
const pendingSortRef = useRef(null);
|
||||||
const initialDrawerOpenedRef = useRef(false);
|
const initialDrawerOpenedRef = useRef(false);
|
||||||
|
const requestRef = useRef(0);
|
||||||
const PAGE_SIZE = 20;
|
const PAGE_SIZE = 20;
|
||||||
|
|
||||||
const load = useCallback(async (targetPage) => {
|
const load = useCallback(async (targetPage) => {
|
||||||
|
const requestId = ++requestRef.current;
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const result = await API.getPosts(sort, null, targetPage, PAGE_SIZE);
|
const result = searchQuery
|
||||||
|
? await API.searchPosts(searchQuery, targetPage, PAGE_SIZE)
|
||||||
|
: await API.getPosts(sort, null, targetPage, PAGE_SIZE);
|
||||||
|
if (requestId !== requestRef.current) return;
|
||||||
setPosts(result.data || []);
|
setPosts(result.data || []);
|
||||||
setTotalPages(result.pagination?.totalPages || 1);
|
setTotalPages(result.pagination?.totalPages || 1);
|
||||||
setPage(result.pagination?.page || 1);
|
setPage(result.pagination?.page || 1);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
if (requestId !== requestRef.current) return;
|
||||||
setError(err.message);
|
setError(err.message);
|
||||||
setPosts([]);
|
setPosts([]);
|
||||||
} finally {
|
} finally {
|
||||||
|
if (requestId !== requestRef.current) return;
|
||||||
if (pendingSortRef.current === sort) {
|
if (pendingSortRef.current === sort) {
|
||||||
requestAnimationFrame(() => {
|
requestAnimationFrame(() => {
|
||||||
setDrawerPhase('opening');
|
setDrawerPhase('opening');
|
||||||
@@ -62,10 +71,35 @@ export default function Feed({ onOpenModal, onReport }) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [sort, refreshKey]);
|
}, [sort, searchQuery, refreshKey]);
|
||||||
|
|
||||||
useEffect(() => { load(page); }, [load]);
|
useEffect(() => { load(page); }, [load]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onPopState = () => {
|
||||||
|
const query = new URLSearchParams(window.location.search).get('q') || '';
|
||||||
|
setSearchInput(query);
|
||||||
|
setSearchQuery(query);
|
||||||
|
setPage(1);
|
||||||
|
};
|
||||||
|
window.addEventListener('popstate', onPopState);
|
||||||
|
return () => window.removeEventListener('popstate', onPopState);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
const next = searchInput.trim();
|
||||||
|
if (next === searchQuery) return;
|
||||||
|
const url = new URL(window.location.href);
|
||||||
|
if (next) url.searchParams.set('q', next);
|
||||||
|
else url.searchParams.delete('q');
|
||||||
|
window.history.replaceState(window.history.state, '', url);
|
||||||
|
setPage(1);
|
||||||
|
setSearchQuery(next);
|
||||||
|
}, 350);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, [searchInput, searchQuery]);
|
||||||
|
|
||||||
// 长帖内容:超过 3 行时加 .has-fade(底部渐变遮罩提示还有更多内容)
|
// 长帖内容:超过 3 行时加 .has-fade(底部渐变遮罩提示还有更多内容)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!posts || posts.length === 0 || !postListRef.current) return;
|
if (!posts || posts.length === 0 || !postListRef.current) return;
|
||||||
@@ -85,6 +119,13 @@ export default function Feed({ onOpenModal, onReport }) {
|
|||||||
useEffect(() => () => clearTimeout(sortTimerRef.current), []);
|
useEffect(() => () => clearTimeout(sortTimerRef.current), []);
|
||||||
|
|
||||||
const handleSortChange = (nextSort) => {
|
const handleSortChange = (nextSort) => {
|
||||||
|
if (searchInput) {
|
||||||
|
setSearchInput('');
|
||||||
|
setSearchQuery('');
|
||||||
|
const url = new URL(window.location.href);
|
||||||
|
url.searchParams.delete('q');
|
||||||
|
window.history.replaceState(window.history.state, '', url);
|
||||||
|
}
|
||||||
if (nextSort === selectedSort) return;
|
if (nextSort === selectedSort) return;
|
||||||
|
|
||||||
setSelectedSort(nextSort);
|
setSelectedSort(nextSort);
|
||||||
@@ -151,6 +192,31 @@ export default function Feed({ onOpenModal, onReport }) {
|
|||||||
<span className="new-post-launch-label">{t('feed.newPost')}</span>
|
<span className="new-post-launch-label">{t('feed.newPost')}</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="feed-search">
|
||||||
|
<Icon name="search" size={18} aria-hidden="true" />
|
||||||
|
<input
|
||||||
|
type="search"
|
||||||
|
name="forumlify-post-search"
|
||||||
|
autoComplete="off"
|
||||||
|
aria-label={t('feed.searchPlaceholder')}
|
||||||
|
placeholder={t('feed.searchPlaceholder')}
|
||||||
|
value={searchInput}
|
||||||
|
maxLength={100}
|
||||||
|
onChange={(event) => setSearchInput(event.target.value)}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === 'Enter') {
|
||||||
|
const next = event.currentTarget.value.trim();
|
||||||
|
const url = new URL(window.location.href);
|
||||||
|
if (next) url.searchParams.set('q', next);
|
||||||
|
else url.searchParams.delete('q');
|
||||||
|
window.history.replaceState(window.history.state, '', url);
|
||||||
|
setPage(1);
|
||||||
|
setSearchQuery(next);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{searchInput && <button type="button" aria-label={t('feed.clearSearch')} onClick={() => setSearchInput('')}><Icon name="close" size={16} /></button>}
|
||||||
|
</div>
|
||||||
<div className={'feed-posts-drawer ' + drawerPhase}>
|
<div className={'feed-posts-drawer ' + drawerPhase}>
|
||||||
<div className="feed-posts-drawer-inner">
|
<div className="feed-posts-drawer-inner">
|
||||||
<div id="postList" ref={postListRef}>
|
<div id="postList" ref={postListRef}>
|
||||||
@@ -159,17 +225,19 @@ export default function Feed({ onOpenModal, onReport }) {
|
|||||||
) : error ? (
|
) : error ? (
|
||||||
<div style={{ textAlign: 'center', color: '#ef4444', padding: '40px 0' }}>{t('feed.loadFailed', { msg: error })}</div>
|
<div style={{ textAlign: 'center', color: '#ef4444', padding: '40px 0' }}>{t('feed.loadFailed', { msg: error })}</div>
|
||||||
) : posts.length === 0 ? (
|
) : posts.length === 0 ? (
|
||||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '60px 0' }}>{t('feed.empty')}</div>
|
<div className="search-empty">{searchQuery ? t('feed.searchEmpty', { query: searchQuery }) : t('feed.empty')}</div>
|
||||||
) : (
|
) : (
|
||||||
posts.map((p) => {
|
posts.map((p) => {
|
||||||
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
|
const time = p.created_at ? new Date(p.created_at).toLocaleString(i18n.language === 'en' ? 'en-US' : 'zh-CN') : '';
|
||||||
return (
|
return (
|
||||||
<div key={p.id} className="post-card" data-post-id={p.id} data-post-ref={p.post_number || p.id} data-username={p.username || ''} style={{ cursor: 'pointer' }}
|
<div key={p.id} className="post-card topic-row" data-post-id={p.id} data-post-ref={p.post_number || p.id} data-username={p.username || ''} style={{ cursor: 'pointer' }}
|
||||||
onClick={(e) => openPost(p.post_number || p.id, e.currentTarget, p)}>
|
onClick={(e) => openPost(p.post_number || p.id, e.currentTarget, p)}>
|
||||||
{p.is_pinned && (
|
<div className="topic-main">
|
||||||
<div className="post-pin-state" style={{ width: 'fit-content', display: 'flex', alignItems: 'center', gap: 3, fontSize: 12, color: 'var(--primary)', fontWeight: 600, marginBottom: 4 }}><Icon name="pin" size={12} /> {t('feed.pinned')}</div>
|
<div className="topic-title-line">
|
||||||
)}
|
{p.is_pinned && <span className="post-pin-state"><Icon name="pin" size={12} /> {t('feed.pinned')}</span>}
|
||||||
<div className="post-header">
|
<div className="post-title">{p.title || t('feed.noTitle')}</div>
|
||||||
|
</div>
|
||||||
|
<div className="post-header topic-meta">
|
||||||
<img
|
<img
|
||||||
src={p.avatar_url || avatar(p.username)}
|
src={p.avatar_url || avatar(p.username)}
|
||||||
className="post-avatar"
|
className="post-avatar"
|
||||||
@@ -199,8 +267,7 @@ export default function Feed({ onOpenModal, onReport }) {
|
|||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="post-title">{p.title || t('feed.noTitle')}</div>
|
<div className="topic-preview" dangerouslySetInnerHTML={{ __html: renderMarkdown(p.content) }} />
|
||||||
<div className="post-content" dangerouslySetInnerHTML={{ __html: renderMarkdown(p.content) }} />
|
|
||||||
{p.images && p.images.length > 0 && (
|
{p.images && p.images.length > 0 && (
|
||||||
<div className="post-images">
|
<div className="post-images">
|
||||||
{p.images.map((img, i) => (
|
{p.images.map((img, i) => (
|
||||||
@@ -208,10 +275,11 @@ export default function Feed({ onOpenModal, onReport }) {
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="post-actions">
|
</div>
|
||||||
<span>
|
<div className="topic-replies post-replies" aria-label={`${p.reply_count || 0} replies`}>
|
||||||
<Icon name="message" size={14} /> {p.reply_count || 0}
|
<Icon name="message" size={14} /> {p.reply_count || 0}
|
||||||
</span>
|
</div>
|
||||||
|
<div className="post-actions topic-actions">
|
||||||
<button className="action-report" onClick={(e) => {
|
<button className="action-report" onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
if (!currentUser) { toast(t('newPost.pleaseLogin'), 'warning'); return; }
|
if (!currentUser) { toast(t('newPost.pleaseLogin'), 'warning'); return; }
|
||||||
|
|||||||
@@ -12,6 +12,11 @@ export function Icon({ name, size = 16, ...rest }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const PATHS = {
|
const PATHS = {
|
||||||
|
search: (
|
||||||
|
<>
|
||||||
|
<circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>
|
||||||
|
</>
|
||||||
|
),
|
||||||
message: (
|
message: (
|
||||||
<>
|
<>
|
||||||
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
|
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
|
||||||
|
|||||||
+72
-10
@@ -22,6 +22,12 @@ export default function Modals({ modal, onClose, reportPostId }) {
|
|||||||
const [resetRecoveryCode, setResetRecoveryCode] = useState('');
|
const [resetRecoveryCode, setResetRecoveryCode] = useState('');
|
||||||
const [resetPassword, setResetPassword] = useState('');
|
const [resetPassword, setResetPassword] = useState('');
|
||||||
const [resetPasswordConfirm, setResetPasswordConfirm] = useState('');
|
const [resetPasswordConfirm, setResetPasswordConfirm] = useState('');
|
||||||
|
const [resetMethod, setResetMethod] = useState('recovery');
|
||||||
|
const [mailReady, setMailReady] = useState(false);
|
||||||
|
const [emailCodeRequired, setEmailCodeRequired] = useState(false);
|
||||||
|
const [regEmailCode, setRegEmailCode] = useState('');
|
||||||
|
const [regCodeCooldown, setRegCodeCooldown] = useState(0);
|
||||||
|
const [resetCodeCooldown, setResetCodeCooldown] = useState(0);
|
||||||
|
|
||||||
// 注册表单
|
// 注册表单
|
||||||
const [regUsername, setRegUsername] = useState('');
|
const [regUsername, setRegUsername] = useState('');
|
||||||
@@ -35,6 +41,12 @@ export default function Modals({ modal, onClose, reportPostId }) {
|
|||||||
|
|
||||||
// 打开注册弹窗时从服务器获取验证码挑战(HMAC 签名)
|
// 打开注册弹窗时从服务器获取验证码挑战(HMAC 签名)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (modal === 'login' || modal === 'register') {
|
||||||
|
API.getSettings().then((settings) => {
|
||||||
|
setMailReady(!!settings.smtp_ready);
|
||||||
|
setEmailCodeRequired(!!settings.email_verify_required);
|
||||||
|
}).catch(() => { setMailReady(false); setEmailCodeRequired(false); });
|
||||||
|
}
|
||||||
if (modal === 'register') {
|
if (modal === 'register') {
|
||||||
API.getCaptcha().then((c) => setRegCaptcha(c)).catch(() => {});
|
API.getCaptcha().then((c) => setRegCaptcha(c)).catch(() => {});
|
||||||
}
|
}
|
||||||
@@ -44,9 +56,19 @@ export default function Modals({ modal, onClose, reportPostId }) {
|
|||||||
setResetRecoveryCode('');
|
setResetRecoveryCode('');
|
||||||
setResetPassword('');
|
setResetPassword('');
|
||||||
setResetPasswordConfirm('');
|
setResetPasswordConfirm('');
|
||||||
|
setResetMethod('recovery');
|
||||||
}
|
}
|
||||||
}, [modal]);
|
}, [modal]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!regCodeCooldown && !resetCodeCooldown) return;
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
setRegCodeCooldown((seconds) => Math.max(0, seconds - 1));
|
||||||
|
setResetCodeCooldown((seconds) => Math.max(0, seconds - 1));
|
||||||
|
}, 1000);
|
||||||
|
return () => clearInterval(timer);
|
||||||
|
}, [regCodeCooldown > 0, resetCodeCooldown > 0]);
|
||||||
|
|
||||||
if (!modal) return null;
|
if (!modal) return null;
|
||||||
|
|
||||||
const close = (e) => {
|
const close = (e) => {
|
||||||
@@ -83,7 +105,11 @@ export default function Modals({ modal, onClose, reportPostId }) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
|
if (resetMethod === 'email') {
|
||||||
|
await API.resetPasswordByEmail(resetEmail.trim(), resetRecoveryCode.trim(), resetPassword);
|
||||||
|
} else {
|
||||||
await API.resetPassword(resetEmail.trim(), resetRecoveryCode.trim(), resetPassword);
|
await API.resetPassword(resetEmail.trim(), resetRecoveryCode.trim(), resetPassword);
|
||||||
|
}
|
||||||
setAuthMode('login');
|
setAuthMode('login');
|
||||||
setLoginEmail(resetEmail.trim());
|
setLoginEmail(resetEmail.trim());
|
||||||
setLoginPassword('');
|
setLoginPassword('');
|
||||||
@@ -97,6 +123,23 @@ export default function Modals({ modal, onClose, reportPostId }) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const sendCode = async (purpose) => {
|
||||||
|
const email = purpose === 'register' ? regEmail.trim() : resetEmail.trim();
|
||||||
|
if (!email) { toast(t('auth.emailRequired'), 'warning'); return; }
|
||||||
|
try {
|
||||||
|
if (purpose === 'register') {
|
||||||
|
await API.sendRegisterCode(email);
|
||||||
|
setRegCodeCooldown(60);
|
||||||
|
} else {
|
||||||
|
await API.sendResetCode(email);
|
||||||
|
setResetCodeCooldown(60);
|
||||||
|
}
|
||||||
|
toast(t('auth.emailCodeSent'), 'success');
|
||||||
|
} catch (error) {
|
||||||
|
toast(t('auth.emailCodeFailed', { msg: error.message }), 'error');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const returnToLogin = () => {
|
const returnToLogin = () => {
|
||||||
setAuthMode('login');
|
setAuthMode('login');
|
||||||
setResetEmail('');
|
setResetEmail('');
|
||||||
@@ -108,18 +151,20 @@ export default function Modals({ modal, onClose, reportPostId }) {
|
|||||||
const handleRegister = async () => {
|
const handleRegister = async () => {
|
||||||
if (!regUsername.trim() || !regEmail.trim() || !regPassword) { toast('请填写完整信息', 'warning'); return; }
|
if (!regUsername.trim() || !regEmail.trim() || !regPassword) { toast('请填写完整信息', 'warning'); return; }
|
||||||
if (regPassword.length < 6) { toast('密码至少6位', 'warning'); return; }
|
if (regPassword.length < 6) { toast('密码至少6位', 'warning'); return; }
|
||||||
|
if (emailCodeRequired && !regEmailCode.trim()) { toast(t('auth.emailCodeRequired'), 'warning'); return; }
|
||||||
if (!regCaptcha || !regCaptchaInput.trim()) {
|
if (!regCaptcha || !regCaptchaInput.trim()) {
|
||||||
toast('请填写验证码', 'warning');
|
toast('请填写验证码', 'warning');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
// 答案由服务端 HMAC 校验,前端不对比答案
|
// 答案由服务端 HMAC 校验,前端不对比答案
|
||||||
await register(regEmail.trim(), regPassword, regUsername.trim(), { id: regCaptcha.id, answer: regCaptchaInput.trim(), sig: regCaptcha.sig });
|
await register(regEmail.trim(), regPassword, regUsername.trim(), { id: regCaptcha.id, answer: regCaptchaInput.trim(), sig: regCaptcha.sig }, regEmailCode.trim());
|
||||||
onClose();
|
onClose();
|
||||||
setRegUsername('');
|
setRegUsername('');
|
||||||
setRegEmail('');
|
setRegEmail('');
|
||||||
setRegPassword('');
|
setRegPassword('');
|
||||||
setRegCaptchaInput('');
|
setRegCaptchaInput('');
|
||||||
|
setRegEmailCode('');
|
||||||
toast('注册成功!', 'success');
|
toast('注册成功!', 'success');
|
||||||
refresh();
|
refresh();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -148,10 +193,11 @@ export default function Modals({ modal, onClose, reportPostId }) {
|
|||||||
<div className="modal-content">
|
<div className="modal-content">
|
||||||
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
|
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
|
||||||
<h2 style={{ marginBottom: 16 }}>{t('auth.login')}</h2>
|
<h2 style={{ marginBottom: 16 }}>{t('auth.login')}</h2>
|
||||||
|
<form onSubmit={(event) => { event.preventDefault(); handleLogin(); }}>
|
||||||
<input type="email" placeholder={t('auth.email')} value={loginEmail} onChange={(e) => setLoginEmail(e.target.value)} />
|
<input type="email" placeholder={t('auth.email')} value={loginEmail} onChange={(e) => setLoginEmail(e.target.value)} />
|
||||||
<input type="password" placeholder={t('auth.password')} value={loginPassword} onChange={(e) => setLoginPassword(e.target.value)}
|
<input type="password" placeholder={t('auth.password')} value={loginPassword} onChange={(e) => setLoginPassword(e.target.value)} />
|
||||||
onKeyDown={(e) => { if (e.key === 'Enter') handleLogin(); }} />
|
<button type="submit" className="btn-primary" style={{ width: '100%' }}>{t('auth.login')}</button>
|
||||||
<button className="btn-primary" style={{ width: '100%' }} onClick={handleLogin}>{t('auth.login')}</button>
|
</form>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="auth-forgot-link"
|
className="auth-forgot-link"
|
||||||
@@ -170,19 +216,27 @@ export default function Modals({ modal, onClose, reportPostId }) {
|
|||||||
<div className="modal active" onClick={close}>
|
<div className="modal active" onClick={close}>
|
||||||
<div className="modal-content">
|
<div className="modal-content">
|
||||||
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
|
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
|
||||||
<h2 style={{ marginBottom: 16 }}>{t('auth.resetTitle')}</h2>
|
<h2 style={{ marginBottom: 16 }}>{t(resetMethod === 'email' ? 'auth.resetEmailTitle' : 'auth.resetTitle')}</h2>
|
||||||
<p className="auth-reset-hint">{t('auth.resetHint')}</p>
|
{mailReady && (
|
||||||
|
<div className="auth-reset-methods">
|
||||||
|
<button type="button" className={resetMethod === 'recovery' ? 'active' : ''} onClick={() => { setResetMethod('recovery'); setResetRecoveryCode(''); }}>{t('auth.recoveryMethod')}</button>
|
||||||
|
<button type="button" className={resetMethod === 'email' ? 'active' : ''} onClick={() => { setResetMethod('email'); setResetRecoveryCode(''); }}>{t('auth.emailMethod')}</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<p className="auth-reset-hint">{t(resetMethod === 'email' ? 'auth.resetEmailHint' : 'auth.resetHint')}</p>
|
||||||
|
<form onSubmit={(event) => { event.preventDefault(); handleResetPassword(); }}>
|
||||||
<input type="email" placeholder={t('auth.email')} value={resetEmail} onChange={(e) => setResetEmail(e.target.value)} />
|
<input type="email" placeholder={t('auth.email')} value={resetEmail} onChange={(e) => setResetEmail(e.target.value)} />
|
||||||
<input type="text" placeholder={t('auth.recoveryCode')} value={resetRecoveryCode} onChange={(e) => setResetRecoveryCode(e.target.value)} />
|
{resetMethod === 'email' && <button type="button" className="auth-send-code" disabled={resetCodeCooldown > 0} onClick={() => sendCode('reset')}>{resetCodeCooldown || t('auth.sendCode')}</button>}
|
||||||
|
<input type="text" placeholder={t(resetMethod === 'email' ? 'auth.emailCode' : 'auth.recoveryCode')} value={resetRecoveryCode} onChange={(e) => setResetRecoveryCode(e.target.value)} />
|
||||||
<input type="password" placeholder={t('auth.newPassword')} value={resetPassword} onChange={(e) => setResetPassword(e.target.value)} />
|
<input type="password" placeholder={t('auth.newPassword')} value={resetPassword} onChange={(e) => setResetPassword(e.target.value)} />
|
||||||
<input
|
<input
|
||||||
type="password"
|
type="password"
|
||||||
placeholder={t('auth.confirmPassword')}
|
placeholder={t('auth.confirmPassword')}
|
||||||
value={resetPasswordConfirm}
|
value={resetPasswordConfirm}
|
||||||
onChange={(e) => setResetPasswordConfirm(e.target.value)}
|
onChange={(e) => setResetPasswordConfirm(e.target.value)}
|
||||||
onKeyDown={(e) => { if (e.key === 'Enter') handleResetPassword(); }}
|
|
||||||
/>
|
/>
|
||||||
<button className="btn-primary" style={{ width: '100%' }} onClick={handleResetPassword}>{t('auth.resetPassword')}</button>
|
<button type="submit" className="btn-primary" style={{ width: '100%' }}>{t('auth.resetPassword')}</button>
|
||||||
|
</form>
|
||||||
<button type="button" className="auth-forgot-link" onClick={returnToLogin}>
|
<button type="button" className="auth-forgot-link" onClick={returnToLogin}>
|
||||||
{t('auth.backToLogin')}
|
{t('auth.backToLogin')}
|
||||||
</button>
|
</button>
|
||||||
@@ -195,8 +249,15 @@ export default function Modals({ modal, onClose, reportPostId }) {
|
|||||||
<div className="modal-content">
|
<div className="modal-content">
|
||||||
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
|
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
|
||||||
<h2 style={{ marginBottom: 16 }}>{t('auth.register')}</h2>
|
<h2 style={{ marginBottom: 16 }}>{t('auth.register')}</h2>
|
||||||
|
<form onSubmit={(event) => { event.preventDefault(); handleRegister(); }}>
|
||||||
<input type="text" placeholder={t('auth.username')} value={regUsername} onChange={(e) => setRegUsername(e.target.value)} />
|
<input type="text" placeholder={t('auth.username')} value={regUsername} onChange={(e) => setRegUsername(e.target.value)} />
|
||||||
<input type="email" placeholder={t('auth.email')} value={regEmail} onChange={(e) => setRegEmail(e.target.value)} />
|
<input type="email" placeholder={t('auth.email')} value={regEmail} onChange={(e) => setRegEmail(e.target.value)} />
|
||||||
|
{emailCodeRequired && (
|
||||||
|
<div className="auth-email-code-row">
|
||||||
|
<input type="text" inputMode="numeric" maxLength={6} placeholder={t('auth.emailCode')} value={regEmailCode} onChange={(e) => setRegEmailCode(e.target.value)} />
|
||||||
|
<button type="button" disabled={regCodeCooldown > 0} onClick={() => sendCode('register')}>{regCodeCooldown || t('auth.sendCode')}</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<input type="password" placeholder={t('auth.passwordHint')} value={regPassword} onChange={(e) => setRegPassword(e.target.value)} />
|
<input type="password" placeholder={t('auth.passwordHint')} value={regPassword} onChange={(e) => setRegPassword(e.target.value)} />
|
||||||
<div className="captcha-row" style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '12px 0' }}>
|
<div className="captcha-row" style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '12px 0' }}>
|
||||||
{regCaptcha ? (
|
{regCaptcha ? (
|
||||||
@@ -206,7 +267,8 @@ export default function Modals({ modal, onClose, reportPostId }) {
|
|||||||
)}
|
)}
|
||||||
<input type="text" placeholder="答案" style={{ width: 80, background: 'var(--bg)', color: 'var(--text)', border: '1px solid var(--border)', padding: '8px 12px', borderRadius: 4 }} value={regCaptchaInput} onChange={(e) => setRegCaptchaInput(e.target.value)} />
|
<input type="text" placeholder="答案" style={{ width: 80, background: 'var(--bg)', color: 'var(--text)', border: '1px solid var(--border)', padding: '8px 12px', borderRadius: 4 }} value={regCaptchaInput} onChange={(e) => setRegCaptchaInput(e.target.value)} />
|
||||||
</div>
|
</div>
|
||||||
<button className="btn-primary" style={{ width: '100%' }} onClick={handleRegister}>{t('auth.register')}</button>
|
<button type="submit" className="btn-primary" style={{ width: '100%' }}>{t('auth.register')}</button>
|
||||||
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { Icon } from './Icons';
|
|||||||
import { useOpenPrivateChat } from './chat/ChatManager';
|
import { useOpenPrivateChat } from './chat/ChatManager';
|
||||||
import { renderMarkdown } from '@/lib/markdown';
|
import { renderMarkdown } from '@/lib/markdown';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { useToast } from './Toast';
|
||||||
|
|
||||||
function avatar(username, size = 128) {
|
function avatar(username, size = 128) {
|
||||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
||||||
@@ -18,7 +19,9 @@ export default function UserProfile({ username, initialUser = null, initialPosts
|
|||||||
const { currentUser, openPost } = useApp();
|
const { currentUser, openPost } = useApp();
|
||||||
const { t, i18n } = useTranslation();
|
const { t, i18n } = useTranslation();
|
||||||
const openPrivateChat = useOpenPrivateChat();
|
const openPrivateChat = useOpenPrivateChat();
|
||||||
|
const { toast, confirmAction } = useToast();
|
||||||
const [user, setUser] = useState(initialUser);
|
const [user, setUser] = useState(initialUser);
|
||||||
|
const [blockStatus, setBlockStatus] = useState(null);
|
||||||
const [posts, setPosts] = useState(initialPosts || []);
|
const [posts, setPosts] = useState(initialPosts || []);
|
||||||
const [error, setError] = useState(null);
|
const [error, setError] = useState(null);
|
||||||
const postsRef = useRef(null);
|
const postsRef = useRef(null);
|
||||||
@@ -45,6 +48,37 @@ export default function UserProfile({ username, initialUser = null, initialPosts
|
|||||||
load();
|
load();
|
||||||
}, [initialPosts, initialUser, load]);
|
}, [initialPosts, initialUser, load]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!currentUser || !user?.id || currentUser.id === user.id) {
|
||||||
|
setBlockStatus(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let canceled = false;
|
||||||
|
API.getBlockStatus(user.id)
|
||||||
|
.then((status) => { if (!canceled) setBlockStatus(status); })
|
||||||
|
.catch(() => { if (!canceled) setBlockStatus(null); });
|
||||||
|
return () => { canceled = true; };
|
||||||
|
}, [currentUser?.id, user?.id]);
|
||||||
|
|
||||||
|
const toggleBlock = async () => {
|
||||||
|
const blocked = !!blockStatus?.blocked_by_me;
|
||||||
|
const confirmed = await confirmAction(t(blocked ? 'blocking.unblockConfirm' : 'blocking.blockConfirm', { name: user.username }), {
|
||||||
|
title: t(blocked ? 'blocking.unblock' : 'blocking.block'),
|
||||||
|
confirmLabel: t(blocked ? 'blocking.unblock' : 'blocking.block'),
|
||||||
|
danger: !blocked,
|
||||||
|
});
|
||||||
|
if (!confirmed) return;
|
||||||
|
try {
|
||||||
|
if (blocked) await API.unblockUser(user.id);
|
||||||
|
else await API.blockUser(user.id);
|
||||||
|
setBlockStatus((previous) => ({ ...previous, blocked_by_me: !blocked }));
|
||||||
|
setPosts(blocked ? (await API.getPosts('latest', user.id)).data || [] : []);
|
||||||
|
toast(t(blocked ? 'blocking.unblocked' : 'blocking.blocked'), 'success');
|
||||||
|
} catch (error) {
|
||||||
|
toast(t('blocking.failed', { msg: error.message }), 'error');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const contents = postsRef.current?.querySelectorAll('.user-post-preview') || [];
|
const contents = postsRef.current?.querySelectorAll('.user-post-preview') || [];
|
||||||
contents.forEach((element) => {
|
contents.forEach((element) => {
|
||||||
@@ -76,14 +110,21 @@ export default function UserProfile({ username, initialUser = null, initialPosts
|
|||||||
<div className="user-profile-details">
|
<div className="user-profile-details">
|
||||||
<p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{user.bio || '这个人很懒,什么都没写'}</p>
|
<p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{user.bio || '这个人很懒,什么都没写'}</p>
|
||||||
{currentUser && currentUser.username !== user.username && (
|
{currentUser && currentUser.username !== user.username && (
|
||||||
|
<div className="user-profile-actions">
|
||||||
|
{!blockStatus?.blocked_by_me && (
|
||||||
<button
|
<button
|
||||||
className="btn-primary"
|
className="btn-primary"
|
||||||
style={{ marginTop: 12, padding: '8px 20px' }}
|
|
||||||
onClick={() => openPrivateChat(user.id, user.username)}
|
onClick={() => openPrivateChat(user.id, user.username)}
|
||||||
>
|
>
|
||||||
<Icon name="message" size={14} /> 发私信
|
<Icon name="message" size={14} /> 发私信
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
<button type="button" className="btn-secondary" onClick={toggleBlock}>
|
||||||
|
<Icon name="shield" size={14} /> {t(blockStatus?.blocked_by_me ? 'blocking.unblock' : 'blocking.block')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{blockStatus?.blocked_by_me && <p className="blocked-user-hint">{t('blocking.blockedHint')}</p>}
|
||||||
<div style={{ display: 'flex', justifyContent: 'center', gap: 32, marginTop: 16, fontSize: 14, color: 'var(--text-secondary)', flexWrap: 'wrap' }}>
|
<div style={{ display: 'flex', justifyContent: 'center', gap: 32, marginTop: 16, fontSize: 14, color: 'var(--text-secondary)', flexWrap: 'wrap' }}>
|
||||||
<span><Icon name="calendar" size={14} /> 加入于 {user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
|
<span><Icon name="calendar" size={14} /> 加入于 {user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
|
||||||
<span><Icon name="file" size={14} /> 发了 {posts.length} 个帖子</span>
|
<span><Icon name="file" size={14} /> 发了 {posts.length} 个帖子</span>
|
||||||
|
|||||||
@@ -0,0 +1,105 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { API } from '@/lib/api';
|
||||||
|
import { Icon } from '../Icons';
|
||||||
|
import { useToast } from '../Toast';
|
||||||
|
|
||||||
|
const DEFAULTS = {
|
||||||
|
enabled: false, host: '', port: 587, secure: false, user: '', password: '',
|
||||||
|
from_name: '', from_email: '', allow_self_signed: false, password_set: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function AdminMailSettings() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { toast, confirmAction } = useToast();
|
||||||
|
const [config, setConfig] = useState(DEFAULTS);
|
||||||
|
const [required, setRequired] = useState(false);
|
||||||
|
const [testTo, setTestTo] = useState('');
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
|
const load = async () => {
|
||||||
|
try {
|
||||||
|
const [smtp, settings] = await Promise.all([API.adminGetSmtp(), API.getSettings()]);
|
||||||
|
setConfig({ ...DEFAULTS, ...smtp, password: '' });
|
||||||
|
setRequired(!!settings.email_verify_required);
|
||||||
|
} catch (error) {
|
||||||
|
toast(t('admin.mailForm.failed', { msg: error.message }), 'error');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
useEffect(() => { load(); }, []);
|
||||||
|
|
||||||
|
const update = (key, value) => setConfig((current) => ({ ...current, [key]: value }));
|
||||||
|
const save = async () => {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await API.adminSaveSmtp(config);
|
||||||
|
await load();
|
||||||
|
toast(t('admin.mailForm.saved'), 'success');
|
||||||
|
} catch (error) {
|
||||||
|
toast(t('admin.mailForm.failed', { msg: error.message }), 'error');
|
||||||
|
} finally { setBusy(false); }
|
||||||
|
};
|
||||||
|
|
||||||
|
const test = async () => {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await API.adminTestSmtp(testTo.trim() || undefined);
|
||||||
|
toast(t('admin.mailForm.testSent'), 'success');
|
||||||
|
} catch (error) {
|
||||||
|
toast(t('admin.mailForm.failed', { msg: error.message }), 'error');
|
||||||
|
} finally { setBusy(false); }
|
||||||
|
};
|
||||||
|
|
||||||
|
const clearPassword = async () => {
|
||||||
|
if (!await confirmAction(t('admin.mailForm.clearPasswordConfirm'))) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await API.adminClearSmtpPassword();
|
||||||
|
await load();
|
||||||
|
toast(t('admin.mailForm.passwordCleared'), 'success');
|
||||||
|
} catch (error) {
|
||||||
|
toast(t('admin.mailForm.failed', { msg: error.message }), 'error');
|
||||||
|
} finally { setBusy(false); }
|
||||||
|
};
|
||||||
|
|
||||||
|
const changeVerification = async (value) => {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await API.adminSetEmailVerification(value);
|
||||||
|
setRequired(value);
|
||||||
|
toast(t('admin.mailForm.saved'), 'success');
|
||||||
|
} catch (error) {
|
||||||
|
toast(t('admin.mailForm.failed', { msg: error.message }), 'error');
|
||||||
|
} finally { setBusy(false); }
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="smtp-settings">
|
||||||
|
<h3><Icon name="message" size={17} /> {t('admin.mailForm.title')}</h3>
|
||||||
|
<p className="admin-forum-hint">{t('admin.mailForm.hint')}</p>
|
||||||
|
<label className="smtp-check"><input type="checkbox" checked={config.enabled} onChange={(event) => update('enabled', event.target.checked)} /> {t('admin.mailForm.enabled')}</label>
|
||||||
|
<div className="smtp-grid">
|
||||||
|
<label>{t('admin.mailForm.host')}<input value={config.host} maxLength={255} onChange={(event) => update('host', event.target.value)} /></label>
|
||||||
|
<label>{t('admin.mailForm.port')}<input type="number" min="1" max="65535" value={config.port} onChange={(event) => update('port', event.target.value)} /></label>
|
||||||
|
<label>{t('admin.mailForm.user')}<input value={config.user} maxLength={255} autoComplete="off" onChange={(event) => update('user', event.target.value)} /></label>
|
||||||
|
<label>{t('admin.mailForm.password')}<input type="password" value={config.password} maxLength={255} autoComplete="new-password" placeholder={config.password_set ? t('admin.mailForm.passwordSaved') : ''} onChange={(event) => update('password', event.target.value)} /></label>
|
||||||
|
<label>{t('admin.mailForm.fromName')}<input value={config.from_name} maxLength={100} onChange={(event) => update('from_name', event.target.value)} /></label>
|
||||||
|
<label>{t('admin.mailForm.fromEmail')}<input type="email" value={config.from_email} maxLength={255} onChange={(event) => update('from_email', event.target.value)} /></label>
|
||||||
|
</div>
|
||||||
|
<label className="smtp-check"><input type="checkbox" checked={config.secure} onChange={(event) => update('secure', event.target.checked)} /> {t('admin.mailForm.secure')}</label>
|
||||||
|
<label className="smtp-check"><input type="checkbox" checked={config.allow_self_signed} onChange={(event) => update('allow_self_signed', event.target.checked)} /> {t('admin.mailForm.selfSigned')}</label>
|
||||||
|
<div className="smtp-actions">
|
||||||
|
<button className="btn-primary" disabled={busy} onClick={save}>{t('admin.mailForm.save')}</button>
|
||||||
|
{config.password_set && <button className="btn-secondary" disabled={busy} onClick={clearPassword}>{t('admin.mailForm.clearPassword')}</button>}
|
||||||
|
</div>
|
||||||
|
<div className="admin-forum-divider" />
|
||||||
|
<label>{t('admin.mailForm.testTo')}<input type="email" value={testTo} onChange={(event) => setTestTo(event.target.value)} placeholder={t('admin.mailForm.testToHint')} /></label>
|
||||||
|
<div className="smtp-actions"><button className="btn-secondary" disabled={busy} onClick={test}>{t('admin.mailForm.sendTest')}</button></div>
|
||||||
|
<div className="admin-forum-divider" />
|
||||||
|
<label className="smtp-check"><input type="checkbox" checked={required} disabled={busy} onChange={(event) => changeVerification(event.target.checked)} /> {t('admin.mailForm.requireVerification')}</label>
|
||||||
|
<p className="admin-forum-hint">{t('admin.mailForm.verifyHint')}</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import { API } from '@/lib/api';
|
|||||||
import { useApp } from '../AppProvider';
|
import { useApp } from '../AppProvider';
|
||||||
import { Icon } from '../Icons';
|
import { Icon } from '../Icons';
|
||||||
import { useToast } from '../Toast';
|
import { useToast } from '../Toast';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
function avatar(username) {
|
function avatar(username) {
|
||||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
||||||
@@ -15,9 +16,12 @@ function avatar(username) {
|
|||||||
export default function ChatWindow({ conversationId, otherUserId, otherUsername, onClose, onRefreshList }) {
|
export default function ChatWindow({ conversationId, otherUserId, otherUsername, onClose, onRefreshList }) {
|
||||||
const { currentUser } = useApp();
|
const { currentUser } = useApp();
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
|
const { t, i18n } = useTranslation();
|
||||||
const [messages, setMessages] = useState(null);
|
const [messages, setMessages] = useState(null);
|
||||||
const [content, setContent] = useState('');
|
const [content, setContent] = useState('');
|
||||||
const containerRef = useRef(null);
|
const containerRef = useRef(null);
|
||||||
|
const waitingForReply = messages && !messages.some((message) => message.sender_id === otherUserId)
|
||||||
|
&& messages.filter((message) => message.sender_id === currentUser?.id).length >= 3;
|
||||||
|
|
||||||
const load = useCallback(async (silent = false) => {
|
const load = useCallback(async (silent = false) => {
|
||||||
if (!silent) setMessages(null);
|
if (!silent) setMessages(null);
|
||||||
@@ -43,14 +47,15 @@ export default function ChatWindow({ conversationId, otherUserId, otherUsername,
|
|||||||
}, [messages]);
|
}, [messages]);
|
||||||
|
|
||||||
const send = async () => {
|
const send = async () => {
|
||||||
if (!content.trim()) return;
|
if (!content.trim() || waitingForReply) return;
|
||||||
try {
|
try {
|
||||||
await API.sendMessage(conversationId, content.trim());
|
await API.sendMessage(conversationId, content.trim());
|
||||||
setContent('');
|
setContent('');
|
||||||
load();
|
load();
|
||||||
onRefreshList();
|
onRefreshList();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
toast('发送失败:' + err.message, 'error');
|
toast(err.status === 429 ? t('chat.limitReached') : err.message, 'error');
|
||||||
|
if (err.status === 429) load(true);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -69,7 +74,7 @@ export default function ChatWindow({ conversationId, otherUserId, otherUsername,
|
|||||||
) : (
|
) : (
|
||||||
messages.map((m) => {
|
messages.map((m) => {
|
||||||
const isMine = m.sender_id === currentUser?.id;
|
const isMine = m.sender_id === currentUser?.id;
|
||||||
const time = m.created_at ? new Date(m.created_at).toLocaleString('zh-CN') : '';
|
const time = m.created_at ? new Date(m.created_at).toLocaleString(i18n.language === 'en' ? 'en-US' : 'zh-CN') : '';
|
||||||
return (
|
return (
|
||||||
<div key={m.id} style={{ display: 'flex', justifyContent: isMine ? 'flex-end' : 'flex-start', marginBottom: 12 }}>
|
<div key={m.id} style={{ display: 'flex', justifyContent: isMine ? 'flex-end' : 'flex-start', marginBottom: 12 }}>
|
||||||
{!isMine && (
|
{!isMine && (
|
||||||
@@ -94,6 +99,7 @@ export default function ChatWindow({ conversationId, otherUserId, otherUsername,
|
|||||||
})
|
})
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
{waitingForReply && <div className="chat-limit-hint">{t('chat.limitReached')}</div>}
|
||||||
<div style={{ display: 'flex', gap: 8, padding: '12px 16px', borderTop: '1px solid var(--border)', flexShrink: 0 }}>
|
<div style={{ display: 'flex', gap: 8, padding: '12px 16px', borderTop: '1px solid var(--border)', flexShrink: 0 }}>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
@@ -101,10 +107,11 @@ export default function ChatWindow({ conversationId, otherUserId, otherUsername,
|
|||||||
placeholder="输入消息..."
|
placeholder="输入消息..."
|
||||||
style={{ flex: 1, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 6, fontSize: 14, background: 'var(--bg)', color: 'var(--text)', outline: 'none' }}
|
style={{ flex: 1, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 6, fontSize: 14, background: 'var(--bg)', color: 'var(--text)', outline: 'none' }}
|
||||||
value={content}
|
value={content}
|
||||||
|
disabled={waitingForReply}
|
||||||
onChange={(e) => setContent(e.target.value)}
|
onChange={(e) => setContent(e.target.value)}
|
||||||
onKeyDown={(e) => { if (e.key === 'Enter') send(); }}
|
onKeyDown={(e) => { if (e.key === 'Enter') send(); }}
|
||||||
/>
|
/>
|
||||||
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={send}>发送</button>
|
<button className="btn-primary" style={{ padding: '8px 16px' }} disabled={waitingForReply} onClick={send}>发送</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { API } from '@/lib/api';
|
import { API } from '@/lib/api';
|
||||||
import { Icon } from '../Icons';
|
import { Icon } from '../Icons';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { useToast } from '../Toast';
|
||||||
|
|
||||||
function avatar(username) {
|
function avatar(username) {
|
||||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
||||||
@@ -11,7 +13,12 @@ function avatar(username) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function ConversationList({ onOpenChat, onClose }) {
|
export default function ConversationList({ onOpenChat, onClose }) {
|
||||||
|
const { t, i18n } = useTranslation();
|
||||||
|
const { toast } = useToast();
|
||||||
const [conversations, setConversations] = useState(null);
|
const [conversations, setConversations] = useState(null);
|
||||||
|
const [search, setSearch] = useState('');
|
||||||
|
const [matches, setMatches] = useState([]);
|
||||||
|
const [searching, setSearching] = useState(false);
|
||||||
|
|
||||||
const load = () => {
|
const load = () => {
|
||||||
API.getConversations()
|
API.getConversations()
|
||||||
@@ -21,23 +28,67 @@ export default function ConversationList({ onOpenChat, onClose }) {
|
|||||||
|
|
||||||
useEffect(load, []);
|
useEffect(load, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const keyword = search.trim();
|
||||||
|
if (!keyword) { setMatches([]); setSearching(false); return; }
|
||||||
|
let canceled = false;
|
||||||
|
const timer = setTimeout(async () => {
|
||||||
|
setSearching(true);
|
||||||
|
try {
|
||||||
|
const result = await API.searchUsers(keyword);
|
||||||
|
if (!canceled) setMatches(result.data || []);
|
||||||
|
} catch (error) {
|
||||||
|
if (!canceled) toast(t('chat.openFailed', { msg: error.message }), 'error');
|
||||||
|
} finally {
|
||||||
|
if (!canceled) setSearching(false);
|
||||||
|
}
|
||||||
|
}, 300);
|
||||||
|
return () => { canceled = true; clearTimeout(timer); };
|
||||||
|
}, [search, t, toast]);
|
||||||
|
|
||||||
|
const startChat = async (user) => {
|
||||||
|
try {
|
||||||
|
const conversation = await API.getOrCreateConversation(user.id);
|
||||||
|
onOpenChat(conversation.id, user.id, user.username);
|
||||||
|
} catch (error) {
|
||||||
|
toast(t('chat.openFailed', { msg: error.message }), 'error');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="modal active" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
|
<div className="modal active" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
|
||||||
<div className="modal-content" style={{ display: 'flex', flexDirection: 'column', height: '70vh', maxHeight: '70vh', padding: 0, overflow: 'hidden' }}>
|
<div className="modal-content" style={{ display: 'flex', flexDirection: 'column', height: '70vh', maxHeight: '70vh', padding: 0, overflow: 'hidden' }}>
|
||||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 20px', borderBottom: '1px solid var(--border)' }}>
|
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 20px', borderBottom: '1px solid var(--border)' }}>
|
||||||
<h2 style={{ fontSize: 18, margin: 0 }}><Icon name="message" size={18} style={{ verticalAlign: -3, marginRight: 6 }} /> 私信</h2>
|
<h2 style={{ fontSize: 18, margin: 0 }}><Icon name="message" size={18} style={{ verticalAlign: -3, marginRight: 6 }} /> {t('chat.title')}</h2>
|
||||||
<span className="close" onClick={onClose} style={{ cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}><Icon name="close" size={20} /></span>
|
<span className="close" onClick={onClose} style={{ cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}><Icon name="close" size={20} /></span>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="chat-user-search">
|
||||||
|
<Icon name="search" size={17} aria-hidden="true" />
|
||||||
|
<input type="search" name="forumlify-user-search" autoComplete="off" maxLength={50}
|
||||||
|
aria-label={t('chat.searchPlaceholder')} placeholder={t('chat.searchPlaceholder')}
|
||||||
|
value={search} onChange={(event) => setSearch(event.target.value)} />
|
||||||
|
</div>
|
||||||
<div id="messageListContent" style={{ flex: 1, overflowY: 'auto', padding: 0 }}>
|
<div id="messageListContent" style={{ flex: 1, overflowY: 'auto', padding: 0 }}>
|
||||||
|
{search.trim() ? (
|
||||||
|
searching ? <div className="chat-search-state">{t('chat.loading')}</div>
|
||||||
|
: matches.length === 0 ? <div className="chat-search-state">{t('chat.searchEmpty')}</div>
|
||||||
|
: matches.map((user) => (
|
||||||
|
<button key={user.id} type="button" className="chat-user-result" onClick={() => startChat(user)}>
|
||||||
|
<img src={user.avatar_url || avatar(user.username)} alt="" />
|
||||||
|
<span>{user.username}</span>
|
||||||
|
</button>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
{conversations === null ? (
|
{conversations === null ? (
|
||||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />加载中...</div>
|
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />{t('chat.loading')}</div>
|
||||||
) : conversations.length === 0 ? (
|
) : conversations.length === 0 ? (
|
||||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>暂无私信</div>
|
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>{t('chat.empty')}</div>
|
||||||
) : (
|
) : (
|
||||||
conversations.map((c) => {
|
conversations.map((c) => {
|
||||||
const unread = c.unread_count || 0;
|
const unread = c.unread_count || 0;
|
||||||
const lastMsg = c.last_message || '暂无消息';
|
const lastMsg = c.last_message || t('chat.noMessage');
|
||||||
const time = c.last_message_time ? new Date(c.last_message_time).toLocaleString('zh-CN') : '';
|
const time = c.last_message_time ? new Date(c.last_message_time).toLocaleString(i18n.language === 'en' ? 'en-US' : 'zh-CN') : '';
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={c.id}
|
key={c.id}
|
||||||
@@ -62,6 +113,8 @@ export default function ConversationList({ onOpenChat, onClose }) {
|
|||||||
);
|
);
|
||||||
})
|
})
|
||||||
)}
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+32
-2
@@ -45,12 +45,21 @@ export const API = {
|
|||||||
getCaptcha() {
|
getCaptcha() {
|
||||||
return apiFetch('/captcha');
|
return apiFetch('/captcha');
|
||||||
},
|
},
|
||||||
register(email, password, username, captcha) {
|
register(email, password, username, captcha, emailCode = '') {
|
||||||
return apiFetch('/auth/register', {
|
return apiFetch('/auth/register', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ email, password, username, captcha_id: captcha?.id, captcha_answer: captcha?.answer, captcha_sig: captcha?.sig }),
|
body: JSON.stringify({ email, password, username, email_code: emailCode, captcha_id: captcha?.id, captcha_answer: captcha?.answer, captcha_sig: captcha?.sig }),
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
sendRegisterCode(email) {
|
||||||
|
return apiFetch('/auth/send-code', { method: 'POST', body: JSON.stringify({ email }) });
|
||||||
|
},
|
||||||
|
sendResetCode(email) {
|
||||||
|
return apiFetch('/auth/forgot-password', { method: 'POST', body: JSON.stringify({ email }) });
|
||||||
|
},
|
||||||
|
resetPasswordByEmail(email, code, newPassword) {
|
||||||
|
return apiFetch('/auth/reset-password-by-email', { method: 'POST', body: JSON.stringify({ email, code, newPassword }) });
|
||||||
|
},
|
||||||
logout() { setToken(null); },
|
logout() { setToken(null); },
|
||||||
getMe() { return apiFetch('/auth/me'); },
|
getMe() { return apiFetch('/auth/me'); },
|
||||||
|
|
||||||
@@ -60,6 +69,9 @@ export const API = {
|
|||||||
if (userId) q += '&user_id=' + userId;
|
if (userId) q += '&user_id=' + userId;
|
||||||
return apiFetch(q);
|
return apiFetch(q);
|
||||||
},
|
},
|
||||||
|
searchPosts(query, page = 1, limit = 20) {
|
||||||
|
return apiFetch(`/posts/search?q=${encodeURIComponent(query)}&page=${page}&limit=${limit}`);
|
||||||
|
},
|
||||||
getPost(postId) { return apiFetch('/posts/' + postId); },
|
getPost(postId) { return apiFetch('/posts/' + postId); },
|
||||||
createPost(title, content, images, captcha) {
|
createPost(title, content, images, captcha) {
|
||||||
return apiFetch('/posts', {
|
return apiFetch('/posts', {
|
||||||
@@ -96,6 +108,13 @@ export const API = {
|
|||||||
getUsers() { return apiFetch('/users'); },
|
getUsers() { return apiFetch('/users'); },
|
||||||
getUsersByUsername(username) { return apiFetch('/users?username=' + encodeURIComponent(username)); },
|
getUsersByUsername(username) { return apiFetch('/users?username=' + encodeURIComponent(username)); },
|
||||||
getUserProfile(username) { return apiFetch('/users/profile/' + encodeURIComponent(username)); },
|
getUserProfile(username) { return apiFetch('/users/profile/' + encodeURIComponent(username)); },
|
||||||
|
searchUsers(query, limit = 10) {
|
||||||
|
return apiFetch(`/users/search?q=${encodeURIComponent(query)}&limit=${limit}`);
|
||||||
|
},
|
||||||
|
getBlockStatus(userId) { return apiFetch(`/users/${encodeURIComponent(userId)}/block-status`); },
|
||||||
|
getBlockedUsers() { return apiFetch('/blocks'); },
|
||||||
|
blockUser(userId) { return apiFetch(`/users/${encodeURIComponent(userId)}/block`, { method: 'POST' }); },
|
||||||
|
unblockUser(userId) { return apiFetch(`/users/${encodeURIComponent(userId)}/block`, { method: 'DELETE' }); },
|
||||||
updateUserRole(userId, role) {
|
updateUserRole(userId, role) {
|
||||||
return apiFetch('/users/' + userId + '/role', { method: 'PUT', body: JSON.stringify({ role }) });
|
return apiFetch('/users/' + userId + '/role', { method: 'PUT', body: JSON.stringify({ role }) });
|
||||||
},
|
},
|
||||||
@@ -127,6 +146,17 @@ export const API = {
|
|||||||
updateSettings(forum_name) {
|
updateSettings(forum_name) {
|
||||||
return apiFetch('/settings', { method: 'PUT', body: JSON.stringify({ forum_name }) });
|
return apiFetch('/settings', { method: 'PUT', body: JSON.stringify({ forum_name }) });
|
||||||
},
|
},
|
||||||
|
adminGetSmtp() { return apiFetch('/admin/smtp'); },
|
||||||
|
adminSaveSmtp(config) {
|
||||||
|
return apiFetch('/admin/smtp', { method: 'PUT', body: JSON.stringify(config) });
|
||||||
|
},
|
||||||
|
adminTestSmtp(to) {
|
||||||
|
return apiFetch('/admin/smtp/test', { method: 'POST', body: JSON.stringify({ to }) });
|
||||||
|
},
|
||||||
|
adminClearSmtpPassword() { return apiFetch('/admin/smtp/password', { method: 'DELETE' }); },
|
||||||
|
adminSetEmailVerification(required) {
|
||||||
|
return apiFetch('/admin/email-verify', { method: 'PUT', body: JSON.stringify({ required }) });
|
||||||
|
},
|
||||||
uploadFavicon(file) {
|
uploadFavicon(file) {
|
||||||
const fd = new FormData();
|
const fd = new FormData();
|
||||||
fd.append('file', file);
|
fd.append('file', file);
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import { createHash, randomInt, timingSafeEqual } from 'node:crypto';
|
||||||
|
import pool from './db';
|
||||||
|
|
||||||
|
let schemaPromise;
|
||||||
|
export function ensureEmailVerificationSchema() {
|
||||||
|
if (!schemaPromise) {
|
||||||
|
schemaPromise = pool.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS email_verifications (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
email VARCHAR(255) NOT NULL,
|
||||||
|
code_hash VARCHAR(64) NOT NULL,
|
||||||
|
purpose VARCHAR(20) NOT NULL DEFAULT 'register',
|
||||||
|
attempts INTEGER NOT NULL DEFAULT 0,
|
||||||
|
consumed_at TIMESTAMPTZ,
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
)
|
||||||
|
`).then(async () => {
|
||||||
|
await pool.query(`CREATE UNIQUE INDEX IF NOT EXISTS idx_email_verifications_active
|
||||||
|
ON email_verifications (LOWER(email), purpose) WHERE consumed_at IS NULL`);
|
||||||
|
await pool.query(`CREATE INDEX IF NOT EXISTS idx_email_verifications_expires
|
||||||
|
ON email_verifications (expires_at)`);
|
||||||
|
await pool.query('ALTER TABLE users ADD COLUMN IF NOT EXISTS email_verified BOOLEAN NOT NULL DEFAULT true');
|
||||||
|
}).catch((error) => { schemaPromise = null; throw error; });
|
||||||
|
}
|
||||||
|
return schemaPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeEmail(value) {
|
||||||
|
const email = typeof value === 'string' ? value.trim().toLowerCase() : '';
|
||||||
|
return email.length <= 255 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) ? email : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hashCode(code) {
|
||||||
|
return createHash('sha256').update(code).digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveEmailCode(email, purpose) {
|
||||||
|
await ensureEmailVerificationSchema();
|
||||||
|
const code = String(randomInt(0, 1000000)).padStart(6, '0');
|
||||||
|
const result = await pool.query(`
|
||||||
|
INSERT INTO email_verifications (email, code_hash, purpose, expires_at)
|
||||||
|
VALUES ($1, $2, $3, now() + interval '10 minutes')
|
||||||
|
ON CONFLICT (LOWER(email), purpose) WHERE consumed_at IS NULL
|
||||||
|
DO UPDATE SET code_hash = EXCLUDED.code_hash, expires_at = EXCLUDED.expires_at,
|
||||||
|
attempts = 0, created_at = now()
|
||||||
|
WHERE email_verifications.created_at < now() - interval '60 seconds'
|
||||||
|
RETURNING id
|
||||||
|
`, [email, hashCode(code), purpose]);
|
||||||
|
return result.rowCount ? code : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function invalidateEmailCode(email, purpose) {
|
||||||
|
await pool.query(`UPDATE email_verifications SET consumed_at = now()
|
||||||
|
WHERE LOWER(email) = $1 AND purpose = $2 AND consumed_at IS NULL`, [email, purpose]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CODE_ERRORS = {
|
||||||
|
missing: '请先获取验证码',
|
||||||
|
expired: '验证码已过期,请重新获取',
|
||||||
|
too_many: '尝试次数过多,请重新获取验证码',
|
||||||
|
mismatch: '验证码错误',
|
||||||
|
};
|
||||||
|
|
||||||
|
// 验证码和最终账号修改在同一事务中提交,失败时验证码不会被消费。
|
||||||
|
export async function withEmailCode(email, purpose, code, action) {
|
||||||
|
await ensureEmailVerificationSchema();
|
||||||
|
const client = await pool.connect();
|
||||||
|
try {
|
||||||
|
await client.query('BEGIN');
|
||||||
|
const result = await client.query(`
|
||||||
|
SELECT id, code_hash, attempts, expires_at FROM email_verifications
|
||||||
|
WHERE LOWER(email) = $1 AND purpose = $2 AND consumed_at IS NULL
|
||||||
|
ORDER BY created_at DESC LIMIT 1 FOR UPDATE
|
||||||
|
`, [email, purpose]);
|
||||||
|
const row = result.rows[0];
|
||||||
|
let failure = null;
|
||||||
|
if (!row) failure = 'missing';
|
||||||
|
else if (new Date(row.expires_at).getTime() <= Date.now()) failure = 'expired';
|
||||||
|
else if (row.attempts >= 5) failure = 'too_many';
|
||||||
|
else {
|
||||||
|
const provided = Buffer.from(hashCode(String(code)));
|
||||||
|
const expected = Buffer.from(row.code_hash);
|
||||||
|
if (provided.length !== expected.length || !timingSafeEqual(provided, expected)) failure = 'mismatch';
|
||||||
|
}
|
||||||
|
if (failure) {
|
||||||
|
if (row && failure === 'mismatch') {
|
||||||
|
await client.query('UPDATE email_verifications SET attempts = attempts + 1 WHERE id = $1', [row.id]);
|
||||||
|
}
|
||||||
|
await client.query('COMMIT');
|
||||||
|
return { failure };
|
||||||
|
}
|
||||||
|
const value = await action(client);
|
||||||
|
await client.query('UPDATE email_verifications SET consumed_at = now() WHERE id = $1', [row.id]);
|
||||||
|
await client.query('COMMIT');
|
||||||
|
return { value };
|
||||||
|
} catch (error) {
|
||||||
|
await client.query('ROLLBACK').catch(() => {});
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
client.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function isEmailVerificationRequired() {
|
||||||
|
const result = await pool.query("SELECT value FROM settings WHERE key = 'email_verify_required'");
|
||||||
|
return result.rows[0]?.value === 'true';
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import nodemailer from 'nodemailer';
|
||||||
|
import pool from './db';
|
||||||
|
|
||||||
|
const KEYS = [
|
||||||
|
'smtp_enabled', 'smtp_host', 'smtp_port', 'smtp_secure', 'smtp_user',
|
||||||
|
'smtp_password', 'smtp_from_name', 'smtp_from_email', 'smtp_allow_self_signed',
|
||||||
|
];
|
||||||
|
|
||||||
|
export async function loadSmtpConfig() {
|
||||||
|
const result = await pool.query('SELECT key, value FROM settings WHERE key = ANY($1::text[])', [KEYS]);
|
||||||
|
const raw = Object.fromEntries(result.rows.map(({ key, value }) => [key, value]));
|
||||||
|
return {
|
||||||
|
enabled: raw.smtp_enabled === 'true',
|
||||||
|
host: raw.smtp_host || '',
|
||||||
|
port: Number(raw.smtp_port || 587),
|
||||||
|
secure: raw.smtp_secure === 'true',
|
||||||
|
user: raw.smtp_user || '',
|
||||||
|
password: raw.smtp_password || '',
|
||||||
|
fromName: raw.smtp_from_name || '',
|
||||||
|
fromEmail: raw.smtp_from_email || '',
|
||||||
|
allowSelfSigned: raw.smtp_allow_self_signed === 'true',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isConfigComplete(config) {
|
||||||
|
return Boolean(config.enabled && config.host && config.port >= 1 && config.port <= 65535 &&
|
||||||
|
config.fromEmail && (!config.user || config.password));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function sendMail(config, { to, subject, text }) {
|
||||||
|
if (!isConfigComplete(config)) throw new Error('站点尚未配置邮件服务,请联系管理员');
|
||||||
|
const transport = nodemailer.createTransport({
|
||||||
|
host: config.host,
|
||||||
|
port: config.port,
|
||||||
|
secure: config.secure,
|
||||||
|
requireTLS: !config.secure,
|
||||||
|
tls: { rejectUnauthorized: !config.allowSelfSigned },
|
||||||
|
...(config.user ? { auth: { user: config.user, pass: config.password } } : {}),
|
||||||
|
connectionTimeout: 10000,
|
||||||
|
greetingTimeout: 10000,
|
||||||
|
socketTimeout: 20000,
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
return await transport.sendMail({
|
||||||
|
from: config.fromName
|
||||||
|
? `"${config.fromName.replace(/["\r\n]/g, '')}" <${config.fromEmail}>`
|
||||||
|
: config.fromEmail,
|
||||||
|
to,
|
||||||
|
subject,
|
||||||
|
text,
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
transport.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function describeSmtpError(error) {
|
||||||
|
if (error?.code === 'EAUTH') return '认证失败,请检查 SMTP 用户名、授权码或 API Key';
|
||||||
|
if (error?.code === 'ETIMEDOUT') return '连接超时,请检查 SMTP 地址、端口及防火墙';
|
||||||
|
if (error?.code === 'ESOCKET') return '连接失败,请检查端口与 TLS 设置';
|
||||||
|
if (/self.signed certificate/i.test(error?.message || '')) return '证书校验失败;自建邮件服务器可在后台允许自签证书';
|
||||||
|
return error?.message || '邮件发送失败';
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import pool from './db';
|
||||||
|
|
||||||
|
let schemaPromise;
|
||||||
|
|
||||||
|
export function ensureUserBlocksSchema() {
|
||||||
|
if (!schemaPromise) {
|
||||||
|
schemaPromise = pool.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS user_blocks (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
blocker_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
blocked_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
UNIQUE (blocker_id, blocked_id),
|
||||||
|
CHECK (blocker_id <> blocked_id)
|
||||||
|
)
|
||||||
|
`).then(async () => {
|
||||||
|
await pool.query('CREATE INDEX IF NOT EXISTS idx_user_blocks_blocker ON user_blocks(blocker_id)');
|
||||||
|
await pool.query('CREATE INDEX IF NOT EXISTS idx_user_blocks_blocked ON user_blocks(blocked_id)');
|
||||||
|
}).catch((error) => {
|
||||||
|
schemaPromise = null;
|
||||||
|
throw error;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return schemaPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||||
|
|
||||||
|
export async function hasBlocked(blockerId, blockedId, client = pool) {
|
||||||
|
await ensureUserBlocksSchema();
|
||||||
|
const result = await client.query(
|
||||||
|
'SELECT EXISTS(SELECT 1 FROM user_blocks WHERE blocker_id = $1 AND blocked_id = $2) AS blocked',
|
||||||
|
[blockerId, blockedId]
|
||||||
|
);
|
||||||
|
return result.rows[0].blocked;
|
||||||
|
}
|
||||||
@@ -16,6 +16,9 @@
|
|||||||
"latest": "Latest posts",
|
"latest": "Latest posts",
|
||||||
"hot": "Latest replies",
|
"hot": "Latest replies",
|
||||||
"newPost": "New post",
|
"newPost": "New post",
|
||||||
|
"searchPlaceholder": "Search post titles or content...",
|
||||||
|
"clearSearch": "Clear search",
|
||||||
|
"searchEmpty": "No posts found for “{{query}}”",
|
||||||
"loading": "Loading...",
|
"loading": "Loading...",
|
||||||
"loadFailed": "Load failed: {{msg}}",
|
"loadFailed": "Load failed: {{msg}}",
|
||||||
"empty": "No posts yet — be the first to publish!",
|
"empty": "No posts yet — be the first to publish!",
|
||||||
@@ -28,6 +31,28 @@
|
|||||||
"noTitle": "Untitled",
|
"noTitle": "Untitled",
|
||||||
"anonymous": "Anonymous"
|
"anonymous": "Anonymous"
|
||||||
},
|
},
|
||||||
|
"chat": {
|
||||||
|
"title": "Messages",
|
||||||
|
"new": "New message",
|
||||||
|
"searchPlaceholder": "Search usernames...",
|
||||||
|
"searchHint": "Enter a username to find someone",
|
||||||
|
"searchEmpty": "No users found",
|
||||||
|
"loading": "Loading...",
|
||||||
|
"empty": "No conversations yet",
|
||||||
|
"noMessage": "No messages yet",
|
||||||
|
"openFailed": "Could not open chat: {{msg}}",
|
||||||
|
"limitReached": "You can send up to 3 messages before they reply"
|
||||||
|
},
|
||||||
|
"blocking": {
|
||||||
|
"block": "Block",
|
||||||
|
"unblock": "Unblock",
|
||||||
|
"blockConfirm": "Block “{{name}}”? You will no longer see their posts or replies, and they cannot message you.",
|
||||||
|
"unblockConfirm": "Unblock “{{name}}”?",
|
||||||
|
"blockedHint": "Blocked: their posts and replies are hidden, and they cannot message you.",
|
||||||
|
"blocked": "User blocked",
|
||||||
|
"unblocked": "User unblocked",
|
||||||
|
"failed": "Action failed: {{msg}}"
|
||||||
|
},
|
||||||
"post": {
|
"post": {
|
||||||
"title": "Post detail",
|
"title": "Post detail",
|
||||||
"back": "← Back",
|
"back": "← Back",
|
||||||
@@ -84,6 +109,16 @@
|
|||||||
"forgotPassword": "Forgot password?",
|
"forgotPassword": "Forgot password?",
|
||||||
"resetTitle": "Reset password with a recovery code",
|
"resetTitle": "Reset password with a recovery code",
|
||||||
"resetHint": "Enter your email and a recovery code generated in Settings to set a new password.",
|
"resetHint": "Enter your email and a recovery code generated in Settings to set a new password.",
|
||||||
|
"resetEmailTitle": "Reset password by email",
|
||||||
|
"resetEmailHint": "Enter your email and request a code to set a new password.",
|
||||||
|
"recoveryMethod": "Recovery code",
|
||||||
|
"emailMethod": "Email code",
|
||||||
|
"emailCode": "Email code",
|
||||||
|
"sendCode": "Send code",
|
||||||
|
"emailRequired": "Enter your email first",
|
||||||
|
"emailCodeRequired": "Enter the email code",
|
||||||
|
"emailCodeSent": "Code sent. Check your inbox.",
|
||||||
|
"emailCodeFailed": "Could not send code: {{msg}}",
|
||||||
"recoveryCode": "Recovery code",
|
"recoveryCode": "Recovery code",
|
||||||
"newPassword": "New password (min 6 characters)",
|
"newPassword": "New password (min 6 characters)",
|
||||||
"confirmPassword": "Confirm new password",
|
"confirmPassword": "Confirm new password",
|
||||||
@@ -187,6 +222,33 @@
|
|||||||
"logs": "Event logs",
|
"logs": "Event logs",
|
||||||
"links": "Links",
|
"links": "Links",
|
||||||
"forumSettings": "Forum settings",
|
"forumSettings": "Forum settings",
|
||||||
|
"mail": "Email service",
|
||||||
|
"mailForm": {
|
||||||
|
"title": "Email service (SMTP)",
|
||||||
|
"hint": "Configure an outgoing mail server for signup verification and password recovery.",
|
||||||
|
"enabled": "Enable SMTP",
|
||||||
|
"host": "Server host",
|
||||||
|
"port": "Port",
|
||||||
|
"user": "Username",
|
||||||
|
"password": "Password or API key",
|
||||||
|
"passwordSaved": "Saved; leave blank to keep it",
|
||||||
|
"fromName": "Sender name",
|
||||||
|
"fromEmail": "Sender email",
|
||||||
|
"secure": "Use SSL/TLS (usually port 465)",
|
||||||
|
"selfSigned": "Allow self-signed certificates (private servers only)",
|
||||||
|
"save": "Save settings",
|
||||||
|
"saved": "Email settings saved",
|
||||||
|
"failed": "Action failed: {{msg}}",
|
||||||
|
"clearPassword": "Clear password",
|
||||||
|
"clearPasswordConfirm": "Clear the saved SMTP password?",
|
||||||
|
"passwordCleared": "Password cleared",
|
||||||
|
"testTo": "Test recipient",
|
||||||
|
"testToHint": "Leave blank to send to this admin",
|
||||||
|
"sendTest": "Send test email",
|
||||||
|
"testSent": "Test email sent",
|
||||||
|
"requireVerification": "Verify email at signup",
|
||||||
|
"verifyHint": "Save and test SMTP before enabling. Off by default."
|
||||||
|
},
|
||||||
"customPages": "Custom pages",
|
"customPages": "Custom pages",
|
||||||
"customCss": "Custom CSS",
|
"customCss": "Custom CSS",
|
||||||
"common": {
|
"common": {
|
||||||
|
|||||||
@@ -16,6 +16,9 @@
|
|||||||
"latest": "最新发布",
|
"latest": "最新发布",
|
||||||
"hot": "最新回复",
|
"hot": "最新回复",
|
||||||
"newPost": "发布新帖",
|
"newPost": "发布新帖",
|
||||||
|
"searchPlaceholder": "搜索帖子标题或内容...",
|
||||||
|
"clearSearch": "清除搜索",
|
||||||
|
"searchEmpty": "没有找到与「{{query}}」相关的帖子",
|
||||||
"loading": "加载中...",
|
"loading": "加载中...",
|
||||||
"loadFailed": "加载失败:{{msg}}",
|
"loadFailed": "加载失败:{{msg}}",
|
||||||
"empty": "还没有帖子,快来发布第一条吧!",
|
"empty": "还没有帖子,快来发布第一条吧!",
|
||||||
@@ -28,6 +31,28 @@
|
|||||||
"noTitle": "无标题",
|
"noTitle": "无标题",
|
||||||
"anonymous": "匿名用户"
|
"anonymous": "匿名用户"
|
||||||
},
|
},
|
||||||
|
"chat": {
|
||||||
|
"title": "私信",
|
||||||
|
"new": "发起私信",
|
||||||
|
"searchPlaceholder": "搜索用户名...",
|
||||||
|
"searchHint": "输入用户名查找用户",
|
||||||
|
"searchEmpty": "没有找到用户",
|
||||||
|
"loading": "加载中...",
|
||||||
|
"empty": "暂无私信",
|
||||||
|
"noMessage": "暂无消息",
|
||||||
|
"openFailed": "打开私信失败:{{msg}}",
|
||||||
|
"limitReached": "对方回复前最多发送 3 条消息,请等待对方回复"
|
||||||
|
},
|
||||||
|
"blocking": {
|
||||||
|
"block": "屏蔽",
|
||||||
|
"unblock": "解除屏蔽",
|
||||||
|
"blockConfirm": "确定屏蔽「{{name}}」?你将不再看到 TA 的帖子和回复,TA 也无法给你发私信。",
|
||||||
|
"unblockConfirm": "解除对「{{name}}」的屏蔽?",
|
||||||
|
"blockedHint": "已屏蔽该用户:你不再看到 TA 的帖子与回复,TA 也无法给你发私信。",
|
||||||
|
"blocked": "已屏蔽该用户",
|
||||||
|
"unblocked": "已解除屏蔽",
|
||||||
|
"failed": "操作失败:{{msg}}"
|
||||||
|
},
|
||||||
"post": {
|
"post": {
|
||||||
"title": "帖子详情",
|
"title": "帖子详情",
|
||||||
"back": "← 返回",
|
"back": "← 返回",
|
||||||
@@ -84,6 +109,16 @@
|
|||||||
"forgotPassword": "忘记密码?",
|
"forgotPassword": "忘记密码?",
|
||||||
"resetTitle": "通过恢复码重置密码",
|
"resetTitle": "通过恢复码重置密码",
|
||||||
"resetHint": "输入邮箱和设置中生成的恢复码,即可设置新密码。",
|
"resetHint": "输入邮箱和设置中生成的恢复码,即可设置新密码。",
|
||||||
|
"resetEmailTitle": "通过邮箱重置密码",
|
||||||
|
"resetEmailHint": "输入邮箱,获取邮件验证码后设置新密码。",
|
||||||
|
"recoveryMethod": "恢复码",
|
||||||
|
"emailMethod": "邮箱验证码",
|
||||||
|
"emailCode": "邮箱验证码",
|
||||||
|
"sendCode": "获取验证码",
|
||||||
|
"emailRequired": "请先填写邮箱",
|
||||||
|
"emailCodeRequired": "请输入邮箱验证码",
|
||||||
|
"emailCodeSent": "验证码已发送,请查收邮件",
|
||||||
|
"emailCodeFailed": "验证码发送失败:{{msg}}",
|
||||||
"recoveryCode": "恢复码",
|
"recoveryCode": "恢复码",
|
||||||
"newPassword": "新密码(至少6位)",
|
"newPassword": "新密码(至少6位)",
|
||||||
"confirmPassword": "确认新密码",
|
"confirmPassword": "确认新密码",
|
||||||
@@ -187,6 +222,33 @@
|
|||||||
"logs": "事件日志",
|
"logs": "事件日志",
|
||||||
"links": "友情链接",
|
"links": "友情链接",
|
||||||
"forumSettings": "论坛设置",
|
"forumSettings": "论坛设置",
|
||||||
|
"mail": "邮件服务",
|
||||||
|
"mailForm": {
|
||||||
|
"title": "邮件服务(SMTP)",
|
||||||
|
"hint": "配置发件服务器后可启用注册邮箱验证和邮件找回密码。",
|
||||||
|
"enabled": "启用 SMTP",
|
||||||
|
"host": "服务器地址",
|
||||||
|
"port": "端口",
|
||||||
|
"user": "用户名",
|
||||||
|
"password": "密码或授权码",
|
||||||
|
"passwordSaved": "已保存,留空保持不变",
|
||||||
|
"fromName": "发件人名称",
|
||||||
|
"fromEmail": "发件人邮箱",
|
||||||
|
"secure": "使用 SSL/TLS(通常为 465 端口)",
|
||||||
|
"selfSigned": "允许自签名证书(仅自建服务器)",
|
||||||
|
"save": "保存配置",
|
||||||
|
"saved": "邮件设置已保存",
|
||||||
|
"failed": "操作失败:{{msg}}",
|
||||||
|
"clearPassword": "清除密码",
|
||||||
|
"clearPasswordConfirm": "确定清除已保存的 SMTP 密码吗?",
|
||||||
|
"passwordCleared": "密码已清除",
|
||||||
|
"testTo": "测试收件人",
|
||||||
|
"testToHint": "留空则发送给当前管理员",
|
||||||
|
"sendTest": "发送测试邮件",
|
||||||
|
"testSent": "测试邮件已发送",
|
||||||
|
"requireVerification": "注册时验证邮箱",
|
||||||
|
"verifyHint": "启用前请先保存配置并发送测试邮件;默认关闭。"
|
||||||
|
},
|
||||||
"customPages": "自定义页面",
|
"customPages": "自定义页面",
|
||||||
"customCss": "自定义 CSS",
|
"customCss": "自定义 CSS",
|
||||||
"common": {
|
"common": {
|
||||||
|
|||||||
Generated
+10
@@ -14,6 +14,7 @@
|
|||||||
"jsonwebtoken": "^9.0.2",
|
"jsonwebtoken": "^9.0.2",
|
||||||
"marked": "^18.0.9",
|
"marked": "^18.0.9",
|
||||||
"next": "16",
|
"next": "16",
|
||||||
|
"nodemailer": "^7.0.13",
|
||||||
"pg": "^8.11.3",
|
"pg": "^8.11.3",
|
||||||
"react": "19",
|
"react": "19",
|
||||||
"react-dom": "19",
|
"react-dom": "19",
|
||||||
@@ -7316,6 +7317,15 @@
|
|||||||
"node": ">=18"
|
"node": ">=18"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/nodemailer": {
|
||||||
|
"version": "7.0.13",
|
||||||
|
"resolved": "https://registry.npmmirror.com/nodemailer/-/nodemailer-7.0.13.tgz",
|
||||||
|
"integrity": "sha512-PNDFSJdP+KFgdsG3ZzMXCgquO7I6McjY2vlqILjtJd0hy8wEvtugS9xKRF2NWlPNGxvLCXlTNIae4serI7dinw==",
|
||||||
|
"license": "MIT-0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/npm-run-path": {
|
"node_modules/npm-run-path": {
|
||||||
"version": "4.0.1",
|
"version": "4.0.1",
|
||||||
"resolved": "https://registry.npmmirror.com/npm-run-path/-/npm-run-path-4.0.1.tgz",
|
"resolved": "https://registry.npmmirror.com/npm-run-path/-/npm-run-path-4.0.1.tgz",
|
||||||
|
|||||||
@@ -20,6 +20,7 @@
|
|||||||
"jsonwebtoken": "^9.0.2",
|
"jsonwebtoken": "^9.0.2",
|
||||||
"marked": "^18.0.9",
|
"marked": "^18.0.9",
|
||||||
"next": "16",
|
"next": "16",
|
||||||
|
"nodemailer": "^7.0.13",
|
||||||
"pg": "^8.11.3",
|
"pg": "^8.11.3",
|
||||||
"react": "19",
|
"react": "19",
|
||||||
"react-dom": "19",
|
"react-dom": "19",
|
||||||
|
|||||||
+45
@@ -277,3 +277,48 @@ ALTER TABLE posts ALTER COLUMN post_number SET DEFAULT nextval('posts_post_numbe
|
|||||||
ALTER SEQUENCE posts_post_number_seq OWNED BY posts.post_number;
|
ALTER SEQUENCE posts_post_number_seq OWNED BY posts.post_number;
|
||||||
ALTER TABLE posts ALTER COLUMN post_number SET NOT NULL;
|
ALTER TABLE posts ALTER COLUMN post_number SET NOT NULL;
|
||||||
CREATE UNIQUE INDEX IF NOT EXISTS posts_post_number_key ON posts(post_number);
|
CREATE UNIQUE INDEX IF NOT EXISTS posts_post_number_key ON posts(post_number);
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- 用户屏蔽(与 Lite 共用结构,既有安装可重复执行)
|
||||||
|
-- ============================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS user_blocks (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
blocker_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
blocked_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
UNIQUE (blocker_id, blocked_id),
|
||||||
|
CHECK (blocker_id <> blocked_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_blocks_blocker ON user_blocks(blocker_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_blocks_blocked ON user_blocks(blocked_id);
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- 邮箱验证码:注册与找回密码共用(默认关闭)
|
||||||
|
-- ============================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS email_verifications (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
email VARCHAR(255) NOT NULL,
|
||||||
|
code_hash VARCHAR(64) NOT NULL,
|
||||||
|
purpose VARCHAR(20) NOT NULL DEFAULT 'register',
|
||||||
|
attempts INTEGER NOT NULL DEFAULT 0,
|
||||||
|
consumed_at TIMESTAMPTZ,
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_email_verifications_active
|
||||||
|
ON email_verifications (LOWER(email), purpose) WHERE consumed_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_email_verifications_expires
|
||||||
|
ON email_verifications (expires_at);
|
||||||
|
ALTER TABLE users ADD COLUMN IF NOT EXISTS email_verified BOOLEAN NOT NULL DEFAULT true;
|
||||||
|
INSERT INTO settings (key, value) VALUES
|
||||||
|
('smtp_enabled', 'false'),
|
||||||
|
('smtp_host', ''),
|
||||||
|
('smtp_port', '587'),
|
||||||
|
('smtp_secure', 'false'),
|
||||||
|
('smtp_user', ''),
|
||||||
|
('smtp_password', ''),
|
||||||
|
('smtp_from_name', ''),
|
||||||
|
('smtp_from_email', ''),
|
||||||
|
('smtp_allow_self_signed', 'false'),
|
||||||
|
('email_verify_required', 'false')
|
||||||
|
ON CONFLICT (key) DO NOTHING;
|
||||||
Reference in new issue
Block a user