Compare commits
3
Commits
| Author | SHA1 | Date | ||
|---|---|---|---|---|
| ||||
|
|
52adf7620d | |||
|
|
3c060ffce8 | |||
|
|
9c0271f5ce | |||
No files matched your search
@@ -4,8 +4,7 @@
|
||||
|
||||
> 一个简洁、优雅的现代社区系统。5 分钟 Docker 一键部署。
|
||||
|
||||
官方演示地址:【维护中】
|
||||
|
||||
官方演示地址:[Forumlify NEXT](https://next.forumlify.org)
|
||||
|
||||
## ✨ 特性
|
||||
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
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,27 +3,20 @@ import bcrypt from 'bcryptjs';
|
||||
import pool from '@/lib/db';
|
||||
import { verifyCaptcha } from '@/lib/captcha';
|
||||
import { logAudit } from '@/lib/audit';
|
||||
import { normalizeEmail, isEmailVerificationRequired, withEmailCode, CODE_ERRORS, ensureEmailVerificationSchema } from '@/lib/email-verification';
|
||||
|
||||
export async function POST(req) {
|
||||
const { email, password, username, email_code, captcha_id, captcha_answer, captcha_sig } = await req.json();
|
||||
const normalizedEmail = normalizeEmail(email);
|
||||
if (!normalizedEmail || !password || !username) {
|
||||
const { email, password, username, captcha_id, captcha_answer, captcha_sig } = await req.json();
|
||||
if (!email || !password || !username) {
|
||||
return Response.json({ error: '请填写完整信息' }, { status: 400 });
|
||||
}
|
||||
if (typeof password !== 'string' || password.length < 6 || password.length > 128 ||
|
||||
typeof username !== 'string' || !username.trim() || username.length > 50) {
|
||||
return Response.json({ error: '用户名或密码长度无效' }, { status: 400 });
|
||||
if (password.length < 6) {
|
||||
return Response.json({ error: '密码至少6位' }, { status: 400 });
|
||||
}
|
||||
// 服务端验证码校验(ENABLE_CAPTCHA 关闭时跳过)
|
||||
if (process.env.ENABLE_CAPTCHA !== 'false' && !verifyCaptcha(captcha_id, captcha_answer, captcha_sig)) {
|
||||
return Response.json({ error: '验证码错误,请重新计算' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const verificationRequired = await isEmailVerificationRequired();
|
||||
if (verificationRequired && !/^\d{6}$/.test(email_code || '')) {
|
||||
return Response.json({ error: '请输入邮箱验证码' }, { status: 400 });
|
||||
}
|
||||
const countResult = await pool.query('SELECT COUNT(*) FROM users');
|
||||
const isFirstUser = parseInt(countResult.rows[0].count) === 0;
|
||||
|
||||
@@ -31,21 +24,12 @@ export async function POST(req) {
|
||||
const avatar = 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) + '&background=6366f1&color=fff&size=64';
|
||||
const role = isFirstUser ? 'admin' : 'user';
|
||||
|
||||
const insert = (client) => client.query(
|
||||
`INSERT INTO users (email, password_hash, username, avatar_url, role, email_verified)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
const r = await pool.query(
|
||||
`INSERT INTO users (email, password_hash, username, avatar_url, role)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING id, username, avatar_url, role, created_at`,
|
||||
[normalizedEmail, hash, username.trim(), avatar, role, verificationRequired]
|
||||
[email, hash, username, avatar, role]
|
||||
);
|
||||
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);
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
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,7 +1,6 @@
|
||||
// GET /api/conversations/[id]/messages, POST /api/conversations/[id]/messages
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
import { ensureUserBlocksSchema } from '@/lib/user-blocks';
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
@@ -50,60 +49,30 @@ export async function POST(req, { params }) {
|
||||
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
|
||||
}
|
||||
const { content } = await req.json();
|
||||
if (typeof content !== 'string' || !content.trim() || content.length > 10000) {
|
||||
return Response.json({ error: '消息长度应为1到10000个字符' }, { status: 400 });
|
||||
if (!content || content.trim().length === 0) {
|
||||
return Response.json({ error: '请填写消息内容' }, { status: 400 });
|
||||
}
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await ensureUserBlocksSchema();
|
||||
await client.query('BEGIN');
|
||||
const check = await client.query(`
|
||||
SELECT id, user1_id, user2_id FROM conversations
|
||||
const check = await pool.query(`
|
||||
SELECT id FROM conversations
|
||||
WHERE id = $1 AND (user1_id = $2 OR user2_id = $2)
|
||||
FOR UPDATE
|
||||
`, [(await params).id, user.id]);
|
||||
if (check.rows.length === 0) {
|
||||
await client.query('ROLLBACK');
|
||||
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
|
||||
}
|
||||
const 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(`
|
||||
const r = await pool.query(`
|
||||
INSERT INTO messages (conversation_id, sender_id, content)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING *
|
||||
`, [(await params).id, user.id, content.trim()]);
|
||||
await client.query('UPDATE conversations SET last_message_at = NOW() WHERE id = $1', [(await params).id]);
|
||||
const userInfo = await client.query('SELECT username, avatar_url FROM users WHERE id = $1', [user.id]);
|
||||
await client.query('COMMIT');
|
||||
`, [(await params).id, user.id, content]);
|
||||
await pool.query('UPDATE conversations SET last_message_at = NOW() WHERE id = $1', [(await params).id]);
|
||||
const userInfo = await pool.query('SELECT username, avatar_url FROM users WHERE id = $1', [user.id]);
|
||||
return Response.json({
|
||||
...r.rows[0],
|
||||
sender_username: userInfo.rows[0].username,
|
||||
sender_avatar_url: userInfo.rows[0].avatar_url,
|
||||
});
|
||||
} catch {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
return Response.json({ error: '发送失败,请稍后重试' }, { status: 500 });
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
// GET /api/conversations, POST /api/conversations
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
import { ensureUserBlocksSchema, hasBlocked, UUID_RE } from '@/lib/user-blocks';
|
||||
|
||||
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
|
||||
export const dynamic = 'force-dynamic';
|
||||
@@ -43,21 +42,17 @@ export async function POST(req) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
const { other_user_id } = await req.json();
|
||||
if (!UUID_RE.test(other_user_id || '')) {
|
||||
return Response.json({ error: '对方用户ID无效' }, { status: 400 });
|
||||
if (!other_user_id) {
|
||||
return Response.json({ error: '缺少对方用户ID' }, { status: 400 });
|
||||
}
|
||||
if (other_user_id === user.id) {
|
||||
return Response.json({ error: '不能与自己私信' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
await ensureUserBlocksSchema();
|
||||
const userCheck = await pool.query('SELECT id FROM users WHERE id = $1', [other_user_id]);
|
||||
if (userCheck.rows.length === 0) {
|
||||
return Response.json({ error: '用户不存在' }, { status: 404 });
|
||||
}
|
||||
if (await hasBlocked(other_user_id, user.id) || await hasBlocked(user.id, other_user_id)) {
|
||||
return Response.json({ error: '无法向该用户发起私信' }, { status: 403 });
|
||||
}
|
||||
const existing = await pool.query(`
|
||||
SELECT id FROM conversations
|
||||
WHERE (user1_id = $1 AND user2_id = $2) OR (user1_id = $2 AND user2_id = $1)
|
||||
@@ -67,9 +62,7 @@ export async function POST(req) {
|
||||
}
|
||||
const r = await pool.query(`
|
||||
INSERT INTO conversations (user1_id, user2_id)
|
||||
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
|
||||
VALUES ($1, $2)
|
||||
RETURNING id
|
||||
`, [user.id, other_user_id]);
|
||||
return Response.json({ id: r.rows[0].id });
|
||||
|
||||
@@ -6,12 +6,8 @@ import { verifyCaptcha } from '@/lib/captcha';
|
||||
import { logAudit } from '@/lib/audit';
|
||||
import { getReplySchemaCapabilities } from '@/lib/reply-schema';
|
||||
import { resolvePostReference } from '@/lib/post-reference';
|
||||
import { ensureUserBlocksSchema } from '@/lib/user-blocks';
|
||||
|
||||
function repliesSelectSql(capabilities, 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
|
||||
)` : '';
|
||||
function repliesSelectSql(capabilities) {
|
||||
if (capabilities.replyToId) {
|
||||
return `SELECT r.id, r.post_id, r.user_id, r.content, r.created_at,
|
||||
r.reply_to_id, u.username, u.avatar_url,
|
||||
@@ -20,7 +16,7 @@ function repliesSelectSql(capabilities, viewer) {
|
||||
JOIN users u ON r.user_id = u.id
|
||||
LEFT JOIN replies rt ON r.reply_to_id = rt.id
|
||||
LEFT JOIN users ru ON rt.user_id = ru.id
|
||||
WHERE r.post_id = $1${visible}
|
||||
WHERE r.post_id = $1
|
||||
ORDER BY r.created_at ASC`;
|
||||
}
|
||||
|
||||
@@ -31,7 +27,7 @@ function repliesSelectSql(capabilities, viewer) {
|
||||
r.reply_to_username
|
||||
FROM replies r
|
||||
JOIN users u ON r.user_id = u.id
|
||||
WHERE r.post_id = $1${visible}
|
||||
WHERE r.post_id = $1
|
||||
ORDER BY r.created_at ASC`;
|
||||
}
|
||||
|
||||
@@ -41,7 +37,7 @@ function repliesSelectSql(capabilities, viewer) {
|
||||
u.username, u.avatar_url
|
||||
FROM replies r
|
||||
JOIN users u ON r.user_id = u.id
|
||||
WHERE r.post_id = $1${visible}
|
||||
WHERE r.post_id = $1
|
||||
ORDER BY r.created_at ASC`;
|
||||
}
|
||||
|
||||
@@ -49,13 +45,9 @@ export async function GET(req, { params }) {
|
||||
try {
|
||||
const reference = await resolvePostReference((await params).id);
|
||||
if (!reference) return Response.json({ error: '帖子不存在' }, { status: 404 });
|
||||
const viewer = getUser(req);
|
||||
if (viewer) await ensureUserBlocksSchema();
|
||||
const capabilities = await getReplySchemaCapabilities();
|
||||
const r = await pool.query(repliesSelectSql(capabilities, viewer), viewer ? [reference.id, viewer.id] : [reference.id]);
|
||||
return viewer
|
||||
? Response.json(r.rows, { headers: { 'Cache-Control': 'private, no-store' } })
|
||||
: jsonWithEtag(req, r.rows);
|
||||
const r = await pool.query(repliesSelectSql(capabilities), [reference.id]);
|
||||
return jsonWithEtag(req, r.rows);
|
||||
} catch (error) {
|
||||
console.error('[replies] list failed:', error?.code || error?.message);
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
|
||||
@@ -3,7 +3,6 @@ import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
import { jsonWithEtag } from '@/lib/http-cache';
|
||||
import { resolvePostReference } from '@/lib/post-reference';
|
||||
import { ensureUserBlocksSchema } from '@/lib/user-blocks';
|
||||
|
||||
function invalidId() {
|
||||
return Response.json({ error: '帖子不存在' }, { status: 404 });
|
||||
@@ -11,25 +10,19 @@ function invalidId() {
|
||||
|
||||
export async function GET(req, { params }) {
|
||||
try {
|
||||
const viewer = getUser(req);
|
||||
const reference = await resolvePostReference((await params).id);
|
||||
if (!reference) return invalidId();
|
||||
if (viewer) await ensureUserBlocksSchema();
|
||||
const r = await pool.query(
|
||||
`SELECT p.*, u.username, u.avatar_url, u.signature
|
||||
FROM posts p
|
||||
JOIN users u ON p.user_id = u.id
|
||||
WHERE p.id = $1${viewer ? ` AND NOT EXISTS (
|
||||
SELECT 1 FROM user_blocks b WHERE b.blocker_id = $2 AND b.blocked_id = p.user_id
|
||||
)` : ''}`,
|
||||
viewer ? [reference.id, viewer.id] : [reference.id]
|
||||
WHERE p.id = $1`,
|
||||
[reference.id]
|
||||
);
|
||||
if (r.rows.length === 0) {
|
||||
return invalidId();
|
||||
}
|
||||
return viewer
|
||||
? Response.json(r.rows[0], { headers: { 'Cache-Control': 'private, no-store' } })
|
||||
: jsonWithEtag(req, r.rows[0]);
|
||||
return jsonWithEtag(req, r.rows[0]);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
|
||||
+6
-19
@@ -5,7 +5,6 @@ import { jsonWithEtag } from '@/lib/http-cache';
|
||||
import { verifyCaptcha } from '@/lib/captcha';
|
||||
import { logAudit } from '@/lib/audit';
|
||||
import { ensurePostNumberSchema } from '@/lib/post-reference';
|
||||
import { ensureUserBlocksSchema } from '@/lib/user-blocks';
|
||||
|
||||
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
|
||||
export const dynamic = 'force-dynamic';
|
||||
@@ -15,7 +14,6 @@ export async function GET(req) {
|
||||
const url = new URL(req.url);
|
||||
const sort = url.searchParams.get('sort') === 'hot' ? 'updated_at' : 'created_at';
|
||||
const userId = url.searchParams.get('user_id');
|
||||
const viewer = getUser(req);
|
||||
const page = Math.max(1, parseInt(url.searchParams.get('page')) || 1);
|
||||
// 分页边界:limit 封顶 50,page 封顶 10000(防深分页 DoS)
|
||||
const limit = Math.min(50, Math.max(1, parseInt(url.searchParams.get('limit')) || 20));
|
||||
@@ -26,19 +24,11 @@ export async function GET(req) {
|
||||
try {
|
||||
await ensurePostNumberSchema();
|
||||
const params = [];
|
||||
const conditions = [];
|
||||
let where = '';
|
||||
if (userId) {
|
||||
params.push(userId);
|
||||
conditions.push(`p.user_id = $${params.length}`);
|
||||
where = ' WHERE p.user_id = $1';
|
||||
(await params).push(userId);
|
||||
}
|
||||
if (viewer) {
|
||||
await ensureUserBlocksSchema();
|
||||
params.push(viewer.id);
|
||||
conditions.push(`NOT EXISTS (
|
||||
SELECT 1 FROM user_blocks b WHERE b.blocker_id = $${params.length} AND b.blocked_id = p.user_id
|
||||
)`);
|
||||
}
|
||||
const where = conditions.length ? ` WHERE ${conditions.join(' AND ')}` : '';
|
||||
|
||||
const countResult = await pool.query(`SELECT COUNT(*) as total FROM posts p${where}`, params);
|
||||
const total = parseInt(countResult.rows[0]?.total || 0);
|
||||
@@ -54,16 +44,13 @@ export async function GET(req) {
|
||||
JOIN users u ON p.user_id = u.id
|
||||
${where}
|
||||
ORDER BY is_pinned DESC, pinned_at DESC NULLS LAST, ${sort} DESC
|
||||
LIMIT $${params.length + 1} OFFSET $${params.length + 2}
|
||||
LIMIT $${(await params).length + 1} OFFSET $${(await params).length + 2}
|
||||
`, [...params, limit, offset]);
|
||||
|
||||
const payload = {
|
||||
return jsonWithEtag(req, {
|
||||
data: r.rows,
|
||||
pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
|
||||
};
|
||||
return viewer
|
||||
? Response.json(payload, { headers: { 'Cache-Control': 'private, no-store' } })
|
||||
: jsonWithEtag(req, payload);
|
||||
});
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
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,7 +2,6 @@
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, requireAdmin } from '@/lib/auth';
|
||||
import { jsonWithEtag } from '@/lib/http-cache';
|
||||
import { loadSmtpConfig, isConfigComplete } from '@/lib/mailer';
|
||||
|
||||
const VERSION_COMMIT = (process.env.FORUMLIFY_COMMIT || 'unknown').slice(0, 7);
|
||||
|
||||
@@ -16,14 +15,10 @@ export async function GET(req) {
|
||||
`INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify')
|
||||
ON CONFLICT (key) DO NOTHING`
|
||||
);
|
||||
const r = await pool.query(`SELECT key, value FROM settings
|
||||
WHERE key = ANY($1::text[]) ORDER BY key`,
|
||||
[['forum_name', 'favicon_url', 'favicon_version', 'custom_css_enabled', 'email_verify_required']]);
|
||||
const r = await pool.query('SELECT key, value FROM settings ORDER BY key');
|
||||
const settings = {};
|
||||
r.rows.forEach((row) => { settings[row.key] = row.value; });
|
||||
const config = await loadSmtpConfig();
|
||||
settings.smtp_ready = isConfigComplete(config);
|
||||
settings.email_verify_required = settings.email_verify_required === 'true' && settings.smtp_ready;
|
||||
delete settings.favicon_object;
|
||||
// 兜底:即使插入失败也保证返回 forum_name
|
||||
if (!settings.forum_name) settings.forum_name = 'Forumlify';
|
||||
settings.version_commit = VERSION_COMMIT;
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
+4
-272
@@ -514,119 +514,6 @@ svg {
|
||||
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-title-label {
|
||||
display: inline-block;
|
||||
@@ -693,152 +580,6 @@ svg {
|
||||
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 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -1757,7 +1498,6 @@ html.post-view-transition::view-transition-group(post-expand),
|
||||
html.home-view-transition.returning-home::view-transition-group(post-expand) {
|
||||
animation-duration: 1.1s;
|
||||
animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1);
|
||||
background: var(--glass-bg);
|
||||
border-radius: var(--radius);
|
||||
overflow: clip;
|
||||
}
|
||||
@@ -1918,25 +1658,17 @@ html.post-view-transition::view-transition-old(post-feed-actions) {
|
||||
}
|
||||
|
||||
html.post-view-transition::view-transition-old(post-body) {
|
||||
animation: postBodyPreviewOut 0.96s linear both;
|
||||
animation: none;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
html.post-view-transition::view-transition-new(post-body) {
|
||||
animation: postBodyDetailIn 0.96s linear both;
|
||||
animation: none;
|
||||
opacity: 1;
|
||||
object-fit: none;
|
||||
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-signature) {
|
||||
animation: detailOnlyPartIn 0.22s 0.62s ease-out both;
|
||||
|
||||
@@ -11,7 +11,6 @@ import AdminLinks from './admin/AdminLinks';
|
||||
import AdminForumSettings from './admin/AdminForumSettings';
|
||||
import AdminCustomPages from './admin/AdminCustomPages';
|
||||
import AdminCustomCss from './admin/AdminCustomCss';
|
||||
import AdminMailSettings from './admin/AdminMailSettings';
|
||||
|
||||
const NAV = [
|
||||
{ key: 'reports', labelKey: 'admin.reports', icon: 'shieldAlert' },
|
||||
@@ -19,7 +18,6 @@ const NAV = [
|
||||
{ key: 'logs', labelKey: 'admin.logs', icon: 'file' },
|
||||
{ key: 'links', labelKey: 'admin.links', icon: 'link' },
|
||||
{ key: 'settings', labelKey: 'admin.forumSettings', icon: 'settings' },
|
||||
{ key: 'mail', labelKey: 'admin.mail', icon: 'message' },
|
||||
{ key: 'custom', labelKey: 'admin.customPages', icon: 'file' },
|
||||
{ key: 'css', labelKey: 'admin.customCss', icon: 'file' },
|
||||
];
|
||||
@@ -125,7 +123,6 @@ export default function AdminPage() {
|
||||
if (tab === 'links') return <AdminLinks />;
|
||||
if (tab === 'custom') return <AdminCustomPages />;
|
||||
if (tab === 'css') return <AdminCustomCss />;
|
||||
if (tab === 'mail') return <AdminMailSettings />;
|
||||
return <AdminForumSettings />;
|
||||
};
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ const POST_TRANSITION_PARTS = [
|
||||
['.post-username', 'post-author'],
|
||||
['.post-title', 'post-heading'],
|
||||
['.post-time', 'post-time'],
|
||||
['.post-content, .topic-preview', 'post-body'],
|
||||
['.post-content', 'post-body'],
|
||||
['.post-images', 'post-media'],
|
||||
['.post-pin-state', 'post-pin-state'],
|
||||
['.post-edited-label', 'post-edited-label'],
|
||||
@@ -937,8 +937,8 @@ export default function AppProvider({ children, cachedName = '' }) {
|
||||
return result;
|
||||
}, []);
|
||||
|
||||
const register = useCallback(async (email, password, username, captcha, emailCode = '') => {
|
||||
const result = await API.register(email, password, username, captcha, emailCode);
|
||||
const register = useCallback(async (email, password, username, captcha) => {
|
||||
const result = await API.register(email, password, username, captcha);
|
||||
const loginResult = await API.login(email, password);
|
||||
if (loginResult.user) {
|
||||
setCurrentUser(loginResult.user);
|
||||
|
||||
+16
-84
@@ -17,7 +17,7 @@ function avatar(username) {
|
||||
|
||||
export default function Feed({ onOpenModal, onReport }) {
|
||||
const { currentUser, sort, setSort, openPost, openUser, navigate, refreshKey } = useApp();
|
||||
const { t, i18n } = useTranslation();
|
||||
const { t } = useTranslation();
|
||||
const { toast, confirmAction } = useToast();
|
||||
const [posts, setPosts] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
@@ -26,33 +26,24 @@ export default function Feed({ onOpenModal, onReport }) {
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const [viewerSrc, setViewerSrc] = useState(null);
|
||||
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 postListRef = useRef(null);
|
||||
const sortTimerRef = useRef(null);
|
||||
const pendingSortRef = useRef(null);
|
||||
const initialDrawerOpenedRef = useRef(false);
|
||||
const requestRef = useRef(0);
|
||||
const PAGE_SIZE = 20;
|
||||
|
||||
const load = useCallback(async (targetPage) => {
|
||||
const requestId = ++requestRef.current;
|
||||
setError(null);
|
||||
try {
|
||||
const result = searchQuery
|
||||
? await API.searchPosts(searchQuery, targetPage, PAGE_SIZE)
|
||||
: await API.getPosts(sort, null, targetPage, PAGE_SIZE);
|
||||
if (requestId !== requestRef.current) return;
|
||||
const result = await API.getPosts(sort, null, targetPage, PAGE_SIZE);
|
||||
setPosts(result.data || []);
|
||||
setTotalPages(result.pagination?.totalPages || 1);
|
||||
setPage(result.pagination?.page || 1);
|
||||
} catch (err) {
|
||||
if (requestId !== requestRef.current) return;
|
||||
setError(err.message);
|
||||
setPosts([]);
|
||||
} finally {
|
||||
if (requestId !== requestRef.current) return;
|
||||
if (pendingSortRef.current === sort) {
|
||||
requestAnimationFrame(() => {
|
||||
setDrawerPhase('opening');
|
||||
@@ -71,35 +62,10 @@ export default function Feed({ onOpenModal, onReport }) {
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [sort, searchQuery, refreshKey]);
|
||||
}, [sort, refreshKey]);
|
||||
|
||||
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(底部渐变遮罩提示还有更多内容)
|
||||
useEffect(() => {
|
||||
if (!posts || posts.length === 0 || !postListRef.current) return;
|
||||
@@ -119,13 +85,6 @@ export default function Feed({ onOpenModal, onReport }) {
|
||||
useEffect(() => () => clearTimeout(sortTimerRef.current), []);
|
||||
|
||||
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;
|
||||
|
||||
setSelectedSort(nextSort);
|
||||
@@ -192,31 +151,6 @@ export default function Feed({ onOpenModal, onReport }) {
|
||||
<span className="new-post-launch-label">{t('feed.newPost')}</span>
|
||||
</button>
|
||||
</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-inner">
|
||||
<div id="postList" ref={postListRef}>
|
||||
@@ -225,19 +159,17 @@ export default function Feed({ onOpenModal, onReport }) {
|
||||
) : error ? (
|
||||
<div style={{ textAlign: 'center', color: '#ef4444', padding: '40px 0' }}>{t('feed.loadFailed', { msg: error })}</div>
|
||||
) : posts.length === 0 ? (
|
||||
<div className="search-empty">{searchQuery ? t('feed.searchEmpty', { query: searchQuery }) : t('feed.empty')}</div>
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '60px 0' }}>{t('feed.empty')}</div>
|
||||
) : (
|
||||
posts.map((p) => {
|
||||
const time = p.created_at ? new Date(p.created_at).toLocaleString(i18n.language === 'en' ? 'en-US' : 'zh-CN') : '';
|
||||
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
|
||||
return (
|
||||
<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' }}
|
||||
<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' }}
|
||||
onClick={(e) => openPost(p.post_number || p.id, e.currentTarget, p)}>
|
||||
<div className="topic-main">
|
||||
<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-title">{p.title || t('feed.noTitle')}</div>
|
||||
</div>
|
||||
<div className="post-header topic-meta">
|
||||
{p.is_pinned && (
|
||||
<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="post-header">
|
||||
<img
|
||||
src={p.avatar_url || avatar(p.username)}
|
||||
className="post-avatar"
|
||||
@@ -267,7 +199,8 @@ export default function Feed({ onOpenModal, onReport }) {
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="topic-preview" dangerouslySetInnerHTML={{ __html: renderMarkdown(p.content) }} />
|
||||
<div className="post-title">{p.title || t('feed.noTitle')}</div>
|
||||
<div className="post-content" dangerouslySetInnerHTML={{ __html: renderMarkdown(p.content) }} />
|
||||
{p.images && p.images.length > 0 && (
|
||||
<div className="post-images">
|
||||
{p.images.map((img, i) => (
|
||||
@@ -275,11 +208,10 @@ export default function Feed({ onOpenModal, onReport }) {
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="topic-replies post-replies" aria-label={`${p.reply_count || 0} replies`}>
|
||||
<Icon name="message" size={14} /> {p.reply_count || 0}
|
||||
</div>
|
||||
<div className="post-actions topic-actions">
|
||||
<div className="post-actions">
|
||||
<span>
|
||||
<Icon name="message" size={14} /> {p.reply_count || 0}
|
||||
</span>
|
||||
<button className="action-report" onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (!currentUser) { toast(t('newPost.pleaseLogin'), 'warning'); return; }
|
||||
|
||||
@@ -12,11 +12,6 @@ export function Icon({ name, size = 16, ...rest }) {
|
||||
}
|
||||
|
||||
const PATHS = {
|
||||
search: (
|
||||
<>
|
||||
<circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>
|
||||
</>
|
||||
),
|
||||
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"/>
|
||||
|
||||
+11
-73
@@ -22,12 +22,6 @@ export default function Modals({ modal, onClose, reportPostId }) {
|
||||
const [resetRecoveryCode, setResetRecoveryCode] = useState('');
|
||||
const [resetPassword, setResetPassword] = 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('');
|
||||
@@ -41,12 +35,6 @@ export default function Modals({ modal, onClose, reportPostId }) {
|
||||
|
||||
// 打开注册弹窗时从服务器获取验证码挑战(HMAC 签名)
|
||||
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') {
|
||||
API.getCaptcha().then((c) => setRegCaptcha(c)).catch(() => {});
|
||||
}
|
||||
@@ -56,19 +44,9 @@ export default function Modals({ modal, onClose, reportPostId }) {
|
||||
setResetRecoveryCode('');
|
||||
setResetPassword('');
|
||||
setResetPasswordConfirm('');
|
||||
setResetMethod('recovery');
|
||||
}
|
||||
}, [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;
|
||||
|
||||
const close = (e) => {
|
||||
@@ -105,11 +83,7 @@ export default function Modals({ modal, onClose, reportPostId }) {
|
||||
return;
|
||||
}
|
||||
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');
|
||||
setLoginEmail(resetEmail.trim());
|
||||
setLoginPassword('');
|
||||
@@ -123,23 +97,6 @@ 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 = () => {
|
||||
setAuthMode('login');
|
||||
setResetEmail('');
|
||||
@@ -151,20 +108,18 @@ export default function Modals({ modal, onClose, reportPostId }) {
|
||||
const handleRegister = async () => {
|
||||
if (!regUsername.trim() || !regEmail.trim() || !regPassword) { toast('请填写完整信息', 'warning'); return; }
|
||||
if (regPassword.length < 6) { toast('密码至少6位', 'warning'); return; }
|
||||
if (emailCodeRequired && !regEmailCode.trim()) { toast(t('auth.emailCodeRequired'), 'warning'); return; }
|
||||
if (!regCaptcha || !regCaptchaInput.trim()) {
|
||||
toast('请填写验证码', 'warning');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
// 答案由服务端 HMAC 校验,前端不对比答案
|
||||
await register(regEmail.trim(), regPassword, regUsername.trim(), { id: regCaptcha.id, answer: regCaptchaInput.trim(), sig: regCaptcha.sig }, regEmailCode.trim());
|
||||
await register(regEmail.trim(), regPassword, regUsername.trim(), { id: regCaptcha.id, answer: regCaptchaInput.trim(), sig: regCaptcha.sig });
|
||||
onClose();
|
||||
setRegUsername('');
|
||||
setRegEmail('');
|
||||
setRegPassword('');
|
||||
setRegCaptchaInput('');
|
||||
setRegEmailCode('');
|
||||
toast('注册成功!', 'success');
|
||||
refresh();
|
||||
} catch (err) {
|
||||
@@ -193,11 +148,10 @@ export default function Modals({ modal, onClose, reportPostId }) {
|
||||
<div className="modal-content">
|
||||
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
|
||||
<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="password" placeholder={t('auth.password')} value={loginPassword} onChange={(e) => setLoginPassword(e.target.value)} />
|
||||
<button type="submit" className="btn-primary" style={{ width: '100%' }}>{t('auth.login')}</button>
|
||||
</form>
|
||||
<input type="password" placeholder={t('auth.password')} value={loginPassword} onChange={(e) => setLoginPassword(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter') handleLogin(); }} />
|
||||
<button className="btn-primary" style={{ width: '100%' }} onClick={handleLogin}>{t('auth.login')}</button>
|
||||
<button
|
||||
type="button"
|
||||
className="auth-forgot-link"
|
||||
@@ -216,27 +170,19 @@ export default function Modals({ modal, onClose, reportPostId }) {
|
||||
<div className="modal active" onClick={close}>
|
||||
<div className="modal-content">
|
||||
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
|
||||
<h2 style={{ marginBottom: 16 }}>{t(resetMethod === 'email' ? 'auth.resetEmailTitle' : 'auth.resetTitle')}</h2>
|
||||
{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(); }}>
|
||||
<h2 style={{ marginBottom: 16 }}>{t('auth.resetTitle')}</h2>
|
||||
<p className="auth-reset-hint">{t('auth.resetHint')}</p>
|
||||
<input type="email" placeholder={t('auth.email')} value={resetEmail} onChange={(e) => setResetEmail(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="text" placeholder={t('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.confirmPassword')}
|
||||
value={resetPasswordConfirm}
|
||||
onChange={(e) => setResetPasswordConfirm(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter') handleResetPassword(); }}
|
||||
/>
|
||||
<button type="submit" className="btn-primary" style={{ width: '100%' }}>{t('auth.resetPassword')}</button>
|
||||
</form>
|
||||
<button className="btn-primary" style={{ width: '100%' }} onClick={handleResetPassword}>{t('auth.resetPassword')}</button>
|
||||
<button type="button" className="auth-forgot-link" onClick={returnToLogin}>
|
||||
{t('auth.backToLogin')}
|
||||
</button>
|
||||
@@ -249,15 +195,8 @@ export default function Modals({ modal, onClose, reportPostId }) {
|
||||
<div className="modal-content">
|
||||
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
|
||||
<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="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)} />
|
||||
<div className="captcha-row" style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '12px 0' }}>
|
||||
{regCaptcha ? (
|
||||
@@ -267,8 +206,7 @@ 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)} />
|
||||
</div>
|
||||
<button type="submit" className="btn-primary" style={{ width: '100%' }}>{t('auth.register')}</button>
|
||||
</form>
|
||||
<button className="btn-primary" style={{ width: '100%' }} onClick={handleRegister}>{t('auth.register')}</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -8,7 +8,6 @@ import { Icon } from './Icons';
|
||||
import { useOpenPrivateChat } from './chat/ChatManager';
|
||||
import { renderMarkdown } from '@/lib/markdown';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useToast } from './Toast';
|
||||
|
||||
function avatar(username, size = 128) {
|
||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
||||
@@ -19,9 +18,7 @@ export default function UserProfile({ username, initialUser = null, initialPosts
|
||||
const { currentUser, openPost } = useApp();
|
||||
const { t, i18n } = useTranslation();
|
||||
const openPrivateChat = useOpenPrivateChat();
|
||||
const { toast, confirmAction } = useToast();
|
||||
const [user, setUser] = useState(initialUser);
|
||||
const [blockStatus, setBlockStatus] = useState(null);
|
||||
const [posts, setPosts] = useState(initialPosts || []);
|
||||
const [error, setError] = useState(null);
|
||||
const postsRef = useRef(null);
|
||||
@@ -48,37 +45,6 @@ export default function UserProfile({ username, initialUser = null, initialPosts
|
||||
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(() => {
|
||||
const contents = postsRef.current?.querySelectorAll('.user-post-preview') || [];
|
||||
contents.forEach((element) => {
|
||||
@@ -110,21 +76,14 @@ export default function UserProfile({ username, initialUser = null, initialPosts
|
||||
<div className="user-profile-details">
|
||||
<p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{user.bio || '这个人很懒,什么都没写'}</p>
|
||||
{currentUser && currentUser.username !== user.username && (
|
||||
<div className="user-profile-actions">
|
||||
{!blockStatus?.blocked_by_me && (
|
||||
<button
|
||||
className="btn-primary"
|
||||
style={{ marginTop: 12, padding: '8px 20px' }}
|
||||
onClick={() => openPrivateChat(user.id, user.username)}
|
||||
>
|
||||
<Icon name="message" size={14} /> 发私信
|
||||
</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' }}>
|
||||
<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>
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
'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,7 +6,6 @@ import { API } from '@/lib/api';
|
||||
import { useApp } from '../AppProvider';
|
||||
import { Icon } from '../Icons';
|
||||
import { useToast } from '../Toast';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
function avatar(username) {
|
||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
||||
@@ -16,12 +15,9 @@ function avatar(username) {
|
||||
export default function ChatWindow({ conversationId, otherUserId, otherUsername, onClose, onRefreshList }) {
|
||||
const { currentUser } = useApp();
|
||||
const { toast } = useToast();
|
||||
const { t, i18n } = useTranslation();
|
||||
const [messages, setMessages] = useState(null);
|
||||
const [content, setContent] = useState('');
|
||||
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) => {
|
||||
if (!silent) setMessages(null);
|
||||
@@ -47,15 +43,14 @@ export default function ChatWindow({ conversationId, otherUserId, otherUsername,
|
||||
}, [messages]);
|
||||
|
||||
const send = async () => {
|
||||
if (!content.trim() || waitingForReply) return;
|
||||
if (!content.trim()) return;
|
||||
try {
|
||||
await API.sendMessage(conversationId, content.trim());
|
||||
setContent('');
|
||||
load();
|
||||
onRefreshList();
|
||||
} catch (err) {
|
||||
toast(err.status === 429 ? t('chat.limitReached') : err.message, 'error');
|
||||
if (err.status === 429) load(true);
|
||||
toast('发送失败:' + err.message, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -74,7 +69,7 @@ export default function ChatWindow({ conversationId, otherUserId, otherUsername,
|
||||
) : (
|
||||
messages.map((m) => {
|
||||
const isMine = m.sender_id === currentUser?.id;
|
||||
const time = m.created_at ? new Date(m.created_at).toLocaleString(i18n.language === 'en' ? 'en-US' : 'zh-CN') : '';
|
||||
const time = m.created_at ? new Date(m.created_at).toLocaleString('zh-CN') : '';
|
||||
return (
|
||||
<div key={m.id} style={{ display: 'flex', justifyContent: isMine ? 'flex-end' : 'flex-start', marginBottom: 12 }}>
|
||||
{!isMine && (
|
||||
@@ -99,7 +94,6 @@ export default function ChatWindow({ conversationId, otherUserId, otherUsername,
|
||||
})
|
||||
)}
|
||||
</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 }}>
|
||||
<input
|
||||
type="text"
|
||||
@@ -107,11 +101,10 @@ export default function ChatWindow({ conversationId, otherUserId, otherUsername,
|
||||
placeholder="输入消息..."
|
||||
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}
|
||||
disabled={waitingForReply}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter') send(); }}
|
||||
/>
|
||||
<button className="btn-primary" style={{ padding: '8px 16px' }} disabled={waitingForReply} onClick={send}>发送</button>
|
||||
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={send}>发送</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -4,8 +4,6 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { Icon } from '../Icons';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useToast } from '../Toast';
|
||||
|
||||
function avatar(username) {
|
||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
||||
@@ -13,12 +11,7 @@ function avatar(username) {
|
||||
}
|
||||
|
||||
export default function ConversationList({ onOpenChat, onClose }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { toast } = useToast();
|
||||
const [conversations, setConversations] = useState(null);
|
||||
const [search, setSearch] = useState('');
|
||||
const [matches, setMatches] = useState([]);
|
||||
const [searching, setSearching] = useState(false);
|
||||
|
||||
const load = () => {
|
||||
API.getConversations()
|
||||
@@ -28,67 +21,23 @@ export default function ConversationList({ onOpenChat, onClose }) {
|
||||
|
||||
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 (
|
||||
<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 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 }} /> {t('chat.title')}</h2>
|
||||
<h2 style={{ fontSize: 18, margin: 0 }}><Icon name="message" size={18} style={{ verticalAlign: -3, marginRight: 6 }} /> 私信</h2>
|
||||
<span className="close" onClick={onClose} style={{ cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}><Icon name="close" size={20} /></span>
|
||||
</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 }}>
|
||||
{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 ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />{t('chat.loading')}</div>
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />加载中...</div>
|
||||
) : conversations.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>{t('chat.empty')}</div>
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>暂无私信</div>
|
||||
) : (
|
||||
conversations.map((c) => {
|
||||
const unread = c.unread_count || 0;
|
||||
const lastMsg = c.last_message || t('chat.noMessage');
|
||||
const time = c.last_message_time ? new Date(c.last_message_time).toLocaleString(i18n.language === 'en' ? 'en-US' : 'zh-CN') : '';
|
||||
const lastMsg = c.last_message || '暂无消息';
|
||||
const time = c.last_message_time ? new Date(c.last_message_time).toLocaleString('zh-CN') : '';
|
||||
return (
|
||||
<div
|
||||
key={c.id}
|
||||
@@ -113,8 +62,6 @@ export default function ConversationList({ onOpenChat, onClose }) {
|
||||
);
|
||||
})
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+2
-32
@@ -45,21 +45,12 @@ export const API = {
|
||||
getCaptcha() {
|
||||
return apiFetch('/captcha');
|
||||
},
|
||||
register(email, password, username, captcha, emailCode = '') {
|
||||
register(email, password, username, captcha) {
|
||||
return apiFetch('/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email, password, username, email_code: emailCode, captcha_id: captcha?.id, captcha_answer: captcha?.answer, captcha_sig: captcha?.sig }),
|
||||
body: JSON.stringify({ email, password, username, 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); },
|
||||
getMe() { return apiFetch('/auth/me'); },
|
||||
|
||||
@@ -69,9 +60,6 @@ export const API = {
|
||||
if (userId) q += '&user_id=' + userId;
|
||||
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); },
|
||||
createPost(title, content, images, captcha) {
|
||||
return apiFetch('/posts', {
|
||||
@@ -108,13 +96,6 @@ export const API = {
|
||||
getUsers() { return apiFetch('/users'); },
|
||||
getUsersByUsername(username) { return apiFetch('/users?username=' + 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) {
|
||||
return apiFetch('/users/' + userId + '/role', { method: 'PUT', body: JSON.stringify({ role }) });
|
||||
},
|
||||
@@ -146,17 +127,6 @@ export const API = {
|
||||
updateSettings(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) {
|
||||
const fd = new FormData();
|
||||
fd.append('file', file);
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
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';
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
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 || '邮件发送失败';
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
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,9 +16,6 @@
|
||||
"latest": "Latest posts",
|
||||
"hot": "Latest replies",
|
||||
"newPost": "New post",
|
||||
"searchPlaceholder": "Search post titles or content...",
|
||||
"clearSearch": "Clear search",
|
||||
"searchEmpty": "No posts found for “{{query}}”",
|
||||
"loading": "Loading...",
|
||||
"loadFailed": "Load failed: {{msg}}",
|
||||
"empty": "No posts yet — be the first to publish!",
|
||||
@@ -31,28 +28,6 @@
|
||||
"noTitle": "Untitled",
|
||||
"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": {
|
||||
"title": "Post detail",
|
||||
"back": "← Back",
|
||||
@@ -109,16 +84,6 @@
|
||||
"forgotPassword": "Forgot password?",
|
||||
"resetTitle": "Reset password with a recovery code",
|
||||
"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",
|
||||
"newPassword": "New password (min 6 characters)",
|
||||
"confirmPassword": "Confirm new password",
|
||||
@@ -222,33 +187,6 @@
|
||||
"logs": "Event logs",
|
||||
"links": "Links",
|
||||
"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",
|
||||
"customCss": "Custom CSS",
|
||||
"common": {
|
||||
|
||||
@@ -16,9 +16,6 @@
|
||||
"latest": "最新发布",
|
||||
"hot": "最新回复",
|
||||
"newPost": "发布新帖",
|
||||
"searchPlaceholder": "搜索帖子标题或内容...",
|
||||
"clearSearch": "清除搜索",
|
||||
"searchEmpty": "没有找到与「{{query}}」相关的帖子",
|
||||
"loading": "加载中...",
|
||||
"loadFailed": "加载失败:{{msg}}",
|
||||
"empty": "还没有帖子,快来发布第一条吧!",
|
||||
@@ -31,28 +28,6 @@
|
||||
"noTitle": "无标题",
|
||||
"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": {
|
||||
"title": "帖子详情",
|
||||
"back": "← 返回",
|
||||
@@ -109,16 +84,6 @@
|
||||
"forgotPassword": "忘记密码?",
|
||||
"resetTitle": "通过恢复码重置密码",
|
||||
"resetHint": "输入邮箱和设置中生成的恢复码,即可设置新密码。",
|
||||
"resetEmailTitle": "通过邮箱重置密码",
|
||||
"resetEmailHint": "输入邮箱,获取邮件验证码后设置新密码。",
|
||||
"recoveryMethod": "恢复码",
|
||||
"emailMethod": "邮箱验证码",
|
||||
"emailCode": "邮箱验证码",
|
||||
"sendCode": "获取验证码",
|
||||
"emailRequired": "请先填写邮箱",
|
||||
"emailCodeRequired": "请输入邮箱验证码",
|
||||
"emailCodeSent": "验证码已发送,请查收邮件",
|
||||
"emailCodeFailed": "验证码发送失败:{{msg}}",
|
||||
"recoveryCode": "恢复码",
|
||||
"newPassword": "新密码(至少6位)",
|
||||
"confirmPassword": "确认新密码",
|
||||
@@ -222,33 +187,6 @@
|
||||
"logs": "事件日志",
|
||||
"links": "友情链接",
|
||||
"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": "自定义页面",
|
||||
"customCss": "自定义 CSS",
|
||||
"common": {
|
||||
|
||||
Generated
-10
@@ -14,7 +14,6 @@
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"marked": "^18.0.9",
|
||||
"next": "16",
|
||||
"nodemailer": "^7.0.13",
|
||||
"pg": "^8.11.3",
|
||||
"react": "19",
|
||||
"react-dom": "19",
|
||||
@@ -7317,15 +7316,6 @@
|
||||
"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": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmmirror.com/npm-run-path/-/npm-run-path-4.0.1.tgz",
|
||||
|
||||
@@ -20,7 +20,6 @@
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"marked": "^18.0.9",
|
||||
"next": "16",
|
||||
"nodemailer": "^7.0.13",
|
||||
"pg": "^8.11.3",
|
||||
"react": "19",
|
||||
"react-dom": "19",
|
||||
|
||||
-45
@@ -277,48 +277,3 @@ 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 TABLE posts ALTER COLUMN post_number SET NOT NULL;
|
||||
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