diff --git a/README.md b/README.md index 228bcd9..408172d 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,11 @@ This app allows an admin to: ## Main Features -- Better-auth admin login +- First-run administrator setup when the user directory is empty +- Better Auth email/password sign-in with public registration disabled +- Administrator-created users with either an initial password or a one-time invitation link +- Non-expiring invitation links with copy, revoke, replace, accepted, and revoked states +- Admin, Editor, and Viewer role management with last-administrator protection - Dashboard summary for: - total servers - total services @@ -30,7 +34,7 @@ This app allows an admin to: - Domain CRUD - DNS check action - Server notes CRUD -- Sample seeded admin and demo dataset +- Optional sample admin and demo dataset ## Database / Entity Overview @@ -137,7 +141,25 @@ bun run db:start bun run db:push ``` -5. Seed sample data +5. Run the application + +```bash +bun run dev +``` + +6. Open the app + +- Web: `http://localhost:5173` +- API: `http://localhost:3000` + +On a new database, Minmon redirects to `/setup`. The first account is assigned the +Admin role, the one-time setup endpoint closes, and ordinary public sign-up remains +disabled. + +### Optional demo data + +Run the explicit demo seed only when you want the sample monitoring inventory and +the fixed demonstration account: ```bash bun run --filter @minmon/db db:seed @@ -148,17 +170,6 @@ Seeded admin: - Email: `admin@minmon.local` - Password: `admin12345` -6. Run the application - -```bash -bun run dev -``` - -7. Open the app - -- Web: `http://localhost:5173` -- API: `http://localhost:3000` - ## Docker Compose Deployment Run the full stack with PostgreSQL, database initialization, API, and web UI: @@ -173,11 +184,12 @@ Default endpoints: - Web: `http://localhost:3001` - API: `http://localhost:3000` -On first startup, the database initializer applies the schema and seeds the sample admin only when the users table is empty. +On startup, the database initializer applies the schema and ensures the default roles +and permissions exist. It does not create a default user. Open the web app to create +the first administrator securely through the setup screen. Docker Compose reads the root `.env` file automatically. Edit it before startup if you need different ports, public URLs, credentials, or secrets. - ## Project Structure ```text diff --git a/apps/web/src/components/dashboard-shell.tsx b/apps/web/src/components/dashboard-shell.tsx index a3ddfee..29a84a8 100644 --- a/apps/web/src/components/dashboard-shell.tsx +++ b/apps/web/src/components/dashboard-shell.tsx @@ -84,29 +84,33 @@ function NavItems({ return ( ); } @@ -175,8 +179,8 @@ export function DashboardShell({ Operations overview for demos and day-to-day admin tasks

- Use this area to review monitored assets, inspect detail - states, currently used to monitor my homelab setup. + Use this area to review monitored assets, inspect detail states, + currently used to monitor my homelab setup.

