32 lines
1.0 KiB
TypeScript
32 lines
1.0 KiB
TypeScript
import { ForbiddenException, UnauthorizedException } from "@nestjs/common";
|
|
import type { FastifyRequest } from "fastify";
|
|
import { ADMIN_SESSION_COOKIE } from "./admin-session-cookie.js";
|
|
import { readIdentity } from "./auth.js";
|
|
|
|
export type AdminIdentity = {
|
|
subject: string;
|
|
brandId: string;
|
|
role: "admin";
|
|
tokenVersion: number;
|
|
};
|
|
|
|
export function readAdminToken(request: FastifyRequest): string | null {
|
|
const header = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
|
if (header) return header;
|
|
return request.cookies?.[ADMIN_SESSION_COOKIE] ?? null;
|
|
}
|
|
|
|
export function requireAdminIdentity(request: FastifyRequest): AdminIdentity {
|
|
const token = readAdminToken(request);
|
|
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
|
|
|
let identity;
|
|
try {
|
|
identity = readIdentity(token);
|
|
} catch {
|
|
throw new UnauthorizedException("管理员登录态无效或已过期");
|
|
}
|
|
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
|
return identity as AdminIdentity;
|
|
}
|