Files
arcticnewone/server/utils/db.ts
T
virtheart 5a7ad8de11 feat: 全面升级——后台优化 / 动态配置 / 个人中心 / OSS 存储
- OSS 文件存储(RustFS / S3 v4 兼容,零依赖手写 SigV4):
  上传/列表/删除走桶 arcticnewone,/uploads 代理服务 + 本地回退;
  server/utils/sigv4.ts 纯函数 + AWS 测试向量验证
- 业务动态配置:settings 表 + /api/settings(公开) + /api/admin/settings(PATCH),
  useSiteSettings 组合式,footer/contact/tools/app.vue/侧边栏/工具页全部接入,
  后台 /admin/settings 修改前台即时生效(站点/联系/社交/工具箱/页脚/SEO)
- 后台全面优化:Admin* 设计系统(按钮/输入/表单/卡片/徽标/弹窗/确认/空态/骨架/
  分页/页头/Toast)14 组件;Dashboard 增强;各列表页搜索/筛选/批量删除/分页;
  布局与侧边栏分组;统一 toast/确认反馈
- 个人中心全新重设计:顶部资料卡 + 统计、精致化改密/删号(二次确认)、
  收藏封面网格、评论卡片、移动端适配
- deploy.sh 支持 OSS 凭据注入(NUXT_OSS_*);.env.example 更新
- 测试 17 例全过(含 SigV4 AWS 向量、settings 默认结构)
2026-08-06 18:40:17 +08:00