@@ -188,21 +192,28 @@ export function DashboardShell({ {userName ?? "Administrator"}

- {userEmail ?? "admin@minmon.local"} + {userEmail ?? "Signed-in account"}

{allowedPermissions.has("servers.create") ? ( - - - + ) : null} {allowedPermissions.has("notes.create") ? ( - - - + ) : null}
diff --git a/apps/web/src/components/header.tsx b/apps/web/src/components/header.tsx index fe5d466..989ce9e 100644 --- a/apps/web/src/components/header.tsx +++ b/apps/web/src/components/header.tsx @@ -8,7 +8,10 @@ export default function Header() {
- + minmon
diff --git a/apps/web/src/components/mode-toggle.tsx b/apps/web/src/components/mode-toggle.tsx index e986716..7f06420 100644 --- a/apps/web/src/components/mode-toggle.tsx +++ b/apps/web/src/components/mode-toggle.tsx @@ -15,14 +15,20 @@ export function ModeToggle() { return ( }> - - + + Toggle theme - setTheme("light")}>Light - setTheme("dark")}>Dark - setTheme("system")}>System + setTheme("light")}> + Light + + setTheme("dark")}> + Dark + + setTheme("system")}> + System + ); diff --git a/apps/web/src/components/sign-in-form.tsx b/apps/web/src/components/sign-in-form.tsx index 352a4df..1642554 100644 --- a/apps/web/src/components/sign-in-form.tsx +++ b/apps/web/src/components/sign-in-form.tsx @@ -56,10 +56,12 @@ export default function SignInForm() {
-

Admin Access

+

+ Private access +

Sign in

- Use your administrator account to open the protected monitoring dashboard. + Use your Minmon account to open the protected monitoring dashboard.

@@ -105,7 +107,10 @@ export default function SignInForm() { ({ canSubmit: state.canSubmit, isSubmitting: state.isSubmitting })} + selector={(state) => ({ + canSubmit: state.canSubmit, + isSubmitting: state.isSubmitting, + })} > {({ canSubmit, isSubmitting }) => (
diff --git a/apps/web/src/components/user-menu.tsx b/apps/web/src/components/user-menu.tsx index f7792d9..c42ac24 100644 --- a/apps/web/src/components/user-menu.tsx +++ b/apps/web/src/components/user-menu.tsx @@ -23,9 +23,13 @@ export default function UserMenu() { if (!session) { return ( - - - + ); } diff --git a/apps/web/src/lib/auth-client.ts b/apps/web/src/lib/auth-client.ts index 04a0c88..7965f69 100644 --- a/apps/web/src/lib/auth-client.ts +++ b/apps/web/src/lib/auth-client.ts @@ -1,6 +1,19 @@ import { env } from "@minmon/env/web"; +import { inferAdditionalFields } from "better-auth/client/plugins"; import { createAuthClient } from "better-auth/react"; export const authClient = createAuthClient({ baseURL: env.VITE_SERVER_URL, + plugins: [ + inferAdditionalFields({ + user: { + mustChangePassword: { + type: "boolean", + required: false, + defaultValue: false, + input: false, + }, + }, + }), + ], }); diff --git a/apps/web/src/lib/protected-route.ts b/apps/web/src/lib/protected-route.ts index f21d9f9..f2ea8e9 100644 --- a/apps/web/src/lib/protected-route.ts +++ b/apps/web/src/lib/protected-route.ts @@ -6,9 +6,32 @@ export async function requireSession() { const session = await authClient.getSession(); if (!session.data) { - redirect({ + throw redirect({ to: "/login", - throw: true, + }); + } + + if (session.data.user.mustChangePassword) { + throw redirect({ + to: "/change-password", + }); + } + + return { session }; +} + +export async function requireInitialPasswordChange() { + const session = await authClient.getSession(); + + if (!session.data) { + throw redirect({ + to: "/login", + }); + } + + if (!session.data.user.mustChangePassword) { + throw redirect({ + to: "/dashboard", }); } diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index 7eeb976..553feb3 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -9,10 +9,13 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' +import { Route as SetupRouteImport } from './routes/setup' import { Route as LoginRouteImport } from './routes/login' import { Route as DashboardRouteImport } from './routes/dashboard' +import { Route as ChangePasswordRouteImport } from './routes/change-password' import { Route as IndexRouteImport } from './routes/index' import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' +import { Route as InviteTokenRouteImport } from './routes/invite.$token' import { Route as DashboardUsersRouteImport } from './routes/dashboard.users' import { Route as DashboardServicesRouteImport } from './routes/dashboard.services' import { Route as DashboardServersRouteImport } from './routes/dashboard.servers' @@ -27,6 +30,11 @@ import { Route as DashboardNotesNoteIdRouteImport } from './routes/dashboard.not import { Route as DashboardDomainsNewRouteImport } from './routes/dashboard.domains_.new' import { Route as DashboardDomainsDomainIdRouteImport } from './routes/dashboard.domains_.$domainId' +const SetupRoute = SetupRouteImport.update({ + id: '/setup', + path: '/setup', + getParentRoute: () => rootRouteImport, +} as any) const LoginRoute = LoginRouteImport.update({ id: '/login', path: '/login', @@ -37,6 +45,11 @@ const DashboardRoute = DashboardRouteImport.update({ path: '/dashboard', getParentRoute: () => rootRouteImport, } as any) +const ChangePasswordRoute = ChangePasswordRouteImport.update({ + id: '/change-password', + path: '/change-password', + getParentRoute: () => rootRouteImport, +} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', @@ -47,6 +60,11 @@ const DashboardIndexRoute = DashboardIndexRouteImport.update({ path: '/', getParentRoute: () => DashboardRoute, } as any) +const InviteTokenRoute = InviteTokenRouteImport.update({ + id: '/invite/$token', + path: '/invite/$token', + getParentRoute: () => rootRouteImport, +} as any) const DashboardUsersRoute = DashboardUsersRouteImport.update({ id: '/users', path: '/users', @@ -118,13 +136,16 @@ const DashboardDomainsDomainIdRoute = export interface FileRoutesByFullPath { '/': typeof IndexRoute + '/change-password': typeof ChangePasswordRoute '/dashboard': typeof DashboardRouteWithChildren '/login': typeof LoginRoute + '/setup': typeof SetupRoute '/dashboard/domains': typeof DashboardDomainsRoute '/dashboard/notes': typeof DashboardNotesRoute '/dashboard/servers': typeof DashboardServersRoute '/dashboard/services': typeof DashboardServicesRoute '/dashboard/users': typeof DashboardUsersRoute + '/invite/$token': typeof InviteTokenRoute '/dashboard/': typeof DashboardIndexRoute '/dashboard/domains/$domainId': typeof DashboardDomainsDomainIdRoute '/dashboard/domains/new': typeof DashboardDomainsNewRoute @@ -137,12 +158,15 @@ export interface FileRoutesByFullPath { } export interface FileRoutesByTo { '/': typeof IndexRoute + '/change-password': typeof ChangePasswordRoute '/login': typeof LoginRoute + '/setup': typeof SetupRoute '/dashboard/domains': typeof DashboardDomainsRoute '/dashboard/notes': typeof DashboardNotesRoute '/dashboard/servers': typeof DashboardServersRoute '/dashboard/services': typeof DashboardServicesRoute '/dashboard/users': typeof DashboardUsersRoute + '/invite/$token': typeof InviteTokenRoute '/dashboard': typeof DashboardIndexRoute '/dashboard/domains/$domainId': typeof DashboardDomainsDomainIdRoute '/dashboard/domains/new': typeof DashboardDomainsNewRoute @@ -156,13 +180,16 @@ export interface FileRoutesByTo { export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute + '/change-password': typeof ChangePasswordRoute '/dashboard': typeof DashboardRouteWithChildren '/login': typeof LoginRoute + '/setup': typeof SetupRoute '/dashboard/domains': typeof DashboardDomainsRoute '/dashboard/notes': typeof DashboardNotesRoute '/dashboard/servers': typeof DashboardServersRoute '/dashboard/services': typeof DashboardServicesRoute '/dashboard/users': typeof DashboardUsersRoute + '/invite/$token': typeof InviteTokenRoute '/dashboard/': typeof DashboardIndexRoute '/dashboard/domains_/$domainId': typeof DashboardDomainsDomainIdRoute '/dashboard/domains_/new': typeof DashboardDomainsNewRoute @@ -177,13 +204,16 @@ export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath fullPaths: | '/' + | '/change-password' | '/dashboard' | '/login' + | '/setup' | '/dashboard/domains' | '/dashboard/notes' | '/dashboard/servers' | '/dashboard/services' | '/dashboard/users' + | '/invite/$token' | '/dashboard/' | '/dashboard/domains/$domainId' | '/dashboard/domains/new' @@ -196,12 +226,15 @@ export interface FileRouteTypes { fileRoutesByTo: FileRoutesByTo to: | '/' + | '/change-password' | '/login' + | '/setup' | '/dashboard/domains' | '/dashboard/notes' | '/dashboard/servers' | '/dashboard/services' | '/dashboard/users' + | '/invite/$token' | '/dashboard' | '/dashboard/domains/$domainId' | '/dashboard/domains/new' @@ -214,13 +247,16 @@ export interface FileRouteTypes { id: | '__root__' | '/' + | '/change-password' | '/dashboard' | '/login' + | '/setup' | '/dashboard/domains' | '/dashboard/notes' | '/dashboard/servers' | '/dashboard/services' | '/dashboard/users' + | '/invite/$token' | '/dashboard/' | '/dashboard/domains_/$domainId' | '/dashboard/domains_/new' @@ -234,12 +270,22 @@ export interface FileRouteTypes { } export interface RootRouteChildren { IndexRoute: typeof IndexRoute + ChangePasswordRoute: typeof ChangePasswordRoute DashboardRoute: typeof DashboardRouteWithChildren LoginRoute: typeof LoginRoute + SetupRoute: typeof SetupRoute + InviteTokenRoute: typeof InviteTokenRoute } declare module '@tanstack/react-router' { interface FileRoutesByPath { + '/setup': { + id: '/setup' + path: '/setup' + fullPath: '/setup' + preLoaderRoute: typeof SetupRouteImport + parentRoute: typeof rootRouteImport + } '/login': { id: '/login' path: '/login' @@ -254,6 +300,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardRouteImport parentRoute: typeof rootRouteImport } + '/change-password': { + id: '/change-password' + path: '/change-password' + fullPath: '/change-password' + preLoaderRoute: typeof ChangePasswordRouteImport + parentRoute: typeof rootRouteImport + } '/': { id: '/' path: '/' @@ -268,6 +321,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardIndexRouteImport parentRoute: typeof DashboardRoute } + '/invite/$token': { + id: '/invite/$token' + path: '/invite/$token' + fullPath: '/invite/$token' + preLoaderRoute: typeof InviteTokenRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard/users': { id: '/dashboard/users' path: '/users' @@ -402,8 +462,11 @@ const DashboardRouteWithChildren = DashboardRoute._addFileChildren( const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, + ChangePasswordRoute: ChangePasswordRoute, DashboardRoute: DashboardRouteWithChildren, LoginRoute: LoginRoute, + SetupRoute: SetupRoute, + InviteTokenRoute: InviteTokenRoute, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/apps/web/src/routes/change-password.tsx b/apps/web/src/routes/change-password.tsx new file mode 100644 index 0000000..5736da9 --- /dev/null +++ b/apps/web/src/routes/change-password.tsx @@ -0,0 +1,236 @@ +import { + Alert, + AlertDescription, + AlertTitle, +} from "@minmon/ui/components/alert"; +import { Button } from "@minmon/ui/components/button"; +import { + Card, + CardContent, + CardDescription, + CardFooter, + CardHeader, + CardTitle, +} from "@minmon/ui/components/card"; +import { + Field, + FieldDescription, + FieldError, + FieldGroup, + FieldLabel, +} from "@minmon/ui/components/field"; +import { Input } from "@minmon/ui/components/input"; +import { useForm } from "@tanstack/react-form"; +import { createFileRoute, useNavigate } from "@tanstack/react-router"; +import { KeyRound, Loader2, ShieldCheck } from "lucide-react"; +import { toast } from "sonner"; +import z from "zod"; + +import { requireInitialPasswordChange } from "@/lib/protected-route"; +import { formatErrorMessage } from "@/utils/errors"; +import { queryClient, trpcClient } from "@/utils/trpc"; + +const passwordSchema = z + .object({ + currentPassword: z.string().min(1, "Enter your initial password"), + newPassword: z.string().min(8, "Password must be at least 8 characters"), + confirmPassword: z.string(), + }) + .refine((value) => value.newPassword === value.confirmPassword, { + message: "Passwords do not match", + path: ["confirmPassword"], + }); + +export const Route = createFileRoute("/change-password")({ + beforeLoad: requireInitialPasswordChange, + component: ChangePasswordPage, +}); + +type FormError = string | { message?: string } | null | undefined; + +function fieldErrors(errors: FormError[]) { + return errors + .map((error) => + typeof error === "string" + ? { message: error } + : error?.message + ? error + : null, + ) + .filter((error): error is { message: string } => Boolean(error)); +} + +function ChangePasswordPage() { + const { session } = Route.useRouteContext(); + const navigate = useNavigate(); + const form = useForm({ + defaultValues: { + currentPassword: "", + newPassword: "", + confirmPassword: "", + }, + validators: { + onSubmit: passwordSchema, + }, + onSubmit: async ({ value }) => { + try { + await trpcClient.users.changeInitialPassword.mutate({ + currentPassword: value.currentPassword, + newPassword: value.newPassword, + }); + await queryClient.invalidateQueries(); + toast.success("Password updated"); + await navigate({ to: "/dashboard" }); + } catch (error) { + toast.error(formatErrorMessage(error, "Could not update the password")); + } + }, + }); + + return ( +
+ + +
+ +
+ + Choose your own password + + + An administrator created {session.data?.user.email} with an initial + password. Replace it before entering the monitoring console. + +
+ + +
{ + event.preventDefault(); + event.stopPropagation(); + form.handleSubmit(); + }} + > + + + {(field) => { + const errors = fieldErrors(field.state.meta.errors); + return ( + 0}> + + Initial password + + 0} + value={field.state.value} + onBlur={field.handleBlur} + onChange={(event) => + field.handleChange(event.target.value) + } + /> + + + ); + }} + + + + {(field) => { + const errors = fieldErrors(field.state.meta.errors); + return ( + 0}> + New password + 0} + value={field.state.value} + onBlur={field.handleBlur} + onChange={(event) => + field.handleChange(event.target.value) + } + /> + + Use at least 8 characters. + + + + ); + }} + + + + {(field) => { + const errors = fieldErrors(field.state.meta.errors); + return ( + 0}> + + Confirm new password + + 0} + value={field.state.value} + onBlur={field.handleBlur} + onChange={(event) => + field.handleChange(event.target.value) + } + /> + + + ); + }} + + + + + + Other sessions will be closed + + Only this browser remains signed in after the password is + changed. + + +
+
+ + + ({ + canSubmit: state.canSubmit, + isSubmitting: state.isSubmitting, + })} + > + {({ canSubmit, isSubmitting }) => ( + + )} + + +
+
+ ); +} diff --git a/apps/web/src/routes/dashboard.users.tsx b/apps/web/src/routes/dashboard.users.tsx index 0fd368f..8041552 100644 --- a/apps/web/src/routes/dashboard.users.tsx +++ b/apps/web/src/routes/dashboard.users.tsx @@ -1,14 +1,58 @@ +import { + Alert, + AlertDescription, + AlertTitle, +} from "@minmon/ui/components/alert"; import { Button } from "@minmon/ui/components/button"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@minmon/ui/components/card"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@minmon/ui/components/card"; import { Checkbox } from "@minmon/ui/components/checkbox"; +import { + Field, + FieldDescription, + FieldError, + FieldGroup, + FieldLabel, + FieldLegend, + FieldSet, +} from "@minmon/ui/components/field"; +import { Input } from "@minmon/ui/components/input"; import { StatusBadge } from "@minmon/ui/components/status-badge"; +import { + ToggleGroup, + ToggleGroupItem, +} from "@minmon/ui/components/toggle-group"; import { useForm } from "@tanstack/react-form"; import { useMutation, useQuery } from "@tanstack/react-query"; import { createFileRoute } from "@tanstack/react-router"; +import { + Check, + Copy, + KeyRound, + Link2, + Loader2, + RefreshCw, + ShieldCheck, + UserPlus, + X, +} from "lucide-react"; +import { useEffect, useState } from "react"; import { toast } from "sonner"; import z from "zod"; -import { ConfirmDeleteIconButton, FormCard, PageSection, QueryStateCard, ResourceListCard, TextField } from "@/components/dashboard-ui"; +import { + ConfirmDeleteIconButton, + FormCard, + PageSection, + QueryStateCard, + ResourceListCard, +} from "@/components/dashboard-ui"; +import { formatErrorMessage } from "@/utils/errors"; import { queryClient, trpc, trpcClient } from "@/utils/trpc"; export const Route = createFileRoute("/dashboard/users")({ @@ -28,13 +72,97 @@ type UserCreateFormValues = { roleIds: string[]; }; +type FormError = string | { message?: string } | null | undefined; + const userCreateSchema = z.object({ - name: z.string().min(2, "Name must be at least 2 characters"), - email: z.email("Invalid email address"), + name: z.string().trim().min(2, "Name must be at least 2 characters"), + email: z.email("Enter a valid email address"), password: z.string().min(8, "Password must be at least 8 characters"), roleIds: z.array(z.string()).min(1, "Select at least one role"), }); +const invitationCreateSchema = z.object({ + roleIds: z.array(z.string()).min(1, "Select at least one role"), +}); + +function fieldErrors(errors: FormError[]) { + return errors + .map((error) => + typeof error === "string" + ? { message: error } + : error?.message + ? error + : null, + ) + .filter((error): error is { message: string } => Boolean(error)); +} + +function RevokeInvitationButton({ + disabled, + onConfirm, +}: { + disabled: boolean; + onConfirm: () => void; +}) { + const [isConfirming, setIsConfirming] = useState(false); + + useEffect(() => { + if (!isConfirming) return; + + const timeoutId = window.setTimeout(() => setIsConfirming(false), 4000); + return () => window.clearTimeout(timeoutId); + }, [isConfirming]); + + useEffect(() => { + if (disabled) setIsConfirming(false); + }, [disabled]); + + return ( + + ); +} + +function defaultRoleIds(roles: RoleOption[]) { + return [ + roles.find((role) => role.name === "Viewer")?.id ?? roles[0]?.id ?? "", + ].filter(Boolean); +} + +function inviteUrl(token: string) { + return `${window.location.origin}/invite/${encodeURIComponent(token)}`; +} + +async function copyInvitationLink(token: string) { + try { + await navigator.clipboard.writeText(inviteUrl(token)); + toast.success("Invitation link copied"); + } catch { + toast.error("Could not copy the invitation link"); + } +} + function RoleBadges({ roles }: { roles: { id: string; name: string }[] }) { if (!roles.length) { return No roles; @@ -43,7 +171,16 @@ function RoleBadges({ roles }: { roles: { id: string; name: string }[] }) { return (
{roles.map((role) => ( - + {role.name} ))} @@ -51,17 +188,545 @@ function RoleBadges({ roles }: { roles: { id: string; name: string }[] }) { ); } -function RoleAssignmentCard({ roles, permissions }: { roles: RoleOption[]; permissions: string[] }) { +function RoleSelector({ + roles, + value, + onChange, + errors, + idPrefix, +}: { + roles: RoleOption[]; + value: string[]; + onChange: (value: string[]) => void; + errors: FormError[]; + idPrefix: string; +}) { + const normalizedErrors = fieldErrors(errors); + + return ( +
+ Initial roles + + Roles control which areas and actions are available after sign-in. + + + {roles.map((role) => { + const checked = value.includes(role.id); + const nextRoleIds = checked + ? value.filter((roleId) => roleId !== role.id) + : [...value, role.id]; + const id = `${idPrefix}-${role.id}`; + + return ( + + onChange(nextRoleIds)} + /> + + + {role.name} + + {role.description} + + + + + ); + })} + + +
+ ); +} + +function CreationMethodSelector({ + value, + onChange, +}: { + value: "password" | "invite"; + onChange: (value: "password" | "invite") => void; +}) { + return ( + + Account setup method + { + const method = nextValue[0]; + if (method === "password" || method === "invite") onChange(method); + }} + > + + + Initial password + + + + Invitation link + + + + Set a temporary credential now, or let the recipient choose every + identity field through a one-time link. + + + ); +} + +function DirectUserForm({ + roles, + onMethodChange, +}: { + roles: RoleOption[]; + onMethodChange: (value: "password" | "invite") => void; +}) { + const createUser = useMutation({ + mutationFn: async (values: UserCreateFormValues) => + trpcClient.users.create.mutate(values), + onSuccess: async () => { + toast.success("User created with an initial password"); + form.reset(); + await queryClient.invalidateQueries(); + }, + onError: (error) => + toast.error(formatErrorMessage(error, "Could not create the user")), + }); + const form = useForm({ + defaultValues: { + name: "", + email: "", + password: "", + roleIds: defaultRoleIds(roles), + } satisfies UserCreateFormValues, + validators: { + onSubmit: userCreateSchema, + }, + onSubmit: async ({ value }) => { + await createUser.mutateAsync(value); + }, + }); + + return ( +
{ + event.preventDefault(); + event.stopPropagation(); + form.handleSubmit(); + }} + > + ({ + canSubmit: state.canSubmit, + isSubmitting: state.isSubmitting, + })} + > + {({ canSubmit, isSubmitting }) => ( + + )} + + } + > + + + + {(field) => { + const errors = fieldErrors(field.state.meta.errors); + return ( + 0}> + Name + 0} + value={field.state.value} + onBlur={field.handleBlur} + onChange={(event) => field.handleChange(event.target.value)} + /> + + + ); + }} + + + {(field) => { + const errors = fieldErrors(field.state.meta.errors); + return ( + 0}> + + Email + + 0} + value={field.state.value} + onBlur={field.handleBlur} + onChange={(event) => field.handleChange(event.target.value)} + /> + + + ); + }} + + + {(field) => { + const errors = fieldErrors(field.state.meta.errors); + return ( + 0}> + + Initial password + + 0} + value={field.state.value} + onBlur={field.handleBlur} + onChange={(event) => field.handleChange(event.target.value)} + /> + At least 8 characters. + + + ); + }} + + + + {(field) => ( + + )} + + +
+ ); +} + +function InvitationForm({ + roles, + onMethodChange, +}: { + roles: RoleOption[]; + onMethodChange: (value: "password" | "invite") => void; +}) { + const [latestToken, setLatestToken] = useState(null); + const createInvitation = useMutation({ + mutationFn: async (values: { roleIds: string[] }) => + trpcClient.users.invitations.create.mutate(values), + onSuccess: async (invitation) => { + form.reset(); + setLatestToken(invitation?.token ?? null); + if (invitation?.token) await copyInvitationLink(invitation.token); + await queryClient.invalidateQueries(); + }, + onError: (error) => + toast.error(formatErrorMessage(error, "Could not create the invitation")), + }); + const form = useForm({ + defaultValues: { + roleIds: defaultRoleIds(roles), + }, + validators: { + onSubmit: invitationCreateSchema, + }, + onSubmit: async ({ value }) => { + await createInvitation.mutateAsync(value); + }, + }); + + return ( +
{ + event.preventDefault(); + event.stopPropagation(); + form.handleSubmit(); + }} + > + ({ + canSubmit: state.canSubmit, + isSubmitting: state.isSubmitting, + })} + > + {({ canSubmit, isSubmitting }) => ( + + )} + + } + > + + + + One-time link with no expiration + + The link remains valid until it is used, revoked, or replaced by an + administrator. + + + + {(field) => ( + + )} + + {latestToken ? ( + + + Invitation ready + + + {inviteUrl(latestToken)} + + + + + ) : null} + +
+ ); +} + +function CreateAccessCard({ roles }: { roles: RoleOption[] }) { + const [method, setMethod] = useState<"password" | "invite">("password"); + return method === "password" ? ( + + ) : ( + + ); +} + +function InvitationListCard() { + const invitations = useQuery(trpc.users.invitations.list.queryOptions()); + const revokeInvitation = useMutation({ + mutationFn: async (id: string) => + trpcClient.users.invitations.revoke.mutate({ id }), + onSuccess: async () => { + toast.success("Invitation revoked"); + await queryClient.invalidateQueries(); + }, + onError: (error) => + toast.error(formatErrorMessage(error, "Could not revoke the invitation")), + }); + const replaceInvitation = useMutation({ + mutationFn: async (id: string) => + trpcClient.users.invitations.reissue.mutate({ id }), + onSuccess: async (replacement) => { + if (replacement?.token) await copyInvitationLink(replacement.token); + await queryClient.invalidateQueries(); + }, + onError: (error) => + toast.error( + formatErrorMessage(error, "Could not replace the invitation"), + ), + }); + + if (invitations.isLoading) { + return ( + + ); + } + + if (invitations.isError || !invitations.data) { + return ( + + ); + } + + return ( + ( + + {new Date(item.createdAt).toLocaleString()} + + ), + }, + { + key: "roles", + header: "Roles", + render: (item: (typeof invitations.data)[number]) => ( + + ), + }, + { + key: "status", + header: "Status", + render: (item: (typeof invitations.data)[number]) => ( + + {item.status} + + ), + }, + { + key: "actions", + header: "Actions", + render: (item: (typeof invitations.data)[number]) => + item.status === "pending" ? ( +
+ + + revokeInvitation.mutate(item.id)} + /> +
+ ) : ( + + No actions available + + ), + }, + ]} + items={invitations.data} + emptyTitle="No invitation links" + emptyDescription="Create an invitation when someone should choose their own account details." + controls={{ + search: { + placeholder: "Search role or status…", + getText: (item) => + [item.status, ...item.roles.map((role) => role.name)].join(" "), + }, + filter: { + label: "Filter by status", + allLabel: "All statuses", + options: [ + { value: "pending", label: "Pending" }, + { value: "accepted", label: "Accepted" }, + { value: "revoked", label: "Revoked" }, + ], + getValue: (item) => item.status, + }, + }} + /> + ); +} + +function RoleAssignmentCard({ + roles, + permissions, + currentUserId, +}: { + roles: RoleOption[]; + permissions: string[]; + currentUserId: string; +}) { const users = useQuery(trpc.users.list.queryOptions()); const allowedPermissions = new Set(permissions); const updateRoles = useMutation({ - mutationFn: async ({ userId, roleIds }: { userId: string; roleIds: string[] }) => - trpcClient.users.updateRoles.mutate({ userId, roleIds }), + mutationFn: async ({ + userId, + roleIds, + }: { + userId: string; + roleIds: string[]; + }) => trpcClient.users.updateRoles.mutate({ userId, roleIds }), onSuccess: async () => { toast.success("User roles updated"); await queryClient.invalidateQueries(); }, - onError: (error) => toast.error(error.message), + onError: (error) => + toast.error(formatErrorMessage(error, "Could not update roles")), }); const removeUser = useMutation({ mutationFn: async (id: string) => trpcClient.users.delete.mutate({ id }), @@ -69,17 +734,32 @@ function RoleAssignmentCard({ roles, permissions }: { roles: RoleOption[]; permi toast.success("User deleted"); await queryClient.invalidateQueries(); }, - onError: (error) => toast.error(error.message), + onError: (error) => + toast.error(formatErrorMessage(error, "Could not delete the user")), }); if (users.isLoading) { - return ; + return ( + + ); } if (users.isError || !users.data) { - return ; + return ( + + ); } + const adminCount = users.data.filter((item) => + item.roles.some((assignedRole) => assignedRole.id === "role_admin"), + ).length; + return ( (
- {item.name} - {item.email} +
+ {item.name} + {item.mustChangePassword ? ( + Initial password + ) : null} +
+ + {item.email} +
), }, { key: "roles", header: "Current roles", - render: (item: (typeof users.data)[number]) => , + render: (item: (typeof users.data)[number]) => ( + + ), }, ...(allowedPermissions.has("users.assignRoles") ? [ @@ -110,22 +799,45 @@ function RoleAssignmentCard({ roles, permissions }: { roles: RoleOption[]; permi key: "assign", header: "Assign roles", render: (item: (typeof users.data)[number]) => { - const assignedRoleIds = new Set(item.roles.map((role) => role.id)); + const assignedRoleIds = new Set( + item.roles.map((assignedRole) => assignedRole.id), + ); + const isLastAdmin = + assignedRoleIds.has("role_admin") && adminCount === 1; return (
{roles.map((role) => { const checked = assignedRoleIds.has(role.id); const nextRoleIds = checked - ? item.roles.map((assignedRole) => assignedRole.id).filter((roleId) => roleId !== role.id) - : [...item.roles.map((assignedRole) => assignedRole.id), role.id]; + ? item.roles + .map((assignedRole) => assignedRole.id) + .filter((roleId) => roleId !== role.id) + : [ + ...item.roles.map( + (assignedRole) => assignedRole.id, + ), + role.id, + ]; + const disabled = + updateRoles.isPending || + nextRoleIds.length === 0 || + (role.id === "role_admin" && isLastAdmin); return ( -