feat: add onboarding and user invitations

This commit is contained in:
Syahdan 2026-08-07 19:53:11 +07:00
parent 24351eb897
commit 762cfe2b16
37 changed files with 5208 additions and 384 deletions

View file

@ -84,29 +84,33 @@ function NavItems({
return (
<nav className="grid gap-1 p-2" aria-label="Dashboard sections">
{dashboardLinks.filter((link) => allowedPermissions.has(link.permission)).map(({ to, label, description, icon: Icon }) => {
const active = isActive(pathname, to);
return (
<Link
key={to}
to={to}
aria-current={active ? "page" : undefined}
onClick={onNavigate}
className={cn(
"grid gap-0.5 border px-3 py-2 text-left transition-colors outline-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50",
active
? "border-foreground/20 bg-muted"
: "border-transparent hover:border-border hover:bg-muted/40",
)}
>
<span className="flex items-center gap-2 text-sm font-medium">
<Icon className="size-4" />
{label}
</span>
<span className="text-xs text-muted-foreground">{description}</span>
</Link>
);
})}
{dashboardLinks
.filter((link) => allowedPermissions.has(link.permission))
.map(({ to, label, description, icon: Icon }) => {
const active = isActive(pathname, to);
return (
<Link
key={to}
to={to}
aria-current={active ? "page" : undefined}
onClick={onNavigate}
className={cn(
"grid gap-0.5 border px-3 py-2 text-left transition-colors outline-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50",
active
? "border-foreground/20 bg-muted"
: "border-transparent hover:border-border hover:bg-muted/40",
)}
>
<span className="flex items-center gap-2 text-sm font-medium">
<Icon className="size-4" />
{label}
</span>
<span className="text-xs text-muted-foreground">
{description}
</span>
</Link>
);
})}
</nav>
);
}
@ -175,8 +179,8 @@ export function DashboardShell({
Operations overview for demos and day-to-day admin tasks
</h1>
<p className="max-w-2xl text-sm text-muted-foreground">
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.
</p>
</div>
<div className="grid gap-3 border-l-0 border-t pt-4 lg:border-l lg:border-t-0 lg:pl-6 lg:pt-0">
@ -188,21 +192,28 @@ export function DashboardShell({
{userName ?? "Administrator"}
</p>
<p className="text-xs text-muted-foreground">
{userEmail ?? "admin@minmon.local"}
{userEmail ?? "Signed-in account"}
</p>
</div>
<div className="flex flex-wrap gap-2">
{allowedPermissions.has("servers.create") ? (
<Link to="/dashboard/servers/new">
<Button size="sm">Add server</Button>
</Link>
<Button
size="sm"
render={<Link to="/dashboard/servers/new" />}
nativeButton={false}
>
Add server
</Button>
) : null}
{allowedPermissions.has("notes.create") ? (
<Link to="/dashboard/notes/new">
<Button size="sm" variant="outline">
New note
</Button>
</Link>
<Button
size="sm"
variant="outline"
render={<Link to="/dashboard/notes/new" />}
nativeButton={false}
>
New note
</Button>
) : null}
</div>
</div>

View file

@ -8,7 +8,10 @@ export default function Header() {
<div className="border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/75">
<div className="mx-auto flex max-w-7xl flex-row items-center justify-between gap-4 px-4 py-3 lg:px-6">
<div className="flex items-center gap-6">
<Link to="/dashboard" className="text-sm font-semibold tracking-[0.2em] uppercase">
<Link
to="/"
className="text-sm font-semibold tracking-[0.2em] uppercase"
>
minmon
</Link>
</div>

View file

@ -15,14 +15,20 @@ export function ModeToggle() {
return (
<DropdownMenu>
<DropdownMenuTrigger render={<Button variant="outline" size="icon" />}>
<Sun className="h-[1.2rem] w-[1.2rem] scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" />
<Moon className="absolute h-[1.2rem] w-[1.2rem] scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" />
<Sun className="size-[1.2rem] scale-100 rotate-0 transition-[transform,opacity] dark:scale-0 dark:-rotate-90" />
<Moon className="absolute size-[1.2rem] scale-0 rotate-90 transition-[transform,opacity] dark:scale-100 dark:rotate-0" />
<span className="sr-only">Toggle theme</span>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setTheme("light")}>Light</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("dark")}>Dark</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("system")}>System</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("light")}>
Light
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("dark")}>
Dark
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("system")}>
System
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);

View file

@ -56,10 +56,12 @@ export default function SignInForm() {
<div className="mx-auto flex min-h-[calc(100dvh-8rem)] w-full max-w-5xl items-center justify-center px-4 py-10">
<div className="grid w-full max-w-md gap-6 border bg-card p-6">
<div className="space-y-2 text-center">
<p className="text-[11px] uppercase tracking-[0.24em] text-muted-foreground">Admin Access</p>
<p className="text-[11px] uppercase tracking-[0.24em] text-muted-foreground">
Private access
</p>
<h1 className="text-3xl font-bold tracking-tight">Sign in</h1>
<p className="text-sm text-muted-foreground">
Use your administrator account to open the protected monitoring dashboard.
Use your Minmon account to open the protected monitoring dashboard.
</p>
</div>
@ -105,7 +107,10 @@ export default function SignInForm() {
</form.Field>
<form.Subscribe
selector={(state) => ({ canSubmit: state.canSubmit, isSubmitting: state.isSubmitting })}
selector={(state) => ({
canSubmit: state.canSubmit,
isSubmitting: state.isSubmitting,
})}
>
{({ canSubmit, isSubmitting }) => (
<Button
@ -121,7 +126,10 @@ export default function SignInForm() {
</form>
<div className="grid gap-2 border-t pt-4 text-center text-xs text-muted-foreground">
<p>Student demo flow uses administrator sign-in only.</p>
<p>
Accounts are created by an administrator or through a one-time
invitation.
</p>
</div>
</div>
</div>

View file

@ -23,9 +23,13 @@ export default function UserMenu() {
if (!session) {
return (
<Link to="/login">
<Button variant="outline">Sign In</Button>
</Link>
<Button
variant="outline"
render={<Link to="/login" />}
nativeButton={false}
>
Sign In
</Button>
);
}

View file

@ -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,
},
},
}),
],
});

