feat: 增加登录鉴权和固定角色权限
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { env } from "../../config/env";
|
||||
import { ok } from "../../shared/response";
|
||||
import { authGuard } from "./auth.guard";
|
||||
import { loginBodySchema } from "./auth.schema";
|
||||
import { authService } from "./auth.service";
|
||||
|
||||
export async function authRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.post("/auth/login", async (request) => {
|
||||
const body = loginBodySchema.parse(request.body);
|
||||
const { user, payload } = await authService.login(body);
|
||||
const token = app.jwt.sign(payload);
|
||||
|
||||
return ok({
|
||||
token,
|
||||
tokenType: "Bearer",
|
||||
expiresIn: env.JWT_EXPIRES_IN,
|
||||
user,
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/auth/me", { preHandler: authGuard }, async (request) => {
|
||||
const user = await authService.getCurrentUser(request.user);
|
||||
|
||||
return ok(user);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { forbidden, unauthorized } from "../../shared/http-error";
|
||||
import { authService } from "./auth.service";
|
||||
|
||||
// 统一 JWT 鉴权入口。后续新增需要登录的路由,复用这个 guard 即可。
|
||||
export async function authGuard(request: FastifyRequest): Promise<void> {
|
||||
const authorization = request.headers.authorization;
|
||||
|
||||
if (!authorization?.startsWith("Bearer ")) {
|
||||
throw unauthorized("请先登录");
|
||||
}
|
||||
|
||||
try {
|
||||
await request.jwtVerify();
|
||||
} catch {
|
||||
throw unauthorized("登录已过期,请重新登录");
|
||||
}
|
||||
}
|
||||
|
||||
// 后台管理系统只允许超级管理员和拥有 admin 角色的员工访问。
|
||||
export async function managementGuard(request: FastifyRequest): Promise<void> {
|
||||
await authGuard(request);
|
||||
|
||||
const user = await authService.getCurrentUser(request.user);
|
||||
|
||||
if (!user.canManage) {
|
||||
throw forbidden("当前账号没有后台管理权限");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
import type { RowDataPacket } from "mysql2/promise";
|
||||
import { pool } from "../../db/pool";
|
||||
import type {
|
||||
EmployeeLoginAccount,
|
||||
SuperAdminStatus,
|
||||
SuperAdminWithPassword,
|
||||
} from "./auth.types";
|
||||
|
||||
interface SuperAdminRow extends RowDataPacket {
|
||||
id: number;
|
||||
username: string;
|
||||
password_hash: string;
|
||||
display_name: string;
|
||||
status: SuperAdminStatus;
|
||||
last_login_at: Date | null;
|
||||
created_at: Date;
|
||||
updated_at: Date;
|
||||
}
|
||||
|
||||
interface EmployeeLoginRow extends RowDataPacket {
|
||||
id: number;
|
||||
username: string;
|
||||
password_hash: string;
|
||||
display_name: string;
|
||||
store_id: number;
|
||||
store_name: string;
|
||||
}
|
||||
|
||||
interface EmployeeRoleRow extends RowDataPacket {
|
||||
employee_id: number;
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
function toIso(value: Date | null): string | null {
|
||||
return value ? value.toISOString() : null;
|
||||
}
|
||||
|
||||
function toSuperAdmin(row: SuperAdminRow): SuperAdminWithPassword {
|
||||
return {
|
||||
id: row.id,
|
||||
username: row.username,
|
||||
passwordHash: row.password_hash,
|
||||
displayName: row.display_name,
|
||||
status: row.status,
|
||||
lastLoginAt: toIso(row.last_login_at),
|
||||
createdAt: toIso(row.created_at) ?? "",
|
||||
updatedAt: toIso(row.updated_at) ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
export const authRepository = {
|
||||
async findActiveByUsername(
|
||||
username: string,
|
||||
): Promise<SuperAdminWithPassword | null> {
|
||||
const [rows] = await pool.execute<SuperAdminRow[]>(
|
||||
`
|
||||
SELECT id, username, password_hash, display_name, status, last_login_at, created_at, updated_at
|
||||
FROM super_admins
|
||||
WHERE username = ? AND status = 'ACTIVE'
|
||||
LIMIT 1
|
||||
`,
|
||||
[username],
|
||||
);
|
||||
|
||||
return rows[0] ? toSuperAdmin(rows[0]) : null;
|
||||
},
|
||||
|
||||
async findActiveById(id: number): Promise<SuperAdminWithPassword | null> {
|
||||
const [rows] = await pool.execute<SuperAdminRow[]>(
|
||||
`
|
||||
SELECT id, username, password_hash, display_name, status, last_login_at, created_at, updated_at
|
||||
FROM super_admins
|
||||
WHERE id = ? AND status = 'ACTIVE'
|
||||
LIMIT 1
|
||||
`,
|
||||
[id],
|
||||
);
|
||||
|
||||
return rows[0] ? toSuperAdmin(rows[0]) : null;
|
||||
},
|
||||
|
||||
async updateLastLoginAt(id: number): Promise<void> {
|
||||
await pool.execute(
|
||||
`
|
||||
UPDATE super_admins
|
||||
SET last_login_at = CURRENT_TIMESTAMP(3)
|
||||
WHERE id = ?
|
||||
`,
|
||||
[id],
|
||||
);
|
||||
},
|
||||
|
||||
async findActiveEmployeeByPhone(
|
||||
phone: string,
|
||||
): Promise<EmployeeLoginAccount | null> {
|
||||
const [rows] = await pool.execute<EmployeeLoginRow[]>(
|
||||
`
|
||||
SELECT
|
||||
e.id,
|
||||
e.phone AS username,
|
||||
e.password_hash,
|
||||
e.name AS display_name,
|
||||
e.store_id,
|
||||
s.name AS store_name
|
||||
FROM employees e
|
||||
INNER JOIN stores s ON s.id = e.store_id
|
||||
WHERE e.phone = ?
|
||||
AND e.status = 'ACTIVE'
|
||||
AND e.deleted_at IS NULL
|
||||
AND s.status = 'ACTIVE'
|
||||
AND s.deleted_at IS NULL
|
||||
LIMIT 1
|
||||
`,
|
||||
[phone],
|
||||
);
|
||||
|
||||
if (!rows[0]) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rolesByEmployeeId = await this.findRolesByEmployeeIds([rows[0].id]);
|
||||
return toEmployeeLoginAccount(
|
||||
rows[0],
|
||||
rolesByEmployeeId.get(rows[0].id) ?? [],
|
||||
);
|
||||
},
|
||||
|
||||
async findActiveEmployeeById(
|
||||
id: number,
|
||||
): Promise<EmployeeLoginAccount | null> {
|
||||
const [rows] = await pool.execute<EmployeeLoginRow[]>(
|
||||
`
|
||||
SELECT
|
||||
e.id,
|
||||
e.phone AS username,
|
||||
e.password_hash,
|
||||
e.name AS display_name,
|
||||
e.store_id,
|
||||
s.name AS store_name
|
||||
FROM employees e
|
||||
INNER JOIN stores s ON s.id = e.store_id
|
||||
WHERE e.id = ?
|
||||
AND e.status = 'ACTIVE'
|
||||
AND e.deleted_at IS NULL
|
||||
AND s.status = 'ACTIVE'
|
||||
AND s.deleted_at IS NULL
|
||||
LIMIT 1
|
||||
`,
|
||||
[id],
|
||||
);
|
||||
|
||||
if (!rows[0]) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rolesByEmployeeId = await this.findRolesByEmployeeIds([rows[0].id]);
|
||||
return toEmployeeLoginAccount(
|
||||
rows[0],
|
||||
rolesByEmployeeId.get(rows[0].id) ?? [],
|
||||
);
|
||||
},
|
||||
|
||||
async updateEmployeeLastLoginAt(id: number): Promise<void> {
|
||||
await pool.execute(
|
||||
`
|
||||
UPDATE employees
|
||||
SET last_login_at = CURRENT_TIMESTAMP(3)
|
||||
WHERE id = ?
|
||||
`,
|
||||
[id],
|
||||
);
|
||||
},
|
||||
|
||||
async findRolesByEmployeeIds(
|
||||
employeeIds: number[],
|
||||
): Promise<Map<number, EmployeeLoginAccount["roles"]>> {
|
||||
const result = new Map<number, EmployeeLoginAccount["roles"]>();
|
||||
|
||||
if (employeeIds.length === 0) {
|
||||
return result;
|
||||
}
|
||||
|
||||
const placeholders = employeeIds.map(() => "?").join(", ");
|
||||
const [rows] = await pool.execute<EmployeeRoleRow[]>(
|
||||
`
|
||||
SELECT er.employee_id, r.id, r.code, r.name
|
||||
FROM employee_roles er
|
||||
INNER JOIN roles r ON r.id = er.role_id
|
||||
WHERE er.employee_id IN (${placeholders})
|
||||
ORDER BY r.id ASC
|
||||
`,
|
||||
employeeIds,
|
||||
);
|
||||
|
||||
for (const row of rows) {
|
||||
const roles = result.get(row.employee_id) ?? [];
|
||||
roles.push({
|
||||
id: row.id,
|
||||
code: row.code,
|
||||
name: row.name,
|
||||
});
|
||||
result.set(row.employee_id, roles);
|
||||
}
|
||||
|
||||
return result;
|
||||
},
|
||||
};
|
||||
|
||||
function toEmployeeLoginAccount(
|
||||
row: EmployeeLoginRow,
|
||||
roles: EmployeeLoginAccount["roles"],
|
||||
): EmployeeLoginAccount {
|
||||
return {
|
||||
id: row.id,
|
||||
username: row.username,
|
||||
passwordHash: row.password_hash,
|
||||
displayName: row.display_name,
|
||||
storeId: row.store_id,
|
||||
storeName: row.store_name,
|
||||
roles,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const loginBodySchema = z.object({
|
||||
username: z.string().trim().min(1).max(50),
|
||||
password: z.string().min(8).max(128),
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
import { unauthorized } from "../../shared/http-error";
|
||||
import { authRepository } from "./auth.repository";
|
||||
import type {
|
||||
AuthJwtPayload,
|
||||
AuthUser,
|
||||
EmployeeLoginAccount,
|
||||
LoginInput,
|
||||
SuperAdmin,
|
||||
} from "./auth.types";
|
||||
import { verifyPassword } from "./password";
|
||||
|
||||
function toAuthUser(admin: SuperAdmin): AuthUser {
|
||||
return {
|
||||
id: admin.id,
|
||||
username: admin.username,
|
||||
displayName: admin.displayName,
|
||||
accountType: "SUPER_ADMIN",
|
||||
roles: [
|
||||
{
|
||||
id: 0,
|
||||
code: "super_admin",
|
||||
name: "超级管理员",
|
||||
},
|
||||
],
|
||||
permissions: ["*"],
|
||||
canManage: true,
|
||||
};
|
||||
}
|
||||
|
||||
function toEmployeeAuthUser(employee: EmployeeLoginAccount): AuthUser {
|
||||
const canManage = employee.roles.some((role) => role.code === "admin");
|
||||
|
||||
return {
|
||||
id: employee.id,
|
||||
username: employee.username,
|
||||
displayName: employee.displayName,
|
||||
accountType: "EMPLOYEE",
|
||||
storeId: employee.storeId,
|
||||
storeName: employee.storeName,
|
||||
roles: employee.roles,
|
||||
permissions: canManage ? ["*"] : [],
|
||||
canManage,
|
||||
};
|
||||
}
|
||||
|
||||
function toJwtPayload(user: AuthUser): AuthJwtPayload {
|
||||
const subjectPrefix =
|
||||
user.accountType === "SUPER_ADMIN" ? "super_admin" : "employee";
|
||||
|
||||
return {
|
||||
sub: `${subjectPrefix}:${user.id}`,
|
||||
accountType: user.accountType,
|
||||
adminId: user.accountType === "SUPER_ADMIN" ? user.id : undefined,
|
||||
employeeId: user.accountType === "EMPLOYEE" ? user.id : undefined,
|
||||
username: user.username,
|
||||
roleCodes: user.roles.map((role) => role.code),
|
||||
permissions: user.permissions,
|
||||
canManage: user.canManage,
|
||||
};
|
||||
}
|
||||
|
||||
export const authService = {
|
||||
async login(input: LoginInput): Promise<{
|
||||
user: AuthUser;
|
||||
payload: AuthJwtPayload;
|
||||
}> {
|
||||
const admin = await authRepository.findActiveByUsername(input.username);
|
||||
|
||||
if (admin) {
|
||||
const passwordMatched = await verifyPassword(
|
||||
input.password,
|
||||
admin.passwordHash,
|
||||
);
|
||||
|
||||
if (!passwordMatched) {
|
||||
throw unauthorized("用户名或密码错误");
|
||||
}
|
||||
|
||||
await authRepository.updateLastLoginAt(admin.id);
|
||||
|
||||
const user = toAuthUser(admin);
|
||||
|
||||
return {
|
||||
user,
|
||||
payload: toJwtPayload(user),
|
||||
};
|
||||
}
|
||||
|
||||
const employee = await authRepository.findActiveEmployeeByPhone(
|
||||
input.username,
|
||||
);
|
||||
|
||||
if (!employee) {
|
||||
throw unauthorized("用户名或密码错误");
|
||||
}
|
||||
|
||||
const passwordMatched = await verifyPassword(
|
||||
input.password,
|
||||
employee.passwordHash,
|
||||
);
|
||||
|
||||
if (!passwordMatched) {
|
||||
throw unauthorized("用户名或密码错误");
|
||||
}
|
||||
|
||||
await authRepository.updateEmployeeLastLoginAt(employee.id);
|
||||
|
||||
const user = toEmployeeAuthUser(employee);
|
||||
|
||||
return {
|
||||
user,
|
||||
payload: toJwtPayload(user),
|
||||
};
|
||||
},
|
||||
|
||||
async getCurrentUser(payload: AuthJwtPayload): Promise<AuthUser> {
|
||||
if (payload.accountType === "SUPER_ADMIN" && payload.adminId) {
|
||||
const admin = await authRepository.findActiveById(payload.adminId);
|
||||
|
||||
if (!admin) {
|
||||
throw unauthorized("登录已失效,请重新登录");
|
||||
}
|
||||
|
||||
return toAuthUser(admin);
|
||||
}
|
||||
|
||||
if (payload.accountType === "EMPLOYEE" && payload.employeeId) {
|
||||
const employee = await authRepository.findActiveEmployeeById(
|
||||
payload.employeeId,
|
||||
);
|
||||
|
||||
if (!employee) {
|
||||
throw unauthorized("登录已失效,请重新登录");
|
||||
}
|
||||
|
||||
return toEmployeeAuthUser(employee);
|
||||
}
|
||||
|
||||
throw unauthorized("登录已失效,请重新登录");
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,71 @@
|
||||
export const SUPER_ADMIN_STATUS = ["ACTIVE", "INACTIVE"] as const;
|
||||
|
||||
export type SuperAdminStatus = (typeof SUPER_ADMIN_STATUS)[number];
|
||||
export type AuthAccountType = "SUPER_ADMIN" | "EMPLOYEE";
|
||||
|
||||
export interface LoginInput {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface SuperAdmin {
|
||||
id: number;
|
||||
username: string;
|
||||
displayName: string;
|
||||
status: SuperAdminStatus;
|
||||
lastLoginAt: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface SuperAdminWithPassword extends SuperAdmin {
|
||||
passwordHash: string;
|
||||
}
|
||||
|
||||
export interface EmployeeLoginAccount {
|
||||
id: number;
|
||||
username: string;
|
||||
passwordHash: string;
|
||||
displayName: string;
|
||||
storeId: number;
|
||||
storeName: string;
|
||||
roles: Array<{
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface AuthUser {
|
||||
id: number;
|
||||
username: string;
|
||||
displayName: string;
|
||||
accountType: AuthAccountType;
|
||||
storeId?: number;
|
||||
storeName?: string;
|
||||
roles: Array<{
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
}>;
|
||||
permissions: string[];
|
||||
canManage: boolean;
|
||||
}
|
||||
|
||||
export interface AuthJwtPayload {
|
||||
sub: string;
|
||||
accountType: AuthAccountType;
|
||||
adminId?: number;
|
||||
employeeId?: number;
|
||||
username: string;
|
||||
roleCodes: string[];
|
||||
permissions: string[];
|
||||
canManage: boolean;
|
||||
}
|
||||
|
||||
declare module "@fastify/jwt" {
|
||||
interface FastifyJWT {
|
||||
payload: AuthJwtPayload;
|
||||
user: AuthJwtPayload;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { pbkdf2, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const pbkdf2Async = promisify(pbkdf2);
|
||||
const HASH_SCHEME = "pbkdf2";
|
||||
const HASH_ALGORITHM = "sha256";
|
||||
const ITERATIONS = 310000;
|
||||
const KEY_LENGTH = 32;
|
||||
|
||||
function toBase64Url(buffer: Buffer): string {
|
||||
return buffer.toString("base64url");
|
||||
}
|
||||
|
||||
function fromBase64Url(value: string): Buffer {
|
||||
return Buffer.from(value, "base64url");
|
||||
}
|
||||
|
||||
// 密码哈希格式:pbkdf2$sha256$310000$salt$hash。
|
||||
// 把算法、迭代次数和 salt 都放进字符串,后续升级算法时也能兼容旧密码。
|
||||
export async function hashPassword(password: string): Promise<string> {
|
||||
const salt = randomBytes(16);
|
||||
const derivedKey = (await pbkdf2Async(
|
||||
password,
|
||||
salt,
|
||||
ITERATIONS,
|
||||
KEY_LENGTH,
|
||||
HASH_ALGORITHM,
|
||||
)) as Buffer;
|
||||
|
||||
return [
|
||||
HASH_SCHEME,
|
||||
HASH_ALGORITHM,
|
||||
String(ITERATIONS),
|
||||
toBase64Url(salt),
|
||||
toBase64Url(derivedKey),
|
||||
].join("$");
|
||||
}
|
||||
|
||||
export async function verifyPassword(
|
||||
password: string,
|
||||
storedHash: string,
|
||||
): Promise<boolean> {
|
||||
const [scheme, algorithm, iterationsText, saltText, hashText] =
|
||||
storedHash.split("$");
|
||||
|
||||
if (
|
||||
scheme !== HASH_SCHEME ||
|
||||
algorithm !== HASH_ALGORITHM ||
|
||||
!iterationsText ||
|
||||
!saltText ||
|
||||
!hashText
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const iterations = Number(iterationsText);
|
||||
|
||||
if (!Number.isInteger(iterations) || iterations <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const salt = fromBase64Url(saltText);
|
||||
const expectedHash = fromBase64Url(hashText);
|
||||
const derivedKey = (await pbkdf2Async(
|
||||
password,
|
||||
salt,
|
||||
iterations,
|
||||
expectedHash.length,
|
||||
algorithm,
|
||||
)) as Buffer;
|
||||
|
||||
return (
|
||||
expectedHash.length === derivedKey.length &&
|
||||
timingSafeEqual(expectedHash, derivedKey)
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user