255 lines
9.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Database from 'better-sqlite3'
import { mkdirSync } from 'node:fs'
import { dirname } from 'node:path'
import { scryptSync, randomBytes } from 'node:crypto'
import { getConfig } from './config'
import { articlesSeed, worksSeed } from './seed'
/** 文章正文内容块 */
export interface ArticleBlock {
type: 'paragraph' | 'heading' | 'quote' | 'image'
text: string
}
/**
* SQLite 数据层单例。
*
* - 数据库文件路径来自 getConfig().dbPath(生产挂载 /data 下的 PVC,开发在 .data/)
* - 惰性初始化 + 幂等建表(CREATE TABLE IF NOT EXISTS),首次使用自动创建
* - WAL 模式提升并发读写可靠性;外键开启
*
* 表结构:
* users 用户(注册/登录)
* sessions 会话(httpOnly Cookie token)
* contacts 联系表单留言
* subscribers 邮箱订阅
* favorites 作品收藏
* comments 新闻评论
*/
let _db: Database.Database | null = null
export function getDb(): Database.Database {
if (_db) return _db
const { dbPath } = getConfig()
mkdirSync(dirname(dbPath), { recursive: true })
_db = new Database(dbPath)
_db.pragma('journal_mode = WAL')
_db.pragma('foreign_keys = ON')
migrate(_db)
seedIfEmpty(_db)
return _db
}
function migrate(db: Database.Database): void {
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL UNIQUE,
phone TEXT,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
expires_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);
CREATE TABLE IF NOT EXISTS contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL,
subject TEXT NOT NULL,
message TEXT NOT NULL,
delivered INTEGER NOT NULL DEFAULT 0,
read INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS subscribers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE,
token TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS favorites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
work_slug TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
UNIQUE (user_id, work_slug)
);
CREATE INDEX IF NOT EXISTS idx_favorites_user ON favorites(user_id);
CREATE TABLE IF NOT EXISTS comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
news_slug TEXT NOT NULL,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
content TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_comments_news ON comments(news_slug);
-- 内容管理系统:动态(articles)与作品(works)
CREATE TABLE IF NOT EXISTS articles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
slug TEXT NOT NULL UNIQUE,
category TEXT NOT NULL,
title_zh TEXT NOT NULL,
title_en TEXT NOT NULL,
excerpt_zh TEXT NOT NULL,
excerpt_en TEXT NOT NULL,
content_zh TEXT NOT NULL DEFAULT '[]',
content_en TEXT NOT NULL DEFAULT '[]',
image TEXT,
date TEXT,
read_time INTEGER NOT NULL DEFAULT 5,
author TEXT NOT NULL DEFAULT 'ArcticNewOne',
published INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_articles_category ON articles(category);
CREATE INDEX IF NOT EXISTS idx_articles_published ON articles(published);
CREATE TABLE IF NOT EXISTS works (
id INTEGER PRIMARY KEY AUTOINCREMENT,
slug TEXT NOT NULL UNIQUE,
category TEXT NOT NULL,
title_zh TEXT NOT NULL,
title_en TEXT NOT NULL,
description_zh TEXT NOT NULL,
description_en TEXT NOT NULL,
overview_zh TEXT NOT NULL DEFAULT '',
overview_en TEXT NOT NULL DEFAULT '',
challenge_zh TEXT NOT NULL DEFAULT '',
challenge_en TEXT NOT NULL DEFAULT '',
solution_zh TEXT NOT NULL DEFAULT '',
solution_en TEXT NOT NULL DEFAULT '',
client_zh TEXT NOT NULL DEFAULT '',
client_en TEXT NOT NULL DEFAULT '',
duration_zh TEXT NOT NULL DEFAULT '',
duration_en TEXT NOT NULL DEFAULT '',
year TEXT NOT NULL DEFAULT '',
tags TEXT NOT NULL DEFAULT '[]',
image TEXT,
gallery TEXT NOT NULL DEFAULT '[]',
url TEXT,
published INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_works_category ON works(category);
CREATE INDEX IF NOT EXISTS idx_works_published ON works(published);
-- 后台操作审计日志
CREATE TABLE IF NOT EXISTS audit_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
actor_id INTEGER,
actor_name TEXT,
action TEXT NOT NULL,
target TEXT NOT NULL,
detail TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_audit_created ON audit_logs(created_at);
-- 业务动态配置(后台可改;value 为 JSON 字符串)
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
`)
// 老库迁移:为已存在的表补充新增列(SQLite 不支持 ADD COLUMN IF NOT EXISTS)
ensureColumn(db, 'contacts', 'read', 'INTEGER NOT NULL DEFAULT 0')
ensureColumn(db, 'subscribers', 'token', 'TEXT')
}
/** 若表中缺少某列则补上(用于老库升级) */
function ensureColumn(db: Database.Database, table: string, column: string, ddl: string): void {
const cols = db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>
if (!cols.some((c) => c.name === column)) {
db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${ddl}`)
}
}
/**
* 初始化种子数据:内容表为空时灌入 articles/works 种子;
* users 为空且配置了 adminInitialPassword 时创建预置管理员。
*/
function seedIfEmpty(db: Database.Database): void {
const { adminInitialPassword, adminEmails } = getConfig()
const articleCount = (db.prepare('SELECT COUNT(*) AS c FROM articles').get() as { c: number }).c
if (articleCount === 0) {
const insert = db.prepare(
`INSERT INTO articles
(slug, category, title_zh, title_en, excerpt_zh, excerpt_en, content_zh, content_en, image, date, read_time, author, published)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
const tx = db.transaction(() => {
for (const a of articlesSeed) {
insert.run(a.slug, a.category, a.titleZh, a.titleEn, a.excerptZh, a.excerptEn,
JSON.stringify(a.contentZh), JSON.stringify(a.contentEn), a.image, a.date, a.readTime, a.author, a.published)
}
})
tx()
}
const workCount = (db.prepare('SELECT COUNT(*) AS c FROM works').get() as { c: number }).c
if (workCount === 0) {
const insert = db.prepare(
`INSERT INTO works
(slug, category, title_zh, title_en, description_zh, description_en,
overview_zh, overview_en, challenge_zh, challenge_en, solution_zh, solution_en,
client_zh, client_en, duration_zh, duration_en, year, tags, image, gallery, url, published)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
const tx = db.transaction(() => {
for (const w of worksSeed) {
insert.run(w.slug, w.category, w.titleZh, w.titleEn, w.descriptionZh, w.descriptionEn,
w.overviewZh, w.overviewEn, w.challengeZh, w.challengeEn, w.solutionZh, w.solutionEn,
w.clientZh, w.clientEn, w.durationZh, w.durationEn, w.year,
JSON.stringify(w.tags), w.image, JSON.stringify(w.gallery), w.url, w.published)
}
})
tx()
}
// 预置管理员(仅当首次初始化且配置了初始密码)
const userCount = (db.prepare('SELECT COUNT(*) AS c FROM users').get() as { c: number }).c
if (userCount === 0 && adminInitialPassword && adminEmails.length > 0) {
const email = adminEmails[0]
const username = 'admin'
// 与 auth.ts 相同的 salt:hash 存储格式(scrypt)
const salt = randomBytes(16).toString('hex')
const hash = scryptSync(adminInitialPassword, salt, 64).toString('hex')
db.prepare('INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)')
.run(username, email, `${salt}:${hash}`, 'admin')
console.log('[seed] 已创建预置管理员账号: admin(邮箱 ' + email + ')')
}
}
/** 供服务端任意位置安全关闭数据库(测试/热更新用) */
export function closeDb(): void {
if (_db) {
_db.close()
_db = null
}
}