View file

@ -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",
});
}

View file

@ -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)

View file

@ -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 (
<main className="mx-auto flex w-full max-w-xl items-center px-4 py-10 lg:py-16">
<Card className="w-full">
<CardHeader>
<div className="mb-2 flex size-10 items-center justify-center border bg-muted text-muted-foreground">
<KeyRound className="size-5" strokeWidth={1.5} />
</div>
<CardTitle className="text-balance text-2xl">
Choose your own password
</CardTitle>
<CardDescription className="text-pretty">
An administrator created {session.data?.user.email} with an initial
password. Replace it before entering the monitoring console.
</CardDescription>
</CardHeader>
<CardContent>
<form
id="initial-password-form"
className="flex flex-col gap-5"
noValidate
onSubmit={(event) => {
event.preventDefault();
event.stopPropagation();
form.handleSubmit();
}}
>
<FieldGroup>
<form.Field name="currentPassword">
{(field) => {
const errors = fieldErrors(field.state.meta.errors);
return (
<Field data-invalid={errors.length > 0}>
<FieldLabel htmlFor={field.name}>
Initial password
</FieldLabel>
<Input
id={field.name}
name={field.name}
type="password"
autoComplete="current-password"
autoFocus
aria-invalid={errors.length > 0}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(event) =>
field.handleChange(event.target.value)
}
/>
<FieldError errors={errors} />
</Field>
);
}}
</form.Field>
<form.Field name="newPassword">
{(field) => {
const errors = fieldErrors(field.state.meta.errors);
return (
<Field data-invalid={errors.length > 0}>
<FieldLabel htmlFor={field.name}>New password</FieldLabel>
<Input
id={field.name}
name={field.name}
type="password"
autoComplete="new-password"
aria-invalid={errors.length > 0}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(event) =>
field.handleChange(event.target.value)
}
/>
<FieldDescription>
Use at least 8 characters.
</FieldDescription>
<FieldError errors={errors} />
</Field>
);
}}
</form.Field>
<form.Field name="confirmPassword">
{(field) => {
const errors = fieldErrors(field.state.meta.errors);
return (
<Field data-invalid={errors.length > 0}>
<FieldLabel htmlFor={field.name}>
Confirm new password
</FieldLabel>
<Input
id={field.name}
name={field.name}
type="password"
autoComplete="new-password"
aria-invalid={errors.length > 0}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(event) =>
field.handleChange(event.target.value)
}
/>
<FieldError errors={errors} />
</Field>
);
}}
</form.Field>
</FieldGroup>
<Alert>
<ShieldCheck />
<AlertTitle>Other sessions will be closed</AlertTitle>
<AlertDescription>
Only this browser remains signed in after the password is
changed.
</AlertDescription>
</Alert>
</form>
</CardContent>
<CardFooter>
<form.Subscribe
selector={(state) => ({
canSubmit: state.canSubmit,
isSubmitting: state.isSubmitting,
})}
>
{({ canSubmit, isSubmitting }) => (
<Button
type="submit"
form="initial-password-form"
disabled={!canSubmit || isSubmitting}
>
{isSubmitting ? (
<Loader2 data-icon="inline-start" className="animate-spin" />
) : (
<KeyRound data-icon="inline-start" />
)}
{isSubmitting ? "Updating password…" : "Update password"}
</Button>
)}
</form.Subscribe>
</CardFooter>
</Card>
</main>
);
}

