feat: add admin accounts and image templates
This commit is contained in:
51
app/api/admin/accounts/groups/route.ts
Normal file
51
app/api/admin/accounts/groups/route.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { jsonError, jsonOk, readJsonBody } from "@/lib/server/api";
|
||||
import { requireAdminSession } from "@/lib/server/auth/current-user";
|
||||
import {
|
||||
createOrganizationGroup,
|
||||
getOrganizationApiConfig,
|
||||
listOrganizationGroups
|
||||
} from "@/lib/server/organization-client";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const session = await requireAdminSession();
|
||||
const context = { accessToken: session.accessToken };
|
||||
const config = getOrganizationApiConfig(context.accessToken);
|
||||
if (!config.configured) {
|
||||
throw Object.assign(new Error(`组织接口配置不完整:${config.missing.join(", ")}`), { status: 503 });
|
||||
}
|
||||
const body = await readJsonBody<Record<string, unknown>>(request);
|
||||
const organizationId = requiredString(body, "organizationId", "组织");
|
||||
const groupName = requiredString(body, "groupName", "部门名称");
|
||||
await createOrganizationGroup({
|
||||
organizationId,
|
||||
groupName,
|
||||
groupDesc: optionalString(body.groupDesc),
|
||||
parentId: optionalString(body.parentId)
|
||||
}, context);
|
||||
const groups = await listOrganizationGroups(organizationId, context);
|
||||
const group = groups.find((item) => item.groupName === groupName) || null;
|
||||
return jsonOk({ ok: true, group, groups });
|
||||
} catch (error) {
|
||||
return jsonError(error, 500, { request, source: "api.admin.accounts.groups", logClientErrors: true });
|
||||
}
|
||||
}
|
||||
|
||||
function requiredString(body: Record<string, unknown>, key: string, label: string): string {
|
||||
const value = optionalString(body[key]);
|
||||
if (!value) throw badRequest(`${label}不能为空。`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function optionalString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
||||
}
|
||||
|
||||
function badRequest(message: string): Error & { status: number } {
|
||||
const error = new Error(message) as Error & { status: number };
|
||||
error.status = 400;
|
||||
return error;
|
||||
}
|
||||
60
app/api/admin/accounts/password/route.ts
Normal file
60
app/api/admin/accounts/password/route.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { jsonError, jsonOk, readJsonBody } from "@/lib/server/api";
|
||||
import { requireAdminSession } from "@/lib/server/auth/current-user";
|
||||
import { getOrganizationApiConfig, resetPlatformUserPassword } from "@/lib/server/organization-client";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const session = await requireAdminSession();
|
||||
const context = { accessToken: session.accessToken };
|
||||
const config = getOrganizationApiConfig(context.accessToken);
|
||||
if (!config.staffConfigured) {
|
||||
throw Object.assign(new Error(`企业端用户接口配置不完整:${config.staffMissing.join(", ")}`), { status: 503 });
|
||||
}
|
||||
const body = await readJsonBody<Record<string, unknown>>(request);
|
||||
await resetPlatformUserPassword({
|
||||
tenantId: tenantIdNumber(config.tenantId),
|
||||
userId: requiredNumber(body.userId, "用户 ID"),
|
||||
newPassword: requiredString(body, "newPassword", "新密码"),
|
||||
mustChangePassword: booleanValue(body.mustChangePassword, true)
|
||||
}, context);
|
||||
return jsonOk({ ok: true });
|
||||
} catch (error) {
|
||||
return jsonError(error, 500, { request, source: "api.admin.accounts.password", logClientErrors: true });
|
||||
}
|
||||
}
|
||||
|
||||
function requiredString(body: Record<string, unknown>, key: string, label: string): string {
|
||||
const value = body[key];
|
||||
if (typeof value === "string" && value.trim()) return value.trim();
|
||||
throw badRequest(`${label}不能为空。`);
|
||||
}
|
||||
|
||||
function requiredNumber(value: unknown, label: string): number {
|
||||
const parsed = typeof value === "number" ? value : Number(value);
|
||||
if (Number.isFinite(parsed)) return parsed;
|
||||
throw badRequest(`${label}必须是数字。`);
|
||||
}
|
||||
|
||||
function tenantIdNumber(value: string): number {
|
||||
const tenantId = Number(value);
|
||||
if (!Number.isFinite(tenantId)) throw badRequest("租户 ID 必须是数字。");
|
||||
return tenantId;
|
||||
}
|
||||
|
||||
function booleanValue(value: unknown, fallback: boolean): boolean {
|
||||
if (typeof value === "boolean") return value;
|
||||
if (typeof value === "string") {
|
||||
if (value === "true") return true;
|
||||
if (value === "false") return false;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function badRequest(message: string): Error & { status: number } {
|
||||
const error = new Error(message) as Error & { status: number };
|
||||
error.status = 400;
|
||||
return error;
|
||||
}
|
||||
266
app/api/admin/accounts/route.ts
Normal file
266
app/api/admin/accounts/route.ts
Normal file
@@ -0,0 +1,266 @@
|
||||
import { jsonError, jsonOk, readJsonBody } from "@/lib/server/api";
|
||||
import { requireAdminSession } from "@/lib/server/auth/current-user";
|
||||
import {
|
||||
addOrganizationMemberAndCreatePlatformUser,
|
||||
emptyPage,
|
||||
getOrganizationApiConfig,
|
||||
isOrganizationPermissionDenied,
|
||||
isOrganizationRouteNotFound,
|
||||
listOrganizationGroups,
|
||||
listOrganizationMembers,
|
||||
listOrganizationRoles,
|
||||
listOrganizations,
|
||||
modifyOrganizationMemberStatus,
|
||||
removeOrganizationMember,
|
||||
updateOrganizationMember
|
||||
} from "@/lib/server/organization-client";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const session = await requireAdminSession();
|
||||
const context = { accessToken: session.accessToken };
|
||||
const config = getOrganizationApiConfig(context.accessToken);
|
||||
const url = new URL(request.url);
|
||||
const pageNum = positiveInteger(url.searchParams.get("pageNum"), 1);
|
||||
const pageSize = positiveInteger(url.searchParams.get("pageSize"), 10, 50);
|
||||
|
||||
if (!config.configured) {
|
||||
return jsonOk({
|
||||
configured: false,
|
||||
missing: config.missing,
|
||||
staffConfigured: config.staffConfigured,
|
||||
staffMissing: config.staffMissing,
|
||||
selectedOrganizationId: config.defaultOrganizationId,
|
||||
organizations: [],
|
||||
groups: [],
|
||||
roles: [],
|
||||
members: emptyPage(pageNum, pageSize),
|
||||
warnings: [],
|
||||
memberListAvailable: false,
|
||||
passwordManagementAvailable: config.staffConfigured
|
||||
});
|
||||
}
|
||||
|
||||
const warnings: string[] = [];
|
||||
let organizations: Awaited<ReturnType<typeof listOrganizations>> = [];
|
||||
try {
|
||||
organizations = await listOrganizations(context);
|
||||
} catch (error) {
|
||||
if (!isOrganizationRouteNotFound(error) || !config.defaultOrganizationId) throw error;
|
||||
warnings.push(error.message);
|
||||
organizations = [{
|
||||
organizationId: config.defaultOrganizationId,
|
||||
organizationName: config.defaultOrganizationId
|
||||
}];
|
||||
}
|
||||
const selectedOrganizationId = url.searchParams.get("organizationId")?.trim() ||
|
||||
config.defaultOrganizationId ||
|
||||
organizations[0]?.organizationId ||
|
||||
"";
|
||||
|
||||
if (!selectedOrganizationId) {
|
||||
return jsonOk({
|
||||
configured: true,
|
||||
missing: [],
|
||||
staffConfigured: config.staffConfigured,
|
||||
staffMissing: config.staffMissing,
|
||||
selectedOrganizationId: "",
|
||||
organizations,
|
||||
groups: [],
|
||||
roles: [],
|
||||
members: emptyPage(pageNum, pageSize),
|
||||
warnings: uniqueWarnings(warnings),
|
||||
memberListAvailable: false,
|
||||
passwordManagementAvailable: config.staffConfigured
|
||||
});
|
||||
}
|
||||
|
||||
const [groupsResult, rolesResult, membersResult] = await Promise.allSettled([
|
||||
listOrganizationGroups(selectedOrganizationId, context),
|
||||
listOrganizationRoles(selectedOrganizationId, context),
|
||||
listOrganizationMembers({
|
||||
organizationId: selectedOrganizationId,
|
||||
pageNum,
|
||||
pageSize,
|
||||
memberName: url.searchParams.get("memberName") || undefined,
|
||||
memberStatus: statusFilter(url.searchParams.get("memberStatus"))
|
||||
}, context)
|
||||
]);
|
||||
const groups = routeFallback(groupsResult, warnings, []);
|
||||
const roles = routeFallback(rolesResult, warnings, []);
|
||||
const members = memberListFallback(membersResult, warnings, emptyPage(pageNum, pageSize));
|
||||
const memberListAvailable = membersResult.status === "fulfilled";
|
||||
|
||||
return jsonOk({
|
||||
configured: true,
|
||||
missing: [],
|
||||
staffConfigured: config.staffConfigured,
|
||||
staffMissing: config.staffMissing,
|
||||
selectedOrganizationId,
|
||||
organizations,
|
||||
groups,
|
||||
roles,
|
||||
members,
|
||||
warnings: uniqueWarnings(warnings),
|
||||
memberListAvailable,
|
||||
passwordManagementAvailable: config.staffConfigured
|
||||
});
|
||||
} catch (error) {
|
||||
return jsonError(error, 500, { request, source: "api.admin.accounts", logClientErrors: true });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const session = await requireAdminSession();
|
||||
const context = { accessToken: session.accessToken };
|
||||
const config = getOrganizationApiConfig(context.accessToken);
|
||||
if (!config.staffConfigured) {
|
||||
throw Object.assign(new Error(`企业端用户接口配置不完整:${config.staffMissing.join(", ")}`), { status: 503 });
|
||||
}
|
||||
const body = await readJsonBody<Record<string, unknown>>(request);
|
||||
const memberName = requiredString(body, "memberName", "成员名称");
|
||||
const memberPhone = requiredString(body, "memberPhone", "手机号");
|
||||
const user = await addOrganizationMemberAndCreatePlatformUser({
|
||||
tenantId: tenantIdNumber(config.tenantId),
|
||||
username: optionalString(body.username),
|
||||
phone: optionalString(body.phone) || memberPhone,
|
||||
name: optionalString(body.name) || memberName,
|
||||
nickname: optionalString(body.nickname) || optionalString(body.name) || memberName,
|
||||
initialPassword: optionalString(body.initialPassword),
|
||||
mustChangePassword: booleanValue(body.mustChangePassword, true),
|
||||
memberName,
|
||||
memberPhone,
|
||||
roleId: requiredString(body, "roleId", "角色"),
|
||||
organizationId: requiredString(body, "organizationId", "组织"),
|
||||
groupId: requiredString(body, "groupId", "部门")
|
||||
}, context);
|
||||
return jsonOk({ ok: true, user });
|
||||
} catch (error) {
|
||||
return jsonError(error, 500, { request, source: "api.admin.accounts", logClientErrors: true });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PATCH(request: Request) {
|
||||
try {
|
||||
const session = await requireAdminSession();
|
||||
const context = { accessToken: session.accessToken };
|
||||
const body = await readJsonBody<Record<string, unknown>>(request);
|
||||
const update = {
|
||||
memberId: requiredString(body, "memberId", "成员 ID"),
|
||||
memberName: optionalString(body.memberName),
|
||||
roleId: optionalString(body.roleId),
|
||||
groupId: optionalString(body.groupId)
|
||||
};
|
||||
if (!update.memberName && !update.roleId && !update.groupId) {
|
||||
throw badRequest("至少需要修改一个成员字段。");
|
||||
}
|
||||
await updateOrganizationMember(update, context);
|
||||
return jsonOk({ ok: true });
|
||||
} catch (error) {
|
||||
return jsonError(error, 500, { request, source: "api.admin.accounts", logClientErrors: true });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: Request) {
|
||||
try {
|
||||
const session = await requireAdminSession();
|
||||
const context = { accessToken: session.accessToken };
|
||||
const body = await readJsonBody<Record<string, unknown>>(request);
|
||||
await modifyOrganizationMemberStatus({
|
||||
memberId: requiredString(body, "memberId", "成员 ID"),
|
||||
memberStatus: memberStatus(requiredString(body, "memberStatus", "成员状态"))
|
||||
}, context);
|
||||
return jsonOk({ ok: true });
|
||||
} catch (error) {
|
||||
return jsonError(error, 500, { request, source: "api.admin.accounts", logClientErrors: true });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request) {
|
||||
try {
|
||||
const session = await requireAdminSession();
|
||||
const context = { accessToken: session.accessToken };
|
||||
const body = await readJsonBody<Record<string, unknown>>(request);
|
||||
await removeOrganizationMember(requiredString(body, "memberId", "成员 ID"), context);
|
||||
return jsonOk({ ok: true });
|
||||
} catch (error) {
|
||||
return jsonError(error, 500, { request, source: "api.admin.accounts", logClientErrors: true });
|
||||
}
|
||||
}
|
||||
|
||||
function requiredString(body: Record<string, unknown>, key: string, label: string): string {
|
||||
const value = optionalString(body[key]);
|
||||
if (!value) throw badRequest(`${label}不能为空。`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function optionalString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
||||
}
|
||||
|
||||
function memberStatus(value: string): "0" | "1" | "2" {
|
||||
if (value === "0" || value === "1" || value === "2") return value;
|
||||
throw badRequest("成员状态只能是 0、1、2。");
|
||||
}
|
||||
|
||||
function statusFilter(value: string | null): string | undefined {
|
||||
return value === "0" || value === "1" || value === "2" ? value : undefined;
|
||||
}
|
||||
|
||||
function routeFallback<T>(result: PromiseSettledResult<T>, warnings: string[], fallback: T): T {
|
||||
if (result.status === "fulfilled") return result.value;
|
||||
if (!isOrganizationRouteNotFound(result.reason)) throw result.reason;
|
||||
warnings.push(result.reason.message);
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function memberListFallback<T>(result: PromiseSettledResult<T>, warnings: string[], fallback: T): T {
|
||||
if (result.status === "fulfilled") return result.value;
|
||||
if (!isOrganizationRouteNotFound(result.reason) && !isOrganizationPermissionDenied(result.reason)) {
|
||||
throw result.reason;
|
||||
}
|
||||
warnings.push(memberListWarning(result.reason));
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function memberListWarning(error: unknown): string {
|
||||
if (isOrganizationPermissionDenied(error)) {
|
||||
return "当前登录 token 缺少上游 hotelStaff 管理员角色,成员列表暂不可用。";
|
||||
}
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function uniqueWarnings(warnings: string[]): string[] {
|
||||
return [...new Set(warnings.filter(Boolean))];
|
||||
}
|
||||
|
||||
function tenantIdNumber(value: string): number {
|
||||
const tenantId = Number(value);
|
||||
if (!Number.isFinite(tenantId)) throw badRequest("租户 ID 必须是数字。");
|
||||
return tenantId;
|
||||
}
|
||||
|
||||
function booleanValue(value: unknown, fallback: boolean): boolean {
|
||||
if (typeof value === "boolean") return value;
|
||||
if (typeof value === "string") {
|
||||
if (value === "true") return true;
|
||||
if (value === "false") return false;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function positiveInteger(value: string | null, fallback: number, max = 200): number {
|
||||
const parsed = Number(value);
|
||||
if (!Number.isInteger(parsed) || parsed < 1) return fallback;
|
||||
return Math.min(parsed, max);
|
||||
}
|
||||
|
||||
function badRequest(message: string): Error & { status: number } {
|
||||
const error = new Error(message) as Error & { status: number };
|
||||
error.status = 400;
|
||||
return error;
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { SESSION_COOKIE_NAME, getAuthRuntimeConfig, safeNextPath, shouldUseSecureAuthCookie } from "@/lib/auth/config";
|
||||
import { getAuthRuntimeConfig, safeNextPath } from "@/lib/auth/config";
|
||||
import { createSessionCookieValue } from "@/lib/auth/session";
|
||||
import { jsonError, jsonOk, readJsonBody } from "@/lib/server/api";
|
||||
import { createSessionFromClaims, verifyAuthJwt } from "@/lib/server/auth/jwt";
|
||||
import { prepareAuthPassword } from "@/lib/server/auth/password";
|
||||
import { setSessionCookieValue } from "@/lib/server/auth/session-cookie";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
@@ -54,19 +55,21 @@ export async function POST(request: Request) {
|
||||
});
|
||||
if (!token.access_token) throw new PasswordLoginError("认证中心没有返回 access_token。", 502);
|
||||
const claims = await verifyAuthJwt(token.access_token, config);
|
||||
const session = createSessionFromClaims(claims, config, parseExpiresIn(token.expires_in));
|
||||
const session = createSessionFromClaims(claims, config, parseExpiresIn(token.expires_in), {
|
||||
accessToken: token.access_token,
|
||||
tokenType: token.token_type
|
||||
});
|
||||
const response = jsonOk({
|
||||
ok: true,
|
||||
redirectTo: safeNextPath(body.next),
|
||||
user: session.user
|
||||
});
|
||||
response.cookies.set(SESSION_COOKIE_NAME, await createSessionCookieValue(session, config.sessionSecret), {
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
secure: shouldUseSecureAuthCookie(request.url),
|
||||
path: "/",
|
||||
expires: new Date(session.expiresAt * 1000)
|
||||
});
|
||||
setSessionCookieValue(
|
||||
response,
|
||||
request.url,
|
||||
await createSessionCookieValue(session, config.sessionSecret),
|
||||
new Date(session.expiresAt * 1000)
|
||||
);
|
||||
return response;
|
||||
} catch (error) {
|
||||
return jsonError(error, 401);
|
||||
|
||||
@@ -5,6 +5,7 @@ import { requestOrigin } from "@/lib/server/runtime";
|
||||
import { submitImageJob } from "@/lib/server/generation-service";
|
||||
import { assemblePrompt, type PromptAssemblyInput, type PromptMaterial } from "@/lib/prompt/assembler";
|
||||
import type { EnabledImageCapability } from "@/lib/types";
|
||||
import type { ImageCreationEngine } from "@/lib/evolink/image-client";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
@@ -23,6 +24,7 @@ export async function POST(request: Request) {
|
||||
const user = await requireAppUser();
|
||||
const body = await readJsonBody<{
|
||||
capability?: EnabledImageCapability;
|
||||
engine?: ImageCreationEngine;
|
||||
prompt?: string;
|
||||
imageUrls?: string[];
|
||||
materials?: PromptMaterial[];
|
||||
@@ -46,6 +48,7 @@ export async function POST(request: Request) {
|
||||
const job = await submitImageJob({
|
||||
ownerId: user.id,
|
||||
capability,
|
||||
engine: body.engine,
|
||||
prompt: body.prompt || assembled?.prompt,
|
||||
imageUrls: body.imageUrls || materialImages,
|
||||
inputAssetIds: body.inputAssetIds || (body.materials || []).map((material) => material.id).filter(Boolean) as string[],
|
||||
|
||||
35
app/api/image-templates/[id]/route.ts
Normal file
35
app/api/image-templates/[id]/route.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { deleteImageTemplate, updateImageTemplate } from "@/lib/server/data-store";
|
||||
import { jsonError, jsonOk, readJsonBody } from "@/lib/server/api";
|
||||
import { requireAppUser } from "@/lib/server/auth/current-user";
|
||||
import { normalizeImageTemplateUpdate } from "@/lib/server/image-template-input";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
type RouteContext = {
|
||||
params: Promise<{ id: string }>;
|
||||
};
|
||||
|
||||
export async function PATCH(request: Request, context: RouteContext) {
|
||||
try {
|
||||
const user = await requireAppUser();
|
||||
const { id } = await context.params;
|
||||
const body = await readJsonBody(request);
|
||||
const template = await updateImageTemplate(id, user.id, normalizeImageTemplateUpdate(body));
|
||||
if (!template) return jsonError(new Error("模板不存在"), 404);
|
||||
return jsonOk({ template });
|
||||
} catch (error) {
|
||||
return jsonError(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(_request: Request, context: RouteContext) {
|
||||
try {
|
||||
const user = await requireAppUser();
|
||||
const { id } = await context.params;
|
||||
const template = await deleteImageTemplate(id, user.id);
|
||||
if (!template) return jsonError(new Error("模板不存在"), 404);
|
||||
return jsonOk({ template });
|
||||
} catch (error) {
|
||||
return jsonError(error);
|
||||
}
|
||||
}
|
||||
29
app/api/image-templates/route.ts
Normal file
29
app/api/image-templates/route.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { createImageTemplate, listImageTemplates } from "@/lib/server/data-store";
|
||||
import { jsonError, jsonOk, readJsonBody } from "@/lib/server/api";
|
||||
import { requireAppUser } from "@/lib/server/auth/current-user";
|
||||
import { normalizeImageTemplateCreate } from "@/lib/server/image-template-input";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const user = await requireAppUser();
|
||||
return jsonOk({ templates: await listImageTemplates(user.id) });
|
||||
} catch (error) {
|
||||
return jsonError(error, 500);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const user = await requireAppUser();
|
||||
const body = await readJsonBody(request);
|
||||
const template = await createImageTemplate({
|
||||
ownerId: user.id,
|
||||
...normalizeImageTemplateCreate(body)
|
||||
});
|
||||
return jsonOk({ template }, { status: 201 });
|
||||
} catch (error) {
|
||||
return jsonError(error);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { jsonError, jsonOk } from "@/lib/server/api";
|
||||
import { requireAdminUser } from "@/lib/server/auth/current-user";
|
||||
import { appLogFilePath, appLogMaxBytes, clearAppLogs, listAppLogs, type AppLogLevel } from "@/lib/server/log-manager";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
@@ -6,6 +7,7 @@ export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
await requireAdminUser();
|
||||
const url = new URL(request.url);
|
||||
const level = parseLevel(url.searchParams.get("level"));
|
||||
const q = url.searchParams.get("q") || undefined;
|
||||
@@ -27,6 +29,7 @@ export async function GET(request: Request) {
|
||||
|
||||
export async function DELETE(request: Request) {
|
||||
try {
|
||||
await requireAdminUser();
|
||||
await clearAppLogs();
|
||||
return jsonOk({ ok: true });
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { getApiSettings, saveApiSettings } from "@/lib/server/app-settings";
|
||||
import { jsonError, jsonOk, readJsonBody } from "@/lib/server/api";
|
||||
import { requireAppUser } from "@/lib/server/auth/current-user";
|
||||
import { requireAdminUser } from "@/lib/server/auth/current-user";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
await requireAppUser();
|
||||
await requireAdminUser();
|
||||
return jsonOk(await getApiSettings());
|
||||
} catch (error) {
|
||||
return jsonError(error, 500);
|
||||
@@ -15,7 +15,7 @@ export async function GET() {
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
await requireAppUser();
|
||||
await requireAdminUser();
|
||||
const body = await readJsonBody<{ values?: Record<string, unknown> }>(request);
|
||||
return jsonOk(await saveApiSettings(body.values || {}));
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { createAsset } from "@/lib/server/data-store";
|
||||
import { jsonOk, readJsonBody } from "@/lib/server/api";
|
||||
import { authenticatePublicApiRequest } from "@/lib/server/public-api-auth";
|
||||
import { authenticatePublicApiRequest, publicApiOwnerId } from "@/lib/server/public-api-auth";
|
||||
import { listPublicApiAssets } from "@/lib/server/public-api-assets";
|
||||
import { publicApiError } from "@/lib/server/public-api-response";
|
||||
import { DEFAULT_OWNER_ID, requestOrigin } from "@/lib/server/runtime";
|
||||
import { requestOrigin } from "@/lib/server/runtime";
|
||||
import { saveUploadAsset } from "@/lib/server/storage";
|
||||
import type { AssetKind } from "@/lib/types";
|
||||
|
||||
@@ -21,13 +21,14 @@ export async function GET(request: Request) {
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const client = authenticatePublicApiRequest(request);
|
||||
const ownerId = publicApiOwnerId(client);
|
||||
const contentType = request.headers.get("content-type") || "";
|
||||
if (contentType.includes("multipart/form-data")) {
|
||||
const form = await request.formData();
|
||||
const files = form.getAll("files").filter((item): item is File => item instanceof File);
|
||||
if (!files.length) throw new Error("No files uploaded.");
|
||||
const assets = await Promise.all(files.map(async (file) => saveUploadAsset({
|
||||
ownerId: DEFAULT_OWNER_ID,
|
||||
ownerId,
|
||||
bytes: await awaitFileBytes(file),
|
||||
fileName: file.name,
|
||||
contentType: file.type || "application/octet-stream",
|
||||
@@ -45,7 +46,7 @@ export async function POST(request: Request) {
|
||||
}>(request);
|
||||
if (!body.url) throw new Error("url is required");
|
||||
const asset = await createAsset({
|
||||
ownerId: DEFAULT_OWNER_ID,
|
||||
ownerId,
|
||||
kind: body.kind || "image",
|
||||
name: body.name || "外部素材",
|
||||
url: body.url,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { clearGenerationJobLock, getGenerationJob, updateGenerationJob } from "@/lib/server/data-store";
|
||||
import { jsonError, jsonOk } from "@/lib/server/api";
|
||||
import { authenticatePublicApiRequest } from "@/lib/server/public-api-auth";
|
||||
import { authenticatePublicApiRequest, publicApiOwnerId } from "@/lib/server/public-api-auth";
|
||||
import { publicApiError } from "@/lib/server/public-api-response";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
@@ -10,7 +10,9 @@ export async function POST(request: Request, context: { params: Promise<{ id: st
|
||||
const client = authenticatePublicApiRequest(request);
|
||||
const { id } = await context.params;
|
||||
const job = await getGenerationJob(id);
|
||||
if (!job || job.externalClientId !== client.id) return jsonError("Job not found.", 404);
|
||||
if (!job || job.ownerId !== publicApiOwnerId(client) || job.externalClientId !== client.id) {
|
||||
return jsonError("Job not found.", 404);
|
||||
}
|
||||
if (["succeeded", "failed", "expired", "cancelled"].includes(job.status)) {
|
||||
return jsonOk({ job });
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { getGenerationJob } from "@/lib/server/data-store";
|
||||
import { jsonError, jsonOk } from "@/lib/server/api";
|
||||
import { authenticatePublicApiRequest } from "@/lib/server/public-api-auth";
|
||||
import { authenticatePublicApiRequest, publicApiOwnerId } from "@/lib/server/public-api-auth";
|
||||
import { publicApiError } from "@/lib/server/public-api-response";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
@@ -10,7 +10,9 @@ export async function GET(request: Request, context: { params: Promise<{ id: str
|
||||
const client = authenticatePublicApiRequest(request);
|
||||
const { id } = await context.params;
|
||||
const job = await getGenerationJob(id);
|
||||
if (!job || job.externalClientId !== client.id) return jsonError("Job not found.", 404);
|
||||
if (!job || job.ownerId !== publicApiOwnerId(client) || job.externalClientId !== client.id) {
|
||||
return jsonError("Job not found.", 404);
|
||||
}
|
||||
return jsonOk({ job });
|
||||
} catch (error) {
|
||||
return publicApiError(error);
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { listGenerationJobsFiltered } from "@/lib/server/data-store";
|
||||
import { jsonOk, readJsonBody } from "@/lib/server/api";
|
||||
import { authenticatePublicApiRequest } from "@/lib/server/public-api-auth";
|
||||
import { authenticatePublicApiRequest, publicApiOwnerId } from "@/lib/server/public-api-auth";
|
||||
import { createPublicGenerationJob, type PublicJobCreateBody } from "@/lib/server/public-api-jobs";
|
||||
import { publicApiError } from "@/lib/server/public-api-response";
|
||||
import { DEFAULT_OWNER_ID, requestOrigin } from "@/lib/server/runtime";
|
||||
import { requestOrigin } from "@/lib/server/runtime";
|
||||
import type { GenerationCapability, GenerationStatus } from "@/lib/types";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
@@ -13,7 +13,7 @@ export async function GET(request: Request) {
|
||||
const client = authenticatePublicApiRequest(request);
|
||||
const url = new URL(request.url);
|
||||
const jobs = await listGenerationJobsFiltered({
|
||||
ownerId: DEFAULT_OWNER_ID,
|
||||
ownerId: publicApiOwnerId(client),
|
||||
externalClientId: client.id,
|
||||
status: parseStatus(url.searchParams.get("status")),
|
||||
capability: parseCapability(url.searchParams.get("capability")),
|
||||
|
||||
@@ -50,6 +50,7 @@ export async function GET(request: Request) {
|
||||
required: ["id", "capability", "provider", "status", "createdAt", "updatedAt"],
|
||||
properties: {
|
||||
id: { type: "string", example: "job_mpqe3wtt_12ed738079" },
|
||||
ownerId: { type: "string", example: "api:partner-a" },
|
||||
externalClientId: { type: "string" },
|
||||
capability: { $ref: "#/components/schemas/GenerationCapability" },
|
||||
provider: { type: "string", enum: ["volcengine-visual", "evolink", "seedance", "mock"] },
|
||||
|
||||
Reference in New Issue
Block a user