184 lines
6.3 KiB
TypeScript
184 lines
6.3 KiB
TypeScript
/**
|
||
* 用户认证 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;
|
||
role: string;
|
||
createdAt: string;
|
||
}
|
||
|
||
/** users 表行(含密码哈希,仅内部使用)。 */
|
||
export interface UserRow {
|
||
id: string;
|
||
phone: string;
|
||
password_hash: string;
|
||
nickname: string | null;
|
||
role: string;
|
||
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,
|
||
role: row.role || "user",
|
||
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);
|
||
} |