File diff suppressed because it is too large Load diff

View file

@ -1,13 +1,27 @@
import { createFileRoute, redirect } from "@tanstack/react-router";
import { authClient } from "@/lib/auth-client";
import { trpcClient } from "@/utils/trpc";
export const Route = createFileRoute("/")({
beforeLoad: async () => {
const session = await authClient.getSession();
const [session, onboarding] = await Promise.all([
authClient.getSession(),
trpcClient.onboarding.status.query(),
]);
if (onboarding.needsSetup) {
throw redirect({
to: "/setup",
});
}
throw redirect({
to: session.data ? "/dashboard" : "/login",
to: session.data?.user.mustChangePassword
? "/change-password"
: session.data
? "/dashboard"
: "/login",
});
},
component: () => null,

View file

@ -0,0 +1,410 @@
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 { Separator } from "@minmon/ui/components/separator";
import { StatusBadge } from "@minmon/ui/components/status-badge";
import { useForm } from "@tanstack/react-form";
import { useQuery } from "@tanstack/react-query";
import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import {
CircleOff,
KeyRound,
Loader2,
LogIn,
ShieldCheck,
TicketCheck,
UserRoundPlus,
} from "lucide-react";
import { toast } from "sonner";
import z from "zod";
import Loader from "@/components/loader";
import { authClient } from "@/lib/auth-client";
import { formatErrorMessage } from "@/utils/errors";
import { queryClient, trpc, trpcClient } from "@/utils/trpc";
const acceptInvitationSchema = z
.object({
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"),
confirmPassword: z.string(),
})
.refine((value) => value.password === value.confirmPassword, {
message: "Passwords do not match",
path: ["confirmPassword"],
});
export const Route = createFileRoute("/invite/$token")({
component: InvitePage,
});
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 InviteUnavailable({
status,
}: {
status: "invalid" | "revoked" | "accepted";
}) {
const session = authClient.useSession();
const content = {
invalid: {
title: "Invitation not found",
description:
"Check that the complete link was copied into the address bar.",
},
revoked: {
title: "Invitation revoked",
description:
"An administrator closed this link. Ask them to create a new invitation.",
},
accepted: {
title: "Invitation already used",
description:
"This one-time link has already created an account and cannot be used again.",
},
}[status];
return (
<main className="mx-auto flex w-full max-w-lg items-center px-4 py-12">
<Card className="w-full">
<CardHeader>
<div className="mb-2 flex size-10 items-center justify-center border bg-muted text-muted-foreground">
<CircleOff className="size-5" strokeWidth={1.5} />
</div>
<CardTitle>{content.title}</CardTitle>
<CardDescription>{content.description}</CardDescription>
</CardHeader>
<CardFooter>
<Button
variant="outline"
render={<Link to={session.data ? "/dashboard" : "/login"} />}
nativeButton={false}
>
<LogIn data-icon="inline-start" />
{session.data ? "Return to dashboard" : "Go to sign in"}
</Button>
</CardFooter>
</Card>
</main>
);
}
function InvitePage() {
const { token } = Route.useParams();
const navigate = useNavigate();
const session = authClient.useSession();
const invitation = useQuery(
trpc.users.invitations.inspect.queryOptions({ token }),
);
const form = useForm({
defaultValues: {
name: "",
email: "",
password: "",
confirmPassword: "",
},
validators: {
onSubmit: acceptInvitationSchema,
},
onSubmit: async ({ value }) => {
try {
await trpcClient.users.invitations.accept.mutate({
token,
name: value.name,
email: value.email,
password: value.password,
});
if (session.data) {
await authClient.signOut();
}
const signIn = await authClient.signIn.email({
email: value.email,
password: value.password,
});
if (signIn.error) {
toast.error("Account created. Sign in with your new password.");
await navigate({ to: "/login" });
return;
}
await queryClient.invalidateQueries();
toast.success("Account created from invitation");
await navigate({ to: "/dashboard" });
} catch (error) {
toast.error(
formatErrorMessage(error, "Could not accept the invitation"),
);
await invitation.refetch();
}
},
});
if (invitation.isLoading) {
return <Loader />;
}
if (invitation.isError || !invitation.data) {
return <InviteUnavailable status="invalid" />;
}
if (invitation.data.status !== "pending") {
return <InviteUnavailable status={invitation.data.status} />;
}
return (
<main className="mx-auto flex w-full max-w-5xl items-center px-4 py-8 lg:px-6 lg:py-14">
<section className="grid w-full overflow-hidden border bg-card shadow-sm lg:grid-cols-[0.72fr_1.28fr]">
<div className="flex flex-col gap-8 bg-muted/30 p-6 sm:p-8">
<div className="flex flex-col gap-3">
<div className="flex size-10 items-center justify-center border bg-background text-muted-foreground">
<TicketCheck className="size-5" strokeWidth={1.5} />
</div>
<p className="font-mono text-[11px] uppercase tracking-[0.22em] text-muted-foreground">
One-time invitation
</p>
<h1 className="text-balance text-3xl font-semibold tracking-tight">
Join this Minmon console.
</h1>
<p className="text-pretty text-sm leading-6 text-muted-foreground">
Choose the identity and password you will use. This link closes as
soon as your account is created.
</p>
</div>
<Separator />
<div className="flex flex-col gap-3">
<p className="text-xs font-medium">Access granted by this link</p>
<div className="flex flex-wrap gap-2">
{invitation.data.roles.map((role) => (
<StatusBadge
key={role.id}
variant={
role.name === "Admin"
? "info"
: role.name === "Editor"
? "warning"
: "neutral"
}
>
{role.name}
</StatusBadge>
))}
</div>
<p className="text-pretty text-xs leading-5 text-muted-foreground">
An administrator can change these roles later from User
management.
</p>
</div>
</div>
<div className="flex flex-col gap-6 p-6 sm:p-8 lg:p-10">
<div className="flex flex-col gap-2">
<h2 className="text-balance text-2xl font-semibold tracking-tight">
Create your account
</h2>
<p className="text-pretty text-sm text-muted-foreground">
Your email is stored as unverified until email verification is
added.
</p>
</div>
{session.data ? (
<Alert>
<UserRoundPlus />
<AlertTitle>
Currently signed in as {session.data.user.email}
</AlertTitle>
<AlertDescription>
Finish this form to switch this browser to the newly created
account.
</AlertDescription>
</Alert>
) : null}
<form
className="flex flex-col gap-6"
noValidate
onSubmit={(event) => {
event.preventDefault();
event.stopPropagation();
form.handleSubmit();
}}
>
<FieldGroup>
<form.Field name="name">
{(field) => {
const errors = fieldErrors(field.state.meta.errors);
return (
<Field data-invalid={errors.length > 0}>
<FieldLabel htmlFor={field.name}>Full name</FieldLabel>
<Input
id={field.name}
name={field.name}
autoComplete="name"
autoFocus
aria-invalid={errors.length > 0}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(event) =>
field.handleChange(event.target.value)
}
/>
<FieldError errors={errors} />
</Field>
);
}}
</form.Field>
<form.Field name="email">
{(field) => {
const errors = fieldErrors(field.state.meta.errors);
return (
<Field data-invalid={errors.length > 0}>
<FieldLabel htmlFor={field.name}>
Email address
</FieldLabel>
<Input
id={field.name}
name={field.name}
type="email"
autoComplete="email"
aria-invalid={errors.length > 0}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(event) =>
field.handleChange(event.target.value)
}
/>
<FieldError errors={errors} />
</Field>
);
}}
</form.Field>
<div className="grid gap-5 sm:grid-cols-2">
<form.Field name="password">
{(field) => {
const errors = fieldErrors(field.state.meta.errors);
return (
<Field data-invalid={errors.length > 0}>
<FieldLabel htmlFor={field.name}>Password</FieldLabel>
<Input
id={field.name}
name={field.name}
type="password"
autoComplete="new-password"
aria-invalid={errors.length > 0}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(event) =>
field.handleChange(event.target.value)
}
/>
<FieldDescription>
Use at least 8 characters.
</FieldDescription>
<FieldError errors={errors} />
</Field>
);
}}
</form.Field>
<form.Field name="confirmPassword">
{(field) => {
const errors = fieldErrors(field.state.meta.errors);
return (
<Field data-invalid={errors.length > 0}>
<FieldLabel htmlFor={field.name}>
Confirm password
</FieldLabel>
<Input
id={field.name}
name={field.name}
type="password"
autoComplete="new-password"
aria-invalid={errors.length > 0}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(event) =>
field.handleChange(event.target.value)
}
/>
<FieldError errors={errors} />
</Field>
);
}}
</form.Field>
</div>
</FieldGroup>
<form.Subscribe
selector={(state) => ({
canSubmit: state.canSubmit,
isSubmitting: state.isSubmitting,
})}
>
{({ canSubmit, isSubmitting }) => (
<Button
type="submit"
size="lg"
disabled={!canSubmit || isSubmitting}
>
{isSubmitting ? (
<Loader2
data-icon="inline-start"
className="animate-spin"
/>
) : (
<KeyRound data-icon="inline-start" />
)}
{isSubmitting ? "Creating account…" : "Create account"}
</Button>
)}
</form.Subscribe>
</form>
<p className="text-pretty text-xs leading-5 text-muted-foreground">
Creating the account consumes this invitation. It has no expiration
date, but an administrator may revoke it before use.
</p>
</div>
</section>
</main>
);
}

