refactor: 收口 Admin 会话与授权边界
This commit is contained in:
1 parent
0788480ce3
commit
4ef4be2071
67 files changed
+1890
-392
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import { ForbiddenException, UnauthorizedException } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { ADMIN_SESSION_COOKIE } from "./admin-session-cookie.js";
|
||||
import { readIdentity } from "./auth.js";
|
||||
|
||||
export type AdminIdentity = {
|
||||
@@ -9,8 +10,14 @@ export type AdminIdentity = {
|
||||
tokenVersion: number;
|
||||
};
|
||||
|
||||
export function readAdminToken(request: FastifyRequest): string | null {
|
||||
const header = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (header) return header;
|
||||
return request.cookies?.[ADMIN_SESSION_COOKIE] ?? null;
|
||||
}
|
||||
|
||||
export function requireAdminIdentity(request: FastifyRequest): AdminIdentity {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
const token = readAdminToken(request);
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
|
||||
let identity;
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
import { ForbiddenException, Injectable, UnauthorizedException } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { PrismaService } from "./prisma.service.js";
|
||||
import { readAdminToken } from "./admin-access.identity.js";
|
||||
import { readIdentity } from "./auth.js";
|
||||
|
||||
@Injectable()
|
||||
export class AdminAccessService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async requireBrand(
|
||||
request: FastifyRequest,
|
||||
): Promise<{ subject: string; brandId: string; role: string }> {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
async requireToken(request: FastifyRequest): Promise<{
|
||||
subject: string;
|
||||
brandId: string;
|
||||
mustChangePassword: boolean;
|
||||
tokenVersion: number;
|
||||
}> {
|
||||
const token = readAdminToken(request);
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
let identity;
|
||||
try {
|
||||
@@ -21,17 +25,30 @@ export class AdminAccessService {
|
||||
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
||||
const user = await this.prisma.adminUser.findUnique({
|
||||
where: { id: identity.subject },
|
||||
select: { mustChangePassword: true, isEnabled: true, tokenVersion: true },
|
||||
select: { isEnabled: true, mustChangePassword: true, tokenVersion: true },
|
||||
});
|
||||
if (!user || identity.tokenVersion !== user.tokenVersion)
|
||||
throw new UnauthorizedException("管理员登录态已失效,请重新登录");
|
||||
if (!user.isEnabled || user.mustChangePassword)
|
||||
if (!user.isEnabled) throw new ForbiddenException("管理员账号已停用");
|
||||
return {
|
||||
subject: identity.subject,
|
||||
brandId: identity.brandId,
|
||||
mustChangePassword: user.mustChangePassword,
|
||||
tokenVersion: user.tokenVersion,
|
||||
};
|
||||
}
|
||||
|
||||
async requireBrand(
|
||||
request: FastifyRequest,
|
||||
): Promise<{ subject: string; brandId: string; role: string }> {
|
||||
const access = await this.requireToken(request);
|
||||
if (access.mustChangePassword)
|
||||
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
|
||||
const membership = await this.prisma.brandMembership.findUnique({
|
||||
where: { adminUserId_brandId: { adminUserId: identity.subject, brandId: identity.brandId } },
|
||||
where: { adminUserId_brandId: { adminUserId: access.subject, brandId: access.brandId } },
|
||||
});
|
||||
if (!membership?.isEnabled) throw new ForbiddenException("管理员没有当前品牌权限");
|
||||
return { subject: identity.subject, brandId: identity.brandId, role: membership.role };
|
||||
return { subject: access.subject, brandId: access.brandId, role: membership.role };
|
||||
}
|
||||
|
||||
async requireRole(request: FastifyRequest, allowedRoles: string[]): Promise<boolean> {
|
||||
@@ -43,30 +60,15 @@ export class AdminAccessService {
|
||||
}
|
||||
|
||||
async requireTemplateAdmin(request: FastifyRequest): Promise<{ subject: string }> {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
let identity;
|
||||
try {
|
||||
identity = readIdentity(token);
|
||||
} catch {
|
||||
throw new UnauthorizedException("管理员登录态无效或已过期");
|
||||
}
|
||||
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
||||
const user = await this.prisma.adminUser.findUnique({
|
||||
where: { id: identity.subject },
|
||||
select: {
|
||||
isEnabled: true,
|
||||
mustChangePassword: true,
|
||||
platformTemplateRole: true,
|
||||
tokenVersion: true,
|
||||
},
|
||||
});
|
||||
if (!user || identity.tokenVersion !== user.tokenVersion)
|
||||
throw new UnauthorizedException("管理员登录态已失效,请重新登录");
|
||||
if (!user.isEnabled || user.mustChangePassword)
|
||||
const access = await this.requireToken(request);
|
||||
if (access.mustChangePassword)
|
||||
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
|
||||
const user = await this.prisma.adminUser.findUniqueOrThrow({
|
||||
where: { id: access.subject },
|
||||
select: { platformTemplateRole: true },
|
||||
});
|
||||
if (user.platformTemplateRole !== "template_admin")
|
||||
throw new ForbiddenException("当前账号没有模板管理权限");
|
||||
return { subject: identity.subject };
|
||||
return { subject: access.subject };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import "reflect-metadata";
|
||||
|
||||
export const ADMIN_AUTH_METADATA = "admin-auth";
|
||||
|
||||
export type AdminAuthMetadata =
|
||||
| { type: "public" }
|
||||
| { type: "token" }
|
||||
| { type: "brand" }
|
||||
| { type: "roles"; roles: string[] }
|
||||
| { type: "template-admin" };
|
||||
|
||||
function adminAuth(metadata: AdminAuthMetadata): ClassDecorator & MethodDecorator {
|
||||
const decorator = ((
|
||||
target: object,
|
||||
propertyKey?: PropertyKey,
|
||||
descriptor?: PropertyDescriptor,
|
||||
) => {
|
||||
// Nest 在 guard 中读取 handler function 的元数据;method decorator 必须写入 descriptor.value。
|
||||
const metadataTarget =
|
||||
propertyKey === undefined ? target : (descriptor?.value as object | undefined);
|
||||
if (metadataTarget) {
|
||||
Reflect.defineMetadata(ADMIN_AUTH_METADATA, metadata, metadataTarget);
|
||||
}
|
||||
}) as ClassDecorator & MethodDecorator;
|
||||
|
||||
return decorator;
|
||||
}
|
||||
|
||||
export const AdminPublic = (): ClassDecorator & MethodDecorator => adminAuth({ type: "public" });
|
||||
|
||||
export const AdminTokenOnly = (): ClassDecorator & MethodDecorator => adminAuth({ type: "token" });
|
||||
|
||||
export const AdminBrand = (): ClassDecorator & MethodDecorator => adminAuth({ type: "brand" });
|
||||
|
||||
export const AdminRoles = (roles: string[]): ClassDecorator & MethodDecorator =>
|
||||
adminAuth({ type: "roles", roles });
|
||||
|
||||
export const AdminTemplateAdmin = (): ClassDecorator & MethodDecorator =>
|
||||
adminAuth({ type: "template-admin" });
|
||||
@@ -1,22 +1,30 @@
|
||||
import { ForbiddenException, Injectable, UnauthorizedException } from "@nestjs/common";
|
||||
import bcrypt from "bcryptjs";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "./admin-access.service.js";
|
||||
import { PrismaService } from "./prisma.service.js";
|
||||
import { signIdentity } from "./auth.js";
|
||||
|
||||
export type AdminLoginSession = {
|
||||
displayName: string;
|
||||
role: string;
|
||||
platformTemplateRole: "none" | "template_admin";
|
||||
mustChangePassword: boolean;
|
||||
};
|
||||
|
||||
export type AdminCurrentSession = AdminLoginSession & { authenticated: true };
|
||||
|
||||
@Injectable()
|
||||
export class AdminAuthService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly access: AdminAccessService,
|
||||
) {}
|
||||
|
||||
async login(
|
||||
username: string,
|
||||
password: string,
|
||||
): Promise<{
|
||||
token: string;
|
||||
displayName: string;
|
||||
mustChangePassword: boolean;
|
||||
role: string;
|
||||
platformTemplateRole: string;
|
||||
}> {
|
||||
): Promise<{ session: AdminLoginSession; token: string }> {
|
||||
const user = await this.prisma.adminUser.findUnique({ where: { username } });
|
||||
if (!user || !user.isEnabled || !(await bcrypt.compare(password, user.passwordHash))) {
|
||||
throw new UnauthorizedException("账号或密码错误");
|
||||
@@ -31,16 +39,37 @@ export class AdminAuthService {
|
||||
});
|
||||
if (!membership) throw new ForbiddenException("管理员没有品牌权限,请先联系平台负责人分配");
|
||||
return {
|
||||
session: {
|
||||
displayName: user.displayName,
|
||||
mustChangePassword: user.mustChangePassword,
|
||||
role: membership.role,
|
||||
platformTemplateRole: user.platformTemplateRole,
|
||||
},
|
||||
token: signIdentity({
|
||||
subject: user.id,
|
||||
brandId: membership.brandId,
|
||||
role: "admin",
|
||||
tokenVersion: user.tokenVersion,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
async currentSession(request: FastifyRequest): Promise<AdminCurrentSession> {
|
||||
const access = await this.access.requireBrand(request);
|
||||
const user = await this.prisma.adminUser.findUniqueOrThrow({
|
||||
where: { id: access.subject },
|
||||
select: {
|
||||
displayName: true,
|
||||
mustChangePassword: true,
|
||||
platformTemplateRole: true,
|
||||
},
|
||||
});
|
||||
return {
|
||||
authenticated: true,
|
||||
displayName: user.displayName,
|
||||
mustChangePassword: user.mustChangePassword,
|
||||
role: membership.role,
|
||||
platformTemplateRole: user.platformTemplateRole,
|
||||
role: access.role,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -55,20 +84,30 @@ export class AdminAuthService {
|
||||
|
||||
async changePassword(
|
||||
userId: string,
|
||||
brandId: string,
|
||||
currentPassword: string,
|
||||
newPassword: string,
|
||||
): Promise<void> {
|
||||
): Promise<{ token: string }> {
|
||||
const user = await this.prisma.adminUser.findUnique({ where: { id: userId } });
|
||||
if (!user?.isEnabled || !(await bcrypt.compare(currentPassword, user.passwordHash))) {
|
||||
throw new UnauthorizedException("当前密码不正确");
|
||||
}
|
||||
await this.prisma.adminUser.update({
|
||||
const updated = await this.prisma.adminUser.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
passwordHash: await bcrypt.hash(newPassword, 12),
|
||||
mustChangePassword: false,
|
||||
tokenVersion: { increment: 1 },
|
||||
},
|
||||
select: { tokenVersion: true },
|
||||
});
|
||||
return {
|
||||
token: signIdentity({
|
||||
subject: user.id,
|
||||
brandId,
|
||||
role: "admin",
|
||||
tokenVersion: updated.tokenVersion,
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,43 +1,40 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { Reflector } from "@nestjs/core";
|
||||
import type { CanActivate, ExecutionContext } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { ADMIN_AUTH_METADATA, type AdminAuthMetadata } from "./admin-auth.decorators.js";
|
||||
import { AdminAccessService } from "./admin-access.service.js";
|
||||
|
||||
const PATH_METADATA = "path";
|
||||
|
||||
function metadataPath(target: object): string | undefined {
|
||||
const value = Reflect.getMetadata(PATH_METADATA, target) as unknown;
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdminMembershipGuard implements CanActivate {
|
||||
constructor(private readonly access: AdminAccessService) {}
|
||||
constructor(
|
||||
private readonly access: AdminAccessService,
|
||||
private readonly reflector: Reflector,
|
||||
) {}
|
||||
|
||||
canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const metadata = this.reflector.getAllAndOverride<AdminAuthMetadata | undefined>(
|
||||
ADMIN_AUTH_METADATA,
|
||||
[context.getHandler(), context.getClass()],
|
||||
);
|
||||
if (!metadata) return true;
|
||||
const request = context.switchToHttp().getRequest<FastifyRequest>();
|
||||
const handlerPath = metadataPath(context.getHandler());
|
||||
const controllerPath = metadataPath(context.getClass());
|
||||
const routePath = `${controllerPath ?? ""}/${handlerPath ?? ""}`.replace(/^\/+|\/+$/g, "");
|
||||
if (routePath === "admin/session/login") return Promise.resolve(true);
|
||||
if (routePath === "admin/session/change-password") return Promise.resolve(true);
|
||||
if (!routePath.startsWith("admin/")) return Promise.resolve(true);
|
||||
if (
|
||||
routePath === "admin/templates" ||
|
||||
routePath.startsWith("admin/templates/") ||
|
||||
routePath === "admin/template-operations" ||
|
||||
routePath.startsWith("admin/template-operations/")
|
||||
) {
|
||||
return this.access.requireTemplateAdmin(request).then(() => true);
|
||||
|
||||
switch (metadata.type) {
|
||||
case "public":
|
||||
return true;
|
||||
case "token":
|
||||
await this.access.requireToken(request);
|
||||
return true;
|
||||
case "roles":
|
||||
await this.access.requireRole(request, metadata.roles);
|
||||
return true;
|
||||
case "template-admin":
|
||||
await this.access.requireTemplateAdmin(request);
|
||||
return true;
|
||||
case "brand":
|
||||
await this.access.requireBrand(request);
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
/^admin\/workspace\/(install|capabilities(?:\/|$)|template(?:\/|$)|fields(?:\/|$))/.test(
|
||||
routePath,
|
||||
) ||
|
||||
/^admin\/config\/visual-template(?:\/|$)/.test(routePath)
|
||||
) {
|
||||
return this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
}
|
||||
return this.access.requireBrand(request).then(() => true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { FastifyReply } from "fastify";
|
||||
|
||||
export const ADMIN_SESSION_COOKIE = "admin_session";
|
||||
const ADMIN_SESSION_MAX_AGE_SECONDS = 60 * 60 * 24 * 7;
|
||||
|
||||
export function setAdminSessionCookie(reply: FastifyReply, token: string): void {
|
||||
reply.setCookie(ADMIN_SESSION_COOKIE, token, {
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
sameSite: "strict",
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
maxAge: ADMIN_SESSION_MAX_AGE_SECONDS,
|
||||
});
|
||||
}
|
||||
|
||||
export function clearAdminSessionCookie(reply: FastifyReply): void {
|
||||
reply.clearCookie(ADMIN_SESSION_COOKIE, {
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
sameSite: "strict",
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
});
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import "reflect-metadata";
|
||||
import { Module, ValidationPipe } from "@nestjs/common";
|
||||
import { APP_GUARD } from "@nestjs/core";
|
||||
import type { NestFastifyApplication } from "@nestjs/platform-fastify";
|
||||
import cookiePlugin from "@fastify/cookie";
|
||||
import { ApiExceptionFilter, RequestIdMiddleware } from "./http.js";
|
||||
import { AdminMembershipGuard } from "./admin-membership.guard.js";
|
||||
import { AdminModule } from "./modules/admin/admin.module.js";
|
||||
@@ -28,13 +29,14 @@ import { WorkspaceModule } from "./modules/workspace/workspace.module.js";
|
||||
})
|
||||
export class AppModule {}
|
||||
|
||||
export function configureApp(app: NestFastifyApplication): void {
|
||||
export async function configureApp(app: NestFastifyApplication): Promise<void> {
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }),
|
||||
);
|
||||
app.useGlobalFilters(new ApiExceptionFilter());
|
||||
const apiPrefix = process.env.API_PREFIX?.replace(/^\/+|\/+$/g, "");
|
||||
if (apiPrefix) app.setGlobalPrefix(apiPrefix);
|
||||
await app.register(cookiePlugin);
|
||||
app.use(new RequestIdMiddleware().use.bind(new RequestIdMiddleware()));
|
||||
const corsOrigins = (process.env.CORS_ORIGINS ?? "")
|
||||
.split(",")
|
||||
|
||||
@@ -26,7 +26,7 @@ export async function createApp(): Promise<NestFastifyApplication> {
|
||||
decorateReply: false,
|
||||
});
|
||||
}
|
||||
configureApp(app);
|
||||
await configureApp(app);
|
||||
return app;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AdminBrand } from "../../admin-auth.decorators.js";
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
@@ -31,6 +32,7 @@ class AdminBookingQueryDto {
|
||||
@IsOptional() @IsString() tagId?: string;
|
||||
}
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/bookings")
|
||||
export class AdminBookingController {
|
||||
constructor(private readonly bookings: BookingService) {}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AdminBrand } from "../../admin-auth.decorators.js";
|
||||
import { Body, Controller, Delete, Get, Param, Patch, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import {
|
||||
@@ -10,6 +11,7 @@ import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||
import { AdminBrandConfigService } from "./admin-brand-config.service.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/config")
|
||||
export class AdminConfigController {
|
||||
constructor(
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { AdminBrand } from "../../admin-auth.decorators.js";
|
||||
import { Controller, Put, Query, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { AdminUploadService } from "./admin-upload.service.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/uploads")
|
||||
export class AdminLocalUploadController {
|
||||
constructor(
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
|
||||
import { Body, Controller, Get, Param, Patch, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
@@ -13,6 +14,7 @@ import {
|
||||
|
||||
type AdminIdentity = { subject: string; brandId: string };
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/miniapp-releases")
|
||||
export class AdminMiniAppReleaseController {
|
||||
constructor(
|
||||
@@ -34,13 +36,13 @@ export class AdminMiniAppReleaseController {
|
||||
return this.settingsService.get(identity.brandId);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Patch("settings")
|
||||
async updateSettings(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: UpdateMiniAppSettingsDto & { privateKey?: string },
|
||||
@Body() body: UpdateMiniAppSettingsDto,
|
||||
): Promise<unknown> {
|
||||
const identity = await this.identity(request);
|
||||
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
return this.settingsService.update(identity.brandId, body);
|
||||
}
|
||||
|
||||
|
||||
@@ -16,5 +16,6 @@ export class UpdateMiniAppSettingsDto {
|
||||
build?: Record<string, unknown>;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
privateKey?: string;
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { AdminBrand } from "../../admin-auth.decorators.js";
|
||||
import { Controller, Get, Param, ParseIntPipe, Post, Body, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { BrandReleaseApiService } from "../../brand-release-api.service.js";
|
||||
import { PublishBrandReleaseDto } from "../../release.dto.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/releases")
|
||||
export class AdminReleaseController {
|
||||
constructor(
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AdminTemplateAdmin } from "../../admin-auth.decorators.js";
|
||||
import { Controller, Get, Param, Post, Query, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
@@ -9,6 +10,7 @@ import { AdminTemplatePackageService } from "./admin-template-package.service.js
|
||||
|
||||
import { AdminTemplatePreviewService } from "./admin-template-preview.service.js";
|
||||
|
||||
@AdminTemplateAdmin()
|
||||
@Controller("admin/templates")
|
||||
export class AdminTemplatePackageController {
|
||||
constructor(
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { AdminBrand } from "../../admin-auth.decorators.js";
|
||||
import { Body, Controller, Get, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { PresignUploadDto } from "./admin-upload.dto.js";
|
||||
import { AdminUploadService } from "./admin-upload.service.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/uploads")
|
||||
export class AdminUploadController {
|
||||
constructor(
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AdminTemplateAdmin } from "../../admin-auth.decorators.js";
|
||||
import { Controller, Get, Query, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { Type } from "class-transformer";
|
||||
@@ -14,6 +15,7 @@ class TemplateOperationMetricsQueryDto {
|
||||
days = 30;
|
||||
}
|
||||
|
||||
@AdminTemplateAdmin()
|
||||
@Controller("admin/template-operations")
|
||||
export class TemplateOperationMetricsController {
|
||||
constructor(
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { Body, Controller, Post, Query, Req, UnauthorizedException } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { Body, Controller, Get, Post, Query, Req, Res } from "@nestjs/common";
|
||||
import type { FastifyReply, FastifyRequest } from "fastify";
|
||||
import { WechatAuthService } from "../../wechat-auth.js";
|
||||
import { AdminBrand, AdminPublic, AdminTokenOnly } from "../../admin-auth.decorators.js";
|
||||
import { clearAdminSessionCookie, setAdminSessionCookie } from "../../admin-session-cookie.js";
|
||||
import { AdminAuthService } from "../../admin-auth.service.js";
|
||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||
import { AdminLoginDto, WechatLoginDto } from "../../admin-auth.dto.js";
|
||||
import { CustomerSessionService } from "./customer-session.service.js";
|
||||
import { ChangeAdminPasswordDto } from "../../admin.dto.js";
|
||||
import { readIdentity } from "../../auth.js";
|
||||
|
||||
@Controller("customer/session")
|
||||
export class CustomerSessionController {
|
||||
@@ -28,37 +30,55 @@ export class CustomerSessionController {
|
||||
export class AdminSessionController {
|
||||
constructor(private readonly auth: AdminAuthService) {}
|
||||
|
||||
@AdminPublic()
|
||||
@Post("login")
|
||||
login(@Body() body: AdminLoginDto): Promise<{
|
||||
token: string;
|
||||
async login(
|
||||
@Body() body: AdminLoginDto,
|
||||
@Res({ passthrough: true }) reply: FastifyReply,
|
||||
): Promise<{
|
||||
displayName: string;
|
||||
mustChangePassword: boolean;
|
||||
role: string;
|
||||
platformTemplateRole: string;
|
||||
platformTemplateRole: "none" | "template_admin";
|
||||
}> {
|
||||
return this.auth.login(body.username, body.password);
|
||||
const { session, token } = await this.auth.login(body.username, body.password);
|
||||
setAdminSessionCookie(reply, token);
|
||||
return session;
|
||||
}
|
||||
|
||||
@AdminBrand()
|
||||
@Get("current")
|
||||
async current(@Req() request: FastifyRequest) {
|
||||
return this.auth.currentSession(request);
|
||||
}
|
||||
|
||||
@AdminTokenOnly()
|
||||
@Post("logout")
|
||||
async logout(@Req() request: FastifyRequest): Promise<{ loggedOut: true }> {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
const identity = readIdentity(token);
|
||||
if (identity.role !== "admin") throw new UnauthorizedException("管理员登录态无效");
|
||||
async logout(
|
||||
@Req() request: FastifyRequest,
|
||||
@Res({ passthrough: true }) reply: FastifyReply,
|
||||
): Promise<{ loggedOut: true }> {
|
||||
const identity = requireAdminIdentity(request);
|
||||
await this.auth.logout(identity.subject);
|
||||
clearAdminSessionCookie(reply);
|
||||
return { loggedOut: true };
|
||||
}
|
||||
|
||||
@AdminTokenOnly()
|
||||
@Post("change-password")
|
||||
async changePassword(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: ChangeAdminPasswordDto,
|
||||
@Res({ passthrough: true }) reply: FastifyReply,
|
||||
): Promise<{ changed: true }> {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
const identity = readIdentity(token);
|
||||
if (identity.role !== "admin") throw new UnauthorizedException("管理员登录态无效");
|
||||
await this.auth.changePassword(identity.subject, body.currentPassword, body.newPassword);
|
||||
const identity = requireAdminIdentity(request);
|
||||
const { token } = await this.auth.changePassword(
|
||||
identity.subject,
|
||||
identity.brandId,
|
||||
body.currentPassword,
|
||||
body.newPassword,
|
||||
);
|
||||
setAdminSessionCookie(reply, token);
|
||||
return { changed: true };
|
||||
}
|
||||
}
|
||||
@@ -1,41 +1,40 @@
|
||||
import { Body, Controller, Get, Param, Patch, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
|
||||
import { Body, Controller, Get, Param, Patch, Post, Req, Res } from "@nestjs/common";
|
||||
import type { FastifyReply, FastifyRequest } from "fastify";
|
||||
import { setAdminSessionCookie } from "../../admin-session-cookie.js";
|
||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||
import { CreateBrandMemberDto, UpdateBrandMemberDto } from "../../admin.dto.js";
|
||||
import { TenantService } from "./tenant.service.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/brands")
|
||||
export class TenantController {
|
||||
constructor(
|
||||
private readonly access: AdminAccessService,
|
||||
private readonly tenants: TenantService,
|
||||
) {}
|
||||
constructor(private readonly tenants: TenantService) {}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Get("members")
|
||||
async listMembers(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
const current = this.adminIdentity(request);
|
||||
return this.tenants.listMembers(current.brandId);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Post("members")
|
||||
async createMember(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: CreateBrandMemberDto,
|
||||
): Promise<unknown> {
|
||||
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
const actor = this.adminIdentity(request);
|
||||
return this.tenants.createMember(actor.brandId, body);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Patch("members/:id")
|
||||
async updateMember(
|
||||
@Req() request: FastifyRequest,
|
||||
@Param("id") id: string,
|
||||
@Body() body: UpdateBrandMemberDto,
|
||||
): Promise<unknown> {
|
||||
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
const actor = this.adminIdentity(request);
|
||||
return this.tenants.updateMember(actor.brandId, actor.subject, id, body);
|
||||
}
|
||||
@@ -50,9 +49,12 @@ export class TenantController {
|
||||
async switchBrand(
|
||||
@Req() request: FastifyRequest,
|
||||
@Param("brandId") brandId: string,
|
||||
): Promise<{ token: string; role: string; brand: unknown }> {
|
||||
@Res({ passthrough: true }) reply: FastifyReply,
|
||||
): Promise<{ role: string; brand: unknown }> {
|
||||
const identity = this.adminIdentity(request);
|
||||
return this.tenants.switchBrand(identity, brandId);
|
||||
const result = await this.tenants.switchBrand(identity, brandId);
|
||||
setAdminSessionCookie(reply, result.token);
|
||||
return { role: result.role, brand: result.brand };
|
||||
}
|
||||
|
||||
private adminIdentity(request: FastifyRequest) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
|
||||
import { Body, Controller, Get, Param, Patch, Post, Query, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import {
|
||||
@@ -9,6 +10,7 @@ import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||
import { AdminSampleContentService } from "./admin-sample-content.service.js";
|
||||
import { AdminWorkspaceCapabilitiesService } from "./admin-workspace-capabilities.service.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/workspace")
|
||||
class AdminCapabilityController {
|
||||
constructor(
|
||||
@@ -16,6 +18,7 @@ class AdminCapabilityController {
|
||||
private readonly sampleContentService: AdminSampleContentService,
|
||||
) {}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Get("capabilities")
|
||||
list(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
return this.capabilitiesService.list(requireAdminIdentity(request).brandId);
|
||||
@@ -38,6 +41,7 @@ class AdminCapabilityController {
|
||||
return this.sampleContentService.import(identity.brandId, identity.subject, body);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Patch("capabilities/:key")
|
||||
update(
|
||||
@Req() request: FastifyRequest,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
|
||||
import { Body, Controller, Delete, Get, Param, Patch, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import {
|
||||
@@ -10,10 +11,12 @@ import {
|
||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||
import { AdminInquiryService } from "./admin-inquiry.service.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/workspace")
|
||||
class AdminInquiryController {
|
||||
constructor(private readonly inquiryService: AdminInquiryService) {}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Post("fields")
|
||||
createField(
|
||||
@Req() request: FastifyRequest,
|
||||
@@ -22,6 +25,7 @@ class AdminInquiryController {
|
||||
return this.inquiryService.createField(requireAdminIdentity(request).brandId, body);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Patch("fields/:id")
|
||||
async updateField(
|
||||
@Req() request: FastifyRequest,
|
||||
@@ -31,6 +35,7 @@ class AdminInquiryController {
|
||||
return this.inquiryService.updateField(requireAdminIdentity(request).brandId, id, body);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Delete("fields/:id")
|
||||
async deleteField(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||
return this.inquiryService.deleteField(requireAdminIdentity(request).brandId, id);
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { Body, Controller, Delete, Get, Param, Patch, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminBrand } from "../../admin-auth.decorators.js";
|
||||
import { CreateOfferingDto, UpdateOfferingDto } from "../../admin.dto.js";
|
||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||
import { AdminOfferingService } from "./admin-offering.service.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/workspace")
|
||||
class AdminOfferingController {
|
||||
constructor(private readonly offeringService: AdminOfferingService) {}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
|
||||
import { Body, Controller, Get, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { RollbackTemplateDto, UpgradeTemplateDto } from "../../admin.dto.js";
|
||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/workspace")
|
||||
class AdminTemplateController {
|
||||
constructor(private readonly templateWorkspace: TemplateWorkspaceService) {}
|
||||
@@ -13,6 +15,7 @@ class AdminTemplateController {
|
||||
return this.templateWorkspace.preview(requireAdminIdentity(request).brandId);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Post("template/upgrade")
|
||||
async upgrade(
|
||||
@Req() request: FastifyRequest,
|
||||
@@ -23,6 +26,7 @@ class AdminTemplateController {
|
||||
return this.templateWorkspace.upgrade(identity.brandId, body, identity.subject, requestId);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Post("template/rollback")
|
||||
async rollback(
|
||||
@Req() request: FastifyRequest,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
|
||||
import { Controller, Get, Post, Body, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { InstallTemplateDto, SelectTemplateVersionDto } from "../../admin.dto.js";
|
||||
@@ -5,6 +6,7 @@ import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||
import { AdminWorkspaceService } from "./admin-workspace.service.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/workspace")
|
||||
class AdminWorkspacePreviewController {
|
||||
constructor(
|
||||
@@ -22,6 +24,7 @@ class AdminWorkspacePreviewController {
|
||||
return this.workspaceService.getPreview(requireAdminIdentity(request).brandId);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Post("install")
|
||||
async install(
|
||||
@Req() request: FastifyRequest,
|
||||
@@ -38,6 +41,7 @@ class AdminWorkspacePreviewController {
|
||||
);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Post("template/select-version")
|
||||
async selectVersion(
|
||||
@Req() request: FastifyRequest,
|
||||
|
||||
Reference in new issue
Block a user