@krak-stack/auth 0.1.39 → 0.1.41

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.
Files changed (40) hide show
  1. package/dist/admin/api.d.ts +196 -0
  2. package/dist/admin/api.js +158 -0
  3. package/dist/admin/index.d.ts +2 -0
  4. package/dist/admin/index.js +2 -0
  5. package/dist/admin/schema.d.ts +128 -0
  6. package/dist/admin/schema.js +190 -0
  7. package/dist/api.d.ts +278 -1
  8. package/dist/api.js +11 -2
  9. package/dist/components/admin-organization-form.d.ts +6 -0
  10. package/dist/components/admin-organization-form.js +126 -0
  11. package/dist/components/admin-organizations.d.ts +7 -0
  12. package/dist/components/admin-organizations.js +122 -0
  13. package/dist/components/admin-users.d.ts +8 -0
  14. package/dist/components/admin-users.js +282 -0
  15. package/dist/components/{auth-api-client.d.ts → auth-client-api.d.ts} +186 -196
  16. package/dist/components/auth-client-api.js +29 -0
  17. package/dist/components/auth-client.d.ts +2 -1
  18. package/dist/components/auth-forms.js +3 -3
  19. package/dist/components/auth-provider.d.ts +16 -15
  20. package/dist/components/auth-provider.js +30 -5
  21. package/dist/components/index.d.ts +3 -0
  22. package/dist/components/index.js +3 -0
  23. package/dist/components/organization-switcher.js +4 -5
  24. package/dist/components/user-button.d.ts +11 -1
  25. package/dist/components/user-button.js +57 -6
  26. package/dist/components/utils.d.ts +11 -0
  27. package/dist/components/utils.js +24 -0
  28. package/dist/index.d.ts +4 -2
  29. package/dist/index.js +4 -2
  30. package/dist/query.d.ts +49 -0
  31. package/dist/query.js +114 -0
  32. package/dist/server/api.d.ts +32 -0
  33. package/dist/server/index.d.ts +2 -2
  34. package/dist/server/index.js +2 -1
  35. package/dist/server/schema.d.ts +4 -0
  36. package/dist/server/schema.js +8 -0
  37. package/dist/service.d.ts +462 -434
  38. package/dist/service.js +2 -2
  39. package/package.json +9 -1
  40. package/dist/components/auth-api-client.js +0 -29
@@ -0,0 +1,126 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // @ts-nocheck
3
+ import { useAtomSet } from "@effect/atom-react";
4
+ import { Schema } from "effect";
5
+ import { Loader2 } from "lucide-react";
6
+ import { useState } from "react";
7
+ import { toast } from "sonner";
8
+ import { ErrorMessage, useAppForm } from "@/components/ui/form";
9
+ import { Button } from "@/components/ui/button";
10
+ import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog";
11
+ import { AdminCreateOrganizationPayload, } from "../admin/schema";
12
+ import { authClientApi } from "./auth-client-api";
13
+ import { useKrakstackAuth } from "./auth-provider";
14
+ import { assetPath, assetUrl } from "./utils";
15
+ const defaultMessages = {
16
+ en: {
17
+ admin_organization_edit_description: "Update {name}'s canonical organization details.",
18
+ field_name: "Name",
19
+ form_submit: "Save",
20
+ organization_create_description: "Create an organization that can be used for Better Auth membership.",
21
+ organization_create_error: "Unable to create organization.",
22
+ organization_create_title: "Create organization",
23
+ organization_created_toast: "Organization created.",
24
+ organization_edit_title: "Edit organization",
25
+ organization_field_logo_url: "Logo",
26
+ organization_slug: "Slug",
27
+ organization_slug_description: "Leave blank to generate one from the name.",
28
+ organization_update_error: "Unable to update organization.",
29
+ organization_updated_toast: "Organization updated.",
30
+ },
31
+ fr: {
32
+ admin_organization_edit_description: "Mettez à jour les détails canoniques de l'organisation {name}.",
33
+ field_name: "Nom",
34
+ form_submit: "Enregistrer",
35
+ organization_create_description: "Créez une organisation utilisable pour les adhésions Better Auth.",
36
+ organization_create_error: "Impossible de créer l'organisation.",
37
+ organization_create_title: "Créer une organisation",
38
+ organization_created_toast: "Organisation créée.",
39
+ organization_edit_title: "Modifier l'organisation",
40
+ organization_field_logo_url: "Logo",
41
+ organization_slug: "Slug",
42
+ organization_slug_description: "Laissez vide pour en générer un à partir du nom.",
43
+ organization_update_error: "Impossible de mettre à jour l'organisation.",
44
+ organization_updated_toast: "Organisation mise à jour.",
45
+ },
46
+ };
47
+ const labels = (locale) => ({
48
+ ...defaultMessages[locale],
49
+ });
50
+ const text = (value, params) => Object.entries(params ?? {}).reduce((current, [key, replacement]) => current.replace(`{${key}}`, replacement), value);
51
+ const slugify = (value) => value
52
+ .trim()
53
+ .toLowerCase()
54
+ .replace(/[^a-z0-9]+/g, "-")
55
+ .replace(/^-+|-+$/g, "");
56
+ const isFile = (value) => value instanceof File;
57
+ const valuesToPayload = (value, logo) => Schema.decodeUnknownSync(AdminCreateOrganizationPayload)({
58
+ name: value.name.trim(),
59
+ slug: slugify(value.slug || value.name),
60
+ logo: logo ?? undefined,
61
+ });
62
+ export function AdminOrganizationForm({ organization, onClose, onSaved, }) {
63
+ const auth = useKrakstackAuth();
64
+ const m = labels(auth?.locale ?? "en");
65
+ const baseUrl = auth?.baseUrl;
66
+ const createOrganization = useAtomSet(authClientApi(baseUrl).mutation("admin", "createOrganization"), { mode: "promise" });
67
+ const updateOrganization = useAtomSet(authClientApi(baseUrl).mutation("admin", "updateOrganization"), { mode: "promise" });
68
+ const uploadLogo = useAtomSet(authClientApi(baseUrl).mutation("authExtra", "uploadOrganizationLogo"), { mode: "promise" });
69
+ const [error, setError] = useState("");
70
+ const isEditing = Boolean(organization);
71
+ const form = useAppForm({
72
+ defaultValues: {
73
+ name: organization?.name ?? "",
74
+ slug: organization?.slug ?? "",
75
+ logo: assetUrl(organization?.logo, baseUrl),
76
+ },
77
+ onSubmit: async ({ value }) => {
78
+ setError("");
79
+ try {
80
+ const logoFile = isFile(value.logo) ? value.logo : null;
81
+ const logo = logoFile
82
+ ? await (async () => {
83
+ const payload = new FormData();
84
+ payload.append("file", logoFile);
85
+ return assetPath((await uploadLogo({ payload })).url);
86
+ })()
87
+ : assetPath(value.logo);
88
+ const payload = valuesToPayload(value, logo);
89
+ const saved = organization
90
+ ? await updateOrganization({
91
+ params: { id: organization.id },
92
+ payload,
93
+ })
94
+ : await createOrganization({ payload });
95
+ toast.success(organization
96
+ ? m.organization_updated_toast
97
+ : m.organization_created_toast);
98
+ onSaved(saved);
99
+ onClose();
100
+ }
101
+ catch (cause) {
102
+ setError(cause instanceof Error
103
+ ? cause.message
104
+ : organization
105
+ ? m.organization_update_error
106
+ : m.organization_create_error);
107
+ }
108
+ },
109
+ });
110
+ return (_jsx(Dialog, { open: true, onOpenChange: (open) => !open && onClose(), children: _jsxs(DialogContent, { className: "max-h-[90vh] overflow-y-auto sm:max-w-2xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { children: isEditing
111
+ ? m.organization_edit_title
112
+ : m.organization_create_title }), _jsx(DialogDescription, { children: isEditing
113
+ ? text(m.admin_organization_edit_description, {
114
+ name: organization?.name ?? "",
115
+ })
116
+ : m.organization_create_description })] }), _jsx(form.AppForm, { children: _jsxs("form", { className: "flex flex-col gap-4", onSubmit: (event) => {
117
+ event.preventDefault();
118
+ event.stopPropagation();
119
+ form.handleSubmit();
120
+ }, children: [_jsx(form.AppField, { name: "name", children: (field) => _jsx(field.TextField, { label: m.field_name, autoFocus: true }) }), _jsx(form.AppField, { name: "slug", children: (field) => (_jsx(field.TextField, { label: m.organization_slug, description: m.organization_slug_description })) }), _jsx(form.AppField, { name: "logo", children: (field) => (_jsx(field.ImageField, { label: m.organization_field_logo_url, size: {
121
+ width: 96,
122
+ height: 96,
123
+ suggestedWidth: 512,
124
+ suggestedHeight: 512,
125
+ } })) }), _jsx(form.FormError, {}), error ? _jsx(ErrorMessage, { text: error }) : null, _jsx(form.Subscribe, { selector: (state) => state.isSubmitting, children: (isSubmitting) => (_jsxs(Button, { disabled: isSubmitting, type: "submit", className: "self-start", children: [isSubmitting ? (_jsx(Loader2, { className: "animate-spin", "data-icon": "inline-start" })) : null, m.form_submit] })) })] }) })] }) }));
126
+ }
@@ -0,0 +1,7 @@
1
+ import type { ValidateFromPath } from "@tanstack/react-router";
2
+ import { type TableParams } from "@/components/ui/data-table";
3
+ export declare function AdminOrganizationsTable({ from, reloadKey, search, }: {
4
+ from?: ValidateFromPath;
5
+ reloadKey?: number;
6
+ search: TableParams;
7
+ }): import("react").JSX.Element;
@@ -0,0 +1,122 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // @ts-nocheck
3
+ import { useAtomValue } from "@effect/atom-react";
4
+ import {} from "@tanstack/react-table";
5
+ import { Atom, AsyncResult } from "effect/unstable/reactivity";
6
+ import { Building2 } from "lucide-react";
7
+ import { useState } from "react";
8
+ import { DataTable } from "@/components/ui/data-table";
9
+ import { ErrorMessage } from "@/components/ui/form";
10
+ import { AppBrand } from "@/components/ui/app-brand";
11
+ import { Badge } from "@/components/ui/badge";
12
+ import { authClientApi } from "./auth-client-api";
13
+ import { useKrakstackAuth } from "./auth-provider";
14
+ import { assetUrl, organizationBranding } from "./utils";
15
+ const defaultMessages = {
16
+ en: {
17
+ admin_column_created: "Created",
18
+ admin_column_organization: "Organization",
19
+ admin_none: "None",
20
+ oauth_client_logo_configured: "Configured",
21
+ organization_fetch_error: "Unable to load organizations.",
22
+ organization_field_logo_url: "Logo",
23
+ },
24
+ fr: {
25
+ admin_column_created: "Créé",
26
+ admin_column_organization: "Organisation",
27
+ admin_none: "Aucun",
28
+ oauth_client_logo_configured: "Configuré",
29
+ organization_fetch_error: "Impossible de charger les organisations.",
30
+ organization_field_logo_url: "Logo",
31
+ },
32
+ };
33
+ const labels = (locale) => ({
34
+ ...defaultMessages[locale],
35
+ });
36
+ const organizationDisplay = (organization, locale, baseUrl) => {
37
+ const branding = organizationBranding(organization, locale);
38
+ return {
39
+ name: branding?.name ?? organization.name,
40
+ image: assetUrl(branding?.logo, baseUrl),
41
+ };
42
+ };
43
+ const organizationsQuery = (search, projectId) => {
44
+ const query = {
45
+ page: search.page ?? 0,
46
+ pageSize: search.pageSize ?? 10,
47
+ ...(search.globalFilter ? { globalFilter: search.globalFilter } : {}),
48
+ ...(search.sort ? { sort: search.sort } : {}),
49
+ ...(projectId ? { projectId } : {}),
50
+ };
51
+ return {
52
+ query,
53
+ key: JSON.stringify(query),
54
+ };
55
+ };
56
+ const organizationsAtom = Atom.family(({ baseUrl, projectId, reloadKey, search, }) => {
57
+ const request = organizationsQuery(search, projectId);
58
+ return authClientApi(baseUrl).query("admin", "listOrganizations", {
59
+ query: request.query,
60
+ timeToLive: "1 minute",
61
+ reactivityKeys: [
62
+ "organizations",
63
+ ...(projectId ? [`project:${projectId}`] : []),
64
+ ],
65
+ serializationKey: `organizations:${reloadKey}:${request.key}`,
66
+ });
67
+ });
68
+ export function AdminOrganizationsTable({ from, reloadKey = 0, search, }) {
69
+ const auth = useKrakstackAuth();
70
+ const locale = auth?.locale ?? "en";
71
+ const m = labels(locale);
72
+ const baseUrl = auth?.baseUrl;
73
+ const projectId = auth?.projectId;
74
+ const [refreshKey, setRefreshKey] = useState(0);
75
+ const result = useAtomValue(organizationsAtom({
76
+ baseUrl,
77
+ projectId,
78
+ reloadKey: reloadKey + refreshKey,
79
+ search,
80
+ }));
81
+ const organizations = AsyncResult.match(result, {
82
+ onInitial: () => [],
83
+ onFailure: () => [],
84
+ onSuccess: ({ value }) => Array.from(value.data),
85
+ });
86
+ const total = AsyncResult.match(result, {
87
+ onInitial: () => 0,
88
+ onFailure: () => 0,
89
+ onSuccess: ({ value }) => value.meta.total,
90
+ });
91
+ const error = AsyncResult.match(result, {
92
+ onInitial: () => "",
93
+ onFailure: () => m.organization_fetch_error,
94
+ onSuccess: () => "",
95
+ });
96
+ const isLoading = AsyncResult.match(result, {
97
+ onInitial: () => true,
98
+ onFailure: () => false,
99
+ onSuccess: () => false,
100
+ });
101
+ return (_jsxs("div", { className: "flex flex-col gap-4", children: [error ? _jsx(ErrorMessage, { text: error }) : null, _jsx(DataTable, { columns: organizationColumns(m, locale, baseUrl), data: organizations, exportFileName: "organizations.csv", features: { gallery: false }, ...(from ? { from } : {}), isLoading: isLoading, onRefresh: () => setRefreshKey((current) => current + 1), serverPagination: { rowCount: total } })] }));
102
+ }
103
+ const organizationColumns = (m, locale, baseUrl) => [
104
+ {
105
+ accessorKey: "name",
106
+ header: m.admin_column_organization,
107
+ cell: ({ row }) => {
108
+ const display = organizationDisplay(row.original, locale, baseUrl);
109
+ return (_jsx(AppBrand, { to: null, label: display.name, subtitle: row.original.slug, icon: Building2, className: "min-w-56", ...(display.image ? { imageSrc: display.image } : {}) }));
110
+ },
111
+ },
112
+ {
113
+ accessorKey: "logo",
114
+ header: m.organization_field_logo_url,
115
+ cell: ({ row }) => row.original.logo ? (_jsx(Badge, { variant: "outline", children: m.oauth_client_logo_configured })) : (_jsx("span", { className: "text-muted-foreground text-sm", children: m.admin_none })),
116
+ },
117
+ {
118
+ accessorKey: "createdAt",
119
+ header: m.admin_column_created,
120
+ cell: ({ row }) => (_jsx("span", { className: "text-muted-foreground text-sm", children: new Date(row.original.createdAt).toLocaleDateString() })),
121
+ },
122
+ ];
@@ -0,0 +1,8 @@
1
+ import { type ValidateFromPath } from "@tanstack/react-router";
2
+ import { type TableParams } from "@/components/ui/data-table";
3
+ export declare function AdminUsersTable({ from, reloadKey, search, }: {
4
+ from?: ValidateFromPath;
5
+ reloadKey?: number;
6
+ search: TableParams;
7
+ }): import("react").JSX.Element;
8
+ export declare function useAdminUsersTotal(search: TableParams): number;
@@ -0,0 +1,282 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // @ts-nocheck
3
+ import { useAtomValue } from "@effect/atom-react";
4
+ import { useNavigate } from "@tanstack/react-router";
5
+ import {} from "@tanstack/react-table";
6
+ import { Atom, AsyncResult } from "effect/unstable/reactivity";
7
+ import { Ban, Loader2, ShieldOff, UserCog, UserIcon } from "lucide-react";
8
+ import { useState } from "react";
9
+ import { DataTable } from "@/components/ui/data-table";
10
+ import { ErrorMessage } from "@/components/ui/form";
11
+ import { AppBrand } from "@/components/ui/app-brand";
12
+ import { Badge } from "@/components/ui/badge";
13
+ import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog";
14
+ import { authClientApi } from "./auth-client-api";
15
+ import { useKrakstackAuth } from "./auth-provider";
16
+ import { assetUrl } from "./utils";
17
+ const defaultMessages = {
18
+ en: {
19
+ admin_action_ban: "Ban",
20
+ admin_action_impersonate: "Impersonate",
21
+ admin_action_unban: "Unban",
22
+ admin_ban_description: "Are you sure you want to ban {name} ({email})? They will not be able to sign in.",
23
+ admin_ban_title: "Ban user",
24
+ admin_column_created: "Created",
25
+ admin_column_role: "Role",
26
+ admin_column_status: "Status",
27
+ admin_column_unverified: "Unverified",
28
+ admin_column_user: "User",
29
+ admin_column_verified: "Verified",
30
+ admin_error_access_required: "Admin access is required.",
31
+ admin_error_ban: "Unable to ban user.",
32
+ admin_error_impersonate: "Unable to impersonate user.",
33
+ admin_error_unban: "Unable to unban user.",
34
+ admin_status_active: "Active",
35
+ admin_status_banned: "Banned",
36
+ admin_unban_description: "Are you sure you want to unban {name} ({email})? They will be able to sign in again.",
37
+ admin_unban_title: "Unban user",
38
+ form_cancel: "Cancel",
39
+ user_role_default: "user",
40
+ },
41
+ fr: {
42
+ admin_action_ban: "Bannir",
43
+ admin_action_impersonate: "Emprunter l'identité",
44
+ admin_action_unban: "Débannir",
45
+ admin_ban_description: "Êtes-vous sûr de vouloir bannir {name} ({email}) ? Il ne pourra plus se connecter.",
46
+ admin_ban_title: "Bannir l'utilisateur",
47
+ admin_column_created: "Créé",
48
+ admin_column_role: "Rôle",
49
+ admin_column_status: "Statut",
50
+ admin_column_unverified: "Non vérifié",
51
+ admin_column_user: "Utilisateur",
52
+ admin_column_verified: "Vérifié",
53
+ admin_error_access_required: "Accès administrateur requis.",
54
+ admin_error_ban: "Impossible de bannir l'utilisateur.",
55
+ admin_error_impersonate: "Impossible d'emprunter l'identité de l'utilisateur.",
56
+ admin_error_unban: "Impossible de débannir l'utilisateur.",
57
+ admin_status_active: "Actif",
58
+ admin_status_banned: "Banni",
59
+ admin_unban_description: "Êtes-vous sûr de vouloir débannir {name} ({email}) ? Il pourra se reconnecter.",
60
+ admin_unban_title: "Débannir l'utilisateur",
61
+ form_cancel: "Annuler",
62
+ user_role_default: "utilisateur",
63
+ },
64
+ };
65
+ const labels = (locale) => ({
66
+ ...defaultMessages[locale],
67
+ });
68
+ const text = (value, params) => Object.entries(params ?? {}).reduce((current, [key, replacement]) => current.replace(`{${key}}`, replacement), value);
69
+ const adminUsersQuery = (search, projectId) => {
70
+ const query = {
71
+ page: search.page ?? 0,
72
+ pageSize: search.pageSize ?? 10,
73
+ ...(search.globalFilter ? { globalFilter: search.globalFilter } : {}),
74
+ ...(search.sort ? { sort: search.sort } : {}),
75
+ ...(projectId ? { projectId } : {}),
76
+ };
77
+ return {
78
+ query,
79
+ key: JSON.stringify(query),
80
+ };
81
+ };
82
+ const usersAtom = Atom.family(({ baseUrl, projectId, reloadKey, search, }) => {
83
+ const request = adminUsersQuery(search, projectId);
84
+ return authClientApi(baseUrl).query("admin", "listUsers", {
85
+ query: request.query,
86
+ timeToLive: "1 minute",
87
+ reactivityKeys: [
88
+ "admin-users",
89
+ ...(projectId ? [`project:${projectId}`] : []),
90
+ ],
91
+ serializationKey: `admin-users:${reloadKey}:${request.key}`,
92
+ });
93
+ });
94
+ const banUser = async (authClient, userId, m) => {
95
+ const result = await authClient.admin.banUser({ userId });
96
+ if (result.error)
97
+ throw new Error(result.error.message ?? m.admin_error_ban);
98
+ };
99
+ const unbanUser = async (authClient, userId, m) => {
100
+ const result = await authClient.admin.unbanUser({ userId });
101
+ if (result.error)
102
+ throw new Error(result.error.message ?? m.admin_error_unban);
103
+ };
104
+ const impersonateUser = async (authClient, userId, m) => {
105
+ const result = await authClient.admin.impersonateUser({ userId });
106
+ if (result.error)
107
+ throw new Error(result.error.message ?? m.admin_error_impersonate);
108
+ };
109
+ export function AdminUsersTable({ from, reloadKey = 0, search, }) {
110
+ const navigate = useNavigate();
111
+ const auth = useKrakstackAuth();
112
+ const m = labels(auth?.locale ?? "en");
113
+ const authClient = auth?.authClient;
114
+ const baseUrl = auth?.baseUrl;
115
+ const projectId = auth?.projectId;
116
+ const [impersonatingUserId, setImpersonatingUserId] = useState(null);
117
+ const [impersonateError, setImpersonateError] = useState("");
118
+ const [refreshKey, setRefreshKey] = useState(0);
119
+ const result = useAtomValue(usersAtom({
120
+ baseUrl,
121
+ projectId,
122
+ search,
123
+ reloadKey: reloadKey + refreshKey,
124
+ }));
125
+ const [banningUser, setBanningUser] = useState(null);
126
+ const [unbanningUser, setUnbanningUser] = useState(null);
127
+ const users = AsyncResult.match(result, {
128
+ onInitial: () => [],
129
+ onFailure: () => [],
130
+ onSuccess: ({ value }) => Array.from(value.data),
131
+ });
132
+ const total = AsyncResult.match(result, {
133
+ onInitial: () => 0,
134
+ onFailure: () => 0,
135
+ onSuccess: ({ value }) => value.meta.total,
136
+ });
137
+ const error = AsyncResult.match(result, {
138
+ onInitial: () => "",
139
+ onFailure: () => m.admin_error_access_required,
140
+ onSuccess: () => "",
141
+ });
142
+ const isLoading = AsyncResult.match(result, {
143
+ onInitial: () => true,
144
+ onFailure: () => false,
145
+ onSuccess: () => false,
146
+ });
147
+ return (_jsxs(_Fragment, { children: [error ? _jsx(ErrorMessage, { text: error }) : null, impersonateError ? _jsx(ErrorMessage, { text: impersonateError }) : null, _jsx(DataTable, { columns: userColumns(m), data: users, exportFileName: "users.csv", features: { gallery: false }, ...(from ? { from } : {}), isLoading: isLoading, onRefresh: () => setRefreshKey((current) => current + 1), serverPagination: { rowCount: total }, rowActions: [
148
+ {
149
+ name: m.admin_action_impersonate,
150
+ icon: impersonatingUserId ? (_jsx(Loader2, { className: "size-4 animate-spin" })) : (_jsx(UserCog, { className: "size-4" })),
151
+ onClick: async (user) => {
152
+ setImpersonateError("");
153
+ setImpersonatingUserId(user.id);
154
+ try {
155
+ if (!authClient)
156
+ throw new Error(m.admin_error_access_required);
157
+ await impersonateUser(authClient, user.id, m);
158
+ await navigate({ to: "/" });
159
+ }
160
+ catch (cause) {
161
+ setImpersonateError(cause instanceof Error
162
+ ? cause.message
163
+ : m.admin_error_impersonate);
164
+ }
165
+ finally {
166
+ setImpersonatingUserId(null);
167
+ }
168
+ },
169
+ visible: (user) => !user.banned,
170
+ },
171
+ {
172
+ name: m.admin_action_ban,
173
+ icon: _jsx(Ban, { className: "size-4" }),
174
+ variant: "destructive",
175
+ onClick: (user) => setBanningUser(user),
176
+ visible: (user) => !user.banned,
177
+ },
178
+ {
179
+ name: m.admin_action_unban,
180
+ icon: _jsx(ShieldOff, { className: "size-4" }),
181
+ onClick: (user) => setUnbanningUser(user),
182
+ visible: (user) => !!user.banned,
183
+ },
184
+ ] }), banningUser ? (_jsx(BanUserDialog, { labels: m, authClient: authClient, user: banningUser, onBanned: () => setRefreshKey((current) => current + 1), onClose: () => setBanningUser(null) })) : null, unbanningUser ? (_jsx(UnbanUserDialog, { labels: m, authClient: authClient, user: unbanningUser, onUnbanned: () => setRefreshKey((current) => current + 1), onClose: () => setUnbanningUser(null) })) : null] }));
185
+ }
186
+ export function useAdminUsersTotal(search) {
187
+ const auth = useKrakstackAuth();
188
+ const result = useAtomValue(usersAtom({
189
+ baseUrl: auth?.baseUrl,
190
+ projectId: auth?.projectId,
191
+ search,
192
+ reloadKey: 0,
193
+ }));
194
+ return AsyncResult.match(result, {
195
+ onInitial: () => 0,
196
+ onFailure: () => 0,
197
+ onSuccess: ({ value }) => value.meta.total,
198
+ });
199
+ }
200
+ const userColumns = (m) => [
201
+ {
202
+ accessorKey: "email",
203
+ header: m.admin_column_user,
204
+ cell: ({ row }) => {
205
+ const image = assetUrl(row.original.image);
206
+ return (_jsx(AppBrand, { to: null, label: row.original.email, subtitle: row.original.name, icon: UserIcon, className: "min-w-48", ...(image ? { imageSrc: image } : {}) }));
207
+ },
208
+ },
209
+ {
210
+ accessorKey: "emailVerified",
211
+ header: m.admin_column_verified,
212
+ cell: ({ row }) => row.original.emailVerified ? (_jsx(Badge, { variant: "outline", children: m.admin_column_verified })) : (_jsx(Badge, { variant: "secondary", children: m.admin_column_unverified })),
213
+ },
214
+ {
215
+ accessorKey: "role",
216
+ header: m.admin_column_role,
217
+ cell: ({ row }) => {
218
+ const role = row.original.role;
219
+ if (!role)
220
+ return _jsx(Badge, { variant: "outline", children: m.user_role_default });
221
+ return (_jsx("div", { className: "flex flex-wrap gap-1.5", children: role.split(",").map((r) => (_jsx(Badge, { variant: r.trim() === "admin" ? "default" : "outline", children: r.trim() }, r.trim()))) }));
222
+ },
223
+ },
224
+ {
225
+ accessorKey: "banned",
226
+ header: m.admin_column_status,
227
+ cell: ({ row }) => row.original.banned ? (_jsx(Badge, { variant: "destructive", children: m.admin_status_banned })) : (_jsx(Badge, { variant: "outline", children: m.admin_status_active })),
228
+ },
229
+ {
230
+ accessorKey: "createdAt",
231
+ header: m.admin_column_created,
232
+ cell: ({ row }) => (_jsx("span", { className: "text-muted-foreground text-sm", children: new Date(row.original.createdAt).toLocaleDateString() })),
233
+ },
234
+ ];
235
+ function BanUserDialog({ labels: m, authClient, user, onBanned, onClose, }) {
236
+ const [isPending, setIsPending] = useState(false);
237
+ const [error, setError] = useState("");
238
+ return (_jsx(AlertDialog, { open: true, onOpenChange: (open) => !open && onClose(), children: _jsxs(AlertDialogContent, { children: [_jsxs(AlertDialogHeader, { children: [_jsx(AlertDialogTitle, { children: m.admin_ban_title }), _jsx(AlertDialogDescription, { children: text(m.admin_ban_description, {
239
+ name: user.name,
240
+ email: user.email,
241
+ }) })] }), error ? _jsx(ErrorMessage, { text: error }) : null, _jsxs(AlertDialogFooter, { children: [_jsx(AlertDialogCancel, { disabled: isPending, children: m.form_cancel }), _jsxs(AlertDialogAction, { onClick: async () => {
242
+ setError("");
243
+ setIsPending(true);
244
+ try {
245
+ if (!authClient)
246
+ throw new Error(m.admin_error_access_required);
247
+ await banUser(authClient, user.id, m);
248
+ onBanned();
249
+ onClose();
250
+ }
251
+ catch (cause) {
252
+ setError(cause instanceof Error ? cause.message : m.admin_error_ban);
253
+ }
254
+ finally {
255
+ setIsPending(false);
256
+ }
257
+ }, disabled: isPending, children: [isPending ? (_jsx(Loader2, { className: "animate-spin", "data-icon": "inline-start" })) : null, m.admin_action_ban] })] })] }) }));
258
+ }
259
+ function UnbanUserDialog({ labels: m, authClient, user, onUnbanned, onClose, }) {
260
+ const [isPending, setIsPending] = useState(false);
261
+ const [error, setError] = useState("");
262
+ return (_jsx(AlertDialog, { open: true, onOpenChange: (open) => !open && onClose(), children: _jsxs(AlertDialogContent, { children: [_jsxs(AlertDialogHeader, { children: [_jsx(AlertDialogTitle, { children: m.admin_unban_title }), _jsx(AlertDialogDescription, { children: text(m.admin_unban_description, {
263
+ name: user.name,
264
+ email: user.email,
265
+ }) })] }), error ? _jsx(ErrorMessage, { text: error }) : null, _jsxs(AlertDialogFooter, { children: [_jsx(AlertDialogCancel, { disabled: isPending, children: m.form_cancel }), _jsxs(AlertDialogAction, { onClick: async () => {
266
+ setError("");
267
+ setIsPending(true);
268
+ try {
269
+ if (!authClient)
270
+ throw new Error(m.admin_error_access_required);
271
+ await unbanUser(authClient, user.id, m);
272
+ onUnbanned();
273
+ onClose();
274
+ }
275
+ catch (cause) {
276
+ setError(cause instanceof Error ? cause.message : m.admin_error_unban);
277
+ }
278
+ finally {
279
+ setIsPending(false);
280
+ }
281
+ }, disabled: isPending, children: [isPending ? (_jsx(Loader2, { className: "animate-spin", "data-icon": "inline-start" })) : null, m.admin_action_unban] })] })] }) }));
282
+ }