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:
1 parent
33e7b38271
commit
3bb67ebf30
25 files changed
+2069
-14
No files matched your search
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user