View file

@ -1,7 +1,27 @@
import SignInForm from "@/components/sign-in-form";
import { createFileRoute } from "@tanstack/react-router";
import { authClient } from "@/lib/auth-client";
import { trpcClient } from "@/utils/trpc";
import { createFileRoute, redirect } from "@tanstack/react-router";
export const Route = createFileRoute("/login")({
beforeLoad: async () => {
const [session, onboarding] = await Promise.all([
authClient.getSession(),
trpcClient.onboarding.status.query(),
]);
if (onboarding.needsSetup) {
throw redirect({ to: "/setup" });
}
if (session.data) {
throw redirect({
to: session.data.user.mustChangePassword
? "/change-password"
: "/dashboard",
});
}
},
component: RouteComponent,
});

View file

@ -0,0 +1,346 @@
import {
Alert,
AlertDescription,
AlertTitle,
} from "@minmon/ui/components/alert";
import { Button } from "@minmon/ui/components/button";
import {
Field,
FieldDescription,
FieldError,
FieldGroup,
FieldLabel,
} from "@minmon/ui/components/field";
import { Input } from "@minmon/ui/components/input";
import { Separator } from "@minmon/ui/components/separator";
import { useForm } from "@tanstack/react-form";
import { createFileRoute, redirect, useNavigate } from "@tanstack/react-router";
import {
Check,
Loader2,
LockKeyhole,
ShieldCheck,
UserRound,
} from "lucide-react";
import { toast } from "sonner";
import z from "zod";
import { authClient } from "@/lib/auth-client";
import { formatErrorMessage } from "@/utils/errors";
import { queryClient, trpcClient } from "@/utils/trpc";
const setupSchema = z
.object({
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"),
confirmPassword: z.string(),
})
.refine((value) => value.password === value.confirmPassword, {
message: "Passwords do not match",
path: ["confirmPassword"],
});
export const Route = createFileRoute("/setup")({
beforeLoad: async () => {
const onboarding = await trpcClient.onboarding.status.query();
if (!onboarding.needsSetup) {
throw redirect({ to: "/" });
}
},
component: SetupPage,
});
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));
}
const readinessSteps = [
{
icon: UserRound,
title: "Create the owner",
description: "The first account receives administrator access.",
},
{
icon: LockKeyhole,
title: "Close registration",
description: "Public sign-up stays disabled after this account is created.",
},
{
icon: ShieldCheck,
title: "Open the console",
description: "You will be signed in and taken straight to the dashboard.",
},
] as const;
function SetupPage() {
const navigate = useNavigate();
const form = useForm({
defaultValues: {
name: "",
email: "",
password: "",
confirmPassword: "",
},
validators: {
onSubmit: setupSchema,
},
onSubmit: async ({ value }) => {
try {
await trpcClient.onboarding.createAdmin.mutate({
name: value.name,
email: value.email,
password: value.password,
});
const signIn = await authClient.signIn.email({
email: value.email,
password: value.password,
});
if (signIn.error) {
throw signIn.error;
}
await queryClient.invalidateQueries();
toast.success("Minmon is ready");
await navigate({ to: "/dashboard" });
} catch (error) {
toast.error(formatErrorMessage(error, "Could not complete setup"));
}
},
});
return (
<main className="mx-auto flex w-full max-w-6xl items-center px-4 py-8 lg:px-6 lg:py-14">
<section className="grid w-full overflow-hidden border bg-card shadow-sm lg:grid-cols-[0.88fr_1.12fr]">
<div className="flex flex-col justify-between gap-10 bg-muted/30 p-6 sm:p-8 lg:p-10">
<div className="flex flex-col gap-4">
<p className="font-mono text-[11px] uppercase tracking-[0.22em] text-muted-foreground">
First-run initialization
</p>
<div className="flex flex-col gap-3">
<h1 className="max-w-md text-balance text-3xl font-semibold tracking-tight sm:text-4xl">
Put one trusted operator in control.
</h1>
<p className="max-w-md text-pretty text-sm leading-6 text-muted-foreground">
Minmon found an empty user directory. Create the owner account
that will manage this private monitoring console.
</p>
</div>
</div>
<div className="flex flex-col gap-0" aria-label="Setup sequence">
{readinessSteps.map(({ icon: Icon, title, description }, index) => (
<div key={title} className="grid grid-cols-[36px_1fr] gap-3">
<div className="flex flex-col items-center">
<span className="flex size-9 items-center justify-center border bg-background text-muted-foreground">
<Icon className="size-4" strokeWidth={1.5} />
</span>
{index < readinessSteps.length - 1 ? (
<span
className="h-full w-px bg-border"
aria-hidden="true"
/>
) : null}
</div>
<div className="flex flex-col gap-1 pb-6 pt-1.5">
<div className="flex items-center gap-2">
<span className="font-mono text-[10px] tabular-nums text-muted-foreground">
0{index + 1}
</span>
<p className="text-sm font-medium">{title}</p>
</div>
<p className="text-pretty text-xs leading-5 text-muted-foreground">
{description}
</p>
</div>
</div>
))}
</div>
</div>
<div className="flex flex-col gap-6 p-6 sm:p-8 lg:p-10">
<div className="flex flex-col gap-2">
<div className="flex items-center gap-2 text-sm font-medium">
<Check className="size-4 text-primary" strokeWidth={2} />
Database connection ready
</div>
<h2 className="text-balance text-2xl font-semibold tracking-tight">
Create administrator
</h2>
<p className="text-pretty text-sm text-muted-foreground">
This is the only account that can be created without an
invitation.
</p>
</div>
<Separator />
<form
className="flex flex-col gap-6"
noValidate
onSubmit={(event) => {
event.preventDefault();
event.stopPropagation();
form.handleSubmit();
}}
>
<FieldGroup>
<form.Field name="name">
{(field) => {
const errors = fieldErrors(field.state.meta.errors);
return (
<Field data-invalid={errors.length > 0}>
<FieldLabel htmlFor={field.name}>Full name</FieldLabel>
<Input
id={field.name}
name={field.name}
autoComplete="name"
autoFocus
aria-invalid={errors.length > 0}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(event) =>
field.handleChange(event.target.value)
}
/>
<FieldError errors={errors} />
</Field>
);
}}
</form.Field>
<form.Field name="email">
{(field) => {
const errors = fieldErrors(field.state.meta.errors);
return (
<Field data-invalid={errors.length > 0}>
<FieldLabel htmlFor={field.name}>
Email address
</FieldLabel>
<Input
id={field.name}
name={field.name}
type="email"
autoComplete="email"
aria-invalid={errors.length > 0}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(event) =>
field.handleChange(event.target.value)
}
/>
<FieldError errors={errors} />
</Field>
);
}}
</form.Field>
<div className="grid gap-5 sm:grid-cols-2">
<form.Field name="password">
{(field) => {
const errors = fieldErrors(field.state.meta.errors);
return (
<Field data-invalid={errors.length > 0}>
<FieldLabel htmlFor={field.name}>Password</FieldLabel>
<Input
id={field.name}
name={field.name}
type="password"
autoComplete="new-password"
aria-invalid={errors.length > 0}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(event) =>
field.handleChange(event.target.value)
}
/>
<FieldDescription>
Use at least 8 characters.
</FieldDescription>
<FieldError errors={errors} />
</Field>
);
}}
</form.Field>
<form.Field name="confirmPassword">
{(field) => {
const errors = fieldErrors(field.state.meta.errors);
return (
<Field data-invalid={errors.length > 0}>
<FieldLabel htmlFor={field.name}>
Confirm password
</FieldLabel>
<Input
id={field.name}
name={field.name}
type="password"
autoComplete="new-password"
aria-invalid={errors.length > 0}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(event) =>
field.handleChange(event.target.value)
}
/>
<FieldError errors={errors} />
</Field>
);
}}
</form.Field>
</div>
</FieldGroup>
<Alert>
<ShieldCheck />
<AlertTitle>Registration closes automatically</AlertTitle>
<AlertDescription>
Additional people can only join through an administrator-created
account or invitation link.
</AlertDescription>
</Alert>
<form.Subscribe
selector={(state) => ({
canSubmit: state.canSubmit,
isSubmitting: state.isSubmitting,
})}
>
{({ canSubmit, isSubmitting }) => (
<Button
type="submit"
size="lg"
disabled={!canSubmit || isSubmitting}
>
{isSubmitting ? (
<Loader2
data-icon="inline-start"
className="animate-spin"
/>
) : (
<ShieldCheck data-icon="inline-start" />
)}
{isSubmitting
? "Creating administrator…"
: "Create administrator"}
</Button>
)}
</form.Subscribe>
</form>
</div>
</section>
</main>
);
}