@mano8/astro-auth-m8 0.1.1-alpha.1 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/src/runtime/client.d.ts +1 -0
- package/dist/src/runtime/client.d.ts.map +1 -1
- package/dist/src/runtime/client.js +1 -0
- package/dist/src/runtime/client.js.map +1 -1
- package/package.json +2 -2
- package/registry/r/account-crud.json +25 -0
- package/registry/r/account-dashboard.json +1 -1
- package/registry/r/admin-users-panel.json +8 -4
- package/registry/r/api-keys-panel.json +11 -3
- package/registry/r/dashboard-overview.json +1 -1
- package/registry/r/registry.json +8 -2
- package/registry.json +39 -5
package/README.md
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# astro-auth-m8
|
|
2
2
|
|
|
3
|
+

|
|
4
|
+
|
|
3
5
|
Astro integration and headless runtime client for `fa-auth-m8`.
|
|
4
6
|
|
|
5
7
|
Part of the M8 auth stack: [mano8/astro-auth-m8](https://github.com/mano8/astro-auth-m8) is the Astro plugin layer for the [mano8/fa-auth-m8](https://github.com/mano8/fa-auth-m8) backend service, and it is ready to compose into [mano8/fa-ui-m8](https://github.com/mano8/fa-ui-m8).
|
|
@@ -14,7 +16,7 @@ Use it with a `fa-auth-m8` backend that satisfies the `fa-auth-m8@1.0` contract.
|
|
|
14
16
|
|
|
15
17
|
## Backend contract
|
|
16
18
|
|
|
17
|
-
This package targets the `fa-auth-m8@1.0` API contract and was tested against `fa-auth-m8` service version `1.
|
|
19
|
+
This package targets the `fa-auth-m8@1.0` API contract and was tested against `fa-auth-m8` service version `1.1.0`. Supported backend service versions are `>=1.0.0 <2.0.0`.
|
|
18
20
|
|
|
19
21
|
Compatibility helpers are exported from `@mano8/astro-auth-m8/compatibility`. `fa-auth-m8` (>= 1.0.0) exposes a public `GET {API_PREFIX}/meta` route returning a `ServiceMeta` payload - pass it straight to the assert:
|
|
20
22
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
export * from "./api/index.js";
|
|
3
3
|
export { clearToken, getToken, setToken } from "./tokenStore.js";
|
|
4
|
+
export { configureAuth, getAuthConfig, type AuthRuntimeConfig } from "./config.js";
|
|
4
5
|
export type RequestOptions<T> = {
|
|
5
6
|
method: "GET" | "POST" | "PATCH" | "PUT" | "DELETE";
|
|
6
7
|
path: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/runtime/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAMxB,cAAc,gBAAgB,CAAC;AAC/B,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/runtime/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAMxB,cAAc,gBAAgB,CAAC;AAC/B,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AACjE,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,KAAK,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEnF,MAAM,MAAM,cAAc,CAAC,CAAC,IAAI;IAC9B,MAAM,EAAE,KAAK,GAAG,MAAM,GAAG,OAAO,GAAG,KAAK,GAAG,QAAQ,CAAC;IACpD,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9B,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,SAAS,GAAG,IAAI,CAAC,CAAC;IACrE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,MAAM,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IACrB,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB,CAAC;AAEF,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAQ5C;AA8BD,wBAAsB,OAAO,CAAC,CAAC,EAAE,OAAO,EAAE,cAAc,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAuDvE"}
|
|
@@ -4,6 +4,7 @@ import { getToken, runRefresh, setToken } from "./tokenStore.js";
|
|
|
4
4
|
import { TokenSchema } from "./schemas.js";
|
|
5
5
|
export * from "./api/index.js";
|
|
6
6
|
export { clearToken, getToken, setToken } from "./tokenStore.js";
|
|
7
|
+
export { configureAuth, getAuthConfig } from "./config.js";
|
|
7
8
|
export function authUrl(path) {
|
|
8
9
|
const { apiBase } = getAuthConfig();
|
|
9
10
|
const origin = typeof window === "undefined" ? "http://localhost" : window.location.origin;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/runtime/client.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACpF,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AACjE,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,cAAc,gBAAgB,CAAC;AAC/B,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/runtime/client.ts"],"names":[],"mappings":"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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mano8/astro-auth-m8",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Astro integration and headless client for fa-auth-m8.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -57,7 +57,7 @@
|
|
|
57
57
|
"test:unit": "vitest run"
|
|
58
58
|
},
|
|
59
59
|
"dependencies": {
|
|
60
|
-
"@mano8/astro-ui-m8": "^
|
|
60
|
+
"@mano8/astro-ui-m8": "^1.3.0"
|
|
61
61
|
},
|
|
62
62
|
"peerDependencies": {
|
|
63
63
|
"astro": "^5.0.0 || ^6.0.0",
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "account-crud",
|
|
4
|
+
"type": "registry:component",
|
|
5
|
+
"title": "Account CRUD Helpers",
|
|
6
|
+
"description": "Shared skin helpers for the fa-auth account panels: a client-side controller for the canonical astro-ui-m8 data-table, a popup form dialog, a delete-confirmation alert, the fixed row-actions cell, and the bottom-right toast host.",
|
|
7
|
+
"dependencies": [
|
|
8
|
+
"lucide-react"
|
|
9
|
+
],
|
|
10
|
+
"registryDependencies": [
|
|
11
|
+
"button",
|
|
12
|
+
"dialog",
|
|
13
|
+
"alert-dialog",
|
|
14
|
+
"./node_modules/@mano8/astro-ui-m8/registry/r/data-table.json",
|
|
15
|
+
"./node_modules/@mano8/astro-ui-m8/registry/r/toast-notification.json"
|
|
16
|
+
],
|
|
17
|
+
"files": [
|
|
18
|
+
{
|
|
19
|
+
"path": "registry/blocks/account/account-crud.tsx",
|
|
20
|
+
"content": "\"use client\";\n\n// Shared skin helpers for the fa-auth account management panels (API keys +\n// admin users). Composes the canonical @mano8/astro-ui-m8 data-table and toast\n// blocks (copied into `@/components/m8-ui/*`) into the CRUD idioms the panels\n// share: a client-side controller for the server data-table, a popup form\n// dialog, a delete confirmation alert, the fixed row-actions cell, and the\n// bottom-right toast host. Copied into the consumer via the @fa-m8-auth\n// registry — edit freely per app.\nimport * as React from \"react\";\nimport { Pencil, Trash2 } from \"lucide-react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n} from \"@/components/ui/dialog\";\nimport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from \"@/components/ui/alert-dialog\";\nimport type { DataTableSortDirection } from \"@/components/m8-ui/data-table\";\nimport {\n ToastNotificationHost,\n toastNotification,\n} from \"@/components/m8-ui/toast-notification\";\n\n// Bottom-right toast host + helpers for every account surface. Mount the host\n// once in the account shell; call `accountToast.success/error/info` from\n// mutation callbacks.\nexport function AccountToastHost() {\n return <ToastNotificationHost position=\"bottom-right\" />;\n}\nexport const accountToast = toastNotification;\n\n// --- client-side controller for the canonical (server-shaped) data-table -----\n// The shared data-table is a controlled/server component; this hook drives it\n// entirely client-side (search + sort + paginate over an in-memory array) so\n// the account panels get the page-size selector, orderable columns, and column\n// visibility for free without a server list endpoint.\nexport interface ClientTableController<TData> {\n data: TData[];\n rowCount: number;\n page: number;\n pageSize: number;\n onPageChange: (page: number) => void;\n onPageSizeChange: (pageSize: number) => void;\n sortBy?: string;\n sortDir?: DataTableSortDirection;\n onSortChange: (sortBy?: string, sortDir?: DataTableSortDirection) => void;\n q: string;\n onSearchChange: (q: string) => void;\n}\n\nexport interface UseClientTableOptions<TData> {\n search?: (row: TData) => string;\n sorters?: Record<string, (row: TData) => string | number>;\n initialSortBy?: string;\n initialSortDir?: DataTableSortDirection;\n initialPageSize?: number;\n}\n\nfunction compareValues(a: string | number, b: string | number): number {\n if (typeof a === \"number\" && typeof b === \"number\") return a - b;\n return String(a).localeCompare(String(b), undefined, {\n numeric: true,\n sensitivity: \"base\",\n });\n}\n\nexport function useClientTable<TData>(\n rows: TData[],\n options: UseClientTableOptions<TData> = {},\n): ClientTableController<TData> {\n const {\n search,\n sorters,\n initialSortBy,\n initialSortDir = \"asc\",\n initialPageSize = 10,\n } = options;\n const [page, setPage] = React.useState(1);\n const [pageSize, setPageSize] = React.useState(initialPageSize);\n const [sortBy, setSortBy] = React.useState<string | undefined>(initialSortBy);\n const [sortDir, setSortDir] = React.useState<DataTableSortDirection | undefined>(\n initialSortBy ? initialSortDir : undefined,\n );\n const [q, setQ] = React.useState(\"\");\n\n const normalizedQuery = q.trim().toLocaleLowerCase();\n const filtered = React.useMemo(() => {\n if (!normalizedQuery || !search) return rows;\n return rows.filter((row) =>\n search(row).toLocaleLowerCase().includes(normalizedQuery),\n );\n }, [rows, normalizedQuery, search]);\n\n const sorted = React.useMemo(() => {\n const sorter = sortBy && sorters ? sorters[sortBy] : undefined;\n if (!sorter || !sortDir) return filtered;\n const direction = sortDir === \"asc\" ? 1 : -1;\n return [...filtered].sort(\n (a, b) => compareValues(sorter(a), sorter(b)) * direction,\n );\n }, [filtered, sortBy, sortDir, sorters]);\n\n const rowCount = sorted.length;\n const pageCount = Math.max(1, Math.ceil(rowCount / Math.max(1, pageSize)));\n const currentPage = Math.min(page, pageCount);\n const pageRows = React.useMemo(\n () => sorted.slice((currentPage - 1) * pageSize, currentPage * pageSize),\n [sorted, currentPage, pageSize],\n );\n\n return {\n data: pageRows,\n rowCount,\n page: currentPage,\n pageSize,\n onPageChange: setPage,\n onPageSizeChange: (next) => {\n setPageSize(next);\n setPage(1);\n },\n sortBy,\n sortDir,\n onSortChange: (nextBy, nextDir) => {\n setSortBy(nextBy);\n setSortDir(nextDir);\n setPage(1);\n },\n q,\n onSearchChange: (next) => {\n setQ(next);\n setPage(1);\n },\n };\n}\n\n// --- fixed row-actions cell (rendered as the 2nd column) --------------------\nexport function RowActions({\n editLabel,\n deleteLabel,\n onEdit,\n onDelete,\n disabled,\n}: {\n editLabel: string;\n deleteLabel: string;\n onEdit: () => void;\n onDelete: () => void;\n disabled?: boolean;\n}) {\n return (\n <div className=\"flex items-center gap-2\" data-account-row-actions=\"\">\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"outline\"\n disabled={disabled}\n onClick={onEdit}\n data-account-action=\"edit\"\n >\n <Pencil className=\"size-3.5\" />\n <span className=\"sr-only lg:not-sr-only\">{editLabel}</span>\n </Button>\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"destructive\"\n disabled={disabled}\n onClick={onDelete}\n data-account-action=\"delete\"\n >\n <Trash2 className=\"size-3.5\" />\n <span className=\"sr-only lg:not-sr-only\">{deleteLabel}</span>\n </Button>\n </div>\n );\n}\n\n// --- popup form dialog ------------------------------------------------------\nexport function EntityFormDialog({\n open,\n onOpenChange,\n title,\n description,\n children,\n}: {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n title: string;\n description?: string;\n children: React.ReactNode;\n}) {\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"sm:max-w-lg\">\n <DialogHeader>\n <DialogTitle>{title}</DialogTitle>\n {description ? (\n <DialogDescription>{description}</DialogDescription>\n ) : null}\n </DialogHeader>\n {children}\n </DialogContent>\n </Dialog>\n );\n}\n\n// --- delete confirmation alert ----------------------------------------------\nexport function ConfirmDeleteDialog({\n open,\n onOpenChange,\n title,\n description,\n confirmLabel,\n cancelLabel,\n pending,\n onConfirm,\n}: {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n title: string;\n description: string;\n confirmLabel: string;\n cancelLabel: string;\n pending?: boolean;\n onConfirm: () => void;\n}) {\n return (\n <AlertDialog open={open} onOpenChange={onOpenChange}>\n <AlertDialogContent>\n <AlertDialogHeader>\n <AlertDialogTitle>{title}</AlertDialogTitle>\n <AlertDialogDescription>{description}</AlertDialogDescription>\n </AlertDialogHeader>\n <AlertDialogFooter>\n <AlertDialogCancel disabled={pending}>{cancelLabel}</AlertDialogCancel>\n <AlertDialogAction\n variant=\"destructive\"\n disabled={pending}\n onClick={(event) => {\n event.preventDefault();\n onConfirm();\n }}\n >\n {confirmLabel}\n </AlertDialogAction>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n );\n}\n\nexport function errorMessage(error: unknown, fallback: string): string {\n return error instanceof Error && error.message ? error.message : fallback;\n}\n",
|
|
21
|
+
"type": "registry:component",
|
|
22
|
+
"target": "components/fa-auth/account-crud.tsx"
|
|
23
|
+
}
|
|
24
|
+
]
|
|
25
|
+
}
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"files": [
|
|
14
14
|
{
|
|
15
15
|
"path": "registry/blocks/account/account-dashboard.tsx",
|
|
16
|
-
"content": "\"use client\";\n\n// fa-auth account view whose FIRST/landing tab is the activity dashboard.\n// Headless auth state comes from the package (@mano8/astro-auth-m8/react); this\n// file is only the shadcn skin and is copied into the consumer via the\n// @fa-m8-auth registry. Secondary tabs (profile/sessions/api-keys/admin) are\n// passed in by the consumer via `extraTabs`, so locale + app-specific panels\n// stay owned by the app. Edit freely per app.\nimport * as React from \"react\";\nimport { LayoutDashboard, LogOut } from \"lucide-react\";\nimport {\n AuthProvider,\n useAuth,\n type AuthContextValue,\n} from \"@mano8/astro-auth-m8/react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Skeleton } from \"@/components/ui/skeleton\";\nimport {\n NavigationMenu,\n NavigationMenuItem,\n NavigationMenuList,\n} from \"@/components/ui/navigation-menu\";\nimport {\n DashboardOverview,\n type DashboardOverviewLabels,\n} from \"@/components/fa-auth/dashboard-overview\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface AccountTab {\n id: string;\n label: string;\n icon?: React.ComponentType<{ className?: string }>;\n content: React.ReactNode;\n /** Only render this tab when the signed-in user is a superuser. */\n superuserOnly?: boolean;\n}\n\nexport interface AccountDashboardLabels {\n dashboardTab: string;\n signOut: string;\n signInRequired: string;\n dashboard: Partial<DashboardOverviewLabels>;\n}\n\nconst DEFAULT_LABELS: AccountDashboardLabels = {\n dashboardTab: \"Dashboard\",\n signOut: \"Sign out\",\n signInRequired: \"Please sign in to view your account.\",\n dashboard: {},\n};\n\nexport interface AccountDashboardProps {\n /** Auth API base path; defaults to PUBLIC_FA_AUTH_API_BASE or \"/user\". */\n apiBase?: string;\n /** Dashboard scope: \"me\" (default) or \"global\" for superuser fleet stats. */\n scope?: \"me\" | \"global\";\n extraTabs?: AccountTab[];\n labels?: Partial<AccountDashboardLabels>;\n /** Rendered when the user is not authenticated. */\n signIn?: React.ReactNode;\n}\n\nfunction AccountShell({\n scope,\n extraTabs,\n labels,\n signIn,\n}: Required<Pick<AccountDashboardProps, \"scope\" | \"extraTabs\">> & {\n labels: AccountDashboardLabels;\n signIn?: React.ReactNode;\n}) {\n const { user, loading, logout }: AuthContextValue = useAuth();\n\n if (loading) {\n return (\n <div className=\"not-content mx-auto w-full max-w-6xl space-y-4\" aria-busy=\"true\">\n <Skeleton className=\"h-10 w-64\" />\n <Skeleton className=\"h-9 w-full max-w-md\" />\n <Skeleton className=\"h-72 w-full\" />\n </div>\n );\n }\n\n if (!user) {\n return (\n <div className=\"not-content mx-auto w-full max-w-md py-10 text-center text-sm text-muted-foreground\">\n {signIn ?? labels.signInRequired}\n </div>\n );\n }\n\n const visibleTabs = extraTabs.filter(\n (tab) => !tab.superuserOnly || user.is_superuser,\n );\n const [activeTab, setActiveTab] = React.useState<string>(\"dashboard\");\n const navItems = [\n {\n id: \"dashboard\",\n label: labels.dashboardTab,\n icon: LayoutDashboard,\n content: <DashboardOverview scope={scope} labels={labels.dashboard} />,\n },\n ...visibleTabs,\n ];\n const columnClass = navItems.length >= 5 ? \"lg:grid-cols-5\" : \"lg:grid-cols-4\";\n\n return (\n <div className=\"not-content mx-auto w-full max-w-6xl
|
|
16
|
+
"content": "\"use client\";\n\n// fa-auth account view whose FIRST/landing tab is the activity dashboard.\n// Headless auth state comes from the package (@mano8/astro-auth-m8/react); this\n// file is only the shadcn skin and is copied into the consumer via the\n// @fa-m8-auth registry. Secondary tabs (profile/sessions/api-keys/admin) are\n// passed in by the consumer via `extraTabs`, so locale + app-specific panels\n// stay owned by the app. Edit freely per app.\nimport * as React from \"react\";\nimport { LayoutDashboard, LogOut } from \"lucide-react\";\nimport {\n AuthProvider,\n useAuth,\n type AuthContextValue,\n} from \"@mano8/astro-auth-m8/react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Skeleton } from \"@/components/ui/skeleton\";\nimport {\n NavigationMenu,\n NavigationMenuItem,\n NavigationMenuList,\n} from \"@/components/ui/navigation-menu\";\nimport {\n DashboardOverview,\n type DashboardOverviewLabels,\n} from \"@/components/fa-auth/dashboard-overview\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface AccountTab {\n id: string;\n label: string;\n icon?: React.ComponentType<{ className?: string }>;\n content: React.ReactNode;\n /** Only render this tab when the signed-in user is a superuser. */\n superuserOnly?: boolean;\n}\n\nexport interface AccountDashboardLabels {\n dashboardTab: string;\n signOut: string;\n signInRequired: string;\n dashboard: Partial<DashboardOverviewLabels>;\n}\n\nconst DEFAULT_LABELS: AccountDashboardLabels = {\n dashboardTab: \"Dashboard\",\n signOut: \"Sign out\",\n signInRequired: \"Please sign in to view your account.\",\n dashboard: {},\n};\n\nexport interface AccountDashboardProps {\n /** Auth API base path; defaults to PUBLIC_FA_AUTH_API_BASE or \"/user\". */\n apiBase?: string;\n /** Dashboard scope: \"me\" (default) or \"global\" for superuser fleet stats. */\n scope?: \"me\" | \"global\";\n extraTabs?: AccountTab[];\n labels?: Partial<AccountDashboardLabels>;\n /** Rendered when the user is not authenticated. */\n signIn?: React.ReactNode;\n}\n\nfunction AccountShell({\n scope,\n extraTabs,\n labels,\n signIn,\n}: Required<Pick<AccountDashboardProps, \"scope\" | \"extraTabs\">> & {\n labels: AccountDashboardLabels;\n signIn?: React.ReactNode;\n}) {\n const { user, loading, logout }: AuthContextValue = useAuth();\n\n if (loading) {\n return (\n <div className=\"not-content mx-auto w-full max-w-6xl space-y-4\" aria-busy=\"true\">\n <Skeleton className=\"h-10 w-64\" />\n <Skeleton className=\"h-9 w-full max-w-md\" />\n <Skeleton className=\"h-72 w-full\" />\n </div>\n );\n }\n\n if (!user) {\n return (\n <div className=\"not-content mx-auto w-full max-w-md py-10 text-center text-sm text-muted-foreground\">\n {signIn ?? labels.signInRequired}\n </div>\n );\n }\n\n const visibleTabs = extraTabs.filter(\n (tab) => !tab.superuserOnly || user.is_superuser,\n );\n const [activeTab, setActiveTab] = React.useState<string>(\"dashboard\");\n const navItems = [\n {\n id: \"dashboard\",\n label: labels.dashboardTab,\n icon: LayoutDashboard,\n content: <DashboardOverview scope={scope} labels={labels.dashboard} />,\n },\n ...visibleTabs,\n ];\n const columnClass = navItems.length >= 5 ? \"lg:grid-cols-5\" : \"lg:grid-cols-4\";\n\n return (\n <div className=\"not-content mx-auto flex w-full max-w-6xl flex-col gap-6\">\n <div className=\"flex flex-col gap-4 border-b pb-5 lg:flex-row lg:items-end lg:justify-between\">\n <div className=\"min-w-0 space-y-2\">\n <h1 className=\"text-2xl font-semibold tracking-tight md:text-3xl\">\n {user.email}\n </h1>\n <div className=\"flex flex-wrap items-center gap-2 text-sm text-muted-foreground\">\n <span className=\"rounded-md border px-2 py-0.5 text-xs uppercase tracking-wide\">\n {user.role}\n </span>\n {user.is_superuser ? (\n <span className=\"rounded-md border px-2 py-0.5 text-xs uppercase tracking-wide\">\n superuser\n </span>\n ) : null}\n </div>\n </div>\n <Button\n variant=\"outline\"\n onClick={() => void logout()}\n className=\"w-full justify-center gap-2 sm:w-auto\"\n >\n <LogOut className=\"size-4\" />\n {labels.signOut}\n </Button>\n </div>\n\n <div className=\"space-y-4\">\n <NavigationMenu viewport={false} className=\"w-full max-w-none justify-stretch\">\n <NavigationMenuList\n className={cn(\n \"grid h-auto w-full grid-cols-1 items-stretch justify-stretch rounded-lg border border-border bg-muted/40 p-1 sm:grid-cols-2\",\n columnClass,\n )}\n >\n {navItems.map((tab) => {\n const Icon = tab.icon;\n const active = activeTab === tab.id;\n return (\n <NavigationMenuItem key={tab.id}>\n <button\n type=\"button\"\n aria-current={active ? \"page\" : undefined}\n className=\"inline-flex h-9 w-full min-w-0 items-center justify-center gap-2 rounded-md px-3 text-sm font-medium whitespace-nowrap transition-colors outline-none select-none hover:bg-background hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50 data-[active=true]:bg-background data-[active=true]:text-foreground data-[active=true]:shadow-xs\"\n data-active={active}\n onClick={() => setActiveTab(tab.id)}\n >\n {Icon ? <Icon className=\"size-4 shrink-0\" /> : null}\n <span className=\"truncate\">{tab.label}</span>\n </button>\n </NavigationMenuItem>\n );\n })}\n </NavigationMenuList>\n </NavigationMenu>\n\n {navItems.map((tab) =>\n activeTab === tab.id ? <React.Fragment key={tab.id}>{tab.content}</React.Fragment> : null,\n )}\n </div>\n </div>\n );\n}\n\nexport default function AccountDashboard({\n apiBase,\n scope = \"me\",\n extraTabs = [],\n labels,\n signIn,\n}: AccountDashboardProps) {\n const resolved: AccountDashboardLabels = {\n ...DEFAULT_LABELS,\n ...labels,\n dashboard: { ...DEFAULT_LABELS.dashboard, ...labels?.dashboard },\n };\n const config = apiBase ? { apiBase } : undefined;\n return (\n <AuthProvider config={config}>\n <AccountShell\n scope={scope}\n extraTabs={extraTabs}\n labels={resolved}\n signIn={signIn}\n />\n </AuthProvider>\n );\n}\n",
|
|
17
17
|
"type": "registry:component",
|
|
18
18
|
"target": "components/fa-auth/account-dashboard.tsx"
|
|
19
19
|
}
|
|
@@ -3,21 +3,25 @@
|
|
|
3
3
|
"name": "admin-users-panel",
|
|
4
4
|
"type": "registry:component",
|
|
5
5
|
"title": "Admin Users Panel",
|
|
6
|
-
"description": "fa-auth superuser-only user management (create/
|
|
6
|
+
"description": "fa-auth superuser-only user management on the canonical data-table (page selector, orderable columns, column visibility), with popup create/edit forms, alert-dialog delete confirm, and bottom-right toasts. Gated by the package's RequireRole and driven by useUsers. Requires @mano8/astro-auth-m8 installed.",
|
|
7
7
|
"dependencies": [
|
|
8
|
-
"lucide-react"
|
|
8
|
+
"lucide-react",
|
|
9
|
+
"@tanstack/react-table"
|
|
9
10
|
],
|
|
10
11
|
"registryDependencies": [
|
|
11
12
|
"card",
|
|
12
13
|
"button",
|
|
13
14
|
"input",
|
|
14
15
|
"label",
|
|
15
|
-
"
|
|
16
|
+
"badge",
|
|
17
|
+
"dialog",
|
|
18
|
+
"./node_modules/@mano8/astro-ui-m8/registry/r/data-table.json",
|
|
19
|
+
"./account-crud.json"
|
|
16
20
|
],
|
|
17
21
|
"files": [
|
|
18
22
|
{
|
|
19
23
|
"path": "registry/blocks/account/admin-users-panel.tsx",
|
|
20
|
-
"content": "\"use client\";\n\n// fa-auth admin users panel: superuser-only user management (create / update /\n// delete). Headless logic stays a live dependency - `useUsers`\n// (@mano8/astro-auth-m8/hooks) owns the API calls, the package Zod schemas\n// validate the forms, and the package's `RequireRole superuser` gates the whole\n// panel. This file is only the shadcn skin, copied into the consumer via the\n// @fa-m8-auth registry - edit (and translate via `labels`) freely per app.\nimport * as React from \"react\";\nimport { RefreshCw, Trash2 } from \"lucide-react\";\nimport { RequireRole } from \"@mano8/astro-auth-m8/react\";\nimport { useUsers } from \"@mano8/astro-auth-m8/hooks\";\nimport {\n RoleTypeSchema,\n UserCreateSchema,\n UserUpdateSchema,\n type UserPublic,\n} from \"@mano8/astro-auth-m8/schemas\";\nimport type { ColumnDef } from \"@tanstack/react-table\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { DataTable } from \"@/components/m8-ui/data-table\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"@/components/ui/card\";\n\nexport interface AdminUsersPanelLabels {\n title: string;\n description: string;\n updateScope: string;\n invalidCreate: string;\n invalidUpdate: string;\n created: string;\n updated: string;\n createFailed: string;\n updateFailed: string;\n deleteFailed: string;\n email: string;\n fullName: string;\n avatar: string;\n avatarPlaceholder: string;\n password: string;\n passwordPlaceholder: string;\n passwordUnsupported: string;\n create: string;\n role: string;\n emailVerified: string;\n superuser: string;\n users: string;\n refresh: string;\n loading: string;\n user: string;\n provider: string;\n providerPassword: string;\n providerGoogle: string;\n actions: string;\n active: string;\n inactive: string;\n save: string;\n delete: string;\n empty: string;\n}\n\nconst DEFAULT_LABELS: AdminUsersPanelLabels = {\n title: \"Admin users\",\n description: \"Superuser-only user management.\",\n updateScope:\n \"User updates support email, full name, avatar, password, and role. Provider, account status, and verification flags are managed by the auth service.\",\n invalidCreate: \"Invalid user payload.\",\n invalidUpdate: \"Invalid update payload.\",\n created: \"User created.\",\n updated: \"User updated.\",\n createFailed: \"Failed to create user.\",\n updateFailed: \"Failed to update user.\",\n deleteFailed: \"Failed to delete user.\",\n email: \"Email\",\n fullName: \"Full name\",\n avatar: \"Avatar URL\",\n avatarPlaceholder: \"https://example.com/avatar.png\",\n password: \"Password\",\n passwordPlaceholder: \"Leave blank to keep current password\",\n passwordUnsupported: \"Password disabled for Google users\",\n create: \"Create\",\n role: \"Role\",\n emailVerified: \"Email verified\",\n superuser: \"Superuser\",\n users: \"users\",\n refresh: \"Refresh\",\n loading: \"Loading users...\",\n user: \"User\",\n provider: \"Provider\",\n providerPassword: \"Password\",\n providerGoogle: \"Google\",\n actions: \"Actions\",\n active: \"Active\",\n inactive: \"Inactive\",\n save: \"Save\",\n delete: \"Delete\",\n empty: \"No users found.\",\n};\n\nfunction formString(formData: FormData, key: string): string | undefined {\n const value = formData.get(key);\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nconst inputClassName =\n \"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40\";\n\nfunction AdminUsersPanelInner({ t }: { t: AdminUsersPanelLabels }) {\n const { users: usersData, loading, error, reload, create, update, remove } = useUsers(false);\n const users = usersData?.data ?? [];\n const count = usersData?.count ?? 0;\n const errorText = error instanceof Error ? error.message : error ? String(error) : null;\n const [message, setMessage] = React.useState<string | null>(null);\n\n React.useEffect(() => {\n reload().catch(() => {});\n }, [reload]);\n\n const handleCreate = async (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n setMessage(null);\n\n const form = event.currentTarget;\n const formData = new FormData(form);\n const role = formString(formData, \"role\");\n // Superadmins create password-based accounts only; OAuth credentials and the\n // email_verified flag are owned by the auth service's internal sign-in flow.\n const parsed = UserCreateSchema.safeParse({\n email: formString(formData, \"email\"),\n password: formString(formData, \"password\"),\n full_name: formString(formData, \"full_name\"),\n avatar: formString(formData, \"avatar\"),\n provider: \"password\",\n role: role ? RoleTypeSchema.parse(role) : \"user\",\n is_active: formData.get(\"is_active\") === \"on\",\n is_superuser: formData.get(\"is_superuser\") === \"on\",\n });\n\n if (!parsed.success) {\n setMessage(parsed.error.issues[0]?.message ?? t.invalidCreate);\n return;\n }\n\n try {\n await create(parsed.data);\n await reload();\n form.reset();\n setMessage(t.created);\n } catch (err) {\n setMessage(err instanceof Error ? err.message : t.createFailed);\n }\n };\n\n const handleUpdate = async (event: React.FormEvent<HTMLFormElement>, id: string) => {\n event.preventDefault();\n setMessage(null);\n\n const formData = new FormData(event.currentTarget);\n // Provider and OAuth user ID are owned by the auth service and not editable here.\n const parsed = UserUpdateSchema.safeParse({\n email: formString(formData, \"email\"),\n full_name: formString(formData, \"full_name\"),\n avatar: formString(formData, \"avatar\"),\n password: formString(formData, \"password\"),\n role: formString(formData, \"role\"),\n });\n\n if (!parsed.success) {\n setMessage(parsed.error.issues[0]?.message ?? t.invalidUpdate);\n return;\n }\n\n try {\n await update(id, parsed.data);\n await reload();\n setMessage(t.updated);\n } catch (err) {\n setMessage(err instanceof Error ? err.message : t.updateFailed);\n }\n };\n\n const handleDelete = React.useCallback(\n async (id: string) => {\n setMessage(null);\n try {\n await remove(id);\n await reload();\n } catch (err) {\n setMessage(err instanceof Error ? err.message : t.deleteFailed);\n }\n },\n [reload, remove, t.deleteFailed],\n );\n\n const columns = React.useMemo<ColumnDef<UserPublic>[]>(\n () => [\n {\n accessorKey: \"email\",\n header: t.user,\n cell: ({ row }) => {\n const user = row.original;\n const formId = `admin-user-${user.id}`;\n return (\n <form\n id={formId}\n onSubmit={(event) => void handleUpdate(event, user.id)}\n className=\"grid min-w-[20rem] gap-2\"\n >\n <Input name=\"email\" type=\"email\" defaultValue={user.email} required />\n <Input\n name=\"full_name\"\n defaultValue={user.full_name ?? \"\"}\n placeholder={t.fullName}\n />\n <Input\n name=\"avatar\"\n type=\"url\"\n defaultValue={user.avatar ?? \"\"}\n placeholder={t.avatarPlaceholder}\n />\n <Input\n name=\"password\"\n type=\"password\"\n placeholder={\n user.provider === \"password\"\n ? t.passwordPlaceholder\n : t.passwordUnsupported\n }\n disabled={user.provider === \"google\"}\n />\n </form>\n );\n },\n },\n {\n accessorKey: \"role\",\n header: t.role,\n cell: ({ row }) => {\n const user = row.original;\n return (\n <select\n name=\"role\"\n form={`admin-user-${user.id}`}\n defaultValue={user.role}\n className={inputClassName}\n >\n {RoleTypeSchema.options.map((role) => (\n <option key={role} value={role}>\n {role}\n </option>\n ))}\n </select>\n );\n },\n },\n {\n accessorKey: \"provider\",\n header: t.provider,\n cell: ({ row }) => {\n const user = row.original;\n return (\n <div className=\"space-y-2\">\n <span className=\"inline-flex h-8 items-center rounded-md border bg-muted/40 px-2 text-sm capitalize\">\n {user.provider === \"google\" ? t.providerGoogle : t.providerPassword}\n </span>\n <p className=\"text-xs text-muted-foreground\">\n {user.is_active ? t.active : t.inactive}\n {user.email_verified ? ` - ${t.emailVerified}` : \"\"}\n {user.is_superuser ? ` - ${t.superuser}` : \"\"}\n </p>\n </div>\n );\n },\n },\n {\n id: \"actions\",\n header: t.actions,\n cell: ({ row }) => {\n const user = row.original;\n return (\n <div className=\"flex flex-wrap gap-2\">\n <Button type=\"submit\" form={`admin-user-${user.id}`} size=\"sm\">\n {t.save}\n </Button>\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"destructive\"\n onClick={() => void handleDelete(user.id)}\n >\n <Trash2 />\n {t.delete}\n </Button>\n </div>\n );\n },\n },\n ],\n [\n handleDelete,\n t.actions,\n t.active,\n t.avatarPlaceholder,\n t.delete,\n t.emailVerified,\n t.fullName,\n t.inactive,\n t.passwordPlaceholder,\n t.passwordUnsupported,\n t.provider,\n t.providerGoogle,\n t.providerPassword,\n t.role,\n t.save,\n t.superuser,\n t.user,\n ],\n );\n\n return (\n <Card className=\"not-content\">\n <CardHeader>\n <CardTitle>{t.title}</CardTitle>\n <CardDescription>{t.description}</CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-6\">\n <p className=\"text-sm text-muted-foreground\">{t.updateScope}</p>\n <form\n onSubmit={handleCreate}\n className=\"grid gap-3 md:grid-cols-2 md:items-end xl:grid-cols-4\"\n >\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-email\" className=\"pb-2\">\n {t.email}\n </Label>\n <Input id=\"admin-create-email\" name=\"email\" type=\"email\" required />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-name\" className=\"pb-2\">\n {t.fullName}\n </Label>\n <Input id=\"admin-create-name\" name=\"full_name\" />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-avatar\" className=\"pb-2\">\n {t.avatar}\n </Label>\n <Input\n id=\"admin-create-avatar\"\n name=\"avatar\"\n type=\"url\"\n placeholder={t.avatarPlaceholder}\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-password\" className=\"pb-2\">\n {t.password}\n </Label>\n <Input\n id=\"admin-create-password\"\n name=\"password\"\n type=\"password\"\n minLength={8}\n required\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-role\" className=\"pb-2\">\n {t.role}\n </Label>\n <select\n id=\"admin-create-role\"\n name=\"role\"\n defaultValue=\"user\"\n className={inputClassName}\n >\n {RoleTypeSchema.options.map((role) => (\n <option key={role} value={role}>\n {role}\n </option>\n ))}\n </select>\n </div>\n <label className=\"flex items-center gap-2 pb-2 text-sm\">\n <input\n name=\"is_active\"\n type=\"checkbox\"\n defaultChecked\n className=\"size-4\"\n />\n {t.active}\n </label>\n <label className=\"flex items-center gap-2 pb-2 text-sm\">\n <input name=\"is_superuser\" type=\"checkbox\" className=\"size-4\" />\n {t.superuser}\n </label>\n <Button type=\"submit\">{t.create}</Button>\n </form>\n\n <div className=\"flex items-center justify-between gap-3\">\n <p className=\"text-sm text-muted-foreground\">\n {count} {t.users}\n </p>\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"outline\"\n onClick={() => void reload()}\n >\n <RefreshCw />\n {t.refresh}\n </Button>\n </div>\n\n {(message || errorText) && (\n <p className=\"rounded-md border p-3 text-sm\">{message ?? errorText}</p>\n )}\n\n {loading && users.length === 0 ? (\n <p className=\"text-sm text-muted-foreground\">{t.loading}</p>\n ) : (\n <DataTable\n columns={columns}\n data={users}\n filterColumn=\"email\"\n filterPlaceholder={t.email}\n emptyMessage={t.empty}\n pageSize={5}\n />\n )}\n </CardContent>\n </Card>\n );\n}\n\nexport function AdminUsersPanel({ labels }: { labels?: Partial<AdminUsersPanelLabels> }) {\n const t = { ...DEFAULT_LABELS, ...labels };\n // Superuser-only: gate the whole panel via the package's RequireRole so the\n // privileged API calls never mount for non-superusers, even if a consumer\n // renders it unconditionally.\n return (\n <RequireRole superuser>\n <AdminUsersPanelInner t={t} />\n </RequireRole>\n );\n}\n",
|
|
24
|
+
"content": "\"use client\";\n\n// fa-auth admin users panel: superuser-only user management (create / update /\n// delete). Headless logic stays a live dependency - `useUsers`\n// (@mano8/astro-auth-m8/hooks) owns the API calls, the package Zod schemas\n// validate the forms, and the package's `RequireRole superuser` gates the whole\n// panel. This file is only the shadcn skin, copied into the consumer via the\n// @fa-m8-auth registry - edit (and translate via `labels`) freely per app.\nimport * as React from \"react\";\nimport type { ColumnDef, RowSelectionState } from \"@tanstack/react-table\";\nimport { UserPlus } from \"lucide-react\";\nimport { RequireRole } from \"@mano8/astro-auth-m8/react\";\nimport { useUsers } from \"@mano8/astro-auth-m8/hooks\";\nimport {\n RoleTypeSchema,\n UserCreateSchema,\n UserUpdateSchema,\n type UserPublic,\n} from \"@mano8/astro-auth-m8/schemas\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Badge } from \"@/components/ui/badge\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"@/components/ui/card\";\nimport { DialogFooter } from \"@/components/ui/dialog\";\nimport {\n DataTable,\n createDataTableSelectionColumn,\n} from \"@/components/m8-ui/data-table\";\nimport { DataTableColumnHeader } from \"@/components/m8-ui/data-table-column-header\";\nimport {\n AccountToastHost,\n accountToast,\n ConfirmDeleteDialog,\n EntityFormDialog,\n RowActions,\n errorMessage,\n useClientTable,\n} from \"./account-crud\";\n\nexport interface AdminUsersPanelLabels {\n title: string;\n description: string;\n updateScope: string;\n invalidCreate: string;\n invalidUpdate: string;\n created: string;\n updated: string;\n createFailed: string;\n updateFailed: string;\n deleteFailed: string;\n deleted: string;\n email: string;\n fullName: string;\n avatar: string;\n avatarPlaceholder: string;\n password: string;\n passwordPlaceholder: string;\n passwordUnsupported: string;\n create: string;\n createTitle: string;\n editTitle: string;\n role: string;\n emailVerified: string;\n superuser: string;\n users: string;\n loading: string;\n provider: string;\n providerPassword: string;\n providerGoogle: string;\n actions: string;\n status: string;\n active: string;\n inactive: string;\n save: string;\n cancel: string;\n edit: string;\n delete: string;\n deleteSelected: string;\n confirmDeleteTitle: string;\n confirmDeleteBody: string;\n empty: string;\n search: string;\n}\n\nconst DEFAULT_LABELS: AdminUsersPanelLabels = {\n title: \"Admin users\",\n description: \"Superuser-only user management.\",\n updateScope:\n \"User updates support email, full name, avatar, password, and role. Provider, account status, and verification flags are managed by the auth service.\",\n invalidCreate: \"Invalid user payload.\",\n invalidUpdate: \"Invalid update payload.\",\n created: \"User created.\",\n updated: \"User updated.\",\n createFailed: \"Failed to create user.\",\n updateFailed: \"Failed to update user.\",\n deleteFailed: \"Failed to delete user.\",\n deleted: \"User deleted.\",\n email: \"Email\",\n fullName: \"Full name\",\n avatar: \"Avatar URL\",\n avatarPlaceholder: \"https://example.com/avatar.png\",\n password: \"Password\",\n passwordPlaceholder: \"Leave blank to keep current password\",\n passwordUnsupported: \"Password disabled for Google users\",\n create: \"Create user\",\n createTitle: \"Create user\",\n editTitle: \"Edit user\",\n role: \"Role\",\n emailVerified: \"Email verified\",\n superuser: \"Superuser\",\n users: \"users\",\n loading: \"Loading users...\",\n provider: \"Provider\",\n providerPassword: \"Password\",\n providerGoogle: \"Google\",\n actions: \"Actions\",\n status: \"Status\",\n active: \"Active\",\n inactive: \"Inactive\",\n save: \"Save\",\n cancel: \"Cancel\",\n edit: \"Edit\",\n delete: \"Delete\",\n deleteSelected: \"Delete selected\",\n confirmDeleteTitle: \"Delete user?\",\n confirmDeleteBody:\n \"This permanently removes the user account and revokes its access.\",\n empty: \"No users found.\",\n search: \"Search users\",\n};\n\ninterface CreateFormState {\n email: string;\n full_name: string;\n avatar: string;\n password: string;\n role: string;\n is_active: boolean;\n is_superuser: boolean;\n}\n\ninterface EditFormState {\n email: string;\n full_name: string;\n avatar: string;\n password: string;\n role: string;\n}\n\nconst EMPTY_CREATE: CreateFormState = {\n email: \"\",\n full_name: \"\",\n avatar: \"\",\n password: \"\",\n role: \"user\",\n is_active: true,\n is_superuser: false,\n};\n\nconst selectClassName =\n \"h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50\";\n\nfunction RoleSelect({\n id,\n value,\n onChange,\n}: {\n id: string;\n value: string;\n onChange: (value: string) => void;\n}) {\n return (\n <select\n id={id}\n aria-label=\"Role\"\n className={selectClassName}\n value={value}\n onChange={(event) => onChange(event.target.value)}\n >\n {RoleTypeSchema.options.map((role) => (\n <option key={role} value={role}>\n {role}\n </option>\n ))}\n </select>\n );\n}\n\nfunction AdminUsersPanelInner({ t }: { t: AdminUsersPanelLabels }) {\n const { users: usersData, loading, reload, create, update, remove } =\n useUsers(false);\n const users = usersData?.data ?? [];\n\n const [creating, setCreating] = React.useState(false);\n const [createForm, setCreateForm] =\n React.useState<CreateFormState>(EMPTY_CREATE);\n const [editing, setEditing] = React.useState<UserPublic | null>(null);\n const [editForm, setEditForm] = React.useState<EditFormState | null>(null);\n const [deleting, setDeleting] = React.useState<UserPublic | null>(null);\n const [bulkDelete, setBulkDelete] = React.useState(false);\n const [submitting, setSubmitting] = React.useState(false);\n const [rowSelection, setRowSelection] = React.useState<RowSelectionState>({});\n\n React.useEffect(() => {\n reload().catch(() => {});\n }, [reload]);\n\n const openCreate = () => {\n setCreateForm(EMPTY_CREATE);\n setCreating(true);\n };\n\n const openEdit = (user: UserPublic) => {\n setEditForm({\n email: user.email,\n full_name: user.full_name ?? \"\",\n avatar: user.avatar ?? \"\",\n password: \"\",\n role: user.role,\n });\n setEditing(user);\n };\n\n const handleCreate = async (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n const parsed = UserCreateSchema.safeParse({\n email: createForm.email || undefined,\n password: createForm.password || undefined,\n full_name: createForm.full_name || undefined,\n avatar: createForm.avatar || undefined,\n provider: \"password\",\n role: createForm.role ? RoleTypeSchema.parse(createForm.role) : \"user\",\n is_active: createForm.is_active,\n is_superuser: createForm.is_superuser,\n });\n if (!parsed.success) {\n accountToast.error({\n title: parsed.error.issues[0]?.message ?? t.invalidCreate,\n });\n return;\n }\n setSubmitting(true);\n try {\n await create(parsed.data);\n // The hook query is disabled (useUsers(false)), so invalidation alone\n // won't repopulate the table — refetch explicitly.\n await reload();\n setCreating(false);\n accountToast.success({ title: t.created });\n } catch (error) {\n accountToast.error({ title: errorMessage(error, t.createFailed) });\n } finally {\n setSubmitting(false);\n }\n };\n\n const handleUpdate = async (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n if (!editing || !editForm) return;\n const parsed = UserUpdateSchema.safeParse({\n email: editForm.email || undefined,\n full_name: editForm.full_name || undefined,\n avatar: editForm.avatar || undefined,\n password: editForm.password || undefined,\n role: editForm.role || undefined,\n });\n if (!parsed.success) {\n accountToast.error({\n title: parsed.error.issues[0]?.message ?? t.invalidUpdate,\n });\n return;\n }\n setSubmitting(true);\n try {\n await update(editing.id, parsed.data);\n await reload();\n setEditing(null);\n setEditForm(null);\n accountToast.success({ title: t.updated });\n } catch (error) {\n accountToast.error({ title: errorMessage(error, t.updateFailed) });\n } finally {\n setSubmitting(false);\n }\n };\n\n const confirmDelete = async (ids: string[]) => {\n setSubmitting(true);\n try {\n for (const id of ids) {\n await remove(id);\n }\n await reload();\n accountToast.success({ title: t.deleted });\n setDeleting(null);\n setBulkDelete(false);\n setRowSelection({});\n } catch (error) {\n accountToast.error({ title: errorMessage(error, t.deleteFailed) });\n } finally {\n setSubmitting(false);\n }\n };\n\n const controller = useClientTable(users, {\n search: (user) => `${user.email} ${user.full_name ?? \"\"}`,\n sorters: {\n email: (user) => user.email,\n role: (user) => user.role,\n provider: (user) => user.provider,\n status: (user) => (user.is_active ? t.active : t.inactive),\n },\n initialSortBy: \"email\",\n });\n\n const columns = React.useMemo<ColumnDef<UserPublic>[]>(\n () => [\n createDataTableSelectionColumn<UserPublic>({\n selectAllVisible: t.actions,\n selectRow: (user) => `${t.edit} ${user.email}`,\n }),\n {\n id: \"actions\",\n header: t.actions,\n enableHiding: false,\n enableSorting: false,\n cell: ({ row }) => (\n <RowActions\n editLabel={t.edit}\n deleteLabel={t.delete}\n onEdit={() => openEdit(row.original)}\n onDelete={() => setDeleting(row.original)}\n />\n ),\n },\n {\n accessorKey: \"email\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.email} />\n ),\n cell: ({ row }) => (\n <div className=\"min-w-0\">\n <div className=\"font-medium\">{row.original.email}</div>\n {row.original.full_name ? (\n <div className=\"text-xs text-muted-foreground\">\n {row.original.full_name}\n </div>\n ) : null}\n </div>\n ),\n },\n {\n accessorKey: \"role\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.role} />\n ),\n cell: ({ row }) => (\n <span className=\"capitalize\">{row.original.role}</span>\n ),\n },\n {\n accessorKey: \"provider\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.provider} />\n ),\n cell: ({ row }) => (\n <Badge variant=\"outline\" className=\"capitalize\">\n {row.original.provider === \"google\"\n ? t.providerGoogle\n : t.providerPassword}\n </Badge>\n ),\n },\n {\n accessorKey: \"status\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.status} />\n ),\n cell: ({ row }) => {\n const user = row.original;\n return (\n <div className=\"flex flex-wrap gap-1\">\n <Badge variant={user.is_active ? \"default\" : \"outline\"}>\n {user.is_active ? t.active : t.inactive}\n </Badge>\n {user.email_verified ? (\n <Badge variant=\"secondary\">{t.emailVerified}</Badge>\n ) : null}\n {user.is_superuser ? (\n <Badge variant=\"secondary\">{t.superuser}</Badge>\n ) : null}\n </div>\n );\n },\n },\n ],\n [t],\n );\n\n const selectedIds = Object.keys(rowSelection).filter((id) => rowSelection[id]);\n const editingGoogle = editing?.provider === \"google\";\n\n return (\n <Card className=\"not-content w-full\">\n <AccountToastHost />\n <CardHeader>\n <CardTitle>{t.title}</CardTitle>\n <CardDescription>{t.description}</CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <p className=\"text-sm text-muted-foreground\">{t.updateScope}</p>\n <DataTable<UserPublic, unknown>\n columns={columns}\n data={controller.data}\n rowCount={controller.rowCount}\n page={controller.page}\n pageSize={controller.pageSize}\n onPageChange={controller.onPageChange}\n onPageSizeChange={controller.onPageSizeChange}\n sortBy={controller.sortBy}\n sortDir={controller.sortDir}\n onSortChange={controller.onSortChange}\n q={controller.q}\n onSearchChange={controller.onSearchChange}\n loading={loading && users.length === 0}\n getRowId={(user) => user.id}\n rowSelection={rowSelection}\n onRowSelectionChange={setRowSelection}\n labels={{\n loading: t.loading,\n empty: t.empty,\n toolbar: { search: t.search },\n }}\n addButton={\n <Button type=\"button\" size=\"sm\" onClick={openCreate}>\n <UserPlus className=\"size-4\" />\n {t.create}\n </Button>\n }\n selectionActions={\n selectedIds.length > 0 ? (\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"destructive\"\n onClick={() => setBulkDelete(true)}\n >\n {t.deleteSelected} ({selectedIds.length})\n </Button>\n ) : null\n }\n />\n </CardContent>\n\n {/* Create popup */}\n <EntityFormDialog\n open={creating}\n onOpenChange={setCreating}\n title={t.createTitle}\n description={t.updateScope}\n >\n <form onSubmit={handleCreate} className=\"space-y-4\">\n <div className=\"grid gap-4 sm:grid-cols-2\">\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-email\">{t.email}</Label>\n <Input\n id=\"admin-create-email\"\n type=\"email\"\n required\n value={createForm.email}\n onChange={(event) =>\n setCreateForm((prev) => ({\n ...prev,\n email: event.target.value,\n }))\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-name\">{t.fullName}</Label>\n <Input\n id=\"admin-create-name\"\n value={createForm.full_name}\n onChange={(event) =>\n setCreateForm((prev) => ({\n ...prev,\n full_name: event.target.value,\n }))\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-avatar\">{t.avatar}</Label>\n <Input\n id=\"admin-create-avatar\"\n type=\"url\"\n placeholder={t.avatarPlaceholder}\n value={createForm.avatar}\n onChange={(event) =>\n setCreateForm((prev) => ({\n ...prev,\n avatar: event.target.value,\n }))\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-password\">{t.password}</Label>\n <Input\n id=\"admin-create-password\"\n type=\"password\"\n minLength={8}\n required\n value={createForm.password}\n onChange={(event) =>\n setCreateForm((prev) => ({\n ...prev,\n password: event.target.value,\n }))\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-role\">{t.role}</Label>\n <RoleSelect\n id=\"admin-create-role\"\n value={createForm.role}\n onChange={(role) => setCreateForm((prev) => ({ ...prev, role }))}\n />\n </div>\n <div className=\"flex items-end gap-4\">\n <label className=\"flex items-center gap-2 text-sm\">\n <input\n type=\"checkbox\"\n className=\"size-4\"\n checked={createForm.is_active}\n onChange={(event) =>\n setCreateForm((prev) => ({\n ...prev,\n is_active: event.target.checked,\n }))\n }\n />\n {t.active}\n </label>\n <label className=\"flex items-center gap-2 text-sm\">\n <input\n type=\"checkbox\"\n className=\"size-4\"\n checked={createForm.is_superuser}\n onChange={(event) =>\n setCreateForm((prev) => ({\n ...prev,\n is_superuser: event.target.checked,\n }))\n }\n />\n {t.superuser}\n </label>\n </div>\n </div>\n <DialogFooter>\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => setCreating(false)}\n >\n {t.cancel}\n </Button>\n <Button type=\"submit\" disabled={submitting}>\n {t.save}\n </Button>\n </DialogFooter>\n </form>\n </EntityFormDialog>\n\n {/* Edit popup */}\n <EntityFormDialog\n open={Boolean(editing) && Boolean(editForm)}\n onOpenChange={(open) => {\n if (!open) {\n setEditing(null);\n setEditForm(null);\n }\n }}\n title={t.editTitle}\n description={editing?.email}\n >\n {editForm ? (\n <form onSubmit={handleUpdate} className=\"space-y-4\">\n <div className=\"grid gap-4 sm:grid-cols-2\">\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-edit-email\">{t.email}</Label>\n <Input\n id=\"admin-edit-email\"\n type=\"email\"\n required\n value={editForm.email}\n onChange={(event) =>\n setEditForm((prev) =>\n prev ? { ...prev, email: event.target.value } : prev,\n )\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-edit-name\">{t.fullName}</Label>\n <Input\n id=\"admin-edit-name\"\n value={editForm.full_name}\n onChange={(event) =>\n setEditForm((prev) =>\n prev ? { ...prev, full_name: event.target.value } : prev,\n )\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-edit-avatar\">{t.avatar}</Label>\n <Input\n id=\"admin-edit-avatar\"\n type=\"url\"\n placeholder={t.avatarPlaceholder}\n value={editForm.avatar}\n onChange={(event) =>\n setEditForm((prev) =>\n prev ? { ...prev, avatar: event.target.value } : prev,\n )\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-edit-password\">{t.password}</Label>\n <Input\n id=\"admin-edit-password\"\n type=\"password\"\n disabled={editingGoogle}\n placeholder={\n editingGoogle\n ? t.passwordUnsupported\n : t.passwordPlaceholder\n }\n value={editForm.password}\n onChange={(event) =>\n setEditForm((prev) =>\n prev ? { ...prev, password: event.target.value } : prev,\n )\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-edit-role\">{t.role}</Label>\n <RoleSelect\n id=\"admin-edit-role\"\n value={editForm.role}\n onChange={(role) =>\n setEditForm((prev) => (prev ? { ...prev, role } : prev))\n }\n />\n </div>\n </div>\n <DialogFooter>\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => {\n setEditing(null);\n setEditForm(null);\n }}\n >\n {t.cancel}\n </Button>\n <Button type=\"submit\" disabled={submitting}>\n {t.save}\n </Button>\n </DialogFooter>\n </form>\n ) : null}\n </EntityFormDialog>\n\n {/* Delete confirmations */}\n <ConfirmDeleteDialog\n open={Boolean(deleting)}\n onOpenChange={(open) => {\n if (!open) setDeleting(null);\n }}\n title={t.confirmDeleteTitle}\n description={t.confirmDeleteBody}\n confirmLabel={t.delete}\n cancelLabel={t.cancel}\n pending={submitting}\n onConfirm={() => deleting && confirmDelete([deleting.id])}\n />\n <ConfirmDeleteDialog\n open={bulkDelete}\n onOpenChange={setBulkDelete}\n title={t.confirmDeleteTitle}\n description={t.confirmDeleteBody}\n confirmLabel={t.deleteSelected}\n cancelLabel={t.cancel}\n pending={submitting}\n onConfirm={() => confirmDelete(selectedIds)}\n />\n </Card>\n );\n}\n\nexport function AdminUsersPanel({\n labels,\n}: {\n labels?: Partial<AdminUsersPanelLabels>;\n}) {\n const t = { ...DEFAULT_LABELS, ...labels };\n // Superuser-only: gate the whole panel via the package's RequireRole so the\n // privileged API calls never mount for non-superusers, even if a consumer\n // renders it unconditionally.\n return (\n <RequireRole superuser>\n <AdminUsersPanelInner t={t} />\n </RequireRole>\n );\n}\n",
|
|
21
25
|
"type": "registry:component",
|
|
22
26
|
"target": "components/fa-auth/admin-users-panel.tsx"
|
|
23
27
|
}
|
|
@@ -3,17 +3,25 @@
|
|
|
3
3
|
"name": "api-keys-panel",
|
|
4
4
|
"type": "registry:component",
|
|
5
5
|
"title": "Account API Keys Panel",
|
|
6
|
-
"description": "fa-auth API token mint/revoke panel
|
|
6
|
+
"description": "fa-auth API token mint/revoke panel on the canonical data-table (page selector, orderable columns, column visibility), with popup create form, alert-dialog revoke confirm, and bottom-right toasts. Driven by the package's useApiKeys hook. Requires @mano8/astro-auth-m8 installed.",
|
|
7
|
+
"dependencies": [
|
|
8
|
+
"lucide-react",
|
|
9
|
+
"@tanstack/react-table"
|
|
10
|
+
],
|
|
7
11
|
"registryDependencies": [
|
|
8
12
|
"card",
|
|
9
13
|
"button",
|
|
10
14
|
"input",
|
|
11
|
-
"label"
|
|
15
|
+
"label",
|
|
16
|
+
"badge",
|
|
17
|
+
"dialog",
|
|
18
|
+
"./node_modules/@mano8/astro-ui-m8/registry/r/data-table.json",
|
|
19
|
+
"./account-crud.json"
|
|
12
20
|
],
|
|
13
21
|
"files": [
|
|
14
22
|
{
|
|
15
23
|
"path": "registry/blocks/account/api-keys-panel.tsx",
|
|
16
|
-
"content": "\"use client\";\n\n// fa-auth API keys panel: mint and revoke programmatic API tokens. Headless\n// logic stays a live dependency — `useApiKeys` (@mano8/astro-auth-m8/hooks) owns\n// the list/create/revoke calls and the package Zod schema validates the form.\n// This file is only the shadcn skin, copied into the consumer via the\n// @fa-m8-auth registry — edit (and translate via `labels`) freely per app.\nimport * as React from \"react\";\nimport { useApiKeys } from \"@mano8/astro-auth-m8/hooks\";\nimport { ApiKeyCreateSchema } from \"@mano8/astro-auth-m8/schemas\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"@/components/ui/card\";\n\nexport interface ApiKeysPanelLabels {\n createTitle: string;\n createDescription: string;\n name: string;\n namePlaceholder: string;\n ttl: string;\n ttlUnit: string;\n unitHours: string;\n unitDays: string;\n unitWeeks: string;\n defaultName: string;\n generating: string;\n mint: string;\n securityNotice: string;\n copied: string;\n copy: string;\n activeTitle: string;\n loading: string;\n empty: string;\n active: string;\n revoked: string;\n expires: string;\n lastUsed: string;\n notUsed: string;\n notAvailable: string;\n revoke: string;\n}\n\nconst DEFAULT_LABELS: ApiKeysPanelLabels = {\n createTitle: \"Create API token\",\n createDescription: \"Provision programmatic client identifiers for remote integrations.\",\n name: \"Token name\",\n namePlaceholder: \"e.g. CI/CD deployment server\",\n ttl: \"Validity\",\n ttlUnit: \"Unit\",\n unitHours: \"Hours\",\n unitDays: \"Days\",\n unitWeeks: \"Weeks\",\n defaultName: \"Default key\",\n generating: \"Generating...\",\n mint: \"Mint new key\",\n securityNotice: \"Security notice: copy this API key now. It will not be shown again.\",\n copied: \"Copied\",\n copy: \"Copy\",\n activeTitle: \"Active credentials\",\n loading: \"Loading API tokens...\",\n empty: \"No active API tokens found.\",\n active: \"Active\",\n revoked: \"Revoked\",\n expires: \"Expires\",\n lastUsed: \"Last used\",\n notUsed: \"Never used\",\n notAvailable: \"n/a\",\n revoke: \"Revoke token\",\n};\n\n// Backend currently accepts whole-hour TTLs only; sub-hour units need an auth-API change.\nconst TTL_UNIT_HOURS = { hours: 1, days: 24, weeks: 168 } as const;\ntype TtlUnit = keyof typeof TTL_UNIT_HOURS;\nconst inputClassName =\n \"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40\";\n\nexport function ApiKeysPanel({ labels }: { labels?: Partial<ApiKeysPanelLabels> }) {\n const t = { ...DEFAULT_LABELS, ...labels };\n const { apiKeys: keys, loading, reload, create, createdKey: lastCreated, revoke } = useApiKeys(false);\n const [isCreating, setIsCreating] = React.useState(false);\n const [copied, setCopied] = React.useState(false);\n\n React.useEffect(() => {\n reload().catch(() => {});\n }, [reload]);\n\n const handleCreateToken = async (e: React.FormEvent<HTMLFormElement>) => {\n e.preventDefault();\n setCopied(false);\n const form = e.currentTarget;\n const formData = new FormData(form);\n\n const amount = Number(formData.get(\"ttl_amount\")) || 1;\n const unit = (formData.get(\"ttl_unit\")?.toString() as TtlUnit) || \"days\";\n const ttl_hours = Math.max(1, Math.round(amount * (TTL_UNIT_HOURS[unit] ?? 24)));\n\n const parsedData = ApiKeyCreateSchema.parse({\n name: formData.get(\"name\")?.toString() || t.defaultName,\n ttl_hours,\n });\n\n setIsCreating(true);\n try {\n await create(parsedData);\n form.reset();\n } finally {\n setIsCreating(false);\n }\n };\n\n const handleCopy = (text: string) => {\n navigator.clipboard.writeText(text);\n setCopied(true);\n setTimeout(() => setCopied(false), 2000);\n };\n\n return (\n <div className=\"not-content space-y-6\">\n <Card>\n <CardHeader>\n <CardTitle>{t.createTitle}</CardTitle>\n <CardDescription>{t.createDescription}</CardDescription>\n </CardHeader>\n <CardContent>\n <form onSubmit={handleCreateToken} className=\"flex flex-wrap items-end gap-4\">\n <div className=\"flex-1 min-w-[200px] space-y-1\">\n <Label htmlFor=\"name\" className=\"pb-2\">{t.name}</Label>\n <Input id=\"name\" name=\"name\" placeholder={t.namePlaceholder} required />\n </div>\n <div className=\"w-24 space-y-1\">\n <Label htmlFor=\"ttl_amount\" className=\"pb-2\">{t.ttl}</Label>\n <Input id=\"ttl_amount\" name=\"ttl_amount\" type=\"number\" min={1} defaultValue=\"30\" required />\n </div>\n <div className=\"w-32 space-y-1\">\n <Label htmlFor=\"ttl_unit\" className=\"pb-2\">{t.ttlUnit}</Label>\n <select\n id=\"ttl_unit\"\n name=\"ttl_unit\"\n defaultValue=\"days\"\n className={inputClassName}\n >\n <option value=\"hours\">{t.unitHours}</option>\n <option value=\"days\">{t.unitDays}</option>\n <option value=\"weeks\">{t.unitWeeks}</option>\n </select>\n </div>\n <Button type=\"submit\" disabled={isCreating}>\n {isCreating ? t.generating : t.mint}\n </Button>\n </form>\n\n {lastCreated && (\n <div className=\"mt-4 p-4 border border-amber-200 bg-amber-50 rounded-md text-amber-900 space-y-2\">\n <p className=\"text-sm font-bold\">{t.securityNotice}</p>\n <div className=\"flex items-center gap-2 bg-white p-2 rounded border font-mono text-xs overflow-x-auto\">\n <span className=\"flex-1 select-all break-all\">{lastCreated.plaintext}</span>\n <Button size=\"sm\" variant=\"ghost\" onClick={() => handleCopy(lastCreated.plaintext)}>\n {copied ? t.copied : t.copy}\n </Button>\n </div>\n </div>\n )}\n </CardContent>\n </Card>\n\n <Card>\n <CardHeader>\n <CardTitle>{t.activeTitle}</CardTitle>\n </CardHeader>\n <CardContent>\n {loading && keys.length === 0 ? (\n <p className=\"text-sm text-muted-foreground py-2 italic\">{t.loading}</p>\n ) : keys.length === 0 ? (\n <p className=\"text-sm text-muted-foreground py-2 italic\">{t.empty}</p>\n ) : (\n <div className=\"divide-y divide-border\">\n {keys.map((key) => (\n <div key={key.id} className=\"flex items-center justify-between gap-3 py-3\">\n <div className=\"min-w-0\">\n <h4 className=\"text-sm font-semibold\">{key.name}</h4>\n <p className=\"text-xs text-muted-foreground\">\n {t.expires}: {key.expires_at ? new Date(key.expires_at).toLocaleString() : t.notAvailable}\n </p>\n <p className=\"text-xs text-muted-foreground\">\n {t.lastUsed}: {key.last_used_at ? new Date(key.last_used_at).toLocaleString() : t.notUsed}\n </p>\n <p className=\"text-xs text-muted-foreground\">\n {key.revoked ? t.revoked : t.active}\n </p>\n </div>\n <Button\n size=\"sm\"\n variant=\"destructive\"\n disabled={key.revoked}\n onClick={() => revoke(key.id)}\n >\n {t.revoke}\n </Button>\n </div>\n ))}\n </div>\n )}\n </CardContent>\n </Card>\n </div>\n );\n}\n",
|
|
24
|
+
"content": "\"use client\";\n\n// fa-auth API keys panel: mint and revoke programmatic API tokens. Headless\n// logic stays a live dependency — `useApiKeys` (@mano8/astro-auth-m8/hooks) owns\n// the list/create/revoke calls and the package Zod schema validates the form.\n// This file is only the shadcn skin, copied into the consumer via the\n// @fa-m8-auth registry — edit (and translate via `labels`) freely per app.\nimport * as React from \"react\";\nimport type { ColumnDef, RowSelectionState } from \"@tanstack/react-table\";\nimport { KeyRound, Trash2 } from \"lucide-react\";\nimport { useApiKeys } from \"@mano8/astro-auth-m8/hooks\";\nimport {\n ApiKeyCreateSchema,\n type ApiKeyPublic,\n} from \"@mano8/astro-auth-m8/schemas\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Badge } from \"@/components/ui/badge\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"@/components/ui/card\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"@/components/ui/dialog\";\nimport {\n DataTable,\n createDataTableSelectionColumn,\n} from \"@/components/m8-ui/data-table\";\nimport { DataTableColumnHeader } from \"@/components/m8-ui/data-table-column-header\";\nimport {\n AccountToastHost,\n accountToast,\n ConfirmDeleteDialog,\n EntityFormDialog,\n errorMessage,\n useClientTable,\n} from \"./account-crud\";\n\nexport interface ApiKeysPanelLabels {\n title: string;\n description: string;\n createTitle: string;\n createDescription: string;\n name: string;\n namePlaceholder: string;\n ttl: string;\n ttlUnit: string;\n unitHours: string;\n unitDays: string;\n unitWeeks: string;\n defaultName: string;\n generating: string;\n mint: string;\n cancel: string;\n securityNotice: string;\n revealTitle: string;\n copied: string;\n copy: string;\n done: string;\n activeTitle: string;\n loading: string;\n empty: string;\n active: string;\n revoked: string;\n status: string;\n expires: string;\n lastUsed: string;\n notUsed: string;\n notAvailable: string;\n revoke: string;\n revokeSelected: string;\n confirmRevokeTitle: string;\n confirmRevokeBody: string;\n actions: string;\n search: string;\n created: string;\n createFailed: string;\n revokedOk: string;\n revokeFailed: string;\n}\n\nconst DEFAULT_LABELS: ApiKeysPanelLabels = {\n title: \"API keys\",\n description: \"Provision and revoke programmatic client identifiers.\",\n createTitle: \"Create API token\",\n createDescription:\n \"Provision programmatic client identifiers for remote integrations.\",\n name: \"Token name\",\n namePlaceholder: \"e.g. CI/CD deployment server\",\n ttl: \"Validity\",\n ttlUnit: \"Unit\",\n unitHours: \"Hours\",\n unitDays: \"Days\",\n unitWeeks: \"Weeks\",\n defaultName: \"Default key\",\n generating: \"Generating...\",\n mint: \"Mint new key\",\n cancel: \"Cancel\",\n securityNotice:\n \"Security notice: copy this API key now. It will not be shown again.\",\n revealTitle: \"API token created\",\n copied: \"Copied\",\n copy: \"Copy\",\n done: \"Done\",\n activeTitle: \"Active credentials\",\n loading: \"Loading API tokens...\",\n empty: \"No active API tokens found.\",\n active: \"Active\",\n revoked: \"Revoked\",\n status: \"Status\",\n expires: \"Expires\",\n lastUsed: \"Last used\",\n notUsed: \"Never used\",\n notAvailable: \"n/a\",\n revoke: \"Revoke\",\n revokeSelected: \"Revoke selected\",\n confirmRevokeTitle: \"Revoke API token?\",\n confirmRevokeBody:\n \"This immediately invalidates the token. Integrations using it will stop working.\",\n actions: \"Actions\",\n search: \"Search tokens\",\n created: \"API token created.\",\n createFailed: \"Failed to create API token.\",\n revokedOk: \"API token revoked.\",\n revokeFailed: \"Failed to revoke API token.\",\n};\n\n// Backend currently accepts whole-hour TTLs only; sub-hour units need an auth-API change.\nconst TTL_UNIT_HOURS = { hours: 1, days: 24, weeks: 168 } as const;\ntype TtlUnit = keyof typeof TTL_UNIT_HOURS;\n\nfunction formatDate(value: string | null | undefined, fallback: string): string {\n return value ? new Date(value).toLocaleString() : fallback;\n}\n\nexport function ApiKeysPanel({ labels }: { labels?: Partial<ApiKeysPanelLabels> }) {\n const t = { ...DEFAULT_LABELS, ...labels };\n const {\n apiKeys: keys,\n loading,\n reload,\n create,\n createdKey: lastCreated,\n revoke,\n } = useApiKeys(false);\n\n const [creating, setCreating] = React.useState(false);\n const [isSubmitting, setIsSubmitting] = React.useState(false);\n const [name, setName] = React.useState(\"\");\n const [ttlAmount, setTtlAmount] = React.useState(\"30\");\n const [ttlUnit, setTtlUnit] = React.useState<TtlUnit>(\"days\");\n\n const [revealOpen, setRevealOpen] = React.useState(false);\n const [copied, setCopied] = React.useState(false);\n\n const [revoking, setRevoking] = React.useState<ApiKeyPublic | null>(null);\n const [bulkRevoke, setBulkRevoke] = React.useState(false);\n const [isRevoking, setIsRevoking] = React.useState(false);\n const [rowSelection, setRowSelection] = React.useState<RowSelectionState>({});\n\n React.useEffect(() => {\n reload().catch(() => {});\n }, [reload]);\n\n const openCreate = () => {\n setName(\"\");\n setTtlAmount(\"30\");\n setTtlUnit(\"days\");\n setCreating(true);\n };\n\n const handleCreate = async (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n const ttlHours = Math.max(\n 1,\n Math.round((Number(ttlAmount) || 1) * TTL_UNIT_HOURS[ttlUnit]),\n );\n const parsed = ApiKeyCreateSchema.safeParse({\n name: name.trim() || t.defaultName,\n ttl_hours: ttlHours,\n });\n if (!parsed.success) {\n accountToast.error({\n title: parsed.error.issues[0]?.message ?? t.createFailed,\n });\n return;\n }\n setIsSubmitting(true);\n try {\n await create(parsed.data);\n // The hook query is disabled (useApiKeys(false)), so invalidation alone\n // won't repopulate the table — refetch explicitly.\n await reload();\n setCreating(false);\n setCopied(false);\n setRevealOpen(true);\n accountToast.success({ title: t.created });\n } catch (error) {\n accountToast.error({ title: errorMessage(error, t.createFailed) });\n } finally {\n setIsSubmitting(false);\n }\n };\n\n const handleCopy = (text: string) => {\n navigator.clipboard?.writeText(text);\n setCopied(true);\n setTimeout(() => setCopied(false), 2000);\n };\n\n const confirmRevoke = async (ids: string[]) => {\n setIsRevoking(true);\n try {\n for (const id of ids) {\n await revoke(id);\n }\n await reload();\n accountToast.success({ title: t.revokedOk });\n setRevoking(null);\n setBulkRevoke(false);\n setRowSelection({});\n } catch (error) {\n accountToast.error({ title: errorMessage(error, t.revokeFailed) });\n } finally {\n setIsRevoking(false);\n }\n };\n\n const controller = useClientTable(keys, {\n search: (key) => key.name,\n sorters: {\n name: (key) => key.name,\n status: (key) => (key.revoked ? t.revoked : t.active),\n expires: (key) => key.expires_at ?? \"\",\n lastUsed: (key) => key.last_used_at ?? \"\",\n },\n initialSortBy: \"name\",\n });\n\n const columns = React.useMemo<ColumnDef<ApiKeyPublic>[]>(\n () => [\n createDataTableSelectionColumn<ApiKeyPublic>({\n selectAllVisible: t.actions,\n selectRow: (key) => `${t.revoke} ${key.name}`,\n }),\n {\n id: \"actions\",\n header: t.actions,\n enableHiding: false,\n enableSorting: false,\n cell: ({ row }) => (\n <div className=\"flex items-center gap-2\" data-account-row-actions=\"\">\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"destructive\"\n disabled={row.original.revoked}\n onClick={() => setRevoking(row.original)}\n data-account-action=\"revoke\"\n >\n <Trash2 className=\"size-3.5\" />\n <span className=\"sr-only lg:not-sr-only\">{t.revoke}</span>\n </Button>\n </div>\n ),\n },\n {\n accessorKey: \"name\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.name} />\n ),\n },\n {\n accessorKey: \"status\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.status} />\n ),\n cell: ({ row }) =>\n row.original.revoked ? (\n <Badge variant=\"outline\">{t.revoked}</Badge>\n ) : (\n <Badge>{t.active}</Badge>\n ),\n },\n {\n accessorKey: \"expires\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.expires} />\n ),\n cell: ({ row }) => formatDate(row.original.expires_at, t.notAvailable),\n },\n {\n accessorKey: \"lastUsed\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.lastUsed} />\n ),\n cell: ({ row }) => formatDate(row.original.last_used_at, t.notUsed),\n },\n ],\n [t],\n );\n\n // A token has no editable fields — both row actions revoke, and a single\n // confirm dialog covers the individual revoke path.\n const selectedIds = Object.keys(rowSelection).filter((id) => rowSelection[id]);\n\n return (\n <div className=\"not-content flex w-full flex-col gap-6\">\n <AccountToastHost />\n <Card>\n <CardHeader>\n <CardTitle>{t.activeTitle}</CardTitle>\n <CardDescription>{t.description}</CardDescription>\n </CardHeader>\n <CardContent>\n <DataTable<ApiKeyPublic, unknown>\n columns={columns}\n data={controller.data}\n rowCount={controller.rowCount}\n page={controller.page}\n pageSize={controller.pageSize}\n onPageChange={controller.onPageChange}\n onPageSizeChange={controller.onPageSizeChange}\n sortBy={controller.sortBy}\n sortDir={controller.sortDir}\n onSortChange={controller.onSortChange}\n q={controller.q}\n onSearchChange={controller.onSearchChange}\n loading={loading && keys.length === 0}\n getRowId={(key) => key.id}\n rowSelection={rowSelection}\n onRowSelectionChange={setRowSelection}\n labels={{\n loading: t.loading,\n empty: t.empty,\n toolbar: { search: t.search },\n }}\n addButton={\n <Button type=\"button\" size=\"sm\" onClick={openCreate}>\n <KeyRound className=\"size-4\" />\n {t.mint}\n </Button>\n }\n selectionActions={\n selectedIds.length > 0 ? (\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"destructive\"\n onClick={() => setBulkRevoke(true)}\n >\n {t.revokeSelected} ({selectedIds.length})\n </Button>\n ) : null\n }\n />\n </CardContent>\n </Card>\n\n {/* Create token popup */}\n <EntityFormDialog\n open={creating}\n onOpenChange={setCreating}\n title={t.createTitle}\n description={t.createDescription}\n >\n <form onSubmit={handleCreate} className=\"space-y-4\">\n <div className=\"space-y-1\">\n <Label htmlFor=\"api-key-name\">{t.name}</Label>\n <Input\n id=\"api-key-name\"\n aria-label={t.name}\n value={name}\n onChange={(event) => setName(event.target.value)}\n placeholder={t.namePlaceholder}\n />\n </div>\n <div className=\"grid grid-cols-2 gap-3\">\n <div className=\"space-y-1\">\n <Label htmlFor=\"api-key-ttl\">{t.ttl}</Label>\n <Input\n id=\"api-key-ttl\"\n type=\"number\"\n min={1}\n value={ttlAmount}\n onChange={(event) => setTtlAmount(event.target.value)}\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"api-key-unit\">{t.ttlUnit}</Label>\n <select\n id=\"api-key-unit\"\n aria-label={t.ttlUnit}\n value={ttlUnit}\n onChange={(event) => setTtlUnit(event.target.value as TtlUnit)}\n className=\"h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50\"\n >\n <option value=\"hours\">{t.unitHours}</option>\n <option value=\"days\">{t.unitDays}</option>\n <option value=\"weeks\">{t.unitWeeks}</option>\n </select>\n </div>\n </div>\n <DialogFooter>\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => setCreating(false)}\n >\n {t.cancel}\n </Button>\n <Button type=\"submit\" disabled={isSubmitting}>\n {isSubmitting ? t.generating : t.mint}\n </Button>\n </DialogFooter>\n </form>\n </EntityFormDialog>\n\n {/* One-time plaintext reveal */}\n <Dialog\n open={revealOpen && Boolean(lastCreated)}\n onOpenChange={setRevealOpen}\n >\n <DialogContent className=\"sm:max-w-lg\">\n <DialogHeader>\n <DialogTitle>{t.revealTitle}</DialogTitle>\n <DialogDescription>{t.securityNotice}</DialogDescription>\n </DialogHeader>\n <div className=\"flex items-center gap-2 overflow-x-auto rounded-md border bg-muted/40 p-2 font-mono text-xs\">\n <span className=\"flex-1 select-all break-all\">\n {lastCreated?.plaintext}\n </span>\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"ghost\"\n onClick={() => lastCreated && handleCopy(lastCreated.plaintext)}\n >\n {copied ? t.copied : t.copy}\n </Button>\n </div>\n <DialogFooter>\n <Button type=\"button\" onClick={() => setRevealOpen(false)}>\n {t.done}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n\n {/* Revoke confirmations */}\n <ConfirmDeleteDialog\n open={Boolean(revoking)}\n onOpenChange={(open) => {\n if (!open) setRevoking(null);\n }}\n title={t.confirmRevokeTitle}\n description={t.confirmRevokeBody}\n confirmLabel={t.revoke}\n cancelLabel={t.cancel}\n pending={isRevoking}\n onConfirm={() => revoking && confirmRevoke([revoking.id])}\n />\n <ConfirmDeleteDialog\n open={bulkRevoke}\n onOpenChange={setBulkRevoke}\n title={t.confirmRevokeTitle}\n description={t.confirmRevokeBody}\n confirmLabel={t.revokeSelected}\n cancelLabel={t.cancel}\n pending={isRevoking}\n onConfirm={() => confirmRevoke(selectedIds)}\n />\n </div>\n );\n}\n",
|
|
17
25
|
"type": "registry:component",
|
|
18
26
|
"target": "components/fa-auth/api-keys-panel.tsx"
|
|
19
27
|
}
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
"files": [
|
|
13
13
|
{
|
|
14
14
|
"path": "registry/blocks/account/dashboard-overview.tsx",
|
|
15
|
-
"content": "\"use client\";\n\n// fa-auth account landing view: an activity dashboard built from the package's\n// headless `useDashboard` hook. Logic stays a live dependency\n// (@mano8/astro-auth-m8/hooks); this file is only the shadcn skin and is copied\n// into the consumer via the @fa-m8-auth registry — edit freely per app.\nimport * as React from \"react\";\nimport { Activity, TrendingUp, Users } from \"lucide-react\";\nimport { useDashboard } from \"@mano8/astro-auth-m8/hooks\";\n\nimport { Card, CardContent, CardHeader, CardTitle } from \"@/components/ui/card\";\nimport { Skeleton } from \"@/components/ui/skeleton\";\nimport { ActivityBarChart } from \"@/components/fa-auth/activity-bar-chart\";\n\nexport interface DashboardOverviewLabels {\n title: string;\n subtitle: string;\n users: string;\n totalAdded: string;\n totalUpdated: string;\n activityTitle: string;\n added: string;\n updated: string;\n empty: string;\n error: string;\n}\n\nconst DEFAULT_LABELS: DashboardOverviewLabels = {\n title: \"Overview\",\n subtitle: \"Account activity at a glance.\",\n users: \"Users\",\n totalAdded: \"Total added\",\n totalUpdated: \"Total updated\",\n activityTitle: \"Activity by model\",\n added: \"Added\",\n updated: \"Updated\",\n empty: \"No activity recorded yet.\",\n error: \"Could not load dashboard activity.\",\n};\n\n/** Scope: \"me\" for the signed-in user, \"global\" for superuser fleet-wide stats. */\nexport interface DashboardOverviewProps {\n scope?: \"me\" | \"global\";\n labels?: Partial<DashboardOverviewLabels>;\n}\n\nfunction StatCard({\n label,\n value,\n icon: Icon,\n}: {\n label: string;\n value: React.ReactNode;\n icon: React.ComponentType<{ className?: string }>;\n}) {\n return (\n <Card className=\"h-full\">\n <CardHeader className=\"flex flex-row items-center justify-between space-y-0 pb-2\">\n <CardTitle className=\"text-sm font-medium text-muted-foreground\">\n {label}\n </CardTitle>\n <Icon className=\"size-4 text-muted-foreground\" />\n </CardHeader>\n <CardContent>\n <div className=\"text-2xl font-semibold tabular-nums\">{value}</div>\n </CardContent>\n </Card>\n );\n}\n\nexport function DashboardOverview({\n scope = \"me\",\n labels,\n}: DashboardOverviewProps) {\n const t = { ...DEFAULT_LABELS, ...labels };\n const { activity, loading, error } = useDashboard(scope);\n\n const counters = activity?.activity.activity ?? [];\n const totals = counters.reduce(\n (acc, row) => ({\n added: acc.added + row.added,\n updated: acc.updated + row.updated,\n }),\n { added: 0, updated: 0 },\n );\n\n if (loading) {\n return (\n <div className=\"not-content space-y-4\" aria-busy=\"true\">\n <div className=\"grid auto-rows-fr gap-4 sm:grid-cols-2 lg:grid-cols-3\">\n {[0, 1, 2].map((i) => (\n <Skeleton key={i} className=\"h-28 w-full\" />\n ))}\n </div>\n <Skeleton className=\"h-64 w-full\" />\n </div>\n );\n }\n\n if (error) {\n return (\n <Card role=\"alert\" className=\"border-destructive/50\">\n <CardContent className=\"py-6 text-sm text-destructive\">\n {t.error}\n </CardContent>\n </Card>\n );\n }\n\n return (\n <div className=\"not-content
|
|
15
|
+
"content": "\"use client\";\n\n// fa-auth account landing view: an activity dashboard built from the package's\n// headless `useDashboard` hook. Logic stays a live dependency\n// (@mano8/astro-auth-m8/hooks); this file is only the shadcn skin and is copied\n// into the consumer via the @fa-m8-auth registry — edit freely per app.\nimport * as React from \"react\";\nimport { Activity, TrendingUp, Users } from \"lucide-react\";\nimport { useDashboard } from \"@mano8/astro-auth-m8/hooks\";\n\nimport { Card, CardContent, CardHeader, CardTitle } from \"@/components/ui/card\";\nimport { Skeleton } from \"@/components/ui/skeleton\";\nimport { ActivityBarChart } from \"@/components/fa-auth/activity-bar-chart\";\n\nexport interface DashboardOverviewLabels {\n title: string;\n subtitle: string;\n users: string;\n totalAdded: string;\n totalUpdated: string;\n activityTitle: string;\n added: string;\n updated: string;\n empty: string;\n error: string;\n}\n\nconst DEFAULT_LABELS: DashboardOverviewLabels = {\n title: \"Overview\",\n subtitle: \"Account activity at a glance.\",\n users: \"Users\",\n totalAdded: \"Total added\",\n totalUpdated: \"Total updated\",\n activityTitle: \"Activity by model\",\n added: \"Added\",\n updated: \"Updated\",\n empty: \"No activity recorded yet.\",\n error: \"Could not load dashboard activity.\",\n};\n\n/** Scope: \"me\" for the signed-in user, \"global\" for superuser fleet-wide stats. */\nexport interface DashboardOverviewProps {\n scope?: \"me\" | \"global\";\n labels?: Partial<DashboardOverviewLabels>;\n}\n\nfunction StatCard({\n label,\n value,\n icon: Icon,\n}: {\n label: string;\n value: React.ReactNode;\n icon: React.ComponentType<{ className?: string }>;\n}) {\n return (\n <Card className=\"h-full\">\n <CardHeader className=\"flex flex-row items-center justify-between space-y-0 pb-2\">\n <CardTitle className=\"text-sm font-medium text-muted-foreground\">\n {label}\n </CardTitle>\n <Icon className=\"size-4 text-muted-foreground\" />\n </CardHeader>\n <CardContent>\n <div className=\"text-2xl font-semibold tabular-nums\">{value}</div>\n </CardContent>\n </Card>\n );\n}\n\nexport function DashboardOverview({\n scope = \"me\",\n labels,\n}: DashboardOverviewProps) {\n const t = { ...DEFAULT_LABELS, ...labels };\n const { activity, loading, error } = useDashboard(scope);\n\n const counters = activity?.activity.activity ?? [];\n const totals = counters.reduce(\n (acc, row) => ({\n added: acc.added + row.added,\n updated: acc.updated + row.updated,\n }),\n { added: 0, updated: 0 },\n );\n\n if (loading) {\n return (\n <div className=\"not-content space-y-4\" aria-busy=\"true\">\n <div className=\"grid auto-rows-fr gap-4 sm:grid-cols-2 lg:grid-cols-3\">\n {[0, 1, 2].map((i) => (\n <Skeleton key={i} className=\"h-28 w-full\" />\n ))}\n </div>\n <Skeleton className=\"h-64 w-full\" />\n </div>\n );\n }\n\n if (error) {\n return (\n <Card role=\"alert\" className=\"border-destructive/50\">\n <CardContent className=\"py-6 text-sm text-destructive\">\n {t.error}\n </CardContent>\n </Card>\n );\n }\n\n return (\n <div className=\"not-content flex flex-col gap-6\">\n <div className=\"space-y-1\">\n <h2 className=\"text-xl font-semibold tracking-tight\">{t.title}</h2>\n <p className=\"text-sm text-muted-foreground\">{t.subtitle}</p>\n </div>\n\n <div className=\"grid auto-rows-fr gap-4 sm:grid-cols-2 lg:grid-cols-3\">\n <StatCard\n label={t.users}\n value={(activity?.nb_users ?? 0).toLocaleString()}\n icon={Users}\n />\n <StatCard\n label={t.totalAdded}\n value={totals.added.toLocaleString()}\n icon={TrendingUp}\n />\n <StatCard\n label={t.totalUpdated}\n value={totals.updated.toLocaleString()}\n icon={Activity}\n />\n </div>\n\n <Card>\n <CardHeader>\n <CardTitle className=\"text-base\">{t.activityTitle}</CardTitle>\n </CardHeader>\n <CardContent>\n {counters.length ? (\n <ActivityBarChart\n data={counters}\n addedLabel={t.added}\n updatedLabel={t.updated}\n className=\"aspect-auto h-64 w-full\"\n />\n ) : (\n <p className=\"py-8 text-center text-sm text-muted-foreground\">\n {t.empty}\n </p>\n )}\n </CardContent>\n </Card>\n </div>\n );\n}\n",
|
|
16
16
|
"type": "registry:component",
|
|
17
17
|
"target": "components/fa-auth/dashboard-overview.tsx"
|
|
18
18
|
}
|
package/registry/r/registry.json
CHANGED
|
@@ -33,17 +33,23 @@
|
|
|
33
33
|
"title": "Account Sessions Panel",
|
|
34
34
|
"description": "fa-auth session details + activity summaries with superuser-only session revocation, driven by the package's useSessions + useDashboard hooks. Requires @mano8/astro-auth-m8 installed."
|
|
35
35
|
},
|
|
36
|
+
{
|
|
37
|
+
"name": "account-crud",
|
|
38
|
+
"type": "registry:component",
|
|
39
|
+
"title": "Account CRUD Helpers",
|
|
40
|
+
"description": "Shared skin helpers for the fa-auth account panels: a client-side controller for the canonical astro-ui-m8 data-table, a popup form dialog, a delete-confirmation alert, the fixed row-actions cell, and the bottom-right toast host."
|
|
41
|
+
},
|
|
36
42
|
{
|
|
37
43
|
"name": "api-keys-panel",
|
|
38
44
|
"type": "registry:component",
|
|
39
45
|
"title": "Account API Keys Panel",
|
|
40
|
-
"description": "fa-auth API token mint/revoke panel
|
|
46
|
+
"description": "fa-auth API token mint/revoke panel on the canonical data-table (page selector, orderable columns, column visibility), with popup create form, alert-dialog revoke confirm, and bottom-right toasts. Driven by the package's useApiKeys hook. Requires @mano8/astro-auth-m8 installed."
|
|
41
47
|
},
|
|
42
48
|
{
|
|
43
49
|
"name": "admin-users-panel",
|
|
44
50
|
"type": "registry:component",
|
|
45
51
|
"title": "Admin Users Panel",
|
|
46
|
-
"description": "fa-auth superuser-only user management (create/
|
|
52
|
+
"description": "fa-auth superuser-only user management on the canonical data-table (page selector, orderable columns, column visibility), with popup create/edit forms, alert-dialog delete confirm, and bottom-right toasts. Gated by the package's RequireRole and driven by useUsers. Requires @mano8/astro-auth-m8 installed."
|
|
47
53
|
}
|
|
48
54
|
]
|
|
49
55
|
}
|
package/registry.json
CHANGED
|
@@ -84,12 +84,43 @@
|
|
|
84
84
|
}
|
|
85
85
|
]
|
|
86
86
|
},
|
|
87
|
+
{
|
|
88
|
+
"name": "account-crud",
|
|
89
|
+
"type": "registry:component",
|
|
90
|
+
"title": "Account CRUD Helpers",
|
|
91
|
+
"description": "Shared skin helpers for the fa-auth account panels: a client-side controller for the canonical astro-ui-m8 data-table, a popup form dialog, a delete-confirmation alert, the fixed row-actions cell, and the bottom-right toast host.",
|
|
92
|
+
"dependencies": ["lucide-react"],
|
|
93
|
+
"registryDependencies": [
|
|
94
|
+
"button",
|
|
95
|
+
"dialog",
|
|
96
|
+
"alert-dialog",
|
|
97
|
+
"./node_modules/@mano8/astro-ui-m8/registry/r/data-table.json",
|
|
98
|
+
"./node_modules/@mano8/astro-ui-m8/registry/r/toast-notification.json"
|
|
99
|
+
],
|
|
100
|
+
"files": [
|
|
101
|
+
{
|
|
102
|
+
"path": "registry/blocks/account/account-crud.tsx",
|
|
103
|
+
"type": "registry:component",
|
|
104
|
+
"target": "components/fa-auth/account-crud.tsx"
|
|
105
|
+
}
|
|
106
|
+
]
|
|
107
|
+
},
|
|
87
108
|
{
|
|
88
109
|
"name": "api-keys-panel",
|
|
89
110
|
"type": "registry:component",
|
|
90
111
|
"title": "Account API Keys Panel",
|
|
91
|
-
"description": "fa-auth API token mint/revoke panel
|
|
92
|
-
"
|
|
112
|
+
"description": "fa-auth API token mint/revoke panel on the canonical data-table (page selector, orderable columns, column visibility), with popup create form, alert-dialog revoke confirm, and bottom-right toasts. Driven by the package's useApiKeys hook. Requires @mano8/astro-auth-m8 installed.",
|
|
113
|
+
"dependencies": ["lucide-react", "@tanstack/react-table"],
|
|
114
|
+
"registryDependencies": [
|
|
115
|
+
"card",
|
|
116
|
+
"button",
|
|
117
|
+
"input",
|
|
118
|
+
"label",
|
|
119
|
+
"badge",
|
|
120
|
+
"dialog",
|
|
121
|
+
"./node_modules/@mano8/astro-ui-m8/registry/r/data-table.json",
|
|
122
|
+
"./account-crud.json"
|
|
123
|
+
],
|
|
93
124
|
"files": [
|
|
94
125
|
{
|
|
95
126
|
"path": "registry/blocks/account/api-keys-panel.tsx",
|
|
@@ -102,14 +133,17 @@
|
|
|
102
133
|
"name": "admin-users-panel",
|
|
103
134
|
"type": "registry:component",
|
|
104
135
|
"title": "Admin Users Panel",
|
|
105
|
-
"description": "fa-auth superuser-only user management (create/
|
|
106
|
-
"dependencies": ["lucide-react"],
|
|
136
|
+
"description": "fa-auth superuser-only user management on the canonical data-table (page selector, orderable columns, column visibility), with popup create/edit forms, alert-dialog delete confirm, and bottom-right toasts. Gated by the package's RequireRole and driven by useUsers. Requires @mano8/astro-auth-m8 installed.",
|
|
137
|
+
"dependencies": ["lucide-react", "@tanstack/react-table"],
|
|
107
138
|
"registryDependencies": [
|
|
108
139
|
"card",
|
|
109
140
|
"button",
|
|
110
141
|
"input",
|
|
111
142
|
"label",
|
|
112
|
-
"
|
|
143
|
+
"badge",
|
|
144
|
+
"dialog",
|
|
145
|
+
"./node_modules/@mano8/astro-ui-m8/registry/r/data-table.json",
|
|
146
|
+
"./account-crud.json"
|
|
113
147
|
],
|
|
114
148
|
"files": [
|
|
115
149
|
{
|