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,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;
|
||||
Reference in new issue
Block a user