fix: 收口依赖兼容与会话撤销
为 miniprogram-ci 和 Jimp 依赖增加兼容 patch 与 smoke test;修复平台模板管理员路由漏配;收紧模板契约校验;为 admin/customer 增加 token 撤销和集中会话存储;同步品牌切换角色、doctor source hash、多屏宽截图证据和 CI 构建门禁。
This commit is contained in:
1 parent
4f0b50c7f1
commit
3017e3eb49
65 files changed
+1623
-975
No files matched your search
@@ -12,6 +12,7 @@ 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 {
|
||||
@@ -43,7 +44,7 @@ export function Dashboard({
|
||||
}: {
|
||||
onLogout: () => void;
|
||||
role: string;
|
||||
platformTemplateRole: string;
|
||||
platformTemplateRole: "none" | "template_admin";
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
@@ -58,7 +59,12 @@ export function Dashboard({
|
||||
const switchBrand = async (brandId: string) => {
|
||||
try {
|
||||
const result = await createApiClient().switchAdminBrand(brandId);
|
||||
localStorage.setItem("adminToken", result.token);
|
||||
saveAdminSession({
|
||||
token: result.token,
|
||||
role: result.role,
|
||||
platformTemplateRole,
|
||||
mustChangePassword: false,
|
||||
});
|
||||
window.location.reload();
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : "品牌切换失败");
|
||||
|
||||
+14
-12
@@ -3,16 +3,17 @@ 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";
|
||||
|
||||
export function Root() {
|
||||
const [loggedIn, setLoggedIn] = useState(Boolean(localStorage.getItem("adminToken")));
|
||||
const [role, setRole] = useState(localStorage.getItem("adminRole") || "owner");
|
||||
const initialSession = readAdminSession();
|
||||
const [loggedIn, setLoggedIn] = useState(initialSession.loggedIn);
|
||||
const [role, setRole] = useState(initialSession.role);
|
||||
const [platformTemplateRole, setPlatformTemplateRole] = useState(
|
||||
localStorage.getItem("adminPlatformTemplateRole") || "none",
|
||||
);
|
||||
const [mustChangePassword, setMustChangePassword] = useState(
|
||||
localStorage.getItem("adminMustChangePassword") === "true",
|
||||
initialSession.platformTemplateRole,
|
||||
);
|
||||
const [mustChangePassword, setMustChangePassword] = useState(initialSession.mustChangePassword);
|
||||
React.useEffect(() => {
|
||||
const expire = () => {
|
||||
message.warning("登录状态已失效,请重新登录");
|
||||
@@ -21,12 +22,13 @@ export function Root() {
|
||||
window.addEventListener("admin-auth-expired", expire);
|
||||
return () => window.removeEventListener("admin-auth-expired", expire);
|
||||
}, []);
|
||||
const logout = () => {
|
||||
localStorage.removeItem("adminToken");
|
||||
localStorage.removeItem("adminRole");
|
||||
localStorage.removeItem("adminPlatformTemplateRole");
|
||||
localStorage.removeItem("adminMustChangePassword");
|
||||
setLoggedIn(false);
|
||||
const logout = async () => {
|
||||
try {
|
||||
await createApiClient().logoutAdmin();
|
||||
} finally {
|
||||
clearAdminSession();
|
||||
setLoggedIn(false);
|
||||
}
|
||||
};
|
||||
if (!loggedIn)
|
||||
return (
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { CloudUploadOutlined, DeleteOutlined, PictureOutlined } from "@ant-design/icons";
|
||||
import { Alert, Button, Image, Popconfirm, Spin, Upload, message } from "antd";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { apiBaseUrl, createApiClient } from "../lib/api.js";
|
||||
import { apiBaseUrl, authenticatedFetch, createApiClient } from "../lib/api.js";
|
||||
import { readAdminToken } from "../lib/auth-storage.js";
|
||||
|
||||
interface ImageUrlFieldProps {
|
||||
id?: string;
|
||||
@@ -54,13 +55,11 @@ export function ImageUrlField({ id, value, onChange, placeholder, scope }: Image
|
||||
const uploadUrl = isLocalUpload
|
||||
? `${apiBaseUrl.replace(/\/$/, "")}${presign.uploadUrl}`
|
||||
: presign.uploadUrl;
|
||||
const response = await fetch(uploadUrl, {
|
||||
const response = await authenticatedFetch(uploadUrl, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"content-type": file.type,
|
||||
...(isLocalUpload
|
||||
? { authorization: `Bearer ${localStorage.getItem("adminToken") ?? ""}` }
|
||||
: {}),
|
||||
...(isLocalUpload ? { authorization: `Bearer ${readAdminToken() ?? ""}` } : {}),
|
||||
},
|
||||
body: file,
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
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";
|
||||
@@ -21,10 +22,7 @@ export function Login({
|
||||
setLoading(true);
|
||||
try {
|
||||
const result = await createApiClient().loginAdmin(values.username, values.password);
|
||||
localStorage.setItem("adminToken", result.token);
|
||||
localStorage.setItem("adminRole", result.role);
|
||||
localStorage.setItem("adminPlatformTemplateRole", result.platformTemplateRole);
|
||||
localStorage.setItem("adminMustChangePassword", String(result.mustChangePassword));
|
||||
saveAdminSession(result);
|
||||
onLogin(result);
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : "登录失败");
|
||||
@@ -81,7 +79,7 @@ export function ChangePassword({ onComplete }: { onComplete: () => void }) {
|
||||
setLoading(true);
|
||||
try {
|
||||
await createApiClient().changeAdminPassword(values.currentPassword, values.newPassword);
|
||||
localStorage.setItem("adminMustChangePassword", "false");
|
||||
markAdminPasswordChanged();
|
||||
message.success("密码已更新");
|
||||
onComplete();
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
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(
|
||||
@@ -7,13 +8,13 @@ export async function authenticatedFetch(
|
||||
): Promise<Response> {
|
||||
const response = await fetch(input, init);
|
||||
if (response.status === 401) {
|
||||
localStorage.removeItem("adminToken");
|
||||
clearAdminSession();
|
||||
window.dispatchEvent(new Event("admin-auth-expired"));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
export function createApiClient(): ApiClient {
|
||||
const token = localStorage.getItem("adminToken");
|
||||
const token = readAdminToken();
|
||||
return new ApiClient({
|
||||
baseUrl: apiBaseUrl,
|
||||
...(token ? { token } : {}),
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
-- 客户 token 版本用于登出后撤销既有登录态。
|
||||
ALTER TABLE "CustomerUser" ADD COLUMN "tokenVersion" INTEGER NOT NULL DEFAULT 0;
|
||||
@@ -365,6 +365,7 @@ model CustomerUser {
|
||||
brandId String
|
||||
brand BrandProfile @relation(fields: [brandId], references: [id])
|
||||
openid String
|
||||
tokenVersion Int @default(0)
|
||||
lastLoginAt DateTime @default(now())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@ -44,6 +44,15 @@ export class AdminAuthService {
|
||||
};
|
||||
}
|
||||
|
||||
async logout(userId: string): Promise<void> {
|
||||
const user = await this.prisma.adminUser.findUnique({ where: { id: userId } });
|
||||
if (!user?.isEnabled) throw new UnauthorizedException("管理员登录态无效或已过期");
|
||||
await this.prisma.adminUser.update({
|
||||
where: { id: userId },
|
||||
data: { tokenVersion: { increment: 1 } },
|
||||
});
|
||||
}
|
||||
|
||||
async changePassword(
|
||||
userId: string,
|
||||
currentPassword: string,
|
||||
|
||||
@@ -22,7 +22,12 @@ export class AdminMembershipGuard implements CanActivate {
|
||||
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/")) {
|
||||
if (
|
||||
routePath === "admin/templates" ||
|
||||
routePath.startsWith("admin/templates/") ||
|
||||
routePath === "admin/template-operations" ||
|
||||
routePath.startsWith("admin/template-operations/")
|
||||
) {
|
||||
return this.access.requireTemplateAdmin(request).then(() => true);
|
||||
}
|
||||
if (
|
||||
|
||||
@@ -22,8 +22,6 @@ export interface CreateBookingInput {
|
||||
items?: Array<{ offeringId: string; quantity: number }>;
|
||||
}
|
||||
|
||||
export type CustomerIdentity = { brandId: string; openid: string };
|
||||
|
||||
@Injectable()
|
||||
export class BookingService {
|
||||
constructor(
|
||||
@@ -31,15 +29,6 @@ export class BookingService {
|
||||
private readonly releases: BrandReleaseService,
|
||||
) {}
|
||||
|
||||
async requireCustomer(identity: CustomerIdentity): Promise<string> {
|
||||
const customer = await this.prisma.customerUser.findUnique({
|
||||
where: { brandId_openid: identity },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!customer) throw new BadRequestException("请先完成微信登录");
|
||||
return customer.id;
|
||||
}
|
||||
|
||||
async create(brandId: string, customerUserId: string, input: CreateBookingInput) {
|
||||
const snapshot = await this.releases.getPublishedSnapshot(brandId);
|
||||
if (!snapshot) throw new BadRequestException("品牌尚未发布");
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { ForbiddenException, Injectable, UnauthorizedException } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { readIdentity } from "../../auth.js";
|
||||
|
||||
export type CustomerIdentity = {
|
||||
brandId: string;
|
||||
openid: string;
|
||||
customerUserId: string;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class CustomerAccessService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async require(request: FastifyRequest): Promise<CustomerIdentity> {
|
||||
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 !== "customer") throw new ForbiddenException("客户登录态无效或已过期");
|
||||
const customer = await this.prisma.customerUser.findUnique({
|
||||
where: { brandId_openid: { brandId: identity.brandId, openid: identity.subject } },
|
||||
select: { id: true, tokenVersion: true },
|
||||
});
|
||||
if (!customer || identity.tokenVersion !== customer.tokenVersion)
|
||||
throw new UnauthorizedException("客户登录态无效或已过期");
|
||||
return {
|
||||
brandId: identity.brandId,
|
||||
openid: identity.subject,
|
||||
customerUserId: customer.id,
|
||||
};
|
||||
}
|
||||
|
||||
async logout(request: FastifyRequest): Promise<void> {
|
||||
const identity = await this.require(request);
|
||||
await this.prisma.customerUser.update({
|
||||
where: { id: identity.customerUserId },
|
||||
data: { tokenVersion: { increment: 1 } },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,21 @@
|
||||
import { BadRequestException, Body, Controller, Get, Param, Post, Req } from "@nestjs/common";
|
||||
import { Body, Controller, Get, Param, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { BookingService } from "../../booking.service.js";
|
||||
import { CreateBookingDto } from "../../booking.dto.js";
|
||||
import { readIdentity } from "../../auth.js";
|
||||
import { CustomerAccessService } from "./customer-access.service.js";
|
||||
|
||||
@Controller("customer/bookings")
|
||||
export class CustomerBookingController {
|
||||
constructor(private readonly bookings: BookingService) {}
|
||||
constructor(
|
||||
private readonly bookings: BookingService,
|
||||
private readonly access: CustomerAccessService,
|
||||
) {}
|
||||
|
||||
@Post()
|
||||
async create(@Req() request: FastifyRequest, @Body() body: CreateBookingDto): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const customerId = await this.bookings.requireCustomer(identity);
|
||||
const identity = await this.identity(request);
|
||||
const customerId = identity.customerUserId;
|
||||
return this.bookings.create(identity.brandId, customerId, {
|
||||
...body,
|
||||
extraData: body.extraData as Prisma.InputJsonObject,
|
||||
@@ -21,28 +24,19 @@ export class CustomerBookingController {
|
||||
|
||||
@Get()
|
||||
async list(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const customerId = await this.bookings.requireCustomer(identity);
|
||||
const identity = await this.identity(request);
|
||||
const customerId = identity.customerUserId;
|
||||
return this.bookings.listForCustomer(identity.brandId, customerId);
|
||||
}
|
||||
|
||||
@Post(":id/cancel")
|
||||
async cancel(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const customerId = await this.bookings.requireCustomer(identity);
|
||||
const identity = await this.identity(request);
|
||||
const customerId = identity.customerUserId;
|
||||
return this.bookings.cancelForCustomer(identity.brandId, customerId, id);
|
||||
}
|
||||
|
||||
private identity(request: FastifyRequest): { brandId: string; openid: string } {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (!token) throw new BadRequestException("缺少客户登录态");
|
||||
try {
|
||||
const identity = readIdentity(token);
|
||||
if (identity.role !== "customer") throw new BadRequestException("客户登录态无效");
|
||||
return { brandId: identity.brandId, openid: identity.subject };
|
||||
} catch (error) {
|
||||
if (error instanceof BadRequestException) throw error;
|
||||
throw new BadRequestException("客户登录态无效");
|
||||
}
|
||||
private identity(request: FastifyRequest) {
|
||||
return this.access.require(request);
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,15 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Req,
|
||||
UnauthorizedException,
|
||||
} from "@nestjs/common";
|
||||
import { Body, Controller, Get, Param, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { readIdentity } from "../../auth.js";
|
||||
import { CustomerAccessService } from "./customer-access.service.js";
|
||||
import { CreateInquirySubmissionDto } from "../../booking.dto.js";
|
||||
import { CustomerInquirySubmissionService } from "./customer-inquiry-submission.service.js";
|
||||
|
||||
@Controller("customer/inquiry-submissions")
|
||||
export class CustomerInquirySubmissionController {
|
||||
constructor(private readonly submissions: CustomerInquirySubmissionService) {}
|
||||
constructor(
|
||||
private readonly submissions: CustomerInquirySubmissionService,
|
||||
private readonly access: CustomerAccessService,
|
||||
) {}
|
||||
private present<T extends { customerSubject: string; adminNote?: string | null }>(submission: T) {
|
||||
const {
|
||||
customerSubject: _customerSubject,
|
||||
@@ -26,34 +20,21 @@ export class CustomerInquirySubmissionController {
|
||||
void _adminNote;
|
||||
return publicSubmission;
|
||||
}
|
||||
private identity(request: FastifyRequest): ReturnType<typeof readIdentity> {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (!token) throw new UnauthorizedException("缺少客户登录态");
|
||||
try {
|
||||
const identity = readIdentity(token);
|
||||
if (identity.role !== "customer") throw new ForbiddenException("无客户权限");
|
||||
return identity;
|
||||
} catch (error) {
|
||||
if (error instanceof ForbiddenException) throw error;
|
||||
throw new UnauthorizedException("客户登录态无效或已过期");
|
||||
}
|
||||
private identity(request: FastifyRequest) {
|
||||
return this.access.require(request);
|
||||
}
|
||||
|
||||
@Get()
|
||||
async list(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const submissions = await this.submissions.listForCustomer(identity.brandId, identity.subject);
|
||||
const identity = await this.identity(request);
|
||||
const submissions = await this.submissions.listForCustomer(identity.brandId, identity.openid);
|
||||
return submissions.map((submission) => this.present(submission));
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
async get(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const submission = await this.submissions.getForCustomer(
|
||||
identity.brandId,
|
||||
identity.subject,
|
||||
id,
|
||||
);
|
||||
const identity = await this.identity(request);
|
||||
const submission = await this.submissions.getForCustomer(identity.brandId, identity.openid, id);
|
||||
return this.present(submission);
|
||||
}
|
||||
|
||||
@@ -62,8 +43,8 @@ export class CustomerInquirySubmissionController {
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: CreateInquirySubmissionDto,
|
||||
): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const submission = await this.submissions.create(identity.brandId, identity.subject, body);
|
||||
const identity = await this.identity(request);
|
||||
const submission = await this.submissions.create(identity.brandId, identity.openid, body);
|
||||
return this.present(submission);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Controller, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { CustomerAccessService } from "./customer-access.service.js";
|
||||
|
||||
@Controller("customer/session")
|
||||
export class CustomerSessionController {
|
||||
constructor(private readonly access: CustomerAccessService) {}
|
||||
|
||||
@Post("logout")
|
||||
async logout(@Req() request: FastifyRequest): Promise<{ loggedOut: true }> {
|
||||
await this.access.logout(request);
|
||||
return { loggedOut: true };
|
||||
}
|
||||
}
|
||||
@@ -5,10 +5,16 @@ import { PublicModule } from "../public/public.module.js";
|
||||
import { CustomerBookingController } from "./customer-booking.controller.js";
|
||||
import { CustomerInquirySubmissionController } from "./customer-inquiry-submission.controller.js";
|
||||
import { CustomerInquirySubmissionService } from "./customer-inquiry-submission.service.js";
|
||||
import { CustomerAccessService } from "./customer-access.service.js";
|
||||
import { CustomerSessionController } from "./customer-session.controller.js";
|
||||
|
||||
@Module({
|
||||
imports: [InfrastructureModule, PublicModule, BookingModule],
|
||||
controllers: [CustomerInquirySubmissionController, CustomerBookingController],
|
||||
providers: [CustomerInquirySubmissionService],
|
||||
controllers: [
|
||||
CustomerInquirySubmissionController,
|
||||
CustomerBookingController,
|
||||
CustomerSessionController,
|
||||
],
|
||||
providers: [CustomerInquirySubmissionService, CustomerAccessService],
|
||||
})
|
||||
export class CustomerModule {}
|
||||
@@ -18,13 +18,18 @@ export class CustomerSessionService {
|
||||
select: { id: true },
|
||||
});
|
||||
if (!brand) throw new BadRequestException("品牌尚未初始化");
|
||||
await this.prisma.customerUser.upsert({
|
||||
const customer = await this.prisma.customerUser.upsert({
|
||||
where: { brandId_openid: { brandId: brand.id, openid: session.openid } },
|
||||
update: { lastLoginAt: new Date() },
|
||||
create: { brandId: brand.id, openid: session.openid },
|
||||
});
|
||||
return {
|
||||
token: signIdentity({ subject: session.openid, brandId: brand.id, role: "customer" }),
|
||||
token: signIdentity({
|
||||
subject: session.openid,
|
||||
brandId: brand.id,
|
||||
role: "customer",
|
||||
tokenVersion: customer.tokenVersion,
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,16 @@ export class AdminSessionController {
|
||||
return this.auth.login(body.username, body.password);
|
||||
}
|
||||
|
||||
@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("管理员登录态无效");
|
||||
await this.auth.logout(identity.subject);
|
||||
return { loggedOut: true };
|
||||
}
|
||||
|
||||
@Post("change-password")
|
||||
async changePassword(
|
||||
@Req() request: FastifyRequest,
|
||||
|
||||
@@ -60,7 +60,7 @@ export class TenantController {
|
||||
async switchBrand(
|
||||
@Req() request: FastifyRequest,
|
||||
@Param("brandId") brandId: string,
|
||||
): Promise<{ token: string; brand: unknown }> {
|
||||
): Promise<{ token: string; role: string; brand: unknown }> {
|
||||
const identity = this.adminIdentity(request);
|
||||
return this.tenants.switchBrand(identity, brandId);
|
||||
}
|
||||
|
||||
@@ -113,6 +113,7 @@ export class TenantService {
|
||||
role: "admin",
|
||||
tokenVersion: identity.tokenVersion ?? 0,
|
||||
}),
|
||||
role: membership.role,
|
||||
brand: membership.brand,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -247,6 +247,30 @@ test("模板失败指标仅平台模板管理员可查,按窗口聚合且不
|
||||
await prisma.adminUser.delete({ where: { id: ordinaryUser.id } });
|
||||
}
|
||||
|
||||
const templateAdminWithoutMembership = await prisma.adminUser.create({
|
||||
data: {
|
||||
username: `metrics-platform-${randomUUID()}`,
|
||||
passwordHash: "unused",
|
||||
displayName: "平台模板管理员",
|
||||
platformTemplateRole: "template_admin",
|
||||
mustChangePassword: false,
|
||||
},
|
||||
});
|
||||
try {
|
||||
const response = await request("/admin/template-operations/failures", {
|
||||
headers: {
|
||||
authorization: `Bearer ${signIdentity({
|
||||
subject: templateAdminWithoutMembership.id,
|
||||
brandId: "00000000-0000-0000-0000-000000000000",
|
||||
role: "admin",
|
||||
})}`,
|
||||
},
|
||||
});
|
||||
assert.equal(response.statusCode, 200, response.body);
|
||||
} finally {
|
||||
await prisma.adminUser.delete({ where: { id: templateAdminWithoutMembership.id } });
|
||||
}
|
||||
|
||||
const login = await request("/admin/session/login", {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
@@ -516,7 +540,10 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
|
||||
/所属行业|must match its key/,
|
||||
],
|
||||
[{ ...stored.manifestSnapshot, requiredCapabilities: ["unknown"] }, /未注册的 capability/],
|
||||
[{ ...stored.manifestSnapshot, visualTemplateKey: "unknown" }, /元数据/],
|
||||
[
|
||||
{ ...stored.manifestSnapshot, visualTemplateKey: "unknown" },
|
||||
/visualTemplateKey must match packageKey|元数据/,
|
||||
],
|
||||
[{ ...stored.manifestSnapshot, runtimeContract: "9.0" }, /契约/],
|
||||
[{ ...stored.manifestSnapshot, dataSlots: [null] }, /契约/],
|
||||
[{ ...stored.manifestSnapshot, navigation: [null] }, /契约/],
|
||||
@@ -3868,6 +3895,54 @@ test("admin login validates credentials", async () => {
|
||||
assert.equal(response.statusCode, 401);
|
||||
});
|
||||
|
||||
test("admin logout revokes the current token", async () => {
|
||||
const username = `logout-admin-${randomUUID()}`;
|
||||
const password = "logout-password-123";
|
||||
const user = await prisma.adminUser.create({
|
||||
data: {
|
||||
username,
|
||||
passwordHash: await bcrypt.hash(password, 12),
|
||||
displayName: "登出测试管理员",
|
||||
mustChangePassword: false,
|
||||
},
|
||||
});
|
||||
await prisma.brandMembership.create({
|
||||
data: { brandId, adminUserId: user.id, role: "owner", isEnabled: true },
|
||||
});
|
||||
try {
|
||||
const login = await request("/admin/session/login", {
|
||||
method: "POST",
|
||||
payload: { username, password },
|
||||
});
|
||||
assert.equal(login.statusCode, 201, login.body);
|
||||
const token = JSON.parse(login.body).token;
|
||||
const headers = { authorization: `Bearer ${token}` };
|
||||
const before = await request("/admin/bookings/unread-count", { headers });
|
||||
assert.equal(before.statusCode, 200);
|
||||
|
||||
const logout = await request("/admin/session/logout", { method: "POST", headers });
|
||||
assert.equal(logout.statusCode, 201);
|
||||
const after = await request("/admin/bookings/unread-count", { headers });
|
||||
assert.equal(after.statusCode, 401);
|
||||
} finally {
|
||||
await prisma.adminUser.delete({ where: { id: user.id } });
|
||||
}
|
||||
});
|
||||
|
||||
test("customer logout revokes the current token", async () => {
|
||||
const openid = `logout-${randomUUID()}`;
|
||||
await prisma.customerUser.create({ data: { brandId, openid } });
|
||||
const token = signIdentity({ subject: openid, brandId, role: "customer" });
|
||||
const headers = { authorization: `Bearer ${token}` };
|
||||
const before = await request("/customer/inquiry-submissions", { headers });
|
||||
assert.equal(before.statusCode, 200);
|
||||
|
||||
const logout = await request("/customer/session/logout", { method: "POST", headers });
|
||||
assert.equal(logout.statusCode, 201);
|
||||
const after = await request("/customer/inquiry-submissions", { headers });
|
||||
assert.equal(after.statusCode, 401);
|
||||
});
|
||||
|
||||
test("admin login does not auto-grant ownership to users without memberships", async () => {
|
||||
const username = `no-membership-${Date.now()}`;
|
||||
const user = await prisma.adminUser.create({
|
||||
@@ -4287,7 +4362,7 @@ test("admin can manage trust content", async () => {
|
||||
|
||||
test("customer booking endpoints require a valid customer session", async () => {
|
||||
const missing = await request("/customer/bookings");
|
||||
assert.equal(missing.statusCode, 400);
|
||||
assert.equal(missing.statusCode, 401);
|
||||
|
||||
const list = await request("/customer/bookings", {
|
||||
headers: { authorization: `Bearer ${customerToken}` },
|
||||
@@ -4774,6 +4849,9 @@ test("atelier template imports selected package and preserves draft publication
|
||||
(await json("/public/workspace?brandSlug=" + slug)).brand.visualPresentation.home.title,
|
||||
"仅草稿可见的新标题",
|
||||
);
|
||||
const atelierCustomer = await prisma.customerUser.create({
|
||||
data: { brandId: brand.id, openid: "atelier-test-customer" },
|
||||
});
|
||||
const customerHeaders = {
|
||||
authorization: `Bearer ${signIdentity({ subject: "atelier-test-customer", brandId: brand.id, role: "customer" })}`,
|
||||
};
|
||||
@@ -4819,6 +4897,7 @@ test("atelier template imports selected package and preserves draft publication
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
await prisma.customerUser.deleteMany({ where: { brandId: brand.id } });
|
||||
await prisma.brandProfile.delete({ where: { id: brand.id } });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { createRequire } from "node:module";
|
||||
import test from "node:test";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const png = Buffer.from(
|
||||
"89504e470d0a1a0a0000000d4948445200000001000000010802000000907753de0000000c49444154789c63f8cfc0000003010100c9fe92ef0000000049454e44ae426082",
|
||||
"hex",
|
||||
);
|
||||
|
||||
test("miniprogram-ci compatibility patches keep overridden runtime APIs usable", async () => {
|
||||
const buildCloud = require(
|
||||
require.resolve("miniprogram-ci/dist/modules/nativecompiler/ios/buildCloud.js"),
|
||||
);
|
||||
assert.equal(typeof buildCloud.default, "object");
|
||||
|
||||
const uuid = require("uuid") as { v4: () => string };
|
||||
assert.match(uuid.v4(), /^[0-9a-f-]{36}$/);
|
||||
|
||||
const imageSize = require("image-size") as {
|
||||
imageSize: (input: Buffer) => { width: number; height: number; type: string };
|
||||
};
|
||||
assert.deepEqual(imageSize.imageSize(png), { width: 1, height: 1, type: "png" });
|
||||
|
||||
const Jimp = require("jimp") as {
|
||||
read: (input: Buffer) => Promise<{ bitmap: { width: number; height: number } }>;
|
||||
};
|
||||
const image = await Jimp.read(png);
|
||||
assert.equal(image.bitmap.width, 1);
|
||||
assert.equal(image.bitmap.height, 1);
|
||||
});
|
||||
@@ -45,7 +45,7 @@ async function main() {
|
||||
.filter((entry) => entry.isDirectory() && entry.name !== targetMigration)
|
||||
.map((entry) => entry.name)
|
||||
.sort();
|
||||
assert.equal(migrationDirs.at(-1), "20261018170000_add_admin_token_version");
|
||||
assert.equal(migrationDirs.at(-1), "20261018180000_add_customer_token_version");
|
||||
await admin.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`);
|
||||
createdSchema = true;
|
||||
|
||||
|
||||
@@ -232,12 +232,17 @@ test("导入包预览矩阵展示身份、资源和完整媒体槽位", async ({
|
||||
|
||||
if (evidenceDirectory) {
|
||||
mkdirSync(evidenceDirectory, { recursive: true });
|
||||
await page.screenshot({
|
||||
path: path.join(
|
||||
evidenceDirectory,
|
||||
`${String(sequence).padStart(2, "0")}-${mediaCase.packageKey}-${mediaCase.industry}.png`,
|
||||
),
|
||||
});
|
||||
// 多屏宽证据:320/375/390 均验证实际渲染,而不是只检查 DOM 存在。
|
||||
for (const viewportWidth of [320, 375, 390]) {
|
||||
await page.setViewportSize({ width: viewportWidth, height: 812 });
|
||||
await expect(modal.locator(".component-template-preview")).toBeVisible();
|
||||
await page.screenshot({
|
||||
path: path.join(
|
||||
evidenceDirectory,
|
||||
`${String(sequence).padStart(2, "0")}-${mediaCase.packageKey}-${mediaCase.industry}-${viewportWidth}.png`,
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 清空业务记录后重新打开真实包预览,验证空态不是仅在源码中存在。
|
||||
@@ -249,6 +254,7 @@ test("导入包预览矩阵展示身份、资源和完整媒体槽位", async ({
|
||||
/正在整理中/,
|
||||
);
|
||||
if (evidenceDirectory) {
|
||||
await page.setViewportSize({ width: 375, height: 812 });
|
||||
await page.screenshot({
|
||||
path: path.join(
|
||||
evidenceDirectory,
|
||||
|
||||
Reference in new issue
Block a user