feat(auth): 用户登录+云端豆仓——JWT认证+库存同步+三语言

后端:
  - schema/users + bead_inventories 表(SQLite+PG 双DDL)
  - auth 模块:注册/登录/me(bcrypt+JWT,双SQL实现)
  - beads 模块:云端库存CRUD(增/查/扣/补/清,requireAuth 保护)
  - 188 测试全过(含新增 auth 17 + beads 12)

前端:
  - auth.ts + useAuth hook + AuthModal 登录/注册弹窗
  - bead-api.ts 云端桥接 + useBeadInventory 云感知改造
  - MyBeadsPage/App 登录态 + 云端同步
  - 三语言 auth 文案(zh-CN/en/zh-TW)
  - 220 测试全过 + typecheck 0 错误 + build 成功
This commit is contained in:
Sisyphus committed 2026-08-21 22:24:35 +08:00
1 parent 33e7b38271
commit 3bb67ebf30
25 files changed
+2069 -14

No files matched your search

+50
View File
@@ -0,0 +1,50 @@
/**
* JWT 工具 —— 签发与校验用户令牌。
*
* HS256 + 对称密钥:密钥来自 JWT_SECRET 环境变量(生产必须设置),
* 缺省回退到开发默认值并打印警告(避免本地启动失败)。
*/
import jwt from "jsonwebtoken";
/** 开发默认密钥(仅本地/测试使用,生产必须用 JWT_SECRET 覆盖)。 */
const DEV_SECRET = "perler-lab-dev-secret-do-not-use-in-prod";
function resolveSecret(): string {
const secret = process.env["JWT_SECRET"];
if (!secret || secret === "") {
if (process.env["NODE_ENV"] !== "test") {
console.warn(
"[auth] JWT_SECRET 未设置,使用开发默认密钥 —— 生产环境必须通过环境变量配置!",
);
}
return DEV_SECRET;
}
return secret;
}
const SECRET = resolveSecret();
/** JWT 载荷(sub = 用户 ID)。 */
export interface JwtPayload {
sub: string;
phone: string;
}
/** 签发访问令牌(默认 30 天,供移动端持续登录)。 */
export function signToken(payload: JwtPayload): string {
return jwt.sign(payload, SECRET, { expiresIn: "30d" });
}
/** 校验令牌:成功返回载荷,失败返回 undefined。 */
export function verifyToken(token: string): JwtPayload | undefined {
try {
const decoded = jwt.verify(token, SECRET);
if (typeof decoded !== "object" || decoded === null) return undefined;
const d = decoded as Record<string, unknown>;
if (typeof d["sub"] !== "string" || typeof d["phone"] !== "string") return undefined;
return { sub: d["sub"], phone: d["phone"] };
} catch {
return undefined;
}
}
+49
View File
@@ -0,0 +1,49 @@
/**
* 认证中间件 —— 从 Authorization: Bearer <token> 解析用户。
*
* 用例:
* router.use(requireAuth); // 整组路由需要登录
* router.get("/x", requireAuth, handler); // 单路由需要登录
*
* 成功:挂 req.userId / req.userPhone,进入下一个中间件。
* 失败:401 { error: "请先登录" },不进入后续处理。
*/
import type { NextFunction, Request, RequestHandler, Response } from "express";
import { verifyToken } from "./jwt.js";
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Express {
interface Request {
userId?: string;
userPhone?: string;
}
}
}
export const AUTH_REQUIRED_MESSAGE = "请先登录";
/**
* 要求登录的中间件工厂。挂载到需要用户上下文的路由上。
*/
export function requireAuth(req: Request, res: Response, next: NextFunction): void {
const header = req.headers.authorization;
if (typeof header !== "string" || !header.startsWith("Bearer ")) {
res.status(401).json({ error: AUTH_REQUIRED_MESSAGE });
return;
}
const token = header.slice("Bearer ".length).trim();
const payload = verifyToken(token);
if (payload === undefined) {
res.status(401).json({ error: AUTH_REQUIRED_MESSAGE });
return;
}
req.userId = payload.sub;
req.userPhone = payload.phone;
next();
}
/** 短路用;路由测试可直接引用该中间件类型。 */
export type { RequestHandler };
export const requireAuthHandler: RequestHandler = requireAuth;
+113
View File
@@ -0,0 +1,113 @@
/**
* 认证路由 —— 注册 / 登录 / 当前用户。
*
* POST /api/auth/register { phone, password, nickname? } → 201 { token, user }
* POST /api/auth/login { phone, password } → 200 { token, user }
* GET /api/auth/me (Bearer) → 200 { user }
*/
import { Router } from "express";
import type { Request, Response } from "express";
import type { Db } from "../db/index.js";
import { getDb } from "../db/index.js";
import { AuthError, AUTH_ERRORS, findUserById, loginUser, registerUser } from "./service.js";
import { signToken } from "./jwt.js";
import { requireAuth } from "./middleware.js";
import { createRateLimiter } from "../security/rate-limit.js";
/** 解析 DB:测试注入优先,否则回退全局单例。 */
function resolveDb(injected?: Db): Db {
return injected ?? getDb();
}
/** 把 AuthError 格式化为 Express 响应。 */
function handleAuthError(res: Response, err: AuthError): void {
res.status(err.status).json({ error: err.message });
}
/** 解析手机号/密码请求体(非法时抛 400)。 */
function parseCredentials(body: unknown): { phone: string; password: string } {
const b = (body ?? {}) as { phone?: unknown; password?: unknown };
const phone = typeof b.phone === "string" ? b.phone.trim() : "";
const password = typeof b.password === "string" ? b.password : "";
if (phone === "" || password === "") {
throw new AuthError("请输入手机号和密码", 400, "MISSING_CREDENTIALS");
}
return { phone, password };
}
/**
* 创建认证路由。可注入 DB 便于测试。
*/
export function createAuthRouter(injectedDb?: Db): Router {
const router = Router();
// 防刷限流:注册 5/lh、登录 10/lh(按 IP)
const registerLimiter = createRateLimiter({ windowMs: 60 * 60 * 1000, max: 5 })("auth-register");
const loginLimiter = createRateLimiter({ windowMs: 60 * 60 * 1000, max: 10 })("auth-login");
/** POST /api/auth/register */
router.post("/register", registerLimiter, async (req: Request, res: Response): Promise<void> => {
try {
const { phone, password } = parseCredentials(req.body);
const b = (req.body ?? {}) as { nickname?: unknown };
const nickname =
typeof b.nickname === "string" && b.nickname.trim() !== "" ? b.nickname.trim() : null;
const db = resolveDb(injectedDb);
const user = await registerUser(db, phone, password);
const token = signToken({ sub: user.id, phone: user.phone });
res.status(201).json({ token, user: { ...user, nickname: user.nickname ?? nickname } });
} catch (err) {
if (err instanceof AuthError) {
handleAuthError(res, err);
} else {
console.error("POST /api/auth/register error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
}
});
/** POST /api/auth/login */
router.post("/login", loginLimiter, async (req: Request, res: Response): Promise<void> => {
try {
const { phone, password } = parseCredentials(req.body);
const db = resolveDb(injectedDb);
const user = await loginUser(db, phone, password);
const token = signToken({ sub: user.id, phone: user.phone });
res.status(200).json({ token, user });
} catch (err) {
if (err instanceof AuthError) {
handleAuthError(res, err);
} else {
console.error("POST /api/auth/login error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
}
});
/** GET /api/auth/me */
router.get("/me", requireAuth, async (req: Request, res: Response): Promise<void> => {
try {
const db = resolveDb(injectedDb);
const row = await findUserById(db, req.userId!);
if (!row) throw AUTH_ERRORS.NOT_FOUND;
res.status(200).json({
user: {
id: row.id,
phone: row.phone,
nickname: row.nickname,
createdAt: row.created_at,
},
});
} catch (err) {
if (err instanceof AuthError) {
handleAuthError(res, err);
} else {
console.error("GET /api/auth/me error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
}
});
return router;
}
+66
View File
@@ -0,0 +1,66 @@
/**
* 用户认证 service —— PostgreSQL 异步实现(生产)。
* 与同步的 SQLite 实现(service.ts 内部)一一对应。
*/
import bcrypt from "bcryptjs";
import type { PgDb } from "../db/index.js";
import {
AUTH_ERRORS,
genUserId,
isValidPassword,
isValidPhone,
SALT_ROUNDS,
toPublicUser,
type PublicUser,
type UserRow,
} from "./service.js";
/** 按手机号查用户(不存在返回 undefined)。 */
export async function findUserByPhonePg(db: PgDb, phone: string): Promise<UserRow | undefined> {
const { rows } = await db.query<UserRow>("SELECT * FROM users WHERE phone = $1", [
phone.trim(),
]);
return rows[0] as UserRow | undefined;
}
/** 按 ID 查用户(不存在返回 undefined)。 */
export async function findUserByIdPg(db: PgDb, id: string): Promise<UserRow | undefined> {
const { rows } = await db.query<UserRow>("SELECT * FROM users WHERE id = $1", [id]);
return rows[0] as UserRow | undefined;
}
/** 注册用户;已存在手机号时抛 PHONE_TAKEN。 */
export async function registerPg(
db: PgDb,
phoneInput: string,
rawPassword: string,
): Promise<PublicUser> {
const phone = phoneInput.trim();
if (!isValidPhone(phone)) throw AUTH_ERRORS.PHONE_INVALID;
if (!isValidPassword(rawPassword)) throw AUTH_ERRORS.PASSWORD_WEAK;
const existing = await findUserByPhonePg(db, phone);
if (existing) throw AUTH_ERRORS.PHONE_TAKEN;
const id = genUserId();
const hash = await bcrypt.hash(rawPassword, SALT_ROUNDS);
await db.query(
"INSERT INTO users (id, phone, password_hash) VALUES ($1, $2, $3)",
[id, phone, hash],
);
const row = await findUserByIdPg(db, id);
return toPublicUser(row!);
}
/** 登录校验;手机号或密码错误一律抛 WRONG_PASSWORD(避免用户枚举)。 */
export async function loginPg(
db: PgDb,
phoneInput: string,
rawPassword: string,
): Promise<PublicUser> {
const row = await findUserByPhonePg(db, phoneInput.trim());
if (!row) throw AUTH_ERRORS.WRONG_PASSWORD;
const ok = await bcrypt.compare(rawPassword, row.password_hash);
if (!ok) throw AUTH_ERRORS.WRONG_PASSWORD;
return toPublicUser(row);
}
+181
View File
@@ -0,0 +1,181 @@
/**
* 用户认证 service —— 注册 / 登录 / 用户查询。
*
* 双数据库实现(与 codes 模块同构):
* - service.ts:同步 SQLite 实现(测试用内存库)+ Dispatcher
* - service.pg.ts:异步 PostgreSQL 实现(生产)
*
* 密码使用 bcrypt 哈希存储;JWT 签发/校验见 jwt.ts 与 middleware.ts。
*/
import { randomBytes } from "node:crypto";
import bcrypt from "bcryptjs";
import type { Db, PgDb, SqliteDb } from "../db/index.js";
import { isPgDb } from "../db/index.js";
import {
findUserByIdPg,
findUserByPhonePg,
loginPg,
registerPg,
} from "./service.pg.js";
// ---------------------------------------------------------------------------
// 类型 & 常量
// ---------------------------------------------------------------------------
/** 用户公开信息(不含密码哈希)。 */
export interface PublicUser {
id: string;
phone: string;
nickname: string | null;
createdAt: string;
}
/** users 表行(含密码哈希,仅内部使用)。 */
export interface UserRow {
id: string;
phone: string;
password_hash: string;
nickname: string | null;
created_at: string;
}
/** 业务错误(与 codes 模块 CodeError 同构)。 */
export class AuthError extends Error {
readonly status: number;
readonly code: string;
constructor(message: string, status: number, code: string) {
super(message);
this.name = "AuthError";
this.status = status;
this.code = code;
}
}
export const AUTH_ERRORS = {
PHONE_INVALID: new AuthError("手机号格式不正确", 400, "PHONE_INVALID"),
PASSWORD_WEAK: new AuthError("密码至少需要 6 位", 400, "PASSWORD_WEAK"),
PHONE_TAKEN: new AuthError("该手机号已注册,请直接登录", 409, "PHONE_TAKEN"),
NOT_FOUND: new AuthError("用户不存在", 404, "USER_NOT_FOUND"),
WRONG_PASSWORD: new AuthError("手机号或密码错误", 401, "WRONG_PASSWORD"),
} as const;
export const SALT_ROUNDS = 10;
/** 手机号宽松校验:1 开头 + 10 位数字(支持 11 位中/港/澳号段)。 */
export function isValidPhone(phone: string): boolean {
return /^1\d{10}$/.test(phone.trim());
}
/** 密码强度:至少 6 位。 */
export function isValidPassword(password: string): boolean {
return typeof password === "string" && password.length >= 6;
}
/** 行 → 公开信息。 */
export function toPublicUser(row: UserRow): PublicUser {
return {
id: row.id,
phone: row.phone,
nickname: row.nickname,
createdAt: row.created_at,
};
}
/** 生成用户 ID(24 位十六进制)。 */
export function genUserId(): string {
return randomBytes(12).toString("hex");
}
// ---------------------------------------------------------------------------
// SQLite 内部实现(同步,测试用)
// ---------------------------------------------------------------------------
function findUserByPhoneSqlite(db: SqliteDb, phone: string): UserRow | undefined {
return db.prepare("SELECT * FROM users WHERE phone = ?").get(phone.trim()) as UserRow | undefined;
}
function findUserByIdSqlite(db: SqliteDb, id: string): UserRow | undefined {
return db.prepare("SELECT * FROM users WHERE id = ?").get(id) as UserRow | undefined;
}
function registerSqlite(db: SqliteDb, phoneInput: string, rawPassword: string): PublicUser {
const phone = phoneInput.trim();
if (!isValidPhone(phone)) throw AUTH_ERRORS.PHONE_INVALID;
if (!isValidPassword(rawPassword)) throw AUTH_ERRORS.PASSWORD_WEAK;
if (findUserByPhoneSqlite(db, phone)) throw AUTH_ERRORS.PHONE_TAKEN;
const id = genUserId();
const hash = bcrypt.hashSync(rawPassword, SALT_ROUNDS);
db.prepare("INSERT INTO users (id, phone, password_hash) VALUES (?, ?, ?)").run(
id,
phone,
hash,
);
const row = findUserByIdSqlite(db, id)!;
return toPublicUser(row);
}
function loginSqlite(db: SqliteDb, phoneInput: string, rawPassword: string): PublicUser {
const row = findUserByPhoneSqlite(db, phoneInput.trim());
if (!row) throw AUTH_ERRORS.WRONG_PASSWORD;
if (!bcrypt.compareSync(rawPassword, row.password_hash)) throw AUTH_ERRORS.WRONG_PASSWORD;
return toPublicUser(row);
}
// ---------------------------------------------------------------------------
// Dispatcher(根据 db 类型路由到 SQLite 或 PostgreSQL)
// ---------------------------------------------------------------------------
type MaybePromise<T> = T | Promise<T>;
export function registerUser(db: SqliteDb, phone: string, password: string): PublicUser;
export function registerUser(db: PgDb, phone: string, password: string): Promise<PublicUser>;
export function registerUser(
db: Db,
phone: string,
password: string,
): MaybePromise<PublicUser>;
export function registerUser(
db: Db,
phone: string,
password: string,
): MaybePromise<PublicUser> {
return isPgDb(db) ? registerPg(db, phone, password) : registerSqlite(db, phone, password);
}
export function findUserByPhone(db: SqliteDb, phone: string): UserRow | undefined;
export function findUserByPhone(db: PgDb, phone: string): Promise<UserRow | undefined>;
export function findUserByPhone(
db: Db,
phone: string,
): MaybePromise<UserRow | undefined>;
export function findUserByPhone(db: Db, phone: string): MaybePromise<UserRow | undefined> {
return isPgDb(db) ? findUserByPhonePg(db, phone) : findUserByPhoneSqlite(db, phone);
}
export function findUserById(db: SqliteDb, id: string): UserRow | undefined;
export function findUserById(db: PgDb, id: string): Promise<UserRow | undefined>;
export function findUserById(db: Db, id: string): MaybePromise<UserRow | undefined>;
export function findUserById(db: Db, id: string): MaybePromise<UserRow | undefined> {
return isPgDb(db) ? findUserByIdPg(db, id) : findUserByIdSqlite(db, id);
}
/**
* 登录校验(不含 JWT 签发,签发在路由层)。返回公开用户信息;
* 手机号不存在或密码错误时一律抛 WRONG_PASSWORD(避免用户枚举)。
*/
export function loginUser(db: SqliteDb, phone: string, password: string): PublicUser;
export function loginUser(db: PgDb, phone: string, password: string): Promise<PublicUser>;
export function loginUser(
db: Db,
phone: string,
password: string,
): MaybePromise<PublicUser>;
export function loginUser(
db: Db,
phone: string,
password: string,
): MaybePromise<PublicUser> {
return isPgDb(db) ? loginPg(db, phone, password) : loginSqlite(db, phone, password);
}
+141
View File
@@ -0,0 +1,141 @@
/**
* 云端豆仓路由 —— 按用户隔离的库存 CRUD(JWT 保护)。
*
* GET /api/beads/inventory → 200 { brandId, bottles: { code: count } }
* POST /api/beads/add { code, count } → 200
* POST /api/beads/consume { entries: [{code,count}] } → 200 { shortages }
* POST /api/beads/ensure { entries: [{code,count}] } → 200
* POST /api/beads/clear → 200
*/
import { Router } from "express";
import type { Request, Response } from "express";
import type { Db } from "../db/index.js";
import { getDb } from "../db/index.js";
import { requireAuth } from "../auth/middleware.js";
import {
getInventory,
addBeads as addBeadsService,
consumeBeads as consumeBeadsService,
ensureStock as ensureStockService,
clearInventory,
} from "./service.js";
function resolveDb(injected?: Db): Db {
return injected ?? getDb();
}
/**
* 创建云端豆仓路由。所有路由均需登录(requireAuth)。
*/
export function createBeadsRouter(injectedDb?: Db): Router {
const router = Router();
// 所有端点需要登录
router.use(requireAuth);
/** GET /api/beads/inventory */
router.get("/inventory", async (req: Request, res: Response): Promise<void> => {
try {
const db = resolveDb(injectedDb);
const rows = await getInventory(db, req.userId!);
const brandId = rows.length > 0 ? rows[0]!.brand_id : "MARD";
const bottles: Record<string, number> = {};
for (const row of rows) {
bottles[row.code] = row.count;
}
res.status(200).json({ brandId, bottles });
} catch (err) {
console.error("GET /api/beads/inventory error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
});
/** POST /api/beads/add */
router.post("/add", async (req: Request, res: Response): Promise<void> => {
try {
const { code, count } = req.body as { code?: unknown; count?: unknown };
if (typeof code !== "string" || code.trim() === "") {
res.status(400).json({ error: "请输入色号" });
return;
}
const n = typeof count === "number" && Number.isFinite(count) ? count : 0;
if (n <= 0) {
res.status(400).json({ error: "数量必须大于 0" });
return;
}
const db = resolveDb(injectedDb);
// 获取当前品牌(从库存第一行推断,没有则默认 MARD)
const rows = await getInventory(db, req.userId!);
const brandId = rows.length > 0 ? rows[0]!.brand_id : "MARD";
await addBeadsService(db, req.userId!, brandId, code.trim().toUpperCase(), n);
res.status(200).json({ ok: true });
} catch (err) {
console.error("POST /api/beads/add error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
});
/** POST /api/beads/consume */
router.post("/consume", async (req: Request, res: Response): Promise<void> => {
try {
const { entries } = req.body as { entries?: unknown };
if (!Array.isArray(entries) || entries.length === 0) {
res.status(400).json({ error: "缺少扣豆清单" });
return;
}
const parsed = entries.map((e: unknown) => {
const item = (e ?? {}) as { code?: unknown; count?: unknown };
return {
code: typeof item.code === "string" ? item.code.trim().toUpperCase() : "",
count: typeof item.count === "number" && Number.isFinite(item.count) ? item.count : 0,
};
});
const db = resolveDb(injectedDb);
const shortages = await consumeBeadsService(db, req.userId!, parsed);
res.status(200).json({ shortages });
} catch (err) {
console.error("POST /api/beads/consume error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
});
/** POST /api/beads/ensure */
router.post("/ensure", async (req: Request, res: Response): Promise<void> => {
try {
const { entries, brandId } = req.body as { entries?: unknown; brandId?: unknown };
if (!Array.isArray(entries) || entries.length === 0) {
res.status(400).json({ error: "缺少补货清单" });
return;
}
const parsed = entries.map((e: unknown) => {
const item = (e ?? {}) as { code?: unknown; count?: unknown };
return {
code: typeof item.code === "string" ? item.code.trim().toUpperCase() : "",
count: typeof item.count === "number" && Number.isFinite(item.count) ? item.count : 0,
};
});
const brand = typeof brandId === "string" && brandId.trim() !== "" ? brandId.trim() : "MARD";
const db = resolveDb(injectedDb);
await ensureStockService(db, req.userId!, brand, parsed);
res.status(200).json({ ok: true });
} catch (err) {
console.error("POST /api/beads/ensure error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
});
/** POST /api/beads/clear */
router.post("/clear", async (req: Request, res: Response): Promise<void> => {
try {
const db = resolveDb(injectedDb);
await clearInventory(db, req.userId!);
res.status(200).json({ ok: true });
} catch (err) {
console.error("POST /api/beads/clear error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
});
return router;
}
+55
View File
@@ -0,0 +1,55 @@
/**
* 云端豆仓 service —— PostgreSQL 异步实现。
* 与同步的 SQLite 实现(service.ts 内部)一一对应。
*/
import type { PgDb } from "../db/index.js";
import type { BeadInventoryRow } from "./service.js";
/** 按用户查询全部库存(返回 {code, count} 记录)。 */
export async function findAllByUserPg(
db: PgDb,
userId: string,
): Promise<BeadInventoryRow[]> {
const { rows } = await db.query<BeadInventoryRow>(
"SELECT code, count, brand_id FROM bead_inventories WHERE user_id = $1",
[userId],
);
return rows as BeadInventoryRow[];
}
/** 按用户 + 色号查询单条记录。 */
export async function findByUserAndCodePg(
db: PgDb,
userId: string,
code: string,
): Promise<BeadInventoryRow | undefined> {
const { rows } = await db.query<BeadInventoryRow>(
"SELECT code, count, brand_id FROM bead_inventories WHERE user_id = $1 AND code = $2",
[userId, code],
);
return rows[0] as BeadInventoryRow | undefined;
}
/** 批量 upsert 库存(无事务,由路由层的事务/批量保证一致性)。 */
export async function upsertBatchPg(
db: PgDb,
userId: string,
brandId: string,
entries: { code: string; count: number }[],
): Promise<void> {
for (const { code, count } of entries) {
await db.query(
`INSERT INTO bead_inventories (user_id, brand_id, code, count, updated_at)
VALUES ($1, $2, $3, $4, now())
ON CONFLICT (user_id, code)
DO UPDATE SET count = EXCLUDED.count, brand_id = EXCLUDED.brand_id, updated_at = now()`,
[userId, brandId, code, count],
);
}
}
/** 删除用户所有库存(清仓换品牌时用)。 */
export async function deleteAllByUserPg(db: PgDb, userId: string): Promise<void> {
await db.query("DELETE FROM bead_inventories WHERE user_id = $1", [userId]);
}
+296
View File
@@ -0,0 +1,296 @@
/**
* 云端豆仓 service —— 按用户隔离的库存 CRUD。
*
* 双数据库实现(与 auth 模块同构):
* - service.ts:同步 SQLite 实现 + Dispatcher
* - service.pg.ts:异步 PostgreSQL 实现
*
* 语义与前端 `bead-inventory.ts` 的纯函数一致:
* - 加豆:addBeads 合并已有库存
* - 扣豆:consumeBeads 扣到 0 为止,返回缺口
* - 补货:ensureStock 补齐到满足用量
*/
import type { Db, PgDb, SqliteDb } from "../db/index.js";
import { isPgDb } from "../db/index.js";
import {
findAllByUserPg,
findByUserAndCodePg,
upsertBatchPg,
deleteAllByUserPg,
} from "./service.pg.js";
// ---------------------------------------------------------------------------
// 类型
// ---------------------------------------------------------------------------
export interface BeadInventoryRow {
code: string;
count: number;
brand_id: string;
}
/** 单条库存编辑操作。 */
export interface BeadEntry {
code: string;
count: number;
}
/** 扣豆结果(缺口列表)。 */
export interface Shortage {
code: string;
count: number;
missing: number;
}
// ---------------------------------------------------------------------------
// SQLite 内部实现(同步,测试用)
// ---------------------------------------------------------------------------
function findAllByUserSqlite(db: SqliteDb, userId: string): BeadInventoryRow[] {
return db.prepare("SELECT code, count, brand_id FROM bead_inventories WHERE user_id = ?").all(userId) as BeadInventoryRow[];
}
function findByUserAndCodeSqlite(db: SqliteDb, userId: string, code: string): BeadInventoryRow | undefined {
return db.prepare("SELECT code, count, brand_id FROM bead_inventories WHERE user_id = ? AND code = ?").get(userId, code) as BeadInventoryRow | undefined;
}
function upsertBatchSqlite(
db: SqliteDb,
userId: string,
brandId: string,
entries: BeadEntry[],
): void {
const upsert = db.prepare(
`INSERT INTO bead_inventories (user_id, brand_id, code, count, updated_at)
VALUES (?, ?, ?, ?, datetime('now'))
ON CONFLICT(user_id, code)
DO UPDATE SET count = excluded.count, brand_id = excluded.brand_id, updated_at = datetime('now')`,
);
const run = db.transaction(() => {
for (const { code, count } of entries) {
upsert.run(userId, brandId, code, count);
}
});
run();
}
function deleteAllByUserSqlite(db: SqliteDb, userId: string): void {
db.prepare("DELETE FROM bead_inventories WHERE user_id = ?").run(userId);
}
// ---------------------------------------------------------------------------
// Dispatcher
// ---------------------------------------------------------------------------
type MaybePromise<T> = T | Promise<T>;
export function getInventory(db: SqliteDb, userId: string): BeadInventoryRow[];
export function getInventory(db: PgDb, userId: string): Promise<BeadInventoryRow[]>;
export function getInventory(db: Db, userId: string): MaybePromise<BeadInventoryRow[]>;
export function getInventory(db: Db, userId: string): MaybePromise<BeadInventoryRow[]> {
return isPgDb(db) ? findAllByUserPg(db, userId) : findAllByUserSqlite(db, userId);
}
/** 加豆:合并增量到已有库存(count 为加量,非绝对值)。 */
/** 加豆:合并增量到已有库存(count 为加量,非绝对值)。count ≤ 0 时静默忽略。 */
export function addBeads(
db: SqliteDb,
userId: string,
brandId: string,
code: string,
count: number,
): void;
export function addBeads(
db: PgDb,
userId: string,
brandId: string,
code: string,
count: number,
): Promise<void>;
export function addBeads(
db: Db,
userId: string,
brandId: string,
code: string,
count: number,
): MaybePromise<void>;
export function addBeads(
db: Db,
userId: string,
brandId: string,
code: string,
count: number,
): MaybePromise<void> {
if (count <= 0 || !Number.isFinite(count)) {
return (isPgDb(db) ? Promise.resolve() : undefined) as MaybePromise<void>;
}
return isPgDb(db)
? upsertBatchPg(db, userId, brandId, [{ code, count }])
: upsertSingleSqlite(db, userId, brandId, code, count);
}
/** SQLite 单条 upsert(加豆专用,合并数量)。 */
function upsertSingleSqlite(
db: SqliteDb,
userId: string,
brandId: string,
code: string,
count: number,
): void {
const existing = findByUserAndCodeSqlite(db, userId, code);
const newCount = (existing?.count ?? 0) + count;
db.prepare(
`INSERT INTO bead_inventories (user_id, brand_id, code, count, updated_at)
VALUES (?, ?, ?, ?, datetime('now'))
ON CONFLICT(user_id, code)
DO UPDATE SET count = excluded.count, brand_id = excluded.brand_id, updated_at = datetime('now')`,
).run(userId, brandId, code, newCount);
}
/** 扣豆:按 entries 扣减,每色号扣到 0 为止,返回缺口。 */
export function consumeBeads(
db: SqliteDb,
userId: string,
entries: BeadEntry[],
): Shortage[];
export function consumeBeads(
db: PgDb,
userId: string,
entries: BeadEntry[],
): Promise<Shortage[]>;
export function consumeBeads(
db: Db,
userId: string,
entries: BeadEntry[],
): MaybePromise<Shortage[]>;
export function consumeBeads(
db: Db,
userId: string,
entries: BeadEntry[],
): MaybePromise<Shortage[]> {
return isPgDb(db) ? consumeBeadsPg(db, userId, entries) : consumeBeadsSqlite(db, userId, entries);
}
function consumeBeadsSqlite(db: SqliteDb, userId: string, entries: BeadEntry[]): Shortage[] {
const shortages: Shortage[] = [];
const setCount = db.prepare(
"UPDATE bead_inventories SET count = ?, updated_at = datetime('now') WHERE user_id = ? AND code = ?",
);
const run = db.transaction(() => {
for (const { code, count } of entries) {
if (count <= 0 || !Number.isFinite(count)) continue;
const row = findByUserAndCodeSqlite(db, userId, code);
const have = row?.count ?? 0;
const actual = Math.min(have, count);
const missing = count - actual;
if (missing > 0) {
shortages.push({ code, count, missing });
}
if (actual > 0) {
setCount.run(have - actual, userId, code);
}
}
});
run();
return shortages;
}
async function consumeBeadsPg(
db: PgDb,
userId: string,
entries: BeadEntry[],
): Promise<Shortage[]> {
const shortages: Shortage[] = [];
for (const { code, count } of entries) {
if (count <= 0 || !Number.isFinite(count)) continue;
const row = await findByUserAndCodePg(db, userId, code);
const have = row?.count ?? 0;
const actual = Math.min(have, count);
const missing = count - actual;
if (missing > 0) {
shortages.push({ code, count, missing });
}
if (actual > 0) {
await db.query(
"UPDATE bead_inventories SET count = $1, updated_at = now() WHERE user_id = $2 AND code = $3",
[have - actual, userId, code],
);
}
}
return shortages;
}
/** 补货:补齐缺口到恰好满足用量(已有库存 ≥ 用量时不动)。 */
export function ensureStock(
db: SqliteDb,
userId: string,
brandId: string,
entries: BeadEntry[],
): void;
export function ensureStock(
db: PgDb,
userId: string,
brandId: string,
entries: BeadEntry[],
): Promise<void>;
export function ensureStock(
db: Db,
userId: string,
brandId: string,
entries: BeadEntry[],
): MaybePromise<void>;
export function ensureStock(
db: Db,
userId: string,
brandId: string,
entries: BeadEntry[],
): MaybePromise<void> {
return isPgDb(db) ? ensureStockPg(db, userId, brandId, entries) : ensureStockSqlite(db, userId, brandId, entries);
}
function ensureStockSqlite(
db: SqliteDb,
userId: string,
brandId: string,
entries: BeadEntry[],
): void {
const toUpsert: BeadEntry[] = [];
for (const { code, count } of entries) {
if (count <= 0 || !Number.isFinite(count)) continue;
const row = findByUserAndCodeSqlite(db, userId, code);
if (!row || row.count < count) {
toUpsert.push({ code, count });
}
}
if (toUpsert.length > 0) {
upsertBatchSqlite(db, userId, brandId, toUpsert);
}
}
async function ensureStockPg(
db: PgDb,
userId: string,
brandId: string,
entries: BeadEntry[],
): Promise<void> {
const toUpsert: { code: string; count: number }[] = [];
for (const { code, count } of entries) {
if (count <= 0 || !Number.isFinite(count)) continue;
const row = await findByUserAndCodePg(db, userId, code);
if (!row || row.count < count) {
toUpsert.push({ code, count });
}
}
if (toUpsert.length > 0) {
await upsertBatchPg(db, userId, brandId, toUpsert);
}
}
/** 清空用户所有库存(换品牌时调用)。 */
export function clearInventory(db: SqliteDb, userId: string): void;
export function clearInventory(db: PgDb, userId: string): Promise<void>;
export function clearInventory(db: Db, userId: string): MaybePromise<void>;
export function clearInventory(db: Db, userId: string): MaybePromise<void> {
return isPgDb(db) ? deleteAllByUserPg(db, userId) : deleteAllByUserSqlite(db, userId);
}
+46
View File
@@ -121,6 +121,29 @@ CREATE TABLE IF NOT EXISTS showcase_works (
-- 索引:按创建时间倒序查询作品列表(Showcase 展示页主路径)
CREATE INDEX IF NOT EXISTS idx_showcase_works_created_at ON showcase_works(created_at DESC, id DESC);
-- 用户表(账号体系:手机号 + bcrypt 密码哈希)
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
phone TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
nickname TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
-- 云端豆仓表(按用户隔离,色号 → 数量)
CREATE TABLE IF NOT EXISTS bead_inventories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL REFERENCES users(id),
brand_id TEXT NOT NULL DEFAULT 'MARD',
code TEXT NOT NULL,
count INTEGER NOT NULL DEFAULT 0 CHECK(count >= 0),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
UNIQUE(user_id, code)
);
-- 索引:按用户查询库存(豆仓主路径)
CREATE INDEX IF NOT EXISTS idx_bead_inventories_user ON bead_inventories(user_id);
`;
/** All DDL statements for creating tables on PostgreSQL. */
@@ -233,6 +256,29 @@ CREATE TABLE IF NOT EXISTS showcase_works (
-- 索引:按创建时间倒序查询作品列表
CREATE INDEX IF NOT EXISTS idx_showcase_works_created_at ON showcase_works(created_at DESC, id DESC);
-- 用户表(账号体系:手机号 + bcrypt 密码哈希)
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
phone TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
nickname TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- 云端豆仓表(按用户隔离,色号 → 数量)
CREATE TABLE IF NOT EXISTS bead_inventories (
id SERIAL PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id),
brand_id TEXT NOT NULL DEFAULT 'MARD',
code TEXT NOT NULL,
count INTEGER NOT NULL DEFAULT 0 CHECK(count >= 0),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE(user_id, code)
);
-- 索引:按用户查询库存
CREATE INDEX IF NOT EXISTS idx_bead_inventories_user ON bead_inventories(user_id);
`;
/** 保留旧名以便渐进切换(SQLite DDL,用于 createTestDatabase)。 */
+4
View File
@@ -10,6 +10,8 @@ import { createPalettesRouter } from "./palettes/routes.js";
import { createExportRouter } from "./export/routes.js";
import { createColorChartRouter } from "./color-chart/routes.js";
import { createShowcaseRouter } from "./showcase/routes.js";
import { createAuthRouter } from "./auth/routes.js";
import { createBeadsRouter } from "./beads/routes.js";
const PORT = parseInt(process.env["PORT"] ?? "8788", 10);
@@ -62,6 +64,8 @@ export function createApp(db?: Db): Express {
app.use("/api/export", createExportRouter());
app.use("/api/color-chart", createColorChartRouter());
app.use("/api/showcase", createShowcaseRouter(db));
app.use("/api/auth", createAuthRouter(db));
app.use("/api/beads", createBeadsRouter(db));
// ---- 404 handler ----
app.use((_req, res) => {
+120
View File
@@ -0,0 +1,120 @@
/**
* 认证模块测试 —— 注册 / 登录 / 当前用户。
*
* 使用内存 SQLite 数据库 + supertest 模拟 HTTP 请求。
*/
import { describe, it, expect } from "vitest";
import request from "supertest";
import { createApp } from "../server.js";
import { createTestDatabase } from "../db/index.js";
describe("POST /api/auth/register", () => {
const app = createApp(createTestDatabase());
it("注册成功返回 201 及 token + user", async () => {
const res = await request(app)
.post("/api/auth/register")
.send({ phone: "13800138000", password: "123456" });
expect(res.status).toBe(201);
expect(typeof res.body.token).toBe("string");
expect(res.body.token.length).toBeGreaterThan(0);
expect(res.body.user.phone).toBe("13800138000");
expect(res.body.user.id).toBeDefined();
});
it("重复手机号返回 409", async () => {
await request(app)
.post("/api/auth/register")
.send({ phone: "13800138001", password: "123456" });
const res = await request(app)
.post("/api/auth/register")
.send({ phone: "13800138001", password: "123456" });
expect(res.status).toBe(409);
expect(res.body.error).toContain("已注册");
});
it("手机号格式错误返回 400", async () => {
const res = await request(app)
.post("/api/auth/register")
.send({ phone: "1234", password: "123456" });
expect(res.status).toBe(400);
expect(res.body.error).toContain("手机号");
});
it("密码少于 6 位返回 400", async () => {
const res = await request(app)
.post("/api/auth/register")
.send({ phone: "13800138002", password: "123" });
expect(res.status).toBe(400);
expect(res.body.error).toContain("密码");
});
});
describe("POST /api/auth/login", () => {
const app = createApp(createTestDatabase());
// 先注册一个用户
const phone = "13900139000";
const password = "654321";
let token = "";
it("注册后登录成功返回 200 + token", async () => {
await request(app).post("/api/auth/register").send({ phone, password });
const res = await request(app).post("/api/auth/login").send({ phone, password });
expect(res.status).toBe(200);
expect(typeof res.body.token).toBe("string");
expect(res.body.user.phone).toBe(phone);
token = res.body.token;
});
it("错误密码返回 401", async () => {
const res = await request(app).post("/api/auth/login").send({ phone, password: "wrong" });
expect(res.status).toBe(401);
expect(res.body.error).toContain("手机号或密码错误");
});
it("不存在的手机号返回 401", async () => {
const res = await request(app)
.post("/api/auth/login")
.send({ phone: "19900000000", password: "123456" });
expect(res.status).toBe(401);
expect(res.body.error).toContain("手机号或密码错误");
});
it("缺少手机号或密码返回 400", async () => {
const res = await request(app).post("/api/auth/login").send({});
expect(res.status).toBe(400);
});
});
describe("GET /api/auth/me", () => {
const app = createApp(createTestDatabase());
it("未登录(无 token)返回 401", async () => {
const res = await request(app).get("/api/auth/me");
expect(res.status).toBe(401);
expect(res.body.error).toContain("请先登录");
});
it("登录后获取当前用户信息", async () => {
const registerRes = await request(app)
.post("/api/auth/register")
.send({ phone: "13700137000", password: "pass123" });
const token = registerRes.body.token;
const res = await request(app)
.get("/api/auth/me")
.set("Authorization", `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.user.phone).toBe("13700137000");
expect(res.body.user.id).toBeDefined();
});
it("无效 token 返回 401", async () => {
const res = await request(app)
.get("/api/auth/me")
.set("Authorization", "Bearer invalidtoken123");
expect(res.status).toBe(401);
});
});
+187
View File
@@ -0,0 +1,187 @@
/**
* 云端豆仓路由测试 —— 增/查/扣/补/清(JWT 保护)。
*
* 流程:
* 1. 注册用户获取 token
* 2. 用 token 操作豆仓 API
* 3. 验证返回结果
*/
import { describe, it, expect } from "vitest";
import request from "supertest";
import { createApp } from "../server.js";
import { createTestDatabase } from "../db/index.js";
/** 递增计数器,每个测试唯一手机号 */
let phoneCounter = 0;
const uniquePhone = () => `1360000${String(10000 + phoneCounter++).slice(1)}`;
/** 注册用户并返回 token。 */
async function registerAndGetToken(app: ReturnType<typeof createApp>): Promise<string> {
const phone = uniquePhone();
const res = await request(app)
.post("/api/auth/register")
.send({ phone, password: "test123456" });
return res.body.token as string;
}
describe("POST /api/beads/add", () => {
const app = createApp(createTestDatabase());
it("未登录返回 401", async () => {
const res = await request(app)
.post("/api/beads/add")
.send({ code: "M001", count: 100 });
expect(res.status).toBe(401);
});
it("登录后添加豆子成功", async () => {
const token = await registerAndGetToken(app);
const res = await request(app)
.post("/api/beads/add")
.set("Authorization", `Bearer ${token}`)
.send({ code: "M001", count: 100 });
expect(res.status).toBe(200);
expect(res.body.ok).toBe(true);
});
it("缺少色号返回 400", async () => {
const token = await registerAndGetToken(app);
const res = await request(app)
.post("/api/beads/add")
.set("Authorization", `Bearer ${token}`)
.send({ count: 100 });
expect(res.status).toBe(400);
expect(res.body.error).toContain("色号");
});
it("数量为 0 返回 400", async () => {
const token = await registerAndGetToken(app);
const res = await request(app)
.post("/api/beads/add")
.set("Authorization", `Bearer ${token}`)
.send({ code: "M001", count: 0 });
expect(res.status).toBe(400);
});
});
describe("GET /api/beads/inventory", () => {
const app = createApp(createTestDatabase());
it("新用户库存为空", async () => {
const token = await registerAndGetToken(app);
const res = await request(app)
.get("/api/beads/inventory")
.set("Authorization", `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.bottles).toEqual({});
});
it("添加后库存包含该色号", async () => {
const token = await registerAndGetToken(app);
await request(app)
.post("/api/beads/add")
.set("Authorization", `Bearer ${token}`)
.send({ code: "M001", count: 100 });
const res = await request(app)
.get("/api/beads/inventory")
.set("Authorization", `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.bottles["M001"]).toBe(100);
});
it("多次添加同一色号累计数量", async () => {
const token = await registerAndGetToken(app);
await request(app).post("/api/beads/add").set("Authorization", `Bearer ${token}`).send({ code: "M001", count: 50 });
await request(app).post("/api/beads/add").set("Authorization", `Bearer ${token}`).send({ code: "M001", count: 30 });
const res = await request(app).get("/api/beads/inventory").set("Authorization", `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.bottles["M001"]).toBe(80);
});
});
describe("POST /api/beads/consume", () => {
const app = createApp(createTestDatabase());
it("扣豆成功返回缺口列表", async () => {
const token = await registerAndGetToken(app);
// 先加 100 颗 M001
await request(app).post("/api/beads/add").set("Authorization", `Bearer ${token}`).send({ code: "M001", count: 100 });
// 扣 30 颗 M001 + 10 颗 M002(缺口)
const res = await request(app)
.post("/api/beads/consume")
.set("Authorization", `Bearer ${token}`)
.send({ entries: [{ code: "M001", count: 30 }, { code: "M002", count: 10 }] });
expect(res.status).toBe(200);
// M001 有货,缺口 0;M002 无货,缺口 10
const shortages = res.body.shortages as { code: string; missing: number }[];
const m002 = shortages.find((s) => s.code === "M002");
expect(m002?.missing).toBe(10);
expect(shortages.find((s) => s.code === "M001")).toBeUndefined();
// 验证库存:M001 剩 70
const inv = await request(app).get("/api/beads/inventory").set("Authorization", `Bearer ${token}`);
expect(inv.body.bottles["M001"]).toBe(70);
});
it("扣豆超过库存时扣到 0 并报缺口", async () => {
const token = await registerAndGetToken(app);
await request(app).post("/api/beads/add").set("Authorization", `Bearer ${token}`).send({ code: "M001", count: 10 });
const res = await request(app)
.post("/api/beads/consume")
.set("Authorization", `Bearer ${token}`)
.send({ entries: [{ code: "M001", count: 100 }] });
expect(res.status).toBe(200);
expect(res.body.shortages[0]?.missing).toBe(90);
// 库存扣到 0
const inv = await request(app).get("/api/beads/inventory").set("Authorization", `Bearer ${token}`);
expect(inv.body.bottles["M001"]).toBe(0);
});
it("缺少 entries 返回 400", async () => {
const token = await registerAndGetToken(app);
const res = await request(app).post("/api/beads/consume").set("Authorization", `Bearer ${token}`).send({});
expect(res.status).toBe(400);
});
});
describe("POST /api/beads/ensure", () => {
const app = createApp(createTestDatabase());
it("补货补齐缺口", async () => {
const token = await registerAndGetToken(app);
// 有 10 颗 M001,需要 100 颗
await request(app).post("/api/beads/add").set("Authorization", `Bearer ${token}`).send({ code: "M001", count: 10 });
await request(app)
.post("/api/beads/ensure")
.set("Authorization", `Bearer ${token}`)
.send({ entries: [{ code: "M001", count: 100 }], brandId: "MARD" });
expect(200);
// 库存补齐到 100
const inv = await request(app).get("/api/beads/inventory").set("Authorization", `Bearer ${token}`);
expect(inv.body.bottles["M001"]).toBe(100);
});
});
describe("POST /api/beads/clear", () => {
const app = createApp(createTestDatabase());
it("清空后库存为空", async () => {
const token = await registerAndGetToken(app);
await request(app).post("/api/beads/add").set("Authorization", `Bearer ${token}`).send({ code: "M001", count: 100 });
await request(app).post("/api/beads/add").set("Authorization", `Bearer ${token}`).send({ code: "M002", count: 50 });
await request(app).post("/api/beads/clear").set("Authorization", `Bearer ${token}`);
expect(200);
const inv = await request(app).get("/api/beads/inventory").set("Authorization", `Bearer ${token}`);
expect(inv.body.bottles).toEqual({});
});
});