refactor: 收口 Admin 会话与授权边界
This commit is contained in:
1 parent
0788480ce3
commit
4ef4be2071
67 files changed
+1890
-392
No files matched your search
@@ -20,6 +20,7 @@
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.1149.0",
|
||||
"@aws-sdk/s3-request-presigner": "^3.1149.0",
|
||||
"@fastify/cookie": "^11.1.3",
|
||||
"@fastify/multipart": "^10.1.3",
|
||||
"@fastify/static": "^10.1.6",
|
||||
"@nestjs/common": "^11.0.11",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
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 = {
|
||||
@@ -9,8 +10,14 @@ export type AdminIdentity = {
|
||||
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 = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
const token = readAdminToken(request);
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
|
||||
let identity;
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
import { ForbiddenException, Injectable, UnauthorizedException } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { PrismaService } from "./prisma.service.js";
|
||||
import { readAdminToken } from "./admin-access.identity.js";
|
||||
import { readIdentity } from "./auth.js";
|
||||
|
||||
@Injectable()
|
||||
export class AdminAccessService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async requireBrand(
|
||||
request: FastifyRequest,
|
||||
): Promise<{ subject: string; brandId: string; role: string }> {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
async requireToken(request: FastifyRequest): Promise<{
|
||||
subject: string;
|
||||
brandId: string;
|
||||
mustChangePassword: boolean;
|
||||
tokenVersion: number;
|
||||
}> {
|
||||
const token = readAdminToken(request);
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
let identity;
|
||||
try {
|
||||
@@ -21,17 +25,30 @@ export class AdminAccessService {
|
||||
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
||||
const user = await this.prisma.adminUser.findUnique({
|
||||
where: { id: identity.subject },
|
||||
select: { mustChangePassword: true, isEnabled: true, tokenVersion: true },
|
||||
select: { isEnabled: true, mustChangePassword: true, tokenVersion: true },
|
||||
});
|
||||
if (!user || identity.tokenVersion !== user.tokenVersion)
|
||||
throw new UnauthorizedException("管理员登录态已失效,请重新登录");
|
||||
if (!user.isEnabled || user.mustChangePassword)
|
||||
if (!user.isEnabled) throw new ForbiddenException("管理员账号已停用");
|
||||
return {
|
||||
subject: identity.subject,
|
||||
brandId: identity.brandId,
|
||||
mustChangePassword: user.mustChangePassword,
|
||||
tokenVersion: user.tokenVersion,
|
||||
};
|
||||
}
|
||||
|
||||
async requireBrand(
|
||||
request: FastifyRequest,
|
||||
): Promise<{ subject: string; brandId: string; role: string }> {
|
||||
const access = await this.requireToken(request);
|
||||
if (access.mustChangePassword)
|
||||
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
|
||||
const membership = await this.prisma.brandMembership.findUnique({
|
||||
where: { adminUserId_brandId: { adminUserId: identity.subject, brandId: identity.brandId } },
|
||||
where: { adminUserId_brandId: { adminUserId: access.subject, brandId: access.brandId } },
|
||||
});
|
||||
if (!membership?.isEnabled) throw new ForbiddenException("管理员没有当前品牌权限");
|
||||
return { subject: identity.subject, brandId: identity.brandId, role: membership.role };
|
||||
return { subject: access.subject, brandId: access.brandId, role: membership.role };
|
||||
}
|
||||
|
||||
async requireRole(request: FastifyRequest, allowedRoles: string[]): Promise<boolean> {
|
||||
@@ -43,30 +60,15 @@ export class AdminAccessService {
|
||||
}
|
||||
|
||||
async requireTemplateAdmin(request: FastifyRequest): Promise<{ subject: string }> {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
let identity;
|
||||
try {
|
||||
identity = readIdentity(token);
|
||||
} catch {
|
||||
throw new UnauthorizedException("管理员登录态无效或已过期");
|
||||
}
|
||||
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
||||
const user = await this.prisma.adminUser.findUnique({
|
||||
where: { id: identity.subject },
|
||||
select: {
|
||||
isEnabled: true,
|
||||
mustChangePassword: true,
|
||||
platformTemplateRole: true,
|
||||
tokenVersion: true,
|
||||
},
|
||||
});
|
||||
if (!user || identity.tokenVersion !== user.tokenVersion)
|
||||
throw new UnauthorizedException("管理员登录态已失效,请重新登录");
|
||||
if (!user.isEnabled || user.mustChangePassword)
|
||||
const access = await this.requireToken(request);
|
||||
if (access.mustChangePassword)
|
||||
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
|
||||
const user = await this.prisma.adminUser.findUniqueOrThrow({
|
||||
where: { id: access.subject },
|
||||
select: { platformTemplateRole: true },
|
||||
});
|
||||
if (user.platformTemplateRole !== "template_admin")
|
||||
throw new ForbiddenException("当前账号没有模板管理权限");
|
||||
return { subject: identity.subject };
|
||||
return { subject: access.subject };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import "reflect-metadata";
|
||||
|
||||
export const ADMIN_AUTH_METADATA = "admin-auth";
|
||||
|
||||
export type AdminAuthMetadata =
|
||||
| { type: "public" }
|
||||
| { type: "token" }
|
||||
| { type: "brand" }
|
||||
| { type: "roles"; roles: string[] }
|
||||
| { type: "template-admin" };
|
||||
|
||||
function adminAuth(metadata: AdminAuthMetadata): ClassDecorator & MethodDecorator {
|
||||
const decorator = ((
|
||||
target: object,
|
||||
propertyKey?: PropertyKey,
|
||||
descriptor?: PropertyDescriptor,
|
||||
) => {
|
||||
// Nest 在 guard 中读取 handler function 的元数据;method decorator 必须写入 descriptor.value。
|
||||
const metadataTarget =
|
||||
propertyKey === undefined ? target : (descriptor?.value as object | undefined);
|
||||
if (metadataTarget) {
|
||||
Reflect.defineMetadata(ADMIN_AUTH_METADATA, metadata, metadataTarget);
|
||||
}
|
||||
}) as ClassDecorator & MethodDecorator;
|
||||
|
||||
return decorator;
|
||||
}
|
||||
|
||||
export const AdminPublic = (): ClassDecorator & MethodDecorator => adminAuth({ type: "public" });
|
||||
|
||||
export const AdminTokenOnly = (): ClassDecorator & MethodDecorator => adminAuth({ type: "token" });
|
||||
|
||||
export const AdminBrand = (): ClassDecorator & MethodDecorator => adminAuth({ type: "brand" });
|
||||
|
||||
export const AdminRoles = (roles: string[]): ClassDecorator & MethodDecorator =>
|
||||
adminAuth({ type: "roles", roles });
|
||||
|
||||
export const AdminTemplateAdmin = (): ClassDecorator & MethodDecorator =>
|
||||
adminAuth({ type: "template-admin" });
|
||||
@@ -1,22 +1,30 @@
|
||||
import { ForbiddenException, Injectable, UnauthorizedException } from "@nestjs/common";
|
||||
import bcrypt from "bcryptjs";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "./admin-access.service.js";
|
||||
import { PrismaService } from "./prisma.service.js";
|
||||
import { signIdentity } from "./auth.js";
|
||||
|
||||
export type AdminLoginSession = {
|
||||
displayName: string;
|
||||
role: string;
|
||||
platformTemplateRole: "none" | "template_admin";
|
||||
mustChangePassword: boolean;
|
||||
};
|
||||
|
||||
export type AdminCurrentSession = AdminLoginSession & { authenticated: true };
|
||||
|
||||
@Injectable()
|
||||
export class AdminAuthService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly access: AdminAccessService,
|
||||
) {}
|
||||
|
||||
async login(
|
||||
username: string,
|
||||
password: string,
|
||||
): Promise<{
|
||||
token: string;
|
||||
displayName: string;
|
||||
mustChangePassword: boolean;
|
||||
role: string;
|
||||
platformTemplateRole: string;
|
||||
}> {
|
||||
): Promise<{ session: AdminLoginSession; token: string }> {
|
||||
const user = await this.prisma.adminUser.findUnique({ where: { username } });
|
||||
if (!user || !user.isEnabled || !(await bcrypt.compare(password, user.passwordHash))) {
|
||||
throw new UnauthorizedException("账号或密码错误");
|
||||
@@ -31,16 +39,37 @@ export class AdminAuthService {
|
||||
});
|
||||
if (!membership) throw new ForbiddenException("管理员没有品牌权限,请先联系平台负责人分配");
|
||||
return {
|
||||
session: {
|
||||
displayName: user.displayName,
|
||||
mustChangePassword: user.mustChangePassword,
|
||||
role: membership.role,
|
||||
platformTemplateRole: user.platformTemplateRole,
|
||||
},
|
||||
token: signIdentity({
|
||||
subject: user.id,
|
||||
brandId: membership.brandId,
|
||||
role: "admin",
|
||||
tokenVersion: user.tokenVersion,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
async currentSession(request: FastifyRequest): Promise<AdminCurrentSession> {
|
||||
const access = await this.access.requireBrand(request);
|
||||
const user = await this.prisma.adminUser.findUniqueOrThrow({
|
||||
where: { id: access.subject },
|
||||
select: {
|
||||
displayName: true,
|
||||
mustChangePassword: true,
|
||||
platformTemplateRole: true,
|
||||
},
|
||||
});
|
||||
return {
|
||||
authenticated: true,
|
||||
displayName: user.displayName,
|
||||
mustChangePassword: user.mustChangePassword,
|
||||
role: membership.role,
|
||||
platformTemplateRole: user.platformTemplateRole,
|
||||
role: access.role,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -55,20 +84,30 @@ export class AdminAuthService {
|
||||
|
||||
async changePassword(
|
||||
userId: string,
|
||||
brandId: string,
|
||||
currentPassword: string,
|
||||
newPassword: string,
|
||||
): Promise<void> {
|
||||
): Promise<{ token: string }> {
|
||||
const user = await this.prisma.adminUser.findUnique({ where: { id: userId } });
|
||||
if (!user?.isEnabled || !(await bcrypt.compare(currentPassword, user.passwordHash))) {
|
||||
throw new UnauthorizedException("当前密码不正确");
|
||||
}
|
||||
await this.prisma.adminUser.update({
|
||||
const updated = await this.prisma.adminUser.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
passwordHash: await bcrypt.hash(newPassword, 12),
|
||||
mustChangePassword: false,
|
||||
tokenVersion: { increment: 1 },
|
||||
},
|
||||
select: { tokenVersion: true },
|
||||
});
|
||||
return {
|
||||
token: signIdentity({
|
||||
subject: user.id,
|
||||
brandId,
|
||||
role: "admin",
|
||||
tokenVersion: updated.tokenVersion,
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,43 +1,40 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { Reflector } from "@nestjs/core";
|
||||
import type { CanActivate, ExecutionContext } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { ADMIN_AUTH_METADATA, type AdminAuthMetadata } from "./admin-auth.decorators.js";
|
||||
import { AdminAccessService } from "./admin-access.service.js";
|
||||
|
||||
const PATH_METADATA = "path";
|
||||
|
||||
function metadataPath(target: object): string | undefined {
|
||||
const value = Reflect.getMetadata(PATH_METADATA, target) as unknown;
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdminMembershipGuard implements CanActivate {
|
||||
constructor(private readonly access: AdminAccessService) {}
|
||||
constructor(
|
||||
private readonly access: AdminAccessService,
|
||||
private readonly reflector: Reflector,
|
||||
) {}
|
||||
|
||||
canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const metadata = this.reflector.getAllAndOverride<AdminAuthMetadata | undefined>(
|
||||
ADMIN_AUTH_METADATA,
|
||||
[context.getHandler(), context.getClass()],
|
||||
);
|
||||
if (!metadata) return true;
|
||||
const request = context.switchToHttp().getRequest<FastifyRequest>();
|
||||
const handlerPath = metadataPath(context.getHandler());
|
||||
const controllerPath = metadataPath(context.getClass());
|
||||
const routePath = `${controllerPath ?? ""}/${handlerPath ?? ""}`.replace(/^\/+|\/+$/g, "");
|
||||
if (routePath === "admin/session/login") return Promise.resolve(true);
|
||||
if (routePath === "admin/session/change-password") return Promise.resolve(true);
|
||||
if (!routePath.startsWith("admin/")) return Promise.resolve(true);
|
||||
if (
|
||||
routePath === "admin/templates" ||
|
||||
routePath.startsWith("admin/templates/") ||
|
||||
routePath === "admin/template-operations" ||
|
||||
routePath.startsWith("admin/template-operations/")
|
||||
) {
|
||||
return this.access.requireTemplateAdmin(request).then(() => true);
|
||||
|
||||
switch (metadata.type) {
|
||||
case "public":
|
||||
return true;
|
||||
case "token":
|
||||
await this.access.requireToken(request);
|
||||
return true;
|
||||
case "roles":
|
||||
await this.access.requireRole(request, metadata.roles);
|
||||
return true;
|
||||
case "template-admin":
|
||||
await this.access.requireTemplateAdmin(request);
|
||||
return true;
|
||||
case "brand":
|
||||
await this.access.requireBrand(request);
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
/^admin\/workspace\/(install|capabilities(?:\/|$)|template(?:\/|$)|fields(?:\/|$))/.test(
|
||||
routePath,
|
||||
) ||
|
||||
/^admin\/config\/visual-template(?:\/|$)/.test(routePath)
|
||||
) {
|
||||
return this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
}
|
||||
return this.access.requireBrand(request).then(() => true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { FastifyReply } from "fastify";
|
||||
|
||||
export const ADMIN_SESSION_COOKIE = "admin_session";
|
||||
const ADMIN_SESSION_MAX_AGE_SECONDS = 60 * 60 * 24 * 7;
|
||||
|
||||
export function setAdminSessionCookie(reply: FastifyReply, token: string): void {
|
||||
reply.setCookie(ADMIN_SESSION_COOKIE, token, {
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
sameSite: "strict",
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
maxAge: ADMIN_SESSION_MAX_AGE_SECONDS,
|
||||
});
|
||||
}
|
||||
|
||||
export function clearAdminSessionCookie(reply: FastifyReply): void {
|
||||
reply.clearCookie(ADMIN_SESSION_COOKIE, {
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
sameSite: "strict",
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
});
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import "reflect-metadata";
|
||||
import { Module, ValidationPipe } from "@nestjs/common";
|
||||
import { APP_GUARD } from "@nestjs/core";
|
||||
import type { NestFastifyApplication } from "@nestjs/platform-fastify";
|
||||
import cookiePlugin from "@fastify/cookie";
|
||||
import { ApiExceptionFilter, RequestIdMiddleware } from "./http.js";
|
||||
import { AdminMembershipGuard } from "./admin-membership.guard.js";
|
||||
import { AdminModule } from "./modules/admin/admin.module.js";
|
||||
@@ -28,13 +29,14 @@ import { WorkspaceModule } from "./modules/workspace/workspace.module.js";
|
||||
})
|
||||
export class AppModule {}
|
||||
|
||||
export function configureApp(app: NestFastifyApplication): void {
|
||||
export async function configureApp(app: NestFastifyApplication): Promise<void> {
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }),
|
||||
);
|
||||
app.useGlobalFilters(new ApiExceptionFilter());
|
||||
const apiPrefix = process.env.API_PREFIX?.replace(/^\/+|\/+$/g, "");
|
||||
if (apiPrefix) app.setGlobalPrefix(apiPrefix);
|
||||
await app.register(cookiePlugin);
|
||||
app.use(new RequestIdMiddleware().use.bind(new RequestIdMiddleware()));
|
||||
const corsOrigins = (process.env.CORS_ORIGINS ?? "")
|
||||
.split(",")
|
||||
|
||||
@@ -26,7 +26,7 @@ export async function createApp(): Promise<NestFastifyApplication> {
|
||||
decorateReply: false,
|
||||
});
|
||||
}
|
||||
configureApp(app);
|
||||
await configureApp(app);
|
||||
return app;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AdminBrand } from "../../admin-auth.decorators.js";
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
@@ -31,6 +32,7 @@ class AdminBookingQueryDto {
|
||||
@IsOptional() @IsString() tagId?: string;
|
||||
}
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/bookings")
|
||||
export class AdminBookingController {
|
||||
constructor(private readonly bookings: BookingService) {}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AdminBrand } from "../../admin-auth.decorators.js";
|
||||
import { Body, Controller, Delete, Get, Param, Patch, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import {
|
||||
@@ -10,6 +11,7 @@ import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||
import { AdminBrandConfigService } from "./admin-brand-config.service.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/config")
|
||||
export class AdminConfigController {
|
||||
constructor(
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { AdminBrand } from "../../admin-auth.decorators.js";
|
||||
import { Controller, Put, Query, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { AdminUploadService } from "./admin-upload.service.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/uploads")
|
||||
export class AdminLocalUploadController {
|
||||
constructor(
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
|
||||
import { Body, Controller, Get, Param, Patch, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
@@ -13,6 +14,7 @@ import {
|
||||
|
||||
type AdminIdentity = { subject: string; brandId: string };
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/miniapp-releases")
|
||||
export class AdminMiniAppReleaseController {
|
||||
constructor(
|
||||
@@ -34,13 +36,13 @@ export class AdminMiniAppReleaseController {
|
||||
return this.settingsService.get(identity.brandId);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Patch("settings")
|
||||
async updateSettings(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: UpdateMiniAppSettingsDto & { privateKey?: string },
|
||||
@Body() body: UpdateMiniAppSettingsDto,
|
||||
): Promise<unknown> {
|
||||
const identity = await this.identity(request);
|
||||
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
return this.settingsService.update(identity.brandId, body);
|
||||
}
|
||||
|
||||
|
||||
@@ -16,5 +16,6 @@ export class UpdateMiniAppSettingsDto {
|
||||
build?: Record<string, unknown>;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
privateKey?: string;
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { AdminBrand } from "../../admin-auth.decorators.js";
|
||||
import { Controller, Get, Param, ParseIntPipe, Post, Body, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { BrandReleaseApiService } from "../../brand-release-api.service.js";
|
||||
import { PublishBrandReleaseDto } from "../../release.dto.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/releases")
|
||||
export class AdminReleaseController {
|
||||
constructor(
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AdminTemplateAdmin } from "../../admin-auth.decorators.js";
|
||||
import { Controller, Get, Param, Post, Query, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
@@ -9,6 +10,7 @@ import { AdminTemplatePackageService } from "./admin-template-package.service.js
|
||||
|
||||
import { AdminTemplatePreviewService } from "./admin-template-preview.service.js";
|
||||
|
||||
@AdminTemplateAdmin()
|
||||
@Controller("admin/templates")
|
||||
export class AdminTemplatePackageController {
|
||||
constructor(
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { AdminBrand } from "../../admin-auth.decorators.js";
|
||||
import { Body, Controller, Get, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { PresignUploadDto } from "./admin-upload.dto.js";
|
||||
import { AdminUploadService } from "./admin-upload.service.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/uploads")
|
||||
export class AdminUploadController {
|
||||
constructor(
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AdminTemplateAdmin } from "../../admin-auth.decorators.js";
|
||||
import { Controller, Get, Query, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { Type } from "class-transformer";
|
||||
@@ -14,6 +15,7 @@ class TemplateOperationMetricsQueryDto {
|
||||
days = 30;
|
||||
}
|
||||
|
||||
@AdminTemplateAdmin()
|
||||
@Controller("admin/template-operations")
|
||||
export class TemplateOperationMetricsController {
|
||||
constructor(
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { Body, Controller, Post, Query, Req, UnauthorizedException } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { Body, Controller, Get, Post, Query, Req, Res } from "@nestjs/common";
|
||||
import type { FastifyReply, FastifyRequest } from "fastify";
|
||||
import { WechatAuthService } from "../../wechat-auth.js";
|
||||
import { AdminBrand, AdminPublic, AdminTokenOnly } from "../../admin-auth.decorators.js";
|
||||
import { clearAdminSessionCookie, setAdminSessionCookie } from "../../admin-session-cookie.js";
|
||||
import { AdminAuthService } from "../../admin-auth.service.js";
|
||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||
import { AdminLoginDto, WechatLoginDto } from "../../admin-auth.dto.js";
|
||||
import { CustomerSessionService } from "./customer-session.service.js";
|
||||
import { ChangeAdminPasswordDto } from "../../admin.dto.js";
|
||||
import { readIdentity } from "../../auth.js";
|
||||
|
||||
@Controller("customer/session")
|
||||
export class CustomerSessionController {
|
||||
@@ -28,37 +30,55 @@ export class CustomerSessionController {
|
||||
export class AdminSessionController {
|
||||
constructor(private readonly auth: AdminAuthService) {}
|
||||
|
||||
@AdminPublic()
|
||||
@Post("login")
|
||||
login(@Body() body: AdminLoginDto): Promise<{
|
||||
token: string;
|
||||
async login(
|
||||
@Body() body: AdminLoginDto,
|
||||
@Res({ passthrough: true }) reply: FastifyReply,
|
||||
): Promise<{
|
||||
displayName: string;
|
||||
mustChangePassword: boolean;
|
||||
role: string;
|
||||
platformTemplateRole: string;
|
||||
platformTemplateRole: "none" | "template_admin";
|
||||
}> {
|
||||
return this.auth.login(body.username, body.password);
|
||||
const { session, token } = await this.auth.login(body.username, body.password);
|
||||
setAdminSessionCookie(reply, token);
|
||||
return session;
|
||||
}
|
||||
|
||||
@AdminBrand()
|
||||
@Get("current")
|
||||
async current(@Req() request: FastifyRequest) {
|
||||
return this.auth.currentSession(request);
|
||||
}
|
||||
|
||||
@AdminTokenOnly()
|
||||
@Post("logout")
|
||||
async logout(@Req() request: FastifyRequest): Promise<{ loggedOut: true }> {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
const identity = readIdentity(token);
|
||||
if (identity.role !== "admin") throw new UnauthorizedException("管理员登录态无效");
|
||||
async logout(
|
||||
@Req() request: FastifyRequest,
|
||||
@Res({ passthrough: true }) reply: FastifyReply,
|
||||
): Promise<{ loggedOut: true }> {
|
||||
const identity = requireAdminIdentity(request);
|
||||
await this.auth.logout(identity.subject);
|
||||
clearAdminSessionCookie(reply);
|
||||
return { loggedOut: true };
|
||||
}
|
||||
|
||||
@AdminTokenOnly()
|
||||
@Post("change-password")
|
||||
async changePassword(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: ChangeAdminPasswordDto,
|
||||
@Res({ passthrough: true }) reply: FastifyReply,
|
||||
): Promise<{ changed: true }> {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
const identity = readIdentity(token);
|
||||
if (identity.role !== "admin") throw new UnauthorizedException("管理员登录态无效");
|
||||
await this.auth.changePassword(identity.subject, body.currentPassword, body.newPassword);
|
||||
const identity = requireAdminIdentity(request);
|
||||
const { token } = await this.auth.changePassword(
|
||||
identity.subject,
|
||||
identity.brandId,
|
||||
body.currentPassword,
|
||||
body.newPassword,
|
||||
);
|
||||
setAdminSessionCookie(reply, token);
|
||||
return { changed: true };
|
||||
}
|
||||
}
|
||||
@@ -1,41 +1,40 @@
|
||||
import { Body, Controller, Get, Param, Patch, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
|
||||
import { Body, Controller, Get, Param, Patch, Post, Req, Res } from "@nestjs/common";
|
||||
import type { FastifyReply, FastifyRequest } from "fastify";
|
||||
import { setAdminSessionCookie } from "../../admin-session-cookie.js";
|
||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||
import { CreateBrandMemberDto, UpdateBrandMemberDto } from "../../admin.dto.js";
|
||||
import { TenantService } from "./tenant.service.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/brands")
|
||||
export class TenantController {
|
||||
constructor(
|
||||
private readonly access: AdminAccessService,
|
||||
private readonly tenants: TenantService,
|
||||
) {}
|
||||
constructor(private readonly tenants: TenantService) {}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Get("members")
|
||||
async listMembers(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
const current = this.adminIdentity(request);
|
||||
return this.tenants.listMembers(current.brandId);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Post("members")
|
||||
async createMember(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: CreateBrandMemberDto,
|
||||
): Promise<unknown> {
|
||||
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
const actor = this.adminIdentity(request);
|
||||
return this.tenants.createMember(actor.brandId, body);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Patch("members/:id")
|
||||
async updateMember(
|
||||
@Req() request: FastifyRequest,
|
||||
@Param("id") id: string,
|
||||
@Body() body: UpdateBrandMemberDto,
|
||||
): Promise<unknown> {
|
||||
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
const actor = this.adminIdentity(request);
|
||||
return this.tenants.updateMember(actor.brandId, actor.subject, id, body);
|
||||
}
|
||||
@@ -50,9 +49,12 @@ export class TenantController {
|
||||
async switchBrand(
|
||||
@Req() request: FastifyRequest,
|
||||
@Param("brandId") brandId: string,
|
||||
): Promise<{ token: string; role: string; brand: unknown }> {
|
||||
@Res({ passthrough: true }) reply: FastifyReply,
|
||||
): Promise<{ role: string; brand: unknown }> {
|
||||
const identity = this.adminIdentity(request);
|
||||
return this.tenants.switchBrand(identity, brandId);
|
||||
const result = await this.tenants.switchBrand(identity, brandId);
|
||||
setAdminSessionCookie(reply, result.token);
|
||||
return { role: result.role, brand: result.brand };
|
||||
}
|
||||
|
||||
private adminIdentity(request: FastifyRequest) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
|
||||
import { Body, Controller, Get, Param, Patch, Post, Query, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import {
|
||||
@@ -9,6 +10,7 @@ import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||
import { AdminSampleContentService } from "./admin-sample-content.service.js";
|
||||
import { AdminWorkspaceCapabilitiesService } from "./admin-workspace-capabilities.service.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/workspace")
|
||||
class AdminCapabilityController {
|
||||
constructor(
|
||||
@@ -16,6 +18,7 @@ class AdminCapabilityController {
|
||||
private readonly sampleContentService: AdminSampleContentService,
|
||||
) {}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Get("capabilities")
|
||||
list(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
return this.capabilitiesService.list(requireAdminIdentity(request).brandId);
|
||||
@@ -38,6 +41,7 @@ class AdminCapabilityController {
|
||||
return this.sampleContentService.import(identity.brandId, identity.subject, body);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Patch("capabilities/:key")
|
||||
update(
|
||||
@Req() request: FastifyRequest,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
|
||||
import { Body, Controller, Delete, Get, Param, Patch, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import {
|
||||
@@ -10,10 +11,12 @@ import {
|
||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||
import { AdminInquiryService } from "./admin-inquiry.service.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/workspace")
|
||||
class AdminInquiryController {
|
||||
constructor(private readonly inquiryService: AdminInquiryService) {}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Post("fields")
|
||||
createField(
|
||||
@Req() request: FastifyRequest,
|
||||
@@ -22,6 +25,7 @@ class AdminInquiryController {
|
||||
return this.inquiryService.createField(requireAdminIdentity(request).brandId, body);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Patch("fields/:id")
|
||||
async updateField(
|
||||
@Req() request: FastifyRequest,
|
||||
@@ -31,6 +35,7 @@ class AdminInquiryController {
|
||||
return this.inquiryService.updateField(requireAdminIdentity(request).brandId, id, body);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Delete("fields/:id")
|
||||
async deleteField(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||
return this.inquiryService.deleteField(requireAdminIdentity(request).brandId, id);
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { Body, Controller, Delete, Get, Param, Patch, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminBrand } from "../../admin-auth.decorators.js";
|
||||
import { CreateOfferingDto, UpdateOfferingDto } from "../../admin.dto.js";
|
||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||
import { AdminOfferingService } from "./admin-offering.service.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/workspace")
|
||||
class AdminOfferingController {
|
||||
constructor(private readonly offeringService: AdminOfferingService) {}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
|
||||
import { Body, Controller, Get, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { RollbackTemplateDto, UpgradeTemplateDto } from "../../admin.dto.js";
|
||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/workspace")
|
||||
class AdminTemplateController {
|
||||
constructor(private readonly templateWorkspace: TemplateWorkspaceService) {}
|
||||
@@ -13,6 +15,7 @@ class AdminTemplateController {
|
||||
return this.templateWorkspace.preview(requireAdminIdentity(request).brandId);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Post("template/upgrade")
|
||||
async upgrade(
|
||||
@Req() request: FastifyRequest,
|
||||
@@ -23,6 +26,7 @@ class AdminTemplateController {
|
||||
return this.templateWorkspace.upgrade(identity.brandId, body, identity.subject, requestId);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Post("template/rollback")
|
||||
async rollback(
|
||||
@Req() request: FastifyRequest,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
|
||||
import { Controller, Get, Post, Body, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { InstallTemplateDto, SelectTemplateVersionDto } from "../../admin.dto.js";
|
||||
@@ -5,6 +6,7 @@ import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||
import { AdminWorkspaceService } from "./admin-workspace.service.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/workspace")
|
||||
class AdminWorkspacePreviewController {
|
||||
constructor(
|
||||
@@ -22,6 +24,7 @@ class AdminWorkspacePreviewController {
|
||||
return this.workspaceService.getPreview(requireAdminIdentity(request).brandId);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Post("install")
|
||||
async install(
|
||||
@Req() request: FastifyRequest,
|
||||
@@ -38,6 +41,7 @@ class AdminWorkspacePreviewController {
|
||||
);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Post("template/select-version")
|
||||
async selectVersion(
|
||||
@Req() request: FastifyRequest,
|
||||
|
||||
@@ -131,7 +131,7 @@ test("模板目录只允许平台模板管理员访问,并支持安全、幂
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
assert.equal(login.statusCode, 201);
|
||||
const headers = { authorization: `Bearer ${JSON.parse(login.body).token}` };
|
||||
const headers = { authorization: `Bearer ${sessionToken(login)}` };
|
||||
const empty = await request("/admin/templates", { headers });
|
||||
assert.equal(empty.statusCode, 200);
|
||||
const baseline = JSON.parse(empty.body);
|
||||
@@ -276,7 +276,7 @@ test("模板失败指标仅平台模板管理员可查,按窗口聚合且不
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
assert.equal(login.statusCode, 201);
|
||||
const adminHeaders = { authorization: `Bearer ${JSON.parse(login.body).token}` };
|
||||
const adminHeaders = { authorization: `Bearer ${sessionToken(login)}` };
|
||||
const now = Date.now();
|
||||
const recentRequestId = `metrics-${randomUUID()}`;
|
||||
await prisma.templateOperationFailureEvent.createMany({
|
||||
@@ -356,7 +356,7 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
assert.equal(login.statusCode, 201);
|
||||
const headers = { authorization: `Bearer ${JSON.parse(login.body).token}` };
|
||||
const headers = { authorization: `Bearer ${sessionToken(login)}` };
|
||||
const invalidArchive = createTemplateArchive("atelier-solopreneur", (manifest) => {
|
||||
manifest.previewFixture.personal.safety.submissions = "enabled";
|
||||
});
|
||||
@@ -700,7 +700,7 @@ test("miniapp release tasks are authorized, idempotent, and state checked", asyn
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const headers = { authorization: `Bearer ${JSON.parse(login.body).token}` };
|
||||
const headers = { authorization: `Bearer ${sessionToken(login)}` };
|
||||
const current = JSON.parse((await request("/admin/releases", { headers })).body).find(
|
||||
(item) => item.status === "published",
|
||||
);
|
||||
@@ -846,7 +846,7 @@ test("miniapp release settings never expose or persist plaintext private keys",
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const headers = { authorization: `Bearer ${JSON.parse(login.body).token}` };
|
||||
const headers = { authorization: `Bearer ${sessionToken(login)}` };
|
||||
const { generateKeyPairSync } = await import("node:crypto");
|
||||
const privateKey = generateKeyPairSync("rsa", {
|
||||
modulusLength: 2048,
|
||||
@@ -1390,7 +1390,7 @@ test("admin release lifecycle is authorized, brand-scoped, and versioned", async
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
assert.equal(login.statusCode, 201);
|
||||
const adminToken = JSON.parse(login.body).token;
|
||||
const adminToken = sessionToken(login);
|
||||
const readiness = await request("/admin/releases/readiness", {
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
@@ -1837,6 +1837,12 @@ function errorMessage(body) {
|
||||
return parsed?.error?.message ?? parsed?.message ?? "";
|
||||
}
|
||||
|
||||
function sessionToken(response) {
|
||||
const cookie = response.cookies?.find((item) => item.name === "admin_session");
|
||||
assert.ok(cookie, "admin session cookie missing");
|
||||
return cookie.value;
|
||||
}
|
||||
|
||||
async function request(url, options = {}) {
|
||||
const { rawPayload, ...injectOptions } = options;
|
||||
return app
|
||||
@@ -1855,7 +1861,7 @@ async function publishReleaseForTests(note = "集成测试发布") {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
return request("/admin/releases/publish", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
@@ -1935,7 +1941,7 @@ test("visual template compatibility is enforced by catalog, preview, and version
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const installation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
|
||||
where: { brandId },
|
||||
});
|
||||
@@ -1982,7 +1988,7 @@ test("industry template state has a single source of truth", async () => {
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const headers = {
|
||||
authorization: `Bearer ${JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token}`,
|
||||
authorization: `Bearer ${sessionToken(login)}`,
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -2143,7 +2149,7 @@ test("admin can update declared capability status with authorization and audit",
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const updated = await request("/admin/workspace/capabilities/inquiry", {
|
||||
method: "PATCH",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
@@ -2177,7 +2183,7 @@ test("editor membership can manage brand content but cannot change system settin
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const identity = readIdentity(token);
|
||||
const membership = await prisma.brandMembership.findUnique({
|
||||
where: { adminUserId_brandId: { adminUserId: identity.subject, brandId } },
|
||||
@@ -2212,7 +2218,7 @@ test("owner can manage brand members without removing the final owner", async ()
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const identity = readIdentity(token);
|
||||
const members = await request("/admin/brands/members", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
@@ -2257,7 +2263,7 @@ test("manually created member must change the initial password before normal use
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const ownerToken = JSON.parse(ownerLogin.body).token;
|
||||
const ownerToken = sessionToken(ownerLogin);
|
||||
const username = `first-login-${Date.now()}`;
|
||||
const created = await request("/admin/brands/members", {
|
||||
method: "POST",
|
||||
@@ -2280,13 +2286,13 @@ test("manually created member must change the initial password before normal use
|
||||
assert.equal(login.statusCode, 201);
|
||||
assert.equal(JSON.parse(login.body).mustChangePassword, true);
|
||||
const blocked = await request("/admin/brands/members", {
|
||||
headers: { authorization: `Bearer ${JSON.parse(login.body).token}` },
|
||||
headers: { authorization: `Bearer ${sessionToken(login)}` },
|
||||
});
|
||||
assert.equal(blocked.statusCode, 403);
|
||||
assert.match(errorMessage(blocked.body), /初始密码/);
|
||||
const changed = await request("/admin/session/change-password", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${JSON.parse(login.body).token}` },
|
||||
headers: { authorization: `Bearer ${sessionToken(login)}` },
|
||||
payload: { currentPassword: "initial-password-123", newPassword: "updated-password-123" },
|
||||
});
|
||||
assert.equal(changed.statusCode, 201);
|
||||
@@ -2309,7 +2315,7 @@ test("admin can install optional quote capability without industry-specific bran
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const response = await request("/admin/workspace/capabilities/quote-request", {
|
||||
method: "PATCH",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
@@ -2346,7 +2352,7 @@ test("admin capability list includes template defaults and brand overrides", asy
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const defaults = await request("/admin/workspace/capabilities", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
@@ -2390,7 +2396,7 @@ test("installing another industry template is rejected without drifting brand id
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const headers = { authorization: `Bearer ${token}` };
|
||||
try {
|
||||
// 品牌身份是 food;装 doors 属于「更换行业模板」,不在本版本范围内。
|
||||
@@ -2442,7 +2448,7 @@ test("cross template requests are rejected without creating a drifted installati
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const headers = {
|
||||
authorization: `Bearer ${JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token}`,
|
||||
authorization: `Bearer ${sessionToken(login)}`,
|
||||
};
|
||||
try {
|
||||
const rejected = await request("/admin/workspace/install", {
|
||||
@@ -2507,7 +2513,7 @@ test("admin can preview and import sample content idempotently", async () => {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const headers = { authorization: `Bearer ${token}` };
|
||||
const preview = await request(
|
||||
`/admin/workspace/sample-content/preview?templatePackageVersionId=${packageVersionId}`,
|
||||
@@ -2601,7 +2607,7 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const before = await request("/admin/workspace");
|
||||
assert.equal(before.statusCode, 401);
|
||||
const customerAccess = await request("/admin/workspace", {
|
||||
@@ -3053,7 +3059,7 @@ test("admin can customize workspace fields with brand isolation", async () => {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const workspace = await request("/admin/workspace", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
@@ -3098,7 +3104,7 @@ test("selected package version is reflected in public runtime workspace", async
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const installation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
|
||||
where: { brandId },
|
||||
});
|
||||
@@ -3349,7 +3355,7 @@ test("admin can create and version an inquiry form", async () => {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const offering = await prisma.offering.findFirst({ where: { brandId, isEnabled: true } });
|
||||
assert.ok(offering);
|
||||
const created = await request("/admin/workspace/forms", {
|
||||
@@ -3592,7 +3598,7 @@ test("admin workspace data stays inside the acting brand", async () => {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const actingBrandId = readIdentity(token).brandId;
|
||||
const otherBrand = await prisma.brandProfile.findFirst({
|
||||
where: { id: { not: actingBrandId } },
|
||||
@@ -3604,7 +3610,7 @@ test("admin workspace data stays inside the acting brand", async () => {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(switchResponse.statusCode, 201);
|
||||
const switchedToken = JSON.parse(switchResponse.body).token;
|
||||
const switchedToken = sessionToken(switchResponse);
|
||||
assert.equal(readIdentity(switchedToken).brandId, otherBrand.id);
|
||||
|
||||
const workspace = await request("/admin/workspace", {
|
||||
@@ -3631,7 +3637,7 @@ test("inquiry form offering link is validated against the brand", async () => {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const headers = { authorization: `Bearer ${token}` };
|
||||
const offering = await prisma.offering.findFirst({ where: { brandId, isEnabled: true } });
|
||||
assert.ok(offering);
|
||||
@@ -3704,7 +3710,7 @@ test("release readiness explains a form whose offering was disabled", async () =
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const headers = { authorization: `Bearer ${token}` };
|
||||
const offering = await prisma.offering.findFirst({ where: { brandId, isEnabled: true } });
|
||||
assert.ok(offering);
|
||||
@@ -3741,7 +3747,7 @@ test("admin rejects invalid dynamic inquiry field definitions", async () => {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const invalid = await request("/admin/workspace/forms", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
@@ -3758,7 +3764,7 @@ test("admin can manage offerings and public endpoint hides disabled offerings",
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const invalidConfig = await request("/admin/workspace/offerings", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
@@ -3836,7 +3842,7 @@ test("offering with an inquiry form cannot be deleted", async () => {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const offering = await prisma.offering.create({
|
||||
data: { brandId, kind: "service", name: `保护测试-${Date.now()}`, description: "测试" },
|
||||
});
|
||||
@@ -3871,7 +3877,7 @@ test("seeded admin can log in and read protected booking resources", async () =>
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
assert.equal(login.statusCode, 201);
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
assert.ok(token);
|
||||
|
||||
const count = await request("/admin/bookings/unread-count", {
|
||||
@@ -3915,7 +3921,7 @@ test("admin logout revokes the current token", async () => {
|
||||
payload: { username, password },
|
||||
});
|
||||
assert.equal(login.statusCode, 201, login.body);
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const headers = { authorization: `Bearer ${token}` };
|
||||
const before = await request("/admin/bookings/unread-count", { headers });
|
||||
assert.equal(before.statusCode, 200);
|
||||
@@ -3984,7 +3990,7 @@ test("changing an admin password revokes existing admin tokens", async () => {
|
||||
payload: { username, password: "initial-password-123" },
|
||||
});
|
||||
assert.equal(login.statusCode, 201, login.body);
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const headers = { authorization: `Bearer ${token}` };
|
||||
const before = await request("/admin/bookings/unread-count", { headers });
|
||||
assert.equal(before.statusCode, 200, before.body);
|
||||
@@ -4008,7 +4014,7 @@ test("admin can list and switch only enabled brand memberships", async () => {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const brands = await request("/admin/brands", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
@@ -4030,7 +4036,7 @@ test("brand switching isolates admin configuration, offerings, and public worksp
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
assert.equal(login.statusCode, 201);
|
||||
const defaultToken = JSON.parse(login.body).token;
|
||||
const defaultToken = sessionToken(login);
|
||||
const memberships = JSON.parse(
|
||||
(
|
||||
await request("/admin/brands", {
|
||||
@@ -4046,7 +4052,7 @@ test("brand switching isolates admin configuration, offerings, and public worksp
|
||||
headers: { authorization: `Bearer ${defaultToken}` },
|
||||
});
|
||||
assert.equal(switched.statusCode, 201);
|
||||
const doorsToken = JSON.parse(switched.body).token;
|
||||
const doorsToken = sessionToken(switched);
|
||||
|
||||
const [
|
||||
defaultConfig,
|
||||
@@ -4101,7 +4107,7 @@ test("disabled brand membership blocks existing admin token", async () => {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const admin = await prisma.adminUser.findUnique({ where: { username: "admin" } });
|
||||
assert.ok(admin);
|
||||
const membership = await prisma.brandMembership.findUnique({
|
||||
@@ -4127,7 +4133,7 @@ test("admin can read and update brand and service configuration", async () => {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const adminToken = JSON.parse(login.body).token;
|
||||
const adminToken = sessionToken(login);
|
||||
const removedAdminRoute = await request("/admin/config/services", {
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
@@ -4242,7 +4248,7 @@ test("admin can update user-facing brand presentation without replacing other co
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
const brand = await prisma.brandProfile.findUnique({ where: { id: brandId } });
|
||||
assert.ok(brand);
|
||||
const originalConfig = brand.config;
|
||||
@@ -4278,7 +4284,7 @@ test("admin can manage trust content", async () => {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const token = sessionToken(login);
|
||||
assert.equal((await request("/admin/config/trust-content")).statusCode, 401);
|
||||
assert.equal(
|
||||
(
|
||||
@@ -4530,7 +4536,7 @@ test("admin can advance booking status but cannot skip the state machine", async
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const adminToken = JSON.parse(login.body).token;
|
||||
const adminToken = sessionToken(login);
|
||||
const contacting = await request(`/admin/bookings/${booking.id}/status`, {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
|
||||
Reference in new issue
Block a user