refactor: 收口 Admin 会话与授权边界

This commit is contained in:
que01 committed 2026-10-19 10:13:13 +08:00
1 parent 0788480ce3
commit 4ef4be2071
67 files changed
+1890 -392

No files matched your search

+1 -8
View File
@@ -12,7 +12,6 @@ import {
} from "@ant-design/icons";
import { useLocation, useNavigate } from "react-router-dom";
import { createApiClient } from "../lib/api.js";
import { saveAdminSession } from "../lib/auth-storage.js";
import { BrandMark } from "../components/BrandMark.js";
import { StatusTag } from "../components/StatusTag.js";
import {
@@ -58,13 +57,7 @@ export function Dashboard({
});
const switchBrand = async (brandId: string) => {
try {
const result = await createApiClient().switchAdminBrand(brandId);
saveAdminSession({
token: result.token,
role: result.role,
platformTemplateRole,
mustChangePassword: false,
});
await createApiClient().switchAdminBrand(brandId);
window.location.reload();
} catch (error) {
message.error(error instanceof Error ? error.message : "品牌切换失败");
+39 -19
View File
@@ -1,52 +1,72 @@
import React, { useState } from "react";
import type { AdminSession } from "@personal-brand/api-client";
import { ChangePassword, Login } from "../features/auth/AuthPages.js";
import { Dashboard } from "./Dashboard.js";
import { AdminRouter } from "./AdminRouter.js";
import { adminMessage as message } from "../components/AdminMessage.js";
import { createApiClient } from "../lib/api.js";
import { clearAdminSession, readAdminSession } from "../lib/auth-storage.js";
import { LoadingStack } from "../components/LoadingStack.js";
type SessionState = Omit<AdminSession, "authenticated">;
export function Root() {
const initialSession = readAdminSession();
const [loggedIn, setLoggedIn] = useState(initialSession.loggedIn);
const [role, setRole] = useState(initialSession.role);
const [platformTemplateRole, setPlatformTemplateRole] = useState(
initialSession.platformTemplateRole,
);
const [mustChangePassword, setMustChangePassword] = useState(initialSession.mustChangePassword);
const [session, setSession] = useState<SessionState | null>(null);
const [loading, setLoading] = useState(true);
React.useEffect(() => {
let active = true;
createApiClient()
.getAdminSession()
.then((current) => {
if (active) setSession(current);
})
.catch(() => {
if (active) setSession(null);
})
.finally(() => {
if (active) setLoading(false);
});
return () => {
active = false;
};
}, []);
React.useEffect(() => {
const expire = () => {
message.warning("登录状态已失效,请重新登录");
setLoggedIn(false);
setSession(null);
};
window.addEventListener("admin-auth-expired", expire);
return () => window.removeEventListener("admin-auth-expired", expire);
}, []);
const logout = async () => {
try {
await createApiClient().logoutAdmin();
} catch {
message.warning("已退出本地会话;服务端撤销请求未完成");
} finally {
clearAdminSession();
setLoggedIn(false);
setSession(null);
}
};
if (!loggedIn)
if (loading) return <LoadingStack />;
if (!session)
return (
<Login
onLogin={(session) => {
setRole(session.role);
setPlatformTemplateRole(session.platformTemplateRole);
setMustChangePassword(session.mustChangePassword);
setLoggedIn(true);
onLogin={(current) => {
setSession(current);
}}
/>
);
if (mustChangePassword) return <ChangePassword onComplete={() => setMustChangePassword(false)} />;
if (session.mustChangePassword) return <ChangePassword onComplete={() => setSession(null)} />;
return (
<AdminRouter>
<Dashboard onLogout={logout} role={role} platformTemplateRole={platformTemplateRole} />
<Dashboard
onLogout={logout}
role={session.role}
platformTemplateRole={session.platformTemplateRole}
/>
</AdminRouter>
);
}
+1 -5
View File
@@ -2,7 +2,6 @@ import { CloudUploadOutlined, DeleteOutlined, PictureOutlined } from "@ant-desig
import { Alert, Button, Image, Popconfirm, Spin, Upload, message } from "antd";
import { useEffect, useMemo, useState } from "react";
import { apiBaseUrl, authenticatedFetch, createApiClient } from "../lib/api.js";
import { readAdminToken } from "../lib/auth-storage.js";
interface ImageUrlFieldProps {
id?: string;
@@ -57,10 +56,7 @@ export function ImageUrlField({ id, value, onChange, placeholder, scope }: Image
: presign.uploadUrl;
const response = await authenticatedFetch(uploadUrl, {
method: "PUT",
headers: {
"content-type": file.type,
...(isLocalUpload ? { authorization: `Bearer ${readAdminToken() ?? ""}` } : {}),
},
headers: { "content-type": file.type },
body: file,
});
if (!response.ok) throw new Error(`upload failed: ${response.status}`);
+2 -12
View File
@@ -1,28 +1,19 @@
import { useState } from "react";
import { createApiClient } from "../../lib/api.js";
import { markAdminPasswordChanged, saveAdminSession } from "../../lib/auth-storage.js";
import { BrandMark } from "../../components/BrandMark.js";
import { adminMessage as message } from "../../components/AdminMessage.js";
import { AdminButton } from "../../components/AdminButton.js";
import { AdminCard } from "../../components/AdminCard.js";
import { AdminForm, AdminInput } from "../../components/AdminForm.js";
import type { AdminLoginSession } from "@personal-brand/api-client";
export function Login({
onLogin,
}: {
onLogin: (session: {
role: string;
mustChangePassword: boolean;
platformTemplateRole: "none" | "template_admin";
}) => void;
}) {
export function Login({ onLogin }: { onLogin: (session: AdminLoginSession) => void }) {
const [form] = AdminForm.useForm();
const [loading, setLoading] = useState(false);
async function submit(values: { username: string; password: string }) {
setLoading(true);
try {
const result = await createApiClient().loginAdmin(values.username, values.password);
saveAdminSession(result);
onLogin(result);
} catch (error) {
message.error(error instanceof Error ? error.message : "登录失败");
@@ -79,7 +70,6 @@ export function ChangePassword({ onComplete }: { onComplete: () => void }) {
setLoading(true);
try {
await createApiClient().changeAdminPassword(values.currentPassword, values.newPassword);
markAdminPasswordChanged();
message.success("密码已更新");
onComplete();
} catch (error) {
+4 -11
View File
@@ -1,23 +1,16 @@
import { ApiClient } from "@personal-brand/api-client";
import { clearAdminSession, readAdminToken } from "./auth-storage.js";
export const apiBaseUrl = import.meta.env.VITE_API_BASE_URL ?? "/api";
export async function authenticatedFetch(
input: RequestInfo | URL,
init?: RequestInit,
): Promise<Response> {
const response = await fetch(input, init);
if (response.status === 401) {
clearAdminSession();
window.dispatchEvent(new Event("admin-auth-expired"));
}
if (response.status === 401) window.dispatchEvent(new Event("admin-auth-expired"));
return response;
}
export function createApiClient(): ApiClient {
const token = readAdminToken();
return new ApiClient({
baseUrl: apiBaseUrl,
...(token ? { token } : {}),
fetcher: authenticatedFetch,
});
return new ApiClient({ baseUrl: apiBaseUrl, fetcher: authenticatedFetch });
}
-48
View File
@@ -1,48 +0,0 @@
export type StoredAdminSession = {
token: string;
role: string;
platformTemplateRole: "none" | "template_admin";
mustChangePassword: boolean;
};
const tokenKey = "adminToken";
const roleKey = "adminRole";
const platformRoleKey = "adminPlatformTemplateRole";
const mustChangePasswordKey = "adminMustChangePassword";
export function saveAdminSession(session: StoredAdminSession): void {
localStorage.setItem(tokenKey, session.token);
localStorage.setItem(roleKey, session.role);
localStorage.setItem(platformRoleKey, session.platformTemplateRole);
localStorage.setItem(mustChangePasswordKey, String(session.mustChangePassword));
}
export function readAdminToken(): string | null {
return localStorage.getItem(tokenKey);
}
export function readAdminSession(): {
loggedIn: boolean;
role: string;
platformTemplateRole: "none" | "template_admin";
mustChangePassword: boolean;
} {
return {
loggedIn: Boolean(localStorage.getItem(tokenKey)),
role: localStorage.getItem(roleKey) || "owner",
platformTemplateRole:
localStorage.getItem(platformRoleKey) === "template_admin" ? "template_admin" : "none",
mustChangePassword: localStorage.getItem(mustChangePasswordKey) === "true",
};
}
export function markAdminPasswordChanged(): void {
localStorage.setItem(mustChangePasswordKey, "false");
}
export function clearAdminSession(): void {
localStorage.removeItem(tokenKey);
localStorage.removeItem(roleKey);
localStorage.removeItem(platformRoleKey);
localStorage.removeItem(mustChangePasswordKey);
}
+1
View File
@@ -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",
+8 -1
View File
@@ -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;
+32 -30
View File
@@ -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 };
}
}
+39
View File
@@ -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" });
+50 -11
View File
@@ -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,
}),
};
}
}
+28 -31
View File
@@ -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);
}
}
+23
View File
@@ -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",
});
}
+3 -1
View File
@@ -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(",")
+1 -1
View File
@@ -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,
+48 -42
View File
@@ -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}` },
+2 -2
View File
@@ -25,8 +25,8 @@ API 地址通过 `API_BASE_URL` 设置,品牌通过 `BRAND_SLUG` 设置。H5
## 构建
```sh
pnpm --filter @personal-brand/taro build:h5
pnpm --filter @personal-brand/taro build:weapp
TEMPLATE_KEY=acheng-campus-food pnpm --filter @personal-brand/taro build:h5
TEMPLATE_KEY=acheng-campus-food pnpm --filter @personal-brand/taro build:weapp
TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:h5
TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:weapp
```
+1 -1
View File
@@ -81,7 +81,7 @@ function resolveTargets(envType, preview) {
if (process.env.MINIAPP_OUTPUT_ROOT)
return [path.resolve(taroRoot, process.env.MINIAPP_OUTPUT_ROOT)];
// 单模板构建默认使用餐饮试点;多模板预览必须显式 --preview。
const templateKey = process.env.TEMPLATE_KEY ?? "acheng-campus-food";
const templateKey = process.env.TEMPLATE_KEY;
if (!templateKey) throw new Error("TEMPLATE_KEY is required for non-preview masking");
return [path.join(taroRoot, "dist", templateKey, envType)];
}
+1
View File
@@ -1,6 +1,7 @@
{
"name": "@personal-brand/taro",
"private": true,
"type": "module",
"scripts": {
"dev:h5": "taro build --type h5 --watch",
"dev:preview": "PREVIEW_ALL_TEMPLATES=true taro build --type h5 --watch",
+38 -4
View File
@@ -235,6 +235,7 @@ runtimeWorkspace.trustItems.push(...additionalFoodTrust);
test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ page }) => {
test.setTimeout(60000);
let rejectOfferingSave = false;
let sessionAuthenticated = false;
await page.setViewportSize({ width: 1920, height: 1000 });
await page.route("http://localhost:3001/public/workspace**", (route) =>
route.fulfill({ json: runtimeWorkspace }),
@@ -243,15 +244,31 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
const request = route.request();
const url = new URL(request.url());
url.pathname = url.pathname.replace(/^\/api/, "");
if (url.pathname === "/admin/session/login")
if (url.pathname === "/admin/session/current") {
if (!sessionAuthenticated) {
return route.fulfill({ status: 401, json: { error: { message: "未登录" } } });
}
return route.fulfill({
json: {
token: "fixture-token",
authenticated: true,
displayName: "测试管理员",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "none",
},
});
}
if (url.pathname === "/admin/session/login") {
sessionAuthenticated = true;
return route.fulfill({
json: {
displayName: "测试管理员",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "none",
},
});
}
if (url.pathname === "/admin/brands")
return route.fulfill({ json: [{ id: brand.id, role: "owner", brand }] });
if (url.pathname === "/admin/config/brand" && request.method() === "PATCH") {
@@ -636,6 +653,7 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
test("林境模板支持首页和主理人区域点选", async ({ page }) => {
test.setTimeout(60000);
let sessionAuthenticated = false;
await page.setViewportSize({ width: 1600, height: 900 });
const editorialBrand = {
...structuredClone(brand),
@@ -730,10 +748,26 @@ test("林境模板支持首页和主理人区域点选", async ({ page }) => {
await page.route("**/api/**", (route) => {
const url = new URL(route.request().url());
const path = url.pathname.replace(/^\/api/, "");
if (path === "/admin/session/login")
if (path === "/admin/session/current") {
if (!sessionAuthenticated) {
return route.fulfill({ status: 401, json: { error: { message: "未登录" } } });
}
return route.fulfill({
json: { token: "fixture-token", displayName: "测试管理员", role: "owner" },
json: {
authenticated: true,
displayName: "测试管理员",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "none",
},
});
}
if (path === "/admin/session/login") {
sessionAuthenticated = true;
return route.fulfill({
json: { displayName: "测试管理员", role: "owner", mustChangePassword: false },
});
}
if (path === "/admin/brands")
return route.fulfill({
json: [{ id: editorialBrand.id, role: "owner", brand: editorialBrand }],
@@ -94,10 +94,11 @@ test("业务编辑弹窗预览列表与详情详情同一份内容", async ({ pa
await page.route("**/api/**", async (route) => {
const url = new URL(route.request().url());
const path = url.pathname.replace(/^\/api/, "");
if (path === "/admin/session/current")
return route.fulfill({ status: 401, json: { error: { message: "未登录" } } });
if (path === "/admin/session/login")
return route.fulfill({
json: {
token: "fixture-token",
displayName: "测试管理员",
role: "owner",
mustChangePassword: false,
@@ -57,9 +57,19 @@ test("模板管理可重试预览,并切换我的、详情和禁止提交的
),
);
await page.setViewportSize({ width: 1440, height: 1000 });
await page.addInitScript(() => {
localStorage.setItem("adminToken", "fixture-token");
localStorage.setItem("adminPlatformTemplateRole", "template_admin");
await page.route("**/api/**", (route) => {
const url = new URL(route.request().url());
if (url.pathname.endsWith("/admin/session/current"))
return route.fulfill({
json: {
authenticated: true,
displayName: "模板管理员",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "template_admin",
},
});
return route.fulfill({ json: {} });
});
let attempts = 0;
const writes: string[] = [];
@@ -71,6 +81,16 @@ test("模板管理可重试预览,并切换我的、详情和禁止提交的
};
await page.route("**/api/**", async (route) => {
const url = new URL(route.request().url());
if (url.pathname.endsWith("/admin/session/current"))
return route.fulfill({
json: {
authenticated: true,
displayName: "模板管理员",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "template_admin",
},
});
if (route.request().method() !== "GET") writes.push(url.pathname);
if (url.pathname.endsWith("/preview")) {
attempts++;
@@ -161,9 +161,19 @@ test("导入包预览矩阵展示身份、资源和完整媒体槽位", async ({
await test.step(`${mediaCase.packageKey}/${mediaCase.industry}`, async () => {
const { preview, version } = await buildPreviewFixture(mediaCase);
assert.ok(version);
await page.addInitScript(() => {
localStorage.setItem("adminToken", "fixture-token");
localStorage.setItem("adminPlatformTemplateRole", "template_admin");
await page.route("**/api/**", (route) => {
const url = new URL(route.request().url());
if (url.pathname.endsWith("/admin/session/current"))
return route.fulfill({
json: {
authenticated: true,
displayName: "模板管理员",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "template_admin",
},
});
return route.fulfill({ json: {} });
});
const emptyPreview = structuredClone(preview);
emptyPreview.workspace.offerings = [];
@@ -175,6 +185,16 @@ test("导入包预览矩阵展示身份、资源和完整媒体槽位", async ({
const writes: string[] = [];
await page.route("**/api/**", async (route) => {
const url = new URL(route.request().url());
if (url.pathname.endsWith("/admin/session/current"))
return route.fulfill({
json: {
authenticated: true,
displayName: "模板管理员",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "template_admin",
},
});
if (route.request().method() !== "GET") writes.push(url.pathname);
if (url.pathname.endsWith("/preview")) {
attempts += 1;