feat: follow lite forum updates

This commit is contained in:
lezi-fun committed 2026-10-01 14:10:12 +08:00
1 parent f59739e36f
commit b42944b687
38 files changed
+1433 -71

No files matched your search

+32 -2
View File
@@ -45,12 +45,21 @@ export const API = {
getCaptcha() {
return apiFetch('/captcha');
},
register(email, password, username, captcha) {
register(email, password, username, captcha, emailCode = '') {
return apiFetch('/auth/register', {
method: 'POST',
body: JSON.stringify({ email, password, username, captcha_id: captcha?.id, captcha_answer: captcha?.answer, captcha_sig: captcha?.sig }),
body: JSON.stringify({ email, password, username, email_code: emailCode, captcha_id: captcha?.id, captcha_answer: captcha?.answer, captcha_sig: captcha?.sig }),
});
},
sendRegisterCode(email) {
return apiFetch('/auth/send-code', { method: 'POST', body: JSON.stringify({ email }) });
},
sendResetCode(email) {
return apiFetch('/auth/forgot-password', { method: 'POST', body: JSON.stringify({ email }) });
},
resetPasswordByEmail(email, code, newPassword) {
return apiFetch('/auth/reset-password-by-email', { method: 'POST', body: JSON.stringify({ email, code, newPassword }) });
},
logout() { setToken(null); },
getMe() { return apiFetch('/auth/me'); },
@@ -60,6 +69,9 @@ 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', {
@@ -96,6 +108,13 @@ 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 }) });
},
@@ -127,6 +146,17 @@ 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);
+108
View File
@@ -0,0 +1,108 @@
import { createHash, randomInt, timingSafeEqual } from 'node:crypto';
import pool from './db';
let schemaPromise;
export function ensureEmailVerificationSchema() {
if (!schemaPromise) {
schemaPromise = pool.query(`
CREATE TABLE IF NOT EXISTS email_verifications (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email VARCHAR(255) NOT NULL,
code_hash VARCHAR(64) NOT NULL,
purpose VARCHAR(20) NOT NULL DEFAULT 'register',
attempts INTEGER NOT NULL DEFAULT 0,
consumed_at TIMESTAMPTZ,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
`).then(async () => {
await pool.query(`CREATE UNIQUE INDEX IF NOT EXISTS idx_email_verifications_active
ON email_verifications (LOWER(email), purpose) WHERE consumed_at IS NULL`);
await pool.query(`CREATE INDEX IF NOT EXISTS idx_email_verifications_expires
ON email_verifications (expires_at)`);
await pool.query('ALTER TABLE users ADD COLUMN IF NOT EXISTS email_verified BOOLEAN NOT NULL DEFAULT true');
}).catch((error) => { schemaPromise = null; throw error; });
}
return schemaPromise;
}
export function normalizeEmail(value) {
const email = typeof value === 'string' ? value.trim().toLowerCase() : '';
return email.length <= 255 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) ? email : null;
}
function hashCode(code) {
return createHash('sha256').update(code).digest('hex');
}
export async function saveEmailCode(email, purpose) {
await ensureEmailVerificationSchema();
const code = String(randomInt(0, 1000000)).padStart(6, '0');
const result = await pool.query(`
INSERT INTO email_verifications (email, code_hash, purpose, expires_at)
VALUES ($1, $2, $3, now() + interval '10 minutes')
ON CONFLICT (LOWER(email), purpose) WHERE consumed_at IS NULL
DO UPDATE SET code_hash = EXCLUDED.code_hash, expires_at = EXCLUDED.expires_at,
attempts = 0, created_at = now()
WHERE email_verifications.created_at < now() - interval '60 seconds'
RETURNING id
`, [email, hashCode(code), purpose]);
return result.rowCount ? code : null;
}
export async function invalidateEmailCode(email, purpose) {
await pool.query(`UPDATE email_verifications SET consumed_at = now()
WHERE LOWER(email) = $1 AND purpose = $2 AND consumed_at IS NULL`, [email, purpose]);
}
export const CODE_ERRORS = {
missing: '请先获取验证码',
expired: '验证码已过期,请重新获取',
too_many: '尝试次数过多,请重新获取验证码',
mismatch: '验证码错误',
};
// 验证码和最终账号修改在同一事务中提交,失败时验证码不会被消费。
export async function withEmailCode(email, purpose, code, action) {
await ensureEmailVerificationSchema();
const client = await pool.connect();
try {
await client.query('BEGIN');
const result = await client.query(`
SELECT id, code_hash, attempts, expires_at FROM email_verifications
WHERE LOWER(email) = $1 AND purpose = $2 AND consumed_at IS NULL
ORDER BY created_at DESC LIMIT 1 FOR UPDATE
`, [email, purpose]);
const row = result.rows[0];
let failure = null;
if (!row) failure = 'missing';
else if (new Date(row.expires_at).getTime() <= Date.now()) failure = 'expired';
else if (row.attempts >= 5) failure = 'too_many';
else {
const provided = Buffer.from(hashCode(String(code)));
const expected = Buffer.from(row.code_hash);
if (provided.length !== expected.length || !timingSafeEqual(provided, expected)) failure = 'mismatch';
}
if (failure) {
if (row && failure === 'mismatch') {
await client.query('UPDATE email_verifications SET attempts = attempts + 1 WHERE id = $1', [row.id]);
}
await client.query('COMMIT');
return { failure };
}
const value = await action(client);
await client.query('UPDATE email_verifications SET consumed_at = now() WHERE id = $1', [row.id]);
await client.query('COMMIT');
return { value };
} catch (error) {
await client.query('ROLLBACK').catch(() => {});
throw error;
} finally {
client.release();
}
}
export async function isEmailVerificationRequired() {
const result = await pool.query("SELECT value FROM settings WHERE key = 'email_verify_required'");
return result.rows[0]?.value === 'true';
}
+63
View File
@@ -0,0 +1,63 @@
import nodemailer from 'nodemailer';
import pool from './db';
const KEYS = [
'smtp_enabled', 'smtp_host', 'smtp_port', 'smtp_secure', 'smtp_user',
'smtp_password', 'smtp_from_name', 'smtp_from_email', 'smtp_allow_self_signed',
];
export async function loadSmtpConfig() {
const result = await pool.query('SELECT key, value FROM settings WHERE key = ANY($1::text[])', [KEYS]);
const raw = Object.fromEntries(result.rows.map(({ key, value }) => [key, value]));
return {
enabled: raw.smtp_enabled === 'true',
host: raw.smtp_host || '',
port: Number(raw.smtp_port || 587),
secure: raw.smtp_secure === 'true',
user: raw.smtp_user || '',
password: raw.smtp_password || '',
fromName: raw.smtp_from_name || '',
fromEmail: raw.smtp_from_email || '',
allowSelfSigned: raw.smtp_allow_self_signed === 'true',
};
}
export function isConfigComplete(config) {
return Boolean(config.enabled && config.host && config.port >= 1 && config.port <= 65535 &&
config.fromEmail && (!config.user || config.password));
}
export async function sendMail(config, { to, subject, text }) {
if (!isConfigComplete(config)) throw new Error('站点尚未配置邮件服务,请联系管理员');
const transport = nodemailer.createTransport({
host: config.host,
port: config.port,
secure: config.secure,
requireTLS: !config.secure,
tls: { rejectUnauthorized: !config.allowSelfSigned },
...(config.user ? { auth: { user: config.user, pass: config.password } } : {}),
connectionTimeout: 10000,
greetingTimeout: 10000,
socketTimeout: 20000,
});
try {
return await transport.sendMail({
from: config.fromName
? `"${config.fromName.replace(/["\r\n]/g, '')}" <${config.fromEmail}>`
: config.fromEmail,
to,
subject,
text,
});
} finally {
transport.close();
}
}
export function describeSmtpError(error) {
if (error?.code === 'EAUTH') return '认证失败,请检查 SMTP 用户名、授权码或 API Key';
if (error?.code === 'ETIMEDOUT') return '连接超时,请检查 SMTP 地址、端口及防火墙';
if (error?.code === 'ESOCKET') return '连接失败,请检查端口与 TLS 设置';
if (/self.signed certificate/i.test(error?.message || '')) return '证书校验失败;自建邮件服务器可在后台允许自签证书';
return error?.message || '邮件发送失败';
}
+36
View File
@@ -0,0 +1,36 @@
import pool from './db';
let schemaPromise;
export function ensureUserBlocksSchema() {
if (!schemaPromise) {
schemaPromise = pool.query(`
CREATE TABLE IF NOT EXISTS user_blocks (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
blocker_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
blocked_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (blocker_id, blocked_id),
CHECK (blocker_id <> blocked_id)
)
`).then(async () => {
await pool.query('CREATE INDEX IF NOT EXISTS idx_user_blocks_blocker ON user_blocks(blocker_id)');
await pool.query('CREATE INDEX IF NOT EXISTS idx_user_blocks_blocked ON user_blocks(blocked_id)');
}).catch((error) => {
schemaPromise = null;
throw error;
});
}
return schemaPromise;
}
export const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export async function hasBlocked(blockerId, blockedId, client = pool) {
await ensureUserBlocksSchema();
const result = await client.query(
'SELECT EXISTS(SELECT 1 FROM user_blocks WHERE blocker_id = $1 AND blocked_id = $2) AS blocked',
[blockerId, blockedId]
);
return result.rows[0].blocked;
}