feat: add organization settings and invitations
This commit is contained in:
@@ -1,14 +1,3 @@
|
||||
import Link from "next/link";
|
||||
import { Activity, Building2, ListChecks, Settings, Users } from "lucide-react";
|
||||
|
||||
const settingsNavItems = [
|
||||
{ href: "/app/settings/users", label: "用户管理", icon: Users },
|
||||
{ href: "/app/settings/organizations", label: "机构管理", icon: Building2 },
|
||||
{ href: "/app/settings/roles", label: "角色权限", icon: Settings },
|
||||
{ href: "/app/settings/audit", label: "审计日志", icon: ListChecks },
|
||||
{ href: "/app/settings/status", label: "运行状态", icon: Activity },
|
||||
];
|
||||
|
||||
type SettingsLayoutProps = {
|
||||
children: React.ReactNode;
|
||||
};
|
||||
@@ -18,18 +7,6 @@ export default function SettingsLayout({ children }: SettingsLayoutProps): React
|
||||
<div className="mx-auto flex w-full max-w-7xl flex-col gap-5">
|
||||
<section className="border-b pb-4">
|
||||
<h1 className="text-2xl font-semibold tracking-normal">系统设置</h1>
|
||||
<nav className="mt-4 flex gap-2 overflow-x-auto" aria-label="系统设置导航">
|
||||
{settingsNavItems.map((item) => (
|
||||
<Link
|
||||
className="inline-flex min-h-10 shrink-0 items-center gap-2 rounded-md border bg-card px-3 text-sm font-medium transition-colors hover:bg-secondary"
|
||||
href={item.href}
|
||||
key={item.href}
|
||||
>
|
||||
<item.icon className="size-4 text-muted-foreground" aria-hidden="true" />
|
||||
{item.label}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
</section>
|
||||
{children}
|
||||
</div>
|
||||
|
||||
173
app/(app)/app/settings/organizations/[id]/page.tsx
Normal file
173
app/(app)/app/settings/organizations/[id]/page.tsx
Normal file
@@ -0,0 +1,173 @@
|
||||
import Link from "next/link";
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import { ArrowLeft, Building2, Users } from "lucide-react";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { getCurrentAuthContext, toPublicAccount } from "@/modules/core/server/auth";
|
||||
import { getRoleDefinitions, hasPermission } from "@/modules/core/server/permissions";
|
||||
import { readData } from "@/modules/core/server/store";
|
||||
import { OrganizationDetailClient } from "@/modules/settings/components/OrganizationDetailClient";
|
||||
|
||||
type OrganizationDetailPageProps = {
|
||||
params: Promise<{
|
||||
id: string;
|
||||
}>;
|
||||
};
|
||||
|
||||
export default async function OrganizationDetailPage({
|
||||
params,
|
||||
}: OrganizationDetailPageProps): Promise<React.ReactElement> {
|
||||
const context = await getCurrentAuthContext();
|
||||
if (!context) {
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
if (!hasPermission(context.permissions, "organization:read")) {
|
||||
redirect("/app/dashboard");
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
const data = await readData();
|
||||
const organization = data.organizations.find((item) => item.id === id);
|
||||
if (!organization) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
if (context.organization?.id && context.organization.id !== organization.id) {
|
||||
redirect("/app/settings/organizations");
|
||||
}
|
||||
|
||||
const roles = await getRoleDefinitions(organization.id);
|
||||
const organizationMemberships = data.memberships.filter((membership) => membership.organizationId === organization.id);
|
||||
const accountById = new Map(data.accounts.map((account) => [account.id, account]));
|
||||
const members = organizationMemberships
|
||||
.map((membership) => {
|
||||
const account = accountById.get(membership.accountId);
|
||||
if (!account) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
account: toPublicAccount(account, membership.roleKey, organization),
|
||||
membership,
|
||||
};
|
||||
})
|
||||
.filter((item): item is NonNullable<typeof item> => item !== null);
|
||||
const invitations = data.organizationInvitations.filter((invitation) => invitation.organizationId === organization.id);
|
||||
const pendingRequests = data.joinRequests.filter(
|
||||
(request) => request.organizationId === organization.id && request.status === "pending",
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<section className="flex flex-col gap-4 border-b pb-5 lg:flex-row lg:items-end lg:justify-between">
|
||||
<div>
|
||||
<Button asChild size="sm" variant="outline">
|
||||
<Link href="/app/settings/organizations">
|
||||
<ArrowLeft className="size-4" aria-hidden="true" />
|
||||
返回机构列表
|
||||
</Link>
|
||||
</Button>
|
||||
<div className="mt-5 flex items-center gap-3">
|
||||
<span className="inline-flex size-11 items-center justify-center rounded-md bg-secondary text-primary">
|
||||
<Building2 className="size-5" aria-hidden="true" />
|
||||
</span>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold">{organization.name}</h2>
|
||||
<p className="text-sm text-muted-foreground">{organization.slug}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Badge variant={organization.status === "active" ? "success" : "danger"}>
|
||||
{organization.status === "active" ? "启用" : "停用"}
|
||||
</Badge>
|
||||
<Badge variant={organization.registrationEnabled ? "success" : "secondary"}>
|
||||
{organization.registrationEnabled ? "开放注册" : "关闭注册"}
|
||||
</Badge>
|
||||
<Badge variant={organization.oidcEnabled ? "success" : "secondary"}>
|
||||
{organization.oidcEnabled ? "OIDC 已启用" : "OIDC 未启用"}
|
||||
</Badge>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="grid gap-4 md:grid-cols-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-3xl">{members.length}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0 text-sm text-muted-foreground">成员</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-3xl">{roles.filter((role) => role.scope === "organization").length}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0 text-sm text-muted-foreground">机构角色</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-3xl">{pendingRequests.length}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0 text-sm text-muted-foreground">待审批申请</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-3xl">{invitations.filter((invitation) => invitation.status === "active").length}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0 text-sm text-muted-foreground">有效邀请</CardContent>
|
||||
</Card>
|
||||
</section>
|
||||
|
||||
<OrganizationDetailClient invitations={invitations} organization={organization} roles={roles} />
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Users className="size-4 text-primary" aria-hidden="true" />
|
||||
机构成员
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[760px] text-sm">
|
||||
<thead className="bg-secondary text-left text-xs text-muted-foreground">
|
||||
<tr>
|
||||
<th className="px-4 py-3 font-medium">账号</th>
|
||||
<th className="px-4 py-3 font-medium">角色</th>
|
||||
<th className="px-4 py-3 font-medium">成员状态</th>
|
||||
<th className="px-4 py-3 font-medium">账号状态</th>
|
||||
<th className="px-4 py-3 text-right font-medium">加入时间</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y bg-card">
|
||||
{members.map(({ account, membership }) => (
|
||||
<tr className="hover:bg-secondary/45" key={membership.id}>
|
||||
<td className="px-4 py-3">
|
||||
<p className="font-medium">{account.name}</p>
|
||||
<p className="text-xs text-muted-foreground">{account.email}</p>
|
||||
</td>
|
||||
<td className="px-4 py-3">{membership.roleLabel}</td>
|
||||
<td className="px-4 py-3">{membership.status}</td>
|
||||
<td className="px-4 py-3">{account.status}</td>
|
||||
<td className="px-4 py-3 text-right text-muted-foreground">
|
||||
{new Date(membership.createdAt).toLocaleString("zh-CN")}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{members.length === 0 ? (
|
||||
<tr>
|
||||
<td className="px-4 py-8 text-center text-muted-foreground" colSpan={5}>
|
||||
暂无成员
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
@@ -74,7 +75,14 @@ export default async function OrganizationsPage({ searchParams }: OrganizationsP
|
||||
<tbody className="divide-y bg-card">
|
||||
{visibleOrganizations.map((organization) => (
|
||||
<tr className="table-row-enter hover:bg-secondary/45" key={organization.id}>
|
||||
<td className="px-4 py-3 font-medium">{organization.name}</td>
|
||||
<td className="px-4 py-3">
|
||||
<Link
|
||||
className="font-medium text-primary underline-offset-4 hover:underline"
|
||||
href={`/app/settings/organizations/${organization.id}`}
|
||||
>
|
||||
{organization.name}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{organization.slug}</td>
|
||||
<td className="px-4 py-3">{organization.status === "active" ? "启用" : "停用"}</td>
|
||||
<td className="px-4 py-3 text-right text-muted-foreground">
|
||||
|
||||
@@ -20,6 +20,7 @@ export async function POST(request: Request): Promise<Response> {
|
||||
const email = readString(body, "email");
|
||||
const password = readString(body, "password");
|
||||
const organizationId = readString(body, "organizationId");
|
||||
const invitationToken = readString(body, "invitationToken");
|
||||
|
||||
if (!name || !email || !password) {
|
||||
return jsonFailure("姓名、邮箱和密码不能为空");
|
||||
@@ -35,6 +36,7 @@ export async function POST(request: Request): Promise<Response> {
|
||||
email,
|
||||
password,
|
||||
organizationId: organizationId || undefined,
|
||||
invitationToken: invitationToken || undefined,
|
||||
});
|
||||
if (created.session) {
|
||||
await setSessionCookie(created.session.id);
|
||||
|
||||
103
app/api/organizations/[id]/invitations/route.ts
Normal file
103
app/api/organizations/[id]/invitations/route.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
|
||||
import { and, eq } from "drizzle-orm";
|
||||
|
||||
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { requirePermission } from "@/modules/core/server/auth";
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { organizationInvitations, organizations, roles } from "@/modules/core/server/schema";
|
||||
|
||||
type RouteContext = {
|
||||
params: Promise<{
|
||||
id: string;
|
||||
}>;
|
||||
};
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readString(source: Record<string, unknown>, key: string): string {
|
||||
const value = source[key];
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
function createInvitationToken(): string {
|
||||
return randomBytes(24).toString("base64url");
|
||||
}
|
||||
|
||||
export async function POST(request: Request, context: RouteContext): Promise<Response> {
|
||||
const { id } = await context.params;
|
||||
const auth = await requirePermission("account:manage", {
|
||||
action: "organizationInvitation.create",
|
||||
targetType: "organization",
|
||||
targetId: id,
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const activeOrganizationId = auth.context.organization?.id;
|
||||
if (activeOrganizationId && activeOrganizationId !== id) {
|
||||
return jsonFailure("不能为其他机构创建邀请", 403);
|
||||
}
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!isRecord(body)) {
|
||||
return jsonFailure("请求数据格式无效");
|
||||
}
|
||||
|
||||
const email = readString(body, "email");
|
||||
const roleId = readString(body, "roleId");
|
||||
if (!roleId) {
|
||||
return jsonFailure("请选择邀请角色");
|
||||
}
|
||||
|
||||
const database = getDatabase();
|
||||
const organizationRows = await database.select().from(organizations).where(eq(organizations.id, id)).limit(1);
|
||||
const organization = organizationRows[0];
|
||||
if (!organization) {
|
||||
return jsonFailure("机构不存在", 404);
|
||||
}
|
||||
|
||||
const roleRows = await database
|
||||
.select()
|
||||
.from(roles)
|
||||
.where(and(eq(roles.id, roleId), eq(roles.organizationId, id), eq(roles.isEnabled, true)))
|
||||
.limit(1);
|
||||
const role = roleRows[0];
|
||||
if (!role) {
|
||||
return jsonFailure("角色不存在", 404);
|
||||
}
|
||||
|
||||
const rows = await database
|
||||
.insert(organizationInvitations)
|
||||
.values({
|
||||
organizationId: id,
|
||||
roleId: role.id,
|
||||
email,
|
||||
token: createInvitationToken(),
|
||||
status: "active",
|
||||
createdByAccountId: auth.context.account.id,
|
||||
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
|
||||
})
|
||||
.returning();
|
||||
const invitation = rows[0];
|
||||
if (!invitation) {
|
||||
return jsonFailure("邀请创建失败", 500);
|
||||
}
|
||||
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId: id,
|
||||
action: "organizationInvitation.create",
|
||||
targetType: "organizationInvitation",
|
||||
targetId: invitation.id,
|
||||
result: "success",
|
||||
reason: `创建机构邀请:${email || "通用邀请"}`,
|
||||
});
|
||||
|
||||
return jsonSuccess("邀请已创建", { invitation }, 201);
|
||||
}
|
||||
@@ -24,6 +24,11 @@ function readString(source: Record<string, unknown>, key: string): string {
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
function readBoolean(source: Record<string, unknown>, key: string): boolean | null {
|
||||
const value = source[key];
|
||||
return typeof value === "boolean" ? value : null;
|
||||
}
|
||||
|
||||
function readStatus(value: unknown): OrganizationStatus | null {
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
@@ -51,12 +56,41 @@ export async function PATCH(request: Request, context: RouteContext): Promise<Re
|
||||
|
||||
const name = readString(body, "name");
|
||||
const slug = readString(body, "slug");
|
||||
const oidcIssuerUrl = readString(body, "oidcIssuerUrl");
|
||||
const oidcClientId = readString(body, "oidcClientId");
|
||||
const oidcClientSecret = readString(body, "oidcClientSecret");
|
||||
const oidcScopes = readString(body, "oidcScopes");
|
||||
const oidcRedirectUri = readString(body, "oidcRedirectUri");
|
||||
const status = "status" in body ? readStatus(body.status) : null;
|
||||
if ("status" in body && !status) {
|
||||
return jsonFailure("机构状态无效");
|
||||
}
|
||||
const registrationEnabled = "registrationEnabled" in body ? readBoolean(body, "registrationEnabled") : null;
|
||||
const oidcEnabled = "oidcEnabled" in body ? readBoolean(body, "oidcEnabled") : null;
|
||||
const oidcAutoProvision = "oidcAutoProvision" in body ? readBoolean(body, "oidcAutoProvision") : null;
|
||||
if ("registrationEnabled" in body && registrationEnabled === null) {
|
||||
return jsonFailure("注册开关无效");
|
||||
}
|
||||
if ("oidcEnabled" in body && oidcEnabled === null) {
|
||||
return jsonFailure("OIDC开关无效");
|
||||
}
|
||||
if ("oidcAutoProvision" in body && oidcAutoProvision === null) {
|
||||
return jsonFailure("OIDC自动开户配置无效");
|
||||
}
|
||||
|
||||
if (!name && !slug && !status) {
|
||||
if (
|
||||
!name &&
|
||||
!slug &&
|
||||
!status &&
|
||||
registrationEnabled === null &&
|
||||
oidcEnabled === null &&
|
||||
!oidcIssuerUrl &&
|
||||
!oidcClientId &&
|
||||
!oidcClientSecret &&
|
||||
!oidcScopes &&
|
||||
!oidcRedirectUri &&
|
||||
oidcAutoProvision === null
|
||||
) {
|
||||
return jsonFailure("请至少填写一个要更新的字段");
|
||||
}
|
||||
|
||||
@@ -64,6 +98,14 @@ export async function PATCH(request: Request, context: RouteContext): Promise<Re
|
||||
name?: string;
|
||||
slug?: string;
|
||||
status?: OrganizationStatus;
|
||||
registrationEnabled?: boolean;
|
||||
oidcEnabled?: boolean;
|
||||
oidcIssuerUrl?: string;
|
||||
oidcClientId?: string;
|
||||
oidcClientSecret?: string;
|
||||
oidcScopes?: string;
|
||||
oidcRedirectUri?: string;
|
||||
oidcAutoProvision?: boolean;
|
||||
updatedAt: Date;
|
||||
} = {
|
||||
updatedAt: new Date(),
|
||||
@@ -78,6 +120,30 @@ export async function PATCH(request: Request, context: RouteContext): Promise<Re
|
||||
if (status) {
|
||||
updateValues.status = status;
|
||||
}
|
||||
if (registrationEnabled !== null) {
|
||||
updateValues.registrationEnabled = registrationEnabled;
|
||||
}
|
||||
if (oidcEnabled !== null) {
|
||||
updateValues.oidcEnabled = oidcEnabled;
|
||||
}
|
||||
if (oidcIssuerUrl) {
|
||||
updateValues.oidcIssuerUrl = oidcIssuerUrl;
|
||||
}
|
||||
if (oidcClientId) {
|
||||
updateValues.oidcClientId = oidcClientId;
|
||||
}
|
||||
if (oidcClientSecret) {
|
||||
updateValues.oidcClientSecret = oidcClientSecret;
|
||||
}
|
||||
if (oidcScopes) {
|
||||
updateValues.oidcScopes = oidcScopes;
|
||||
}
|
||||
if (oidcRedirectUri) {
|
||||
updateValues.oidcRedirectUri = oidcRedirectUri;
|
||||
}
|
||||
if (oidcAutoProvision !== null) {
|
||||
updateValues.oidcAutoProvision = oidcAutoProvision;
|
||||
}
|
||||
|
||||
const database = getDatabase();
|
||||
try {
|
||||
|
||||
@@ -31,14 +31,24 @@ export async function GET(): Promise<Response> {
|
||||
const rows = await database.select().from(organizations).where(eq(organizations.status, "active"));
|
||||
|
||||
return jsonSuccess("机构列表已加载", {
|
||||
organizations: rows.map((organization) => ({
|
||||
id: organization.id,
|
||||
name: organization.name,
|
||||
slug: organization.slug,
|
||||
status: organization.status,
|
||||
createdAt: organization.createdAt.toISOString(),
|
||||
updatedAt: organization.updatedAt.toISOString(),
|
||||
})),
|
||||
organizations: rows
|
||||
.filter((organization) => organization.registrationEnabled)
|
||||
.map((organization) => ({
|
||||
id: organization.id,
|
||||
name: organization.name,
|
||||
slug: organization.slug,
|
||||
status: organization.status,
|
||||
registrationEnabled: organization.registrationEnabled,
|
||||
oidcEnabled: organization.oidcEnabled,
|
||||
oidcIssuerUrl: "",
|
||||
oidcClientId: "",
|
||||
oidcHasClientSecret: organization.oidcClientSecret.length > 0,
|
||||
oidcScopes: organization.oidcScopes,
|
||||
oidcRedirectUri: organization.oidcRedirectUri,
|
||||
oidcAutoProvision: organization.oidcAutoProvision,
|
||||
createdAt: organization.createdAt.toISOString(),
|
||||
updatedAt: organization.updatedAt.toISOString(),
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -39,6 +39,14 @@ function toOrganization(row: typeof organizations.$inferSelect): Organization {
|
||||
name: row.name,
|
||||
slug: row.slug,
|
||||
status: row.status,
|
||||
registrationEnabled: row.registrationEnabled,
|
||||
oidcEnabled: row.oidcEnabled,
|
||||
oidcIssuerUrl: row.oidcIssuerUrl,
|
||||
oidcClientId: row.oidcClientId,
|
||||
oidcHasClientSecret: row.oidcClientSecret.length > 0,
|
||||
oidcScopes: row.oidcScopes,
|
||||
oidcRedirectUri: row.oidcRedirectUri,
|
||||
oidcAutoProvision: row.oidcAutoProvision,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
};
|
||||
|
||||
@@ -155,6 +155,14 @@ export async function POST(request: Request): Promise<Response> {
|
||||
name: created.organization.name,
|
||||
slug: created.organization.slug,
|
||||
status: created.organization.status,
|
||||
registrationEnabled: created.organization.registrationEnabled,
|
||||
oidcEnabled: created.organization.oidcEnabled,
|
||||
oidcIssuerUrl: created.organization.oidcIssuerUrl,
|
||||
oidcClientId: created.organization.oidcClientId,
|
||||
oidcHasClientSecret: created.organization.oidcClientSecret.length > 0,
|
||||
oidcScopes: created.organization.oidcScopes,
|
||||
oidcRedirectUri: created.organization.oidcRedirectUri,
|
||||
oidcAutoProvision: created.organization.oidcAutoProvision,
|
||||
createdAt: created.organization.createdAt.toISOString(),
|
||||
updatedAt: created.organization.updatedAt.toISOString(),
|
||||
}),
|
||||
|
||||
@@ -83,11 +83,9 @@ a,
|
||||
@keyframes page-enter {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(6px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user