@krak-stack/auth 0.1.39 → 0.1.40

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