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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
28
drizzle/0001_tired_queen_noir.sql
Normal file
28
drizzle/0001_tired_queen_noir.sql
Normal file
@@ -0,0 +1,28 @@
|
||||
CREATE TABLE "organization_invitations" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"organization_id" uuid NOT NULL,
|
||||
"role_id" uuid NOT NULL,
|
||||
"email" text DEFAULT '' NOT NULL,
|
||||
"token" text NOT NULL,
|
||||
"status" text DEFAULT 'active' NOT NULL,
|
||||
"created_by_account_id" uuid,
|
||||
"accepted_by_account_id" uuid,
|
||||
"accepted_at" timestamp with time zone,
|
||||
"expires_at" timestamp with time zone NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "organizations" ADD COLUMN "registration_enabled" boolean DEFAULT true NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "organizations" ADD COLUMN "oidc_enabled" boolean DEFAULT false NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "organizations" ADD COLUMN "oidc_issuer_url" text DEFAULT '' NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "organizations" ADD COLUMN "oidc_client_id" text DEFAULT '' NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "organizations" ADD COLUMN "oidc_client_secret" text DEFAULT '' NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "organizations" ADD COLUMN "oidc_scopes" text DEFAULT 'openid profile email' NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "organizations" ADD COLUMN "oidc_redirect_uri" text DEFAULT '' NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "organizations" ADD COLUMN "oidc_auto_provision" boolean DEFAULT false NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "organization_invitations" ADD CONSTRAINT "organization_invitations_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "organization_invitations" ADD CONSTRAINT "organization_invitations_role_id_roles_id_fk" FOREIGN KEY ("role_id") REFERENCES "public"."roles"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "organization_invitations" ADD CONSTRAINT "organization_invitations_created_by_account_id_accounts_id_fk" FOREIGN KEY ("created_by_account_id") REFERENCES "public"."accounts"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "organization_invitations" ADD CONSTRAINT "organization_invitations_accepted_by_account_id_accounts_id_fk" FOREIGN KEY ("accepted_by_account_id") REFERENCES "public"."accounts"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "organization_invitations_token_unique" ON "organization_invitations" USING btree ("token");
|
||||
1987
drizzle/meta/0001_snapshot.json
Normal file
1987
drizzle/meta/0001_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@@ -8,6 +8,13 @@
|
||||
"when": 1782975351852,
|
||||
"tag": "0000_bouncy_micromax",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 1,
|
||||
"version": "7",
|
||||
"when": 1782994149630,
|
||||
"tag": "0001_tired_queen_noir",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -28,6 +28,7 @@ function AuthPanelContent({ mode }: AuthPanelProps): React.ReactElement {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const redirectTo = searchParams.get("redirectTo") ?? "/app/dashboard";
|
||||
const invitationToken = searchParams.get("invite") ?? "";
|
||||
const [message, setMessage] = useState("");
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const [hasAccounts, setHasAccounts] = useState<boolean | null>(null);
|
||||
@@ -117,6 +118,7 @@ function AuthPanelContent({ mode }: AuthPanelProps): React.ReactElement {
|
||||
password,
|
||||
organization,
|
||||
organizationId,
|
||||
invitationToken,
|
||||
}),
|
||||
});
|
||||
const result = (await response.json()) as ApiResult<{ account: unknown; pendingApproval?: boolean }>;
|
||||
@@ -195,7 +197,13 @@ function AuthPanelContent({ mode }: AuthPanelProps): React.ReactElement {
|
||||
</label>
|
||||
) : null}
|
||||
|
||||
{mode === "register" && organizations.length > 0 ? (
|
||||
{mode === "register" && invitationToken ? (
|
||||
<p className="rounded-md bg-secondary px-3 py-2 text-sm text-secondary-foreground">
|
||||
正在使用机构邀请注册,完成后将自动加入机构。
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{mode === "register" && !invitationToken && organizations.length > 0 ? (
|
||||
<label className="block space-y-2">
|
||||
<span className="text-sm font-medium">申请加入机构</span>
|
||||
<select
|
||||
|
||||
@@ -7,7 +7,15 @@ import { jsonFailure } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { getPermissionsForRole, hasPermission, seedOrganizationRoles } from "@/modules/core/server/permissions";
|
||||
import { accounts, joinRequests, memberships, organizations, roles, sessions } from "@/modules/core/server/schema";
|
||||
import {
|
||||
accounts,
|
||||
joinRequests,
|
||||
memberships,
|
||||
organizationInvitations,
|
||||
organizations,
|
||||
roles,
|
||||
sessions,
|
||||
} from "@/modules/core/server/schema";
|
||||
import type { Account, AuthContext, Membership, Organization, Permission, PublicAccount, Session } from "@/modules/core/types";
|
||||
|
||||
const SESSION_COOKIE = "teatea_session";
|
||||
@@ -33,6 +41,14 @@ function toOrganization(row: OrganizationRow): 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: toIsoString(row.createdAt),
|
||||
updatedAt: toIsoString(row.updatedAt),
|
||||
};
|
||||
@@ -251,6 +267,7 @@ export async function createRegistration(input: {
|
||||
email: string;
|
||||
password: string;
|
||||
organizationId?: string;
|
||||
invitationToken?: string;
|
||||
}): Promise<{ account: PublicAccount; session?: Session }> {
|
||||
const database = getDatabase();
|
||||
const password = hashPassword(input.password);
|
||||
@@ -263,6 +280,39 @@ export async function createRegistration(input: {
|
||||
return null;
|
||||
}
|
||||
|
||||
const invitationRows = input.invitationToken
|
||||
? await transaction
|
||||
.select({ invitation: organizationInvitations, organization: organizations, role: roles })
|
||||
.from(organizationInvitations)
|
||||
.innerJoin(organizations, eq(organizations.id, organizationInvitations.organizationId))
|
||||
.innerJoin(roles, eq(roles.id, organizationInvitations.roleId))
|
||||
.where(eq(organizationInvitations.token, input.invitationToken))
|
||||
.limit(1)
|
||||
: [];
|
||||
const invitation = invitationRows[0];
|
||||
if (input.invitationToken && !invitation) {
|
||||
throw new Error("邀请链接无效");
|
||||
}
|
||||
if (invitation && (invitation.invitation.status !== "active" || invitation.invitation.expiresAt < new Date())) {
|
||||
throw new Error("邀请链接已失效");
|
||||
}
|
||||
|
||||
const targetOrganizationId = invitation?.invitation.organizationId ?? input.organizationId;
|
||||
if (targetOrganizationId && !invitation) {
|
||||
const organizationRows = await transaction
|
||||
.select()
|
||||
.from(organizations)
|
||||
.where(eq(organizations.id, targetOrganizationId))
|
||||
.limit(1);
|
||||
const organization = organizationRows[0];
|
||||
if (!organization) {
|
||||
throw new Error("机构不存在");
|
||||
}
|
||||
if (!organization.registrationEnabled) {
|
||||
throw new Error("该机构暂未开放注册");
|
||||
}
|
||||
}
|
||||
|
||||
const accountRows = await transaction
|
||||
.insert(accounts)
|
||||
.values({
|
||||
@@ -270,7 +320,7 @@ export async function createRegistration(input: {
|
||||
email: normalizedEmail,
|
||||
passwordHash: password.hash,
|
||||
passwordSalt: password.salt,
|
||||
status: input.organizationId ? "pending" : "active",
|
||||
status: targetOrganizationId && !invitation ? "pending" : "active",
|
||||
})
|
||||
.returning();
|
||||
const account = accountRows[0];
|
||||
@@ -278,43 +328,63 @@ export async function createRegistration(input: {
|
||||
throw new Error("账号创建失败");
|
||||
}
|
||||
|
||||
const sessionRows = input.organizationId
|
||||
if (invitation) {
|
||||
await transaction.insert(memberships).values({
|
||||
accountId: account.id,
|
||||
organizationId: invitation.invitation.organizationId,
|
||||
roleId: invitation.invitation.roleId,
|
||||
status: "active",
|
||||
});
|
||||
await transaction
|
||||
.update(organizationInvitations)
|
||||
.set({
|
||||
status: "accepted",
|
||||
acceptedByAccountId: account.id,
|
||||
acceptedAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(organizationInvitations.id, invitation.invitation.id));
|
||||
}
|
||||
|
||||
const sessionRows = targetOrganizationId && !invitation
|
||||
? []
|
||||
: await transaction
|
||||
.insert(sessions)
|
||||
.values({
|
||||
accountId: account.id,
|
||||
activeOrganizationId: invitation?.invitation.organizationId,
|
||||
expiresAt,
|
||||
})
|
||||
.returning();
|
||||
const session = sessionRows[0];
|
||||
|
||||
if (input.organizationId) {
|
||||
if (targetOrganizationId && !invitation) {
|
||||
await transaction.insert(joinRequests).values({
|
||||
accountId: account.id,
|
||||
organizationId: input.organizationId,
|
||||
organizationId: targetOrganizationId,
|
||||
status: "pending",
|
||||
reason: "公开注册申请加入机构",
|
||||
});
|
||||
}
|
||||
|
||||
return { account, session };
|
||||
return { account, organization: invitation?.organization, role: invitation?.role, session };
|
||||
});
|
||||
|
||||
if (!created) {
|
||||
throw new Error("账号已存在");
|
||||
}
|
||||
|
||||
const publicAccount = toPublicAccount(created.account);
|
||||
const organization = created.organization ? toOrganization(created.organization) : undefined;
|
||||
const publicAccount = toPublicAccount(created.account, created.role?.key, organization);
|
||||
const session = created.session ? toSession(created.session) : undefined;
|
||||
await recordAuditLog({
|
||||
actor: publicAccount,
|
||||
organizationId: input.organizationId,
|
||||
organizationId: organization?.id ?? input.organizationId,
|
||||
action: "account.register",
|
||||
targetType: "account",
|
||||
targetId: publicAccount.id,
|
||||
result: "success",
|
||||
reason: input.organizationId ? "注册账号并申请加入机构" : "注册独立账号",
|
||||
reason: input.invitationToken ? "通过邀请注册并加入机构" : input.organizationId ? "注册账号并申请加入机构" : "注册独立账号",
|
||||
});
|
||||
|
||||
return { account: publicAccount, session };
|
||||
|
||||
@@ -29,6 +29,14 @@ export const organizations = pgTable("organizations", {
|
||||
name: text("name").notNull(),
|
||||
slug: text("slug").notNull(),
|
||||
status: organizationStatusEnum("status").notNull().default("active"),
|
||||
registrationEnabled: boolean("registration_enabled").notNull().default(true),
|
||||
oidcEnabled: boolean("oidc_enabled").notNull().default(false),
|
||||
oidcIssuerUrl: text("oidc_issuer_url").notNull().default(""),
|
||||
oidcClientId: text("oidc_client_id").notNull().default(""),
|
||||
oidcClientSecret: text("oidc_client_secret").notNull().default(""),
|
||||
oidcScopes: text("oidc_scopes").notNull().default("openid profile email"),
|
||||
oidcRedirectUri: text("oidc_redirect_uri").notNull().default(""),
|
||||
oidcAutoProvision: boolean("oidc_auto_provision").notNull().default(false),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
}, (table) => ({
|
||||
@@ -114,6 +122,23 @@ export const joinRequests = pgTable("join_requests", {
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
|
||||
export const organizationInvitations = pgTable("organization_invitations", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||
roleId: uuid("role_id").notNull().references(() => roles.id),
|
||||
email: text("email").notNull().default(""),
|
||||
token: text("token").notNull(),
|
||||
status: text("status").notNull().default("active"),
|
||||
createdByAccountId: uuid("created_by_account_id").references(() => accounts.id),
|
||||
acceptedByAccountId: uuid("accepted_by_account_id").references(() => accounts.id),
|
||||
acceptedAt: timestamp("accepted_at", { withTimezone: true }),
|
||||
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
}, (table) => ({
|
||||
tokenUnique: uniqueIndex("organization_invitations_token_unique").on(table.token),
|
||||
}));
|
||||
|
||||
export const campuses = pgTable("campuses", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
elders,
|
||||
joinRequests,
|
||||
memberships,
|
||||
organizationInvitations,
|
||||
organizations,
|
||||
roles,
|
||||
rooms,
|
||||
@@ -23,6 +24,7 @@ import type {
|
||||
JoinRequest,
|
||||
Membership,
|
||||
Organization,
|
||||
OrganizationInvitation,
|
||||
Room,
|
||||
Session,
|
||||
SystemIncident,
|
||||
@@ -40,6 +42,7 @@ export async function readData(): Promise<AppData> {
|
||||
accountRows,
|
||||
membershipRows,
|
||||
joinRequestRows,
|
||||
invitationRows,
|
||||
sessionRows,
|
||||
elderRows,
|
||||
roomRows,
|
||||
@@ -62,6 +65,16 @@ export async function readData(): Promise<AppData> {
|
||||
.innerJoin(accounts, eq(accounts.id, joinRequests.accountId))
|
||||
.innerJoin(organizations, eq(organizations.id, joinRequests.organizationId))
|
||||
.orderBy(desc(joinRequests.createdAt)),
|
||||
database
|
||||
.select({
|
||||
invitation: organizationInvitations,
|
||||
organizationName: organizations.name,
|
||||
roleLabel: roles.label,
|
||||
})
|
||||
.from(organizationInvitations)
|
||||
.innerJoin(organizations, eq(organizations.id, organizationInvitations.organizationId))
|
||||
.innerJoin(roles, eq(roles.id, organizationInvitations.roleId))
|
||||
.orderBy(desc(organizationInvitations.createdAt)),
|
||||
database.select().from(sessions).orderBy(desc(sessions.createdAt)),
|
||||
database.select().from(elders).orderBy(desc(elders.createdAt)),
|
||||
database.select().from(rooms).orderBy(desc(rooms.createdAt)),
|
||||
@@ -112,6 +125,14 @@ export async function readData(): Promise<AppData> {
|
||||
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: iso(row.createdAt),
|
||||
updatedAt: iso(row.updatedAt),
|
||||
}));
|
||||
@@ -158,6 +179,23 @@ export async function readData(): Promise<AppData> {
|
||||
createdAt: iso(row.request.createdAt),
|
||||
}));
|
||||
|
||||
const organizationInvitationsData: OrganizationInvitation[] = invitationRows.map((row) => ({
|
||||
id: row.invitation.id,
|
||||
organizationId: row.invitation.organizationId,
|
||||
organizationName: row.organizationName,
|
||||
roleId: row.invitation.roleId,
|
||||
roleLabel: row.roleLabel,
|
||||
email: row.invitation.email,
|
||||
token: row.invitation.token,
|
||||
status: row.invitation.status as OrganizationInvitation["status"],
|
||||
createdByAccountId: row.invitation.createdByAccountId ?? undefined,
|
||||
acceptedByAccountId: row.invitation.acceptedByAccountId ?? undefined,
|
||||
acceptedAt: row.invitation.acceptedAt ? iso(row.invitation.acceptedAt) : undefined,
|
||||
expiresAt: iso(row.invitation.expiresAt),
|
||||
createdAt: iso(row.invitation.createdAt),
|
||||
updatedAt: iso(row.invitation.updatedAt),
|
||||
}));
|
||||
|
||||
const sessionsData: Session[] = sessionRows.map((row) => ({
|
||||
id: row.id,
|
||||
accountId: row.accountId,
|
||||
@@ -243,6 +281,7 @@ export async function readData(): Promise<AppData> {
|
||||
accounts: accountsData,
|
||||
memberships: membershipsData,
|
||||
joinRequests: joinRequestsData,
|
||||
organizationInvitations: organizationInvitationsData,
|
||||
sessions: sessionsData,
|
||||
elders: eldersData,
|
||||
rooms: roomsData,
|
||||
|
||||
@@ -68,6 +68,14 @@ export type Organization = {
|
||||
name: string;
|
||||
slug: string;
|
||||
status: OrganizationStatus;
|
||||
registrationEnabled: boolean;
|
||||
oidcEnabled: boolean;
|
||||
oidcIssuerUrl: string;
|
||||
oidcClientId: string;
|
||||
oidcHasClientSecret: boolean;
|
||||
oidcScopes: string;
|
||||
oidcRedirectUri: string;
|
||||
oidcAutoProvision: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
@@ -102,6 +110,25 @@ export type JoinRequest = {
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
export type OrganizationInvitationStatus = "active" | "accepted" | "revoked" | "expired";
|
||||
|
||||
export type OrganizationInvitation = {
|
||||
id: string;
|
||||
organizationId: string;
|
||||
organizationName: string;
|
||||
roleId: string;
|
||||
roleLabel: string;
|
||||
email: string;
|
||||
token: string;
|
||||
status: OrganizationInvitationStatus;
|
||||
createdByAccountId?: string;
|
||||
acceptedByAccountId?: string;
|
||||
acceptedAt?: string;
|
||||
expiresAt: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type Account = {
|
||||
id: string;
|
||||
platformRoleId?: string;
|
||||
@@ -206,6 +233,7 @@ export type AppData = {
|
||||
accounts: Account[];
|
||||
memberships: Membership[];
|
||||
joinRequests: JoinRequest[];
|
||||
organizationInvitations: OrganizationInvitation[];
|
||||
sessions: Session[];
|
||||
elders: Elder[];
|
||||
rooms: Room[];
|
||||
|
||||
255
modules/settings/components/OrganizationDetailClient.tsx
Normal file
255
modules/settings/components/OrganizationDetailClient.tsx
Normal file
@@ -0,0 +1,255 @@
|
||||
"use client";
|
||||
|
||||
import { FormEvent, useState } from "react";
|
||||
import { Copy, LinkIcon, Save, Send } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import type { ApiResult } from "@/modules/core/server/api";
|
||||
import type { Organization, OrganizationInvitation, RoleDefinition } from "@/modules/core/types";
|
||||
|
||||
type OrganizationDetailClientProps = {
|
||||
invitations: OrganizationInvitation[];
|
||||
organization: Organization;
|
||||
roles: RoleDefinition[];
|
||||
};
|
||||
|
||||
function getInviteHref(token: string): string {
|
||||
return `/register?invite=${encodeURIComponent(token)}`;
|
||||
}
|
||||
|
||||
export function OrganizationDetailClient({
|
||||
invitations,
|
||||
organization,
|
||||
roles,
|
||||
}: OrganizationDetailClientProps): React.ReactElement {
|
||||
const router = useRouter();
|
||||
const [settingsMessage, setSettingsMessage] = useState("");
|
||||
const [inviteMessage, setInviteMessage] = useState("");
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const organizationRoles = roles.filter((role) => role.scope === "organization" && role.organizationId === organization.id && role.isEnabled);
|
||||
const defaultRoleId = organizationRoles.find((role) => role.key === "caregiver")?.id ?? organizationRoles[0]?.id ?? "";
|
||||
|
||||
async function handleSettingsSubmit(event: FormEvent<HTMLFormElement>): Promise<void> {
|
||||
event.preventDefault();
|
||||
setSettingsMessage("");
|
||||
setIsPending(true);
|
||||
const formData = new FormData(event.currentTarget);
|
||||
const response = await fetch(`/api/organizations/${organization.id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
registrationEnabled: formData.get("registrationEnabled") === "on",
|
||||
oidcEnabled: formData.get("oidcEnabled") === "on",
|
||||
oidcIssuerUrl: String(formData.get("oidcIssuerUrl") ?? ""),
|
||||
oidcClientId: String(formData.get("oidcClientId") ?? ""),
|
||||
oidcClientSecret: String(formData.get("oidcClientSecret") ?? ""),
|
||||
oidcScopes: String(formData.get("oidcScopes") ?? ""),
|
||||
oidcRedirectUri: String(formData.get("oidcRedirectUri") ?? ""),
|
||||
oidcAutoProvision: formData.get("oidcAutoProvision") === "on",
|
||||
}),
|
||||
});
|
||||
const result = (await response.json()) as ApiResult<{ organization: Organization }>;
|
||||
setIsPending(false);
|
||||
|
||||
if (!result.success) {
|
||||
setSettingsMessage(result.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
setSettingsMessage(result.reason);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
async function handleInviteSubmit(event: FormEvent<HTMLFormElement>): Promise<void> {
|
||||
event.preventDefault();
|
||||
setInviteMessage("");
|
||||
setIsPending(true);
|
||||
const formData = new FormData(event.currentTarget);
|
||||
const response = await fetch(`/api/organizations/${organization.id}/invitations`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
email: String(formData.get("email") ?? ""),
|
||||
roleId: String(formData.get("roleId") ?? ""),
|
||||
}),
|
||||
});
|
||||
const result = (await response.json()) as ApiResult<{ invitation: OrganizationInvitation }>;
|
||||
setIsPending(false);
|
||||
|
||||
if (!result.success) {
|
||||
setInviteMessage(result.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
setInviteMessage(`${result.reason}:${getInviteHref(result.invitation.token)}`);
|
||||
event.currentTarget.reset();
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid gap-5 xl:grid-cols-[0.95fr_1.05fr]">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>机构访问配置</CardTitle>
|
||||
<CardDescription>控制公开注册、OIDC 登录入口和自动开户策略。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form className="grid gap-4" onSubmit={handleSettingsSubmit}>
|
||||
<label className="flex items-center justify-between gap-4 rounded-md border p-3 text-sm">
|
||||
<span>
|
||||
<span className="block font-medium">开放公开注册</span>
|
||||
<span className="block text-xs text-muted-foreground">关闭后,注册页不再展示该机构;邀请链接仍可使用。</span>
|
||||
</span>
|
||||
<input defaultChecked={organization.registrationEnabled} name="registrationEnabled" type="checkbox" />
|
||||
</label>
|
||||
|
||||
<label className="flex items-center justify-between gap-4 rounded-md border p-3 text-sm">
|
||||
<span>
|
||||
<span className="block font-medium">启用 OIDC 登录</span>
|
||||
<span className="block text-xs text-muted-foreground">保存标准 OIDC 配置,后续登录入口按该开关展示。</span>
|
||||
</span>
|
||||
<input defaultChecked={organization.oidcEnabled} name="oidcEnabled" type="checkbox" />
|
||||
</label>
|
||||
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">Issuer URL</span>
|
||||
<Input defaultValue={organization.oidcIssuerUrl} name="oidcIssuerUrl" placeholder="https://idp.example.com" />
|
||||
</label>
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">Client ID</span>
|
||||
<Input defaultValue={organization.oidcClientId} name="oidcClientId" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">Client Secret</span>
|
||||
<Input
|
||||
name="oidcClientSecret"
|
||||
placeholder={organization.oidcHasClientSecret ? "已配置,留空则不修改" : "未配置"}
|
||||
type="password"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">Scopes</span>
|
||||
<Input defaultValue={organization.oidcScopes} name="oidcScopes" placeholder="openid profile email" />
|
||||
</label>
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">Redirect URI</span>
|
||||
<Input defaultValue={organization.oidcRedirectUri} name="oidcRedirectUri" placeholder="/api/auth/oidc/callback" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label className="flex items-center justify-between gap-4 rounded-md border p-3 text-sm">
|
||||
<span>
|
||||
<span className="block font-medium">OIDC 自动开户</span>
|
||||
<span className="block text-xs text-muted-foreground">首次 OIDC 登录时自动创建账号并进入本机构。</span>
|
||||
</span>
|
||||
<input defaultChecked={organization.oidcAutoProvision} name="oidcAutoProvision" type="checkbox" />
|
||||
</label>
|
||||
|
||||
{settingsMessage ? (
|
||||
<p className="rounded-md bg-secondary px-3 py-2 text-sm text-secondary-foreground" role="status">
|
||||
{settingsMessage}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<Button className="w-fit" disabled={isPending} type="submit">
|
||||
<Save className="size-4" aria-hidden="true" />
|
||||
保存配置
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>机构邀请</CardTitle>
|
||||
<CardDescription>生成邀请链接后发送给成员;可限定邮箱,也可生成通用邀请。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4">
|
||||
<form className="grid gap-3 md:grid-cols-[1fr_1fr_auto]" onSubmit={handleInviteSubmit}>
|
||||
<Input name="email" placeholder="邮箱,可留空" type="email" />
|
||||
<select
|
||||
className="h-11 w-full rounded-md border bg-background px-3 text-sm outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring"
|
||||
defaultValue={defaultRoleId}
|
||||
name="roleId"
|
||||
required
|
||||
>
|
||||
{organizationRoles.map((role) => (
|
||||
<option key={role.id} value={role.id}>
|
||||
{role.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Button disabled={isPending || !defaultRoleId} type="submit">
|
||||
<Send className="size-4" aria-hidden="true" />
|
||||
生成邀请
|
||||
</Button>
|
||||
</form>
|
||||
{inviteMessage ? (
|
||||
<p className="rounded-md bg-secondary px-3 py-2 text-sm text-secondary-foreground" role="status">
|
||||
{inviteMessage}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="overflow-x-auto rounded-md border">
|
||||
<table className="w-full min-w-[720px] 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">
|
||||
{invitations.map((invitation) => (
|
||||
<tr className="hover:bg-secondary/45" key={invitation.id}>
|
||||
<td className="px-4 py-3">{invitation.email || "通用邀请"}</td>
|
||||
<td className="px-4 py-3">{invitation.roleLabel}</td>
|
||||
<td className="px-4 py-3">
|
||||
<Badge variant={invitation.status === "active" ? "success" : "secondary"}>{invitation.status}</Badge>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">
|
||||
{new Date(invitation.expiresAt).toLocaleString("zh-CN")}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-right">
|
||||
<Button
|
||||
onClick={() => void navigator.clipboard.writeText(getInviteHref(invitation.token))}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
<Copy className="size-4" aria-hidden="true" />
|
||||
复制
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{invitations.length === 0 ? (
|
||||
<tr>
|
||||
<td className="px-4 py-8 text-center text-muted-foreground" colSpan={5}>
|
||||
暂无邀请
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<LinkIcon className="size-4" aria-hidden="true" />
|
||||
邀请链接使用 `/register?invite=...`,注册后自动加入机构。
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -28,84 +28,106 @@ type NavItem = {
|
||||
icon: LucideIcon;
|
||||
};
|
||||
|
||||
const navItems: NavItem[] = [
|
||||
type NavGroup = {
|
||||
label: string;
|
||||
items: NavItem[];
|
||||
};
|
||||
|
||||
const navGroups: NavGroup[] = [
|
||||
{
|
||||
href: "/app/dashboard",
|
||||
label: "运营看板",
|
||||
icon: LayoutDashboard,
|
||||
label: "运营",
|
||||
items: [
|
||||
{
|
||||
href: "/app/dashboard",
|
||||
label: "运营看板",
|
||||
icon: LayoutDashboard,
|
||||
},
|
||||
{
|
||||
href: "/app/elders",
|
||||
label: "老人档案",
|
||||
icon: Users,
|
||||
},
|
||||
{
|
||||
href: "/app/beds",
|
||||
label: "床位房间",
|
||||
icon: BedDouble,
|
||||
},
|
||||
{
|
||||
href: "/app/health",
|
||||
label: "健康照护",
|
||||
icon: HeartPulse,
|
||||
},
|
||||
{
|
||||
href: "/app/care",
|
||||
label: "护理服务",
|
||||
icon: ClipboardCheck,
|
||||
},
|
||||
{
|
||||
href: "/app/emergency",
|
||||
label: "安全应急",
|
||||
icon: ShieldAlert,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
href: "/app/elders",
|
||||
label: "老人档案",
|
||||
icon: Users,
|
||||
label: "协同",
|
||||
items: [
|
||||
{
|
||||
href: "/app/devices",
|
||||
label: "设备运维",
|
||||
icon: Wrench,
|
||||
},
|
||||
{
|
||||
href: "/app/notices",
|
||||
label: "公告通知",
|
||||
icon: Bell,
|
||||
},
|
||||
{
|
||||
href: "/app/alerts",
|
||||
label: "规则预警",
|
||||
icon: Radio,
|
||||
},
|
||||
{
|
||||
href: "/app/family",
|
||||
label: "家属服务",
|
||||
icon: TabletSmartphone,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
href: "/app/beds",
|
||||
label: "床位房间",
|
||||
icon: BedDouble,
|
||||
},
|
||||
{
|
||||
href: "/app/health",
|
||||
label: "健康照护",
|
||||
icon: HeartPulse,
|
||||
},
|
||||
{
|
||||
href: "/app/care",
|
||||
label: "护理服务",
|
||||
icon: ClipboardCheck,
|
||||
},
|
||||
{
|
||||
href: "/app/emergency",
|
||||
label: "安全应急",
|
||||
icon: ShieldAlert,
|
||||
},
|
||||
{
|
||||
href: "/app/devices",
|
||||
label: "设备运维",
|
||||
icon: Wrench,
|
||||
},
|
||||
{
|
||||
href: "/app/notices",
|
||||
label: "公告通知",
|
||||
icon: Bell,
|
||||
},
|
||||
{
|
||||
href: "/app/alerts",
|
||||
label: "规则预警",
|
||||
icon: Radio,
|
||||
},
|
||||
{
|
||||
href: "/app/family",
|
||||
label: "家属服务",
|
||||
icon: TabletSmartphone,
|
||||
},
|
||||
{
|
||||
href: "/app/settings/organizations",
|
||||
label: "机构管理",
|
||||
icon: Building2,
|
||||
},
|
||||
{
|
||||
href: "/app/settings/users",
|
||||
label: "用户管理",
|
||||
icon: Users,
|
||||
},
|
||||
{
|
||||
href: "/app/settings/roles",
|
||||
label: "角色权限",
|
||||
icon: Settings,
|
||||
},
|
||||
{
|
||||
href: "/app/settings/audit",
|
||||
label: "审计日志",
|
||||
icon: ListChecks,
|
||||
},
|
||||
{
|
||||
href: "/app/settings/status",
|
||||
label: "运行状态",
|
||||
icon: Wrench,
|
||||
label: "系统设置",
|
||||
items: [
|
||||
{
|
||||
href: "/app/settings/organizations",
|
||||
label: "机构管理",
|
||||
icon: Building2,
|
||||
},
|
||||
{
|
||||
href: "/app/settings/users",
|
||||
label: "用户管理",
|
||||
icon: Users,
|
||||
},
|
||||
{
|
||||
href: "/app/settings/roles",
|
||||
label: "角色权限",
|
||||
icon: Settings,
|
||||
},
|
||||
{
|
||||
href: "/app/settings/audit",
|
||||
label: "审计日志",
|
||||
icon: ListChecks,
|
||||
},
|
||||
{
|
||||
href: "/app/settings/status",
|
||||
label: "运行状态",
|
||||
icon: Wrench,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const navItems: NavItem[] = navGroups.flatMap((group) => group.items);
|
||||
|
||||
type AppShellProps = {
|
||||
children: React.ReactNode;
|
||||
account: PublicAccount;
|
||||
@@ -129,22 +151,29 @@ export function AppShell({ children, account, permissions }: AppShellProps): Rea
|
||||
</Link>
|
||||
|
||||
<nav className="min-h-0 flex-1 overflow-y-auto px-3 py-4" aria-label="主导航">
|
||||
<ul className="space-y-1">
|
||||
{navItems.map((item) => (
|
||||
<li key={item.href}>
|
||||
<Link
|
||||
href={item.href}
|
||||
className="group flex min-h-11 items-center gap-3 rounded-md px-3 text-sm transition-colors hover:bg-secondary"
|
||||
>
|
||||
<item.icon
|
||||
className="size-4 shrink-0 text-muted-foreground group-hover:text-primary"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="min-w-0 truncate font-medium">{item.label}</span>
|
||||
</Link>
|
||||
</li>
|
||||
<div className="space-y-5">
|
||||
{navGroups.map((group) => (
|
||||
<section key={group.label}>
|
||||
<p className="px-3 pb-2 text-xs font-semibold text-muted-foreground">{group.label}</p>
|
||||
<ul className="space-y-1">
|
||||
{group.items.map((item) => (
|
||||
<li key={item.href}>
|
||||
<Link
|
||||
href={item.href}
|
||||
className="group flex min-h-11 items-center gap-3 rounded-md px-3 text-sm transition-colors hover:bg-secondary"
|
||||
>
|
||||
<item.icon
|
||||
className="size-4 shrink-0 text-muted-foreground group-hover:text-primary"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="min-w-0 truncate font-medium">{item.label}</span>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
Reference in New Issue
Block a user