feat: add onboarding and user invitations
This commit is contained in:
parent
24351eb897
commit
762cfe2b16
37 changed files with 5208 additions and 384 deletions
44
README.md
44
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
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
236
apps/web/src/routes/change-password.tsx
Normal file
236
apps/web/src/routes/change-password.tsx
Normal 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
|
|
@ -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,
|
||||
|
|
|
|||
410
apps/web/src/routes/invite.$token.tsx
Normal file
410
apps/web/src/routes/invite.$token.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
|
|
@ -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,
|
||||
});
|
||||
|
||||
|
|
|
|||
346
apps/web/src/routes/setup.tsx
Normal file
346
apps/web/src/routes/setup.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
|
|
@ -6,8 +6,14 @@ Minmon is a student-friendly web dashboard for managing private servers, service
|
|||
|
||||
## Current Main Features
|
||||
|
||||
- Admin sign-in with better-auth
|
||||
- First-run administrator registration when no users exist
|
||||
- Better Auth sign-in with ordinary public registration disabled
|
||||
- User creation by initial password or one-time invitation link
|
||||
- Invitation copy, revoke, replace, accepted, and revoked lifecycle states
|
||||
- Forced password replacement for administrator-created initial passwords
|
||||
- Root route (`/`) redirects automatically:
|
||||
- no users -> `/setup`
|
||||
- initial-password replacement required -> `/change-password`
|
||||
- logged in -> `/dashboard`
|
||||
- not logged in -> `/login`
|
||||
- Dashboard summary for:
|
||||
|
|
@ -29,12 +35,15 @@ Minmon is a student-friendly web dashboard for managing private servers, service
|
|||
- service -> server
|
||||
- domain -> service
|
||||
- note -> server
|
||||
- Sample seeded admin and demo dataset
|
||||
- Optional sample admin and demo dataset
|
||||
|
||||
## Current Route Structure
|
||||
|
||||
- `/` -> auth-based redirect
|
||||
- `/setup` -> first administrator registration, available only while there are no users
|
||||
- `/login` -> sign-in page
|
||||
- `/change-password` -> required initial-password replacement
|
||||
- `/invite/$token` -> one-time invitation acceptance
|
||||
- `/dashboard` -> summary page
|
||||
- `/dashboard/servers` -> server list
|
||||
- `/dashboard/servers/new` -> create server
|
||||
|
|
@ -48,6 +57,7 @@ Minmon is a student-friendly web dashboard for managing private servers, service
|
|||
- `/dashboard/notes` -> note list
|
||||
- `/dashboard/notes/new` -> create note
|
||||
- `/dashboard/notes/$noteId` -> note detail + edit
|
||||
- `/dashboard/users` -> users, roles, and invitation lifecycle management
|
||||
|
||||
## Local Setup
|
||||
|
||||
|
|
@ -92,7 +102,25 @@ bun run db:start
|
|||
bun run db:push
|
||||
```
|
||||
|
||||
7. Seed sample data
|
||||
7. Run the apps
|
||||
|
||||
```bash
|
||||
bun run dev
|
||||
```
|
||||
|
||||
8. Open the app
|
||||
|
||||
- Web: `http://localhost:5173`
|
||||
- API: `http://localhost:3000`
|
||||
|
||||
With an empty user table, the root and login routes redirect to `/setup`. Create the
|
||||
first administrator there. The backend serializes first-account creation and rejects
|
||||
any later public registration attempt.
|
||||
|
||||
### Optional demo seed
|
||||
|
||||
The explicit demo seed is still available when the sample inventory and fixed demo
|
||||
administrator are needed:
|
||||
|
||||
```bash
|
||||
bun run --filter @minmon/db db:seed
|
||||
|
|
@ -103,17 +131,6 @@ Seeded admin login:
|
|||
- Email: `admin@minmon.local`
|
||||
- Password: `admin12345`
|
||||
|
||||
8. Run the apps
|
||||
|
||||
```bash
|
||||
bun run dev
|
||||
```
|
||||
|
||||
9. Open the app
|
||||
|
||||
- Web: `http://localhost:5173`
|
||||
- API: `http://localhost:3000`
|
||||
|
||||
## Docker Compose Deployment
|
||||
|
||||
Run the deployable stack with one command:
|
||||
|
|
@ -128,11 +145,12 @@ Default Docker endpoints:
|
|||
- Web: `http://localhost:3001`
|
||||
- API: `http://localhost:3000`
|
||||
|
||||
The Compose stack starts PostgreSQL, applies the schema, and seeds the sample admin only if the users table is empty.
|
||||
The Compose stack starts PostgreSQL, applies the schema, and ensures the default
|
||||
roles and permissions exist. It does not seed a default user; finish initialization
|
||||
from the first-run setup screen.
|
||||
|
||||
Docker Compose reads the root `.env` file automatically. Edit it before startup if you need different ports, public URLs, credentials, or secrets.
|
||||
|
||||
|
||||
## Current Behavior Notes
|
||||
|
||||
### List Ordering
|
||||
|
|
|
|||
|
|
@ -21,7 +21,11 @@ async function getAuthorization(userId: string) {
|
|||
.where(eq(userRole.userId, userId));
|
||||
|
||||
return {
|
||||
roles: Array.from(new Map(rows.map((row) => [row.roleId, { id: row.roleId, name: row.roleName }])).values()),
|
||||
roles: Array.from(
|
||||
new Map(
|
||||
rows.map((row) => [row.roleId, { id: row.roleId, name: row.roleName }]),
|
||||
).values(),
|
||||
),
|
||||
permissions: Array.from(new Set(rows.map((row) => row.permissionName))),
|
||||
};
|
||||
}
|
||||
|
|
@ -31,12 +35,15 @@ export async function createContext({ context }: CreateContextOptions) {
|
|||
headers: context.request.headers,
|
||||
});
|
||||
|
||||
const authorization = session ? await getAuthorization(session.user.id) : { roles: [], permissions: [] };
|
||||
const authorization = session
|
||||
? await getAuthorization(session.user.id)
|
||||
: { roles: [], permissions: [] };
|
||||
|
||||
return {
|
||||
auth: null,
|
||||
auth,
|
||||
session,
|
||||
authorization,
|
||||
requestHeaders: context.request.headers,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -35,6 +35,13 @@ export function requirePermission(permission: Permission) {
|
|||
});
|
||||
}
|
||||
|
||||
if (ctx.session.user.mustChangePassword) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "Change the initial password before using Minmon",
|
||||
});
|
||||
}
|
||||
|
||||
if (!ctx.authorization.permissions.includes(permission)) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
|
|
|
|||
67
packages/api/src/lib/invitation-token.ts
Normal file
67
packages/api/src/lib/invitation-token.ts
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
import { env } from "@minmon/env/server";
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const inviteKeyMaterial = textEncoder.encode(
|
||||
`${env.BETTER_AUTH_SECRET}:minmon-user-invitations:v1`,
|
||||
);
|
||||
|
||||
const inviteKeyPromise = crypto.subtle
|
||||
.digest("SHA-256", inviteKeyMaterial)
|
||||
.then((digest) =>
|
||||
crypto.subtle.importKey("raw", digest, { name: "AES-GCM" }, false, [
|
||||
"encrypt",
|
||||
"decrypt",
|
||||
]),
|
||||
);
|
||||
|
||||
function encodeBytes(value: ArrayBuffer | Uint8Array) {
|
||||
return Buffer.from(
|
||||
value instanceof Uint8Array ? value : new Uint8Array(value),
|
||||
).toString("base64url");
|
||||
}
|
||||
|
||||
function decodeBytes(value: string) {
|
||||
return new Uint8Array(Buffer.from(value, "base64url"));
|
||||
}
|
||||
|
||||
export async function hashInvitationToken(token: string) {
|
||||
const digest = await crypto.subtle.digest(
|
||||
"SHA-256",
|
||||
textEncoder.encode(token),
|
||||
);
|
||||
return Buffer.from(digest).toString("hex");
|
||||
}
|
||||
|
||||
export async function createInvitationToken() {
|
||||
const tokenBytes = crypto.getRandomValues(new Uint8Array(32));
|
||||
const token = encodeBytes(tokenBytes);
|
||||
const tokenHash = await hashInvitationToken(token);
|
||||
const tokenIvBytes = crypto.getRandomValues(new Uint8Array(12));
|
||||
const key = await inviteKeyPromise;
|
||||
const encrypted = await crypto.subtle.encrypt(
|
||||
{ name: "AES-GCM", iv: tokenIvBytes },
|
||||
key,
|
||||
textEncoder.encode(token),
|
||||
);
|
||||
|
||||
return {
|
||||
token,
|
||||
tokenHash,
|
||||
tokenEncrypted: encodeBytes(encrypted),
|
||||
tokenIv: encodeBytes(tokenIvBytes),
|
||||
};
|
||||
}
|
||||
|
||||
export async function decryptInvitationToken(
|
||||
tokenEncrypted: string,
|
||||
tokenIv: string,
|
||||
) {
|
||||
const key = await inviteKeyPromise;
|
||||
const decrypted = await crypto.subtle.decrypt(
|
||||
{ name: "AES-GCM", iv: decodeBytes(tokenIv) },
|
||||
key,
|
||||
decodeBytes(tokenEncrypted),
|
||||
);
|
||||
|
||||
return new TextDecoder().decode(decrypted);
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ import { publicProcedure, router } from "../index";
|
|||
import { dashboardRouter } from "./dashboard";
|
||||
import { domainsRouter } from "./domains";
|
||||
import { notesRouter } from "./notes";
|
||||
import { onboardingRouter } from "./onboarding";
|
||||
import { serversRouter } from "./servers";
|
||||
import { servicesRouter } from "./services";
|
||||
import { usersRouter } from "./users";
|
||||
|
|
@ -11,6 +12,7 @@ export const appRouter = router({
|
|||
healthCheck: publicProcedure.query(() => {
|
||||
return "OK";
|
||||
}),
|
||||
onboarding: onboardingRouter,
|
||||
dashboard: dashboardRouter,
|
||||
servers: serversRouter,
|
||||
services: servicesRouter,
|
||||
|
|
|
|||
119
packages/api/src/routers/onboarding.ts
Normal file
119
packages/api/src/routers/onboarding.ts
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import {
|
||||
account,
|
||||
db,
|
||||
permission,
|
||||
role,
|
||||
rolePermission,
|
||||
user,
|
||||
userRole,
|
||||
} from "@minmon/db";
|
||||
import { hashCredentialPassword } from "@minmon/db/auth-utils";
|
||||
import { permissions, roleDefinitions } from "@minmon/db/rbac";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { sql } from "drizzle-orm";
|
||||
|
||||
import { publicProcedure, router } from "../index";
|
||||
import { onboardingCreateAdminSchema } from "./schemas";
|
||||
import { createEntityId } from "./utils";
|
||||
|
||||
const ADMIN_ROLE_ID = "role_admin";
|
||||
|
||||
export const onboardingRouter = router({
|
||||
status: publicProcedure.query(async () => {
|
||||
const [existingUser] = await db.select({ id: user.id }).from(user).limit(1);
|
||||
return { needsSetup: !existingUser };
|
||||
}),
|
||||
|
||||
createAdmin: publicProcedure
|
||||
.input(onboardingCreateAdminSchema)
|
||||
.mutation(async ({ input }) => {
|
||||
const passwordHash = await hashCredentialPassword(input.password);
|
||||
const userId = createEntityId();
|
||||
const accountId = createEntityId();
|
||||
const email = input.email.trim().toLowerCase();
|
||||
|
||||
return db.transaction(async (tx) => {
|
||||
await tx.execute(sql`select pg_advisory_xact_lock(612984117)`);
|
||||
|
||||
const [existingUser] = await tx
|
||||
.select({ id: user.id })
|
||||
.from(user)
|
||||
.limit(1);
|
||||
if (existingUser) {
|
||||
throw new TRPCError({
|
||||
code: "CONFLICT",
|
||||
message: "Minmon setup has already been completed",
|
||||
});
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
|
||||
await tx
|
||||
.insert(permission)
|
||||
.values(
|
||||
permissions.map((name) => ({
|
||||
id: name,
|
||||
name,
|
||||
description: `Allows ${name.replace(".", " ")}`,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})),
|
||||
)
|
||||
.onConflictDoNothing();
|
||||
|
||||
await tx
|
||||
.insert(role)
|
||||
.values(
|
||||
roleDefinitions.map((definition) => ({
|
||||
id: definition.id,
|
||||
name: definition.name,
|
||||
description: definition.description,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})),
|
||||
)
|
||||
.onConflictDoNothing();
|
||||
|
||||
await tx
|
||||
.insert(rolePermission)
|
||||
.values(
|
||||
roleDefinitions.flatMap((definition) =>
|
||||
definition.permissions.map((permissionName) => ({
|
||||
roleId: definition.id,
|
||||
permissionId: permissionName,
|
||||
createdAt: now,
|
||||
})),
|
||||
),
|
||||
)
|
||||
.onConflictDoNothing();
|
||||
|
||||
await tx.insert(user).values({
|
||||
id: userId,
|
||||
name: input.name,
|
||||
email,
|
||||
emailVerified: false,
|
||||
mustChangePassword: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await tx.insert(account).values({
|
||||
id: accountId,
|
||||
accountId: userId,
|
||||
providerId: "credential",
|
||||
userId,
|
||||
password: passwordHash,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await tx.insert(userRole).values({
|
||||
userId,
|
||||
roleId: ADMIN_ROLE_ID,
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
return { userId, email };
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
|
@ -10,7 +10,12 @@ export const ipv4Schema = z
|
|||
"Must be a valid IPv4 address",
|
||||
);
|
||||
|
||||
export const optionalTextSchema = z.string().trim().max(5000).nullable().optional();
|
||||
export const optionalTextSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.max(5000)
|
||||
.nullable()
|
||||
.optional();
|
||||
|
||||
export const hostnameSchema = z
|
||||
.string()
|
||||
|
|
@ -23,10 +28,27 @@ export const hostnameSchema = z
|
|||
);
|
||||
|
||||
export const serverStatusSchema = z.enum(["active", "maintenance", "inactive"]);
|
||||
export const serviceTypeSchema = z.enum(["web_app", "mail", "database", "api", "proxy", "other"]);
|
||||
export const serviceProtocolSchema = z.enum(["http", "https", "tcp", "udp", "other"]);
|
||||
export const serviceTypeSchema = z.enum([
|
||||
"web_app",
|
||||
"mail",
|
||||
"database",
|
||||
"api",
|
||||
"proxy",
|
||||
"other",
|
||||
]);
|
||||
export const serviceProtocolSchema = z.enum([
|
||||
"http",
|
||||
"https",
|
||||
"tcp",
|
||||
"udp",
|
||||
"other",
|
||||
]);
|
||||
export const serviceStatusSchema = z.enum(["active", "down", "maintenance"]);
|
||||
export const domainCheckStatusSchema = z.enum(["MATCH", "MISMATCH", "UNRESOLVED"]);
|
||||
export const domainCheckStatusSchema = z.enum([
|
||||
"MATCH",
|
||||
"MISMATCH",
|
||||
"UNRESOLVED",
|
||||
]);
|
||||
|
||||
export const byIdSchema = z.object({
|
||||
id: entityIdSchema,
|
||||
|
|
@ -114,6 +136,47 @@ export const updateUserRolesSchema = z.object({
|
|||
export const userCreateSchema = z.object({
|
||||
name: z.string().trim().min(2, "Name must be at least 2 characters").max(120),
|
||||
email: z.email("Invalid email address").max(255),
|
||||
password: z.string().min(8, "Password must be at least 8 characters").max(255),
|
||||
password: z
|
||||
.string()
|
||||
.min(8, "Password must be at least 8 characters")
|
||||
.max(255),
|
||||
roleIds: z.array(entityIdSchema).min(1, "Select at least one role"),
|
||||
});
|
||||
|
||||
export const onboardingCreateAdminSchema = z.object({
|
||||
name: z.string().trim().min(2, "Name must be at least 2 characters").max(120),
|
||||
email: z.email("Invalid email address").max(255),
|
||||
password: z
|
||||
.string()
|
||||
.min(8, "Password must be at least 8 characters")
|
||||
.max(255),
|
||||
});
|
||||
|
||||
export const userInvitationCreateSchema = z.object({
|
||||
roleIds: z.array(entityIdSchema).min(1, "Select at least one role"),
|
||||
});
|
||||
|
||||
export const invitationTokenSchema = z.object({
|
||||
token: z
|
||||
.string()
|
||||
.min(32, "Invalid invitation link")
|
||||
.max(128, "Invalid invitation link")
|
||||
.regex(/^[A-Za-z0-9_-]+$/, "Invalid invitation link"),
|
||||
});
|
||||
|
||||
export const userInvitationAcceptSchema = invitationTokenSchema.extend({
|
||||
name: z.string().trim().min(2, "Name must be at least 2 characters").max(120),
|
||||
email: z.email("Invalid email address").max(255),
|
||||
password: z
|
||||
.string()
|
||||
.min(8, "Password must be at least 8 characters")
|
||||
.max(255),
|
||||
});
|
||||
|
||||
export const changeInitialPasswordSchema = z.object({
|
||||
currentPassword: z.string().min(1, "Enter your current password").max(255),
|
||||
newPassword: z
|
||||
.string()
|
||||
.min(8, "Password must be at least 8 characters")
|
||||
.max(255),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,11 +1,42 @@
|
|||
import { db, account, role, user, userRole } from "@minmon/db";
|
||||
import { auth } from "@minmon/auth";
|
||||
import {
|
||||
account,
|
||||
db,
|
||||
role,
|
||||
session,
|
||||
user,
|
||||
userInvitation,
|
||||
userInvitationRole,
|
||||
userRole,
|
||||
} from "@minmon/db";
|
||||
import { hashCredentialPassword } from "@minmon/db/auth-utils";
|
||||
import { asc, eq } from "drizzle-orm";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { and, asc, count, desc, eq, isNull, ne, sql } from "drizzle-orm";
|
||||
|
||||
import { permissionedProcedure, protectedProcedure, router } from "../index";
|
||||
import { byIdSchema, updateUserRolesSchema, userCreateSchema } from "./schemas";
|
||||
import {
|
||||
createInvitationToken,
|
||||
decryptInvitationToken,
|
||||
hashInvitationToken,
|
||||
} from "../lib/invitation-token";
|
||||
import {
|
||||
permissionedProcedure,
|
||||
protectedProcedure,
|
||||
publicProcedure,
|
||||
router,
|
||||
} from "../index";
|
||||
import {
|
||||
byIdSchema,
|
||||
changeInitialPasswordSchema,
|
||||
invitationTokenSchema,
|
||||
updateUserRolesSchema,
|
||||
userCreateSchema,
|
||||
userInvitationAcceptSchema,
|
||||
userInvitationCreateSchema,
|
||||
} from "./schemas";
|
||||
import { badRequest, createEntityId, notFound } from "./utils";
|
||||
|
||||
const ADMIN_ROLE_ID = "role_admin";
|
||||
|
||||
async function getUsersWithRoles() {
|
||||
const [users, assignments] = await Promise.all([
|
||||
db
|
||||
|
|
@ -14,6 +45,7 @@ async function getUsersWithRoles() {
|
|||
name: user.name,
|
||||
email: user.email,
|
||||
emailVerified: user.emailVerified,
|
||||
mustChangePassword: user.mustChangePassword,
|
||||
image: user.image,
|
||||
createdAt: user.createdAt,
|
||||
updatedAt: user.updatedAt,
|
||||
|
|
@ -35,16 +67,84 @@ async function getUsersWithRoles() {
|
|||
...item,
|
||||
roles: assignments
|
||||
.filter((assignment) => assignment.userId === item.id)
|
||||
.map((assignment) => ({ id: assignment.roleId, name: assignment.roleName })),
|
||||
.map((assignment) => ({
|
||||
id: assignment.roleId,
|
||||
name: assignment.roleName,
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
async function getInvitationsWithRoles() {
|
||||
const [invitations, assignments] = await Promise.all([
|
||||
db
|
||||
.select({
|
||||
id: userInvitation.id,
|
||||
tokenEncrypted: userInvitation.tokenEncrypted,
|
||||
tokenIv: userInvitation.tokenIv,
|
||||
createdByUserId: userInvitation.createdByUserId,
|
||||
acceptedUserId: userInvitation.acceptedUserId,
|
||||
revokedAt: userInvitation.revokedAt,
|
||||
acceptedAt: userInvitation.acceptedAt,
|
||||
createdAt: userInvitation.createdAt,
|
||||
updatedAt: userInvitation.updatedAt,
|
||||
})
|
||||
.from(userInvitation)
|
||||
.orderBy(desc(userInvitation.createdAt), desc(userInvitation.id)),
|
||||
db
|
||||
.select({
|
||||
invitationId: userInvitationRole.invitationId,
|
||||
roleId: role.id,
|
||||
roleName: role.name,
|
||||
})
|
||||
.from(userInvitationRole)
|
||||
.innerJoin(role, eq(role.id, userInvitationRole.roleId))
|
||||
.orderBy(asc(role.name)),
|
||||
]);
|
||||
|
||||
return Promise.all(
|
||||
invitations.map(async (invitation) => {
|
||||
const status = invitation.acceptedAt
|
||||
? ("accepted" as const)
|
||||
: invitation.revokedAt
|
||||
? ("revoked" as const)
|
||||
: ("pending" as const);
|
||||
const token =
|
||||
status === "pending"
|
||||
? await decryptInvitationToken(
|
||||
invitation.tokenEncrypted,
|
||||
invitation.tokenIv,
|
||||
).catch(() => null)
|
||||
: null;
|
||||
|
||||
return {
|
||||
id: invitation.id,
|
||||
createdByUserId: invitation.createdByUserId,
|
||||
acceptedUserId: invitation.acceptedUserId,
|
||||
revokedAt: invitation.revokedAt,
|
||||
acceptedAt: invitation.acceptedAt,
|
||||
createdAt: invitation.createdAt,
|
||||
updatedAt: invitation.updatedAt,
|
||||
status,
|
||||
token,
|
||||
roles: assignments
|
||||
.filter((assignment) => assignment.invitationId === invitation.id)
|
||||
.map((assignment) => ({
|
||||
id: assignment.roleId,
|
||||
name: assignment.roleName,
|
||||
})),
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function validateRoleIds(roleIds: string[]) {
|
||||
const roles = await db.select({ id: role.id }).from(role);
|
||||
const validRoleIds = new Set(roles.map((item) => item.id));
|
||||
const uniqueRoleIds = Array.from(new Set(roleIds));
|
||||
|
||||
const invalidRoleId = uniqueRoleIds.find((roleId) => !validRoleIds.has(roleId));
|
||||
const invalidRoleId = uniqueRoleIds.find(
|
||||
(roleId) => !validRoleIds.has(roleId),
|
||||
);
|
||||
if (invalidRoleId) {
|
||||
notFound(`Role not found: ${invalidRoleId}`);
|
||||
}
|
||||
|
|
@ -53,13 +153,26 @@ async function validateRoleIds(roleIds: string[]) {
|
|||
}
|
||||
|
||||
export const usersRouter = router({
|
||||
me: protectedProcedure.query(({ ctx }) => ({
|
||||
user: ctx.session.user,
|
||||
roles: ctx.authorization.roles,
|
||||
permissions: ctx.authorization.permissions,
|
||||
})),
|
||||
me: protectedProcedure.query(async ({ ctx }) => {
|
||||
const [currentUser] = await db
|
||||
.select({ mustChangePassword: user.mustChangePassword })
|
||||
.from(user)
|
||||
.where(eq(user.id, ctx.session.user.id))
|
||||
.limit(1);
|
||||
|
||||
list: permissionedProcedure("users.read").query(async () => getUsersWithRoles()),
|
||||
return {
|
||||
user: {
|
||||
...ctx.session.user,
|
||||
mustChangePassword: currentUser?.mustChangePassword ?? false,
|
||||
},
|
||||
roles: ctx.authorization.roles,
|
||||
permissions: ctx.authorization.permissions,
|
||||
};
|
||||
}),
|
||||
|
||||
list: permissionedProcedure("users.read").query(async () =>
|
||||
getUsersWithRoles(),
|
||||
),
|
||||
|
||||
roles: permissionedProcedure("users.read").query(async () =>
|
||||
db
|
||||
|
|
@ -75,7 +188,12 @@ export const usersRouter = router({
|
|||
create: permissionedProcedure("users.create")
|
||||
.input(userCreateSchema)
|
||||
.mutation(async ({ input }) => {
|
||||
const [existingUser] = await db.select({ id: user.id }).from(user).where(eq(user.email, input.email)).limit(1);
|
||||
const email = input.email.trim().toLowerCase();
|
||||
const [existingUser] = await db
|
||||
.select({ id: user.id })
|
||||
.from(user)
|
||||
.where(eq(sql<string>`lower(${user.email})`, email))
|
||||
.limit(1);
|
||||
|
||||
if (existingUser) {
|
||||
badRequest("A user with this email already exists");
|
||||
|
|
@ -83,74 +201,429 @@ export const usersRouter = router({
|
|||
|
||||
const uniqueRoleIds = await validateRoleIds(input.roleIds);
|
||||
const userId = createEntityId();
|
||||
const now = new Date();
|
||||
const passwordHash = await hashCredentialPassword(input.password);
|
||||
|
||||
await db.insert(user).values({
|
||||
id: userId,
|
||||
name: input.name,
|
||||
email: input.email,
|
||||
emailVerified: true,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
await db.transaction(async (tx) => {
|
||||
const now = new Date();
|
||||
|
||||
await db.insert(account).values({
|
||||
id: createEntityId(),
|
||||
accountId: userId,
|
||||
providerId: "credential",
|
||||
userId,
|
||||
password: passwordHash,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
await tx.insert(user).values({
|
||||
id: userId,
|
||||
name: input.name,
|
||||
email,
|
||||
emailVerified: false,
|
||||
mustChangePassword: true,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await db.insert(userRole).values(
|
||||
uniqueRoleIds.map((roleId) => ({
|
||||
await tx.insert(account).values({
|
||||
id: createEntityId(),
|
||||
accountId: userId,
|
||||
providerId: "credential",
|
||||
userId,
|
||||
roleId,
|
||||
})),
|
||||
);
|
||||
password: passwordHash,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await tx.insert(userRole).values(
|
||||
uniqueRoleIds.map((roleId) => ({
|
||||
userId,
|
||||
roleId,
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
const users = await getUsersWithRoles();
|
||||
return users.find((item) => item.id === userId);
|
||||
}),
|
||||
|
||||
invitations: router({
|
||||
list: permissionedProcedure("users.create").query(async () =>
|
||||
getInvitationsWithRoles(),
|
||||
),
|
||||
|
||||
create: permissionedProcedure("users.create")
|
||||
.input(userInvitationCreateSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const uniqueRoleIds = await validateRoleIds(input.roleIds);
|
||||
const invitationId = createEntityId();
|
||||
const invitationToken = await createInvitationToken();
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
const now = new Date();
|
||||
|
||||
await tx.insert(userInvitation).values({
|
||||
id: invitationId,
|
||||
tokenHash: invitationToken.tokenHash,
|
||||
tokenEncrypted: invitationToken.tokenEncrypted,
|
||||
tokenIv: invitationToken.tokenIv,
|
||||
createdByUserId: ctx.session.user.id,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await tx.insert(userInvitationRole).values(
|
||||
uniqueRoleIds.map((roleId) => ({
|
||||
invitationId,
|
||||
roleId,
|
||||
createdAt: now,
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
const invitations = await getInvitationsWithRoles();
|
||||
return invitations.find((invitation) => invitation.id === invitationId);
|
||||
}),
|
||||
|
||||
revoke: permissionedProcedure("users.create")
|
||||
.input(byIdSchema)
|
||||
.mutation(async ({ input }) => {
|
||||
const now = new Date();
|
||||
const [revoked] = await db
|
||||
.update(userInvitation)
|
||||
.set({ revokedAt: now, updatedAt: now })
|
||||
.where(
|
||||
and(
|
||||
eq(userInvitation.id, input.id),
|
||||
isNull(userInvitation.revokedAt),
|
||||
isNull(userInvitation.acceptedAt),
|
||||
),
|
||||
)
|
||||
.returning({ id: userInvitation.id });
|
||||
|
||||
if (!revoked) {
|
||||
badRequest("Only a pending invitation can be revoked");
|
||||
}
|
||||
|
||||
return { id: input.id };
|
||||
}),
|
||||
|
||||
reissue: permissionedProcedure("users.create")
|
||||
.input(byIdSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const invitationToken = await createInvitationToken();
|
||||
const replacementId = createEntityId();
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
const now = new Date();
|
||||
const [replaced] = await tx
|
||||
.update(userInvitation)
|
||||
.set({ revokedAt: now, updatedAt: now })
|
||||
.where(
|
||||
and(
|
||||
eq(userInvitation.id, input.id),
|
||||
isNull(userInvitation.revokedAt),
|
||||
isNull(userInvitation.acceptedAt),
|
||||
),
|
||||
)
|
||||
.returning({ id: userInvitation.id });
|
||||
|
||||
if (!replaced) {
|
||||
badRequest("Only a pending invitation can be replaced");
|
||||
}
|
||||
|
||||
const assignedRoles = await tx
|
||||
.select({ roleId: userInvitationRole.roleId })
|
||||
.from(userInvitationRole)
|
||||
.where(eq(userInvitationRole.invitationId, input.id));
|
||||
|
||||
if (!assignedRoles.length) {
|
||||
badRequest("The invitation has no roles to carry forward");
|
||||
}
|
||||
|
||||
await tx.insert(userInvitation).values({
|
||||
id: replacementId,
|
||||
tokenHash: invitationToken.tokenHash,
|
||||
tokenEncrypted: invitationToken.tokenEncrypted,
|
||||
tokenIv: invitationToken.tokenIv,
|
||||
createdByUserId: ctx.session.user.id,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await tx.insert(userInvitationRole).values(
|
||||
assignedRoles.map(({ roleId }) => ({
|
||||
invitationId: replacementId,
|
||||
roleId,
|
||||
createdAt: now,
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
const invitations = await getInvitationsWithRoles();
|
||||
return invitations.find(
|
||||
(invitation) => invitation.id === replacementId,
|
||||
);
|
||||
}),
|
||||
|
||||
inspect: publicProcedure
|
||||
.input(invitationTokenSchema)
|
||||
.query(async ({ input }) => {
|
||||
const tokenHash = await hashInvitationToken(input.token);
|
||||
const [invitation] = await db
|
||||
.select({
|
||||
id: userInvitation.id,
|
||||
revokedAt: userInvitation.revokedAt,
|
||||
acceptedAt: userInvitation.acceptedAt,
|
||||
})
|
||||
.from(userInvitation)
|
||||
.where(eq(userInvitation.tokenHash, tokenHash))
|
||||
.limit(1);
|
||||
|
||||
if (!invitation) {
|
||||
return { status: "invalid" as const, roles: [] };
|
||||
}
|
||||
|
||||
const assignedRoles = await db
|
||||
.select({ id: role.id, name: role.name })
|
||||
.from(userInvitationRole)
|
||||
.innerJoin(role, eq(role.id, userInvitationRole.roleId))
|
||||
.where(eq(userInvitationRole.invitationId, invitation.id))
|
||||
.orderBy(asc(role.name));
|
||||
|
||||
return {
|
||||
status: invitation.acceptedAt
|
||||
? ("accepted" as const)
|
||||
: invitation.revokedAt
|
||||
? ("revoked" as const)
|
||||
: ("pending" as const),
|
||||
roles: assignedRoles,
|
||||
};
|
||||
}),
|
||||
|
||||
accept: publicProcedure
|
||||
.input(userInvitationAcceptSchema)
|
||||
.mutation(async ({ input }) => {
|
||||
const tokenHash = await hashInvitationToken(input.token);
|
||||
const [activeInvitation] = await db
|
||||
.select({ id: userInvitation.id })
|
||||
.from(userInvitation)
|
||||
.where(
|
||||
and(
|
||||
eq(userInvitation.tokenHash, tokenHash),
|
||||
isNull(userInvitation.revokedAt),
|
||||
isNull(userInvitation.acceptedAt),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!activeInvitation) {
|
||||
badRequest("This invitation link is invalid or no longer active");
|
||||
}
|
||||
|
||||
const email = input.email.trim().toLowerCase();
|
||||
const passwordHash = await hashCredentialPassword(input.password);
|
||||
const userId = createEntityId();
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
const now = new Date();
|
||||
const [claimedInvitation] = await tx
|
||||
.update(userInvitation)
|
||||
.set({ acceptedAt: now, updatedAt: now })
|
||||
.where(
|
||||
and(
|
||||
eq(userInvitation.tokenHash, tokenHash),
|
||||
isNull(userInvitation.revokedAt),
|
||||
isNull(userInvitation.acceptedAt),
|
||||
),
|
||||
)
|
||||
.returning({ id: userInvitation.id });
|
||||
|
||||
if (!claimedInvitation) {
|
||||
badRequest("This invitation link has already been used or revoked");
|
||||
}
|
||||
|
||||
const assignedRoles = await tx
|
||||
.select({ roleId: userInvitationRole.roleId })
|
||||
.from(userInvitationRole)
|
||||
.where(eq(userInvitationRole.invitationId, claimedInvitation.id));
|
||||
|
||||
if (!assignedRoles.length) {
|
||||
badRequest("This invitation no longer grants an access role");
|
||||
}
|
||||
|
||||
const [existingUser] = await tx
|
||||
.select({ id: user.id })
|
||||
.from(user)
|
||||
.where(eq(sql<string>`lower(${user.email})`, email))
|
||||
.limit(1);
|
||||
|
||||
if (existingUser) {
|
||||
badRequest("A user with this email already exists");
|
||||
}
|
||||
|
||||
await tx.insert(user).values({
|
||||
id: userId,
|
||||
name: input.name,
|
||||
email,
|
||||
emailVerified: false,
|
||||
mustChangePassword: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await tx.insert(account).values({
|
||||
id: createEntityId(),
|
||||
accountId: userId,
|
||||
providerId: "credential",
|
||||
userId,
|
||||
password: passwordHash,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await tx.insert(userRole).values(
|
||||
assignedRoles.map(({ roleId }) => ({
|
||||
userId,
|
||||
roleId,
|
||||
createdAt: now,
|
||||
})),
|
||||
);
|
||||
|
||||
await tx
|
||||
.update(userInvitation)
|
||||
.set({ acceptedUserId: userId, updatedAt: now })
|
||||
.where(eq(userInvitation.id, claimedInvitation.id));
|
||||
});
|
||||
|
||||
return { userId, email };
|
||||
}),
|
||||
}),
|
||||
|
||||
updateRoles: permissionedProcedure("users.assignRoles")
|
||||
.input(updateUserRolesSchema)
|
||||
.mutation(async ({ input }) => {
|
||||
const [existingUser] = await db.select({ id: user.id }).from(user).where(eq(user.id, input.userId)).limit(1);
|
||||
|
||||
if (!existingUser) {
|
||||
notFound("User not found");
|
||||
}
|
||||
|
||||
const uniqueRoleIds = await validateRoleIds(input.roleIds);
|
||||
|
||||
await db.delete(userRole).where(eq(userRole.userId, input.userId));
|
||||
await db.insert(userRole).values(
|
||||
uniqueRoleIds.map((roleId) => ({
|
||||
userId: input.userId,
|
||||
roleId,
|
||||
})),
|
||||
);
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.execute(sql`select pg_advisory_xact_lock(612984119)`);
|
||||
|
||||
const [existingUser] = await tx
|
||||
.select({ id: user.id })
|
||||
.from(user)
|
||||
.where(eq(user.id, input.userId))
|
||||
.limit(1);
|
||||
|
||||
if (!existingUser) {
|
||||
notFound("User not found");
|
||||
}
|
||||
|
||||
const existingRoles = await tx
|
||||
.select({ roleId: userRole.roleId })
|
||||
.from(userRole)
|
||||
.where(eq(userRole.userId, input.userId));
|
||||
const removesAdmin =
|
||||
existingRoles.some(({ roleId }) => roleId === ADMIN_ROLE_ID) &&
|
||||
!uniqueRoleIds.includes(ADMIN_ROLE_ID);
|
||||
|
||||
if (removesAdmin) {
|
||||
const [adminCount] = await tx
|
||||
.select({ value: count() })
|
||||
.from(userRole)
|
||||
.where(eq(userRole.roleId, ADMIN_ROLE_ID));
|
||||
|
||||
if ((adminCount?.value ?? 0) <= 1) {
|
||||
badRequest("Minmon must always have at least one administrator");
|
||||
}
|
||||
}
|
||||
|
||||
await tx.delete(userRole).where(eq(userRole.userId, input.userId));
|
||||
await tx.insert(userRole).values(
|
||||
uniqueRoleIds.map((roleId) => ({
|
||||
userId: input.userId,
|
||||
roleId,
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
const updated = await getUsersWithRoles();
|
||||
return updated.find((item) => item.id === input.userId);
|
||||
}),
|
||||
|
||||
delete: permissionedProcedure("users.delete").input(byIdSchema).mutation(async ({ ctx, input }) => {
|
||||
if (ctx.session.user.id === input.id) {
|
||||
badRequest("You cannot delete your own user account while signed in");
|
||||
}
|
||||
changeInitialPassword: protectedProcedure
|
||||
.input(changeInitialPasswordSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
try {
|
||||
await auth.api.changePassword({
|
||||
body: {
|
||||
currentPassword: input.currentPassword,
|
||||
newPassword: input.newPassword,
|
||||
revokeOtherSessions: false,
|
||||
},
|
||||
headers: ctx.requestHeaders,
|
||||
});
|
||||
} catch {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message:
|
||||
"The current password is incorrect or the new password is invalid",
|
||||
});
|
||||
}
|
||||
|
||||
const [existingUser] = await db.select({ id: user.id }).from(user).where(eq(user.id, input.id)).limit(1);
|
||||
await db.transaction(async (tx) => {
|
||||
await tx
|
||||
.update(user)
|
||||
.set({ mustChangePassword: false, updatedAt: new Date() })
|
||||
.where(eq(user.id, ctx.session.user.id));
|
||||
await tx
|
||||
.delete(session)
|
||||
.where(
|
||||
and(
|
||||
eq(session.userId, ctx.session.user.id),
|
||||
ne(session.id, ctx.session.session.id),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
if (!existingUser) {
|
||||
notFound("User not found");
|
||||
}
|
||||
return { status: true };
|
||||
}),
|
||||
|
||||
await db.delete(user).where(eq(user.id, input.id));
|
||||
return { id: input.id };
|
||||
}),
|
||||
delete: permissionedProcedure("users.delete")
|
||||
.input(byIdSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (ctx.session.user.id === input.id) {
|
||||
badRequest("You cannot delete your own user account while signed in");
|
||||
}
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.execute(sql`select pg_advisory_xact_lock(612984119)`);
|
||||
|
||||
const [existingUser] = await tx
|
||||
.select({ id: user.id })
|
||||
.from(user)
|
||||
.where(eq(user.id, input.id))
|
||||
.limit(1);
|
||||
|
||||
if (!existingUser) {
|
||||
notFound("User not found");
|
||||
}
|
||||
|
||||
const [adminRole] = await tx
|
||||
.select({ roleId: userRole.roleId })
|
||||
.from(userRole)
|
||||
.where(
|
||||
and(
|
||||
eq(userRole.userId, input.id),
|
||||
eq(userRole.roleId, ADMIN_ROLE_ID),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (adminRole) {
|
||||
const [adminCount] = await tx
|
||||
.select({ value: count() })
|
||||
.from(userRole)
|
||||
.where(eq(userRole.roleId, ADMIN_ROLE_ID));
|
||||
|
||||
if ((adminCount?.value ?? 0) <= 1) {
|
||||
badRequest("The last administrator cannot be deleted");
|
||||
}
|
||||
}
|
||||
|
||||
await tx.delete(user).where(eq(user.id, input.id));
|
||||
});
|
||||
|
||||
return { id: input.id };
|
||||
}),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -17,6 +17,17 @@ export function createAuth() {
|
|||
trustedOrigins: [env.CORS_ORIGIN],
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
disableSignUp: true,
|
||||
},
|
||||
user: {
|
||||
additionalFields: {
|
||||
mustChangePassword: {
|
||||
type: "boolean",
|
||||
required: false,
|
||||
defaultValue: false,
|
||||
input: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
secret: env.BETTER_AUTH_SECRET,
|
||||
baseURL: env.BETTER_AUTH_URL,
|
||||
|
|
|
|||
40
packages/db/src/migrations/0004_lean_jazinda.sql
Normal file
40
packages/db/src/migrations/0004_lean_jazinda.sql
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
ALTER TABLE "user" ADD COLUMN "must_change_password" boolean DEFAULT false NOT NULL;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "user_invitation" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"token_hash" text NOT NULL,
|
||||
"token_encrypted" text NOT NULL,
|
||||
"token_iv" text NOT NULL,
|
||||
"created_by_user_id" text,
|
||||
"accepted_user_id" text,
|
||||
"revoked_at" timestamp,
|
||||
"accepted_at" timestamp,
|
||||
"created_at" timestamp DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "user_invitation_token_hash_unique" UNIQUE("token_hash")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "user_invitation_role" (
|
||||
"invitation_id" text NOT NULL,
|
||||
"role_id" text NOT NULL,
|
||||
"created_at" timestamp DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "user_invitation_role_invitation_id_role_id_pk" PRIMARY KEY("invitation_id","role_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "user_invitation" ADD CONSTRAINT "user_invitation_created_by_user_id_user_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "user_invitation" ADD CONSTRAINT "user_invitation_accepted_user_id_user_id_fk" FOREIGN KEY ("accepted_user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "user_invitation_role" ADD CONSTRAINT "user_invitation_role_invitation_id_user_invitation_id_fk" FOREIGN KEY ("invitation_id") REFERENCES "public"."user_invitation"("id") ON DELETE cascade ON UPDATE no action;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "user_invitation_role" ADD CONSTRAINT "user_invitation_role_role_id_role_id_fk" FOREIGN KEY ("role_id") REFERENCES "public"."role"("id") ON DELETE cascade ON UPDATE no action;
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX "user_invitation_created_by_user_id_idx" ON "user_invitation" USING btree ("created_by_user_id");
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX "user_invitation_accepted_user_id_idx" ON "user_invitation" USING btree ("accepted_user_id");
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX "user_invitation_created_at_idx" ON "user_invitation" USING btree ("created_at");
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX "user_invitation_role_invitation_id_idx" ON "user_invitation_role" USING btree ("invitation_id");
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX "user_invitation_role_role_id_idx" ON "user_invitation_role" USING btree ("role_id");
|
||||
1625
packages/db/src/migrations/meta/0004_snapshot.json
Normal file
1625
packages/db/src/migrations/meta/0004_snapshot.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -29,6 +29,13 @@
|
|||
"when": 1786104000000,
|
||||
"tag": "0003_add_domain_check_history",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 4,
|
||||
"version": "7",
|
||||
"when": 1786105359203,
|
||||
"tag": "0004_lean_jazinda",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -1,11 +1,19 @@
|
|||
import { relations } from "drizzle-orm";
|
||||
import { pgTable, text, timestamp, boolean, index, primaryKey } from "drizzle-orm/pg-core";
|
||||
import {
|
||||
pgTable,
|
||||
text,
|
||||
timestamp,
|
||||
boolean,
|
||||
index,
|
||||
primaryKey,
|
||||
} from "drizzle-orm/pg-core";
|
||||
|
||||
export const user = pgTable("user", {
|
||||
id: text("id").primaryKey(),
|
||||
name: text("name").notNull(),
|
||||
email: text("email").notNull().unique(),
|
||||
emailVerified: boolean("email_verified").default(false).notNull(),
|
||||
mustChangePassword: boolean("must_change_password").default(false).notNull(),
|
||||
image: text("image"),
|
||||
createdAt: timestamp("created_at").defaultNow().notNull(),
|
||||
updatedAt: timestamp("updated_at")
|
||||
|
|
@ -131,10 +139,62 @@ export const userRole = pgTable(
|
|||
],
|
||||
);
|
||||
|
||||
export const userInvitation = pgTable(
|
||||
"user_invitation",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
tokenHash: text("token_hash").notNull().unique(),
|
||||
tokenEncrypted: text("token_encrypted").notNull(),
|
||||
tokenIv: text("token_iv").notNull(),
|
||||
createdByUserId: text("created_by_user_id").references(() => user.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
acceptedUserId: text("accepted_user_id").references(() => user.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
revokedAt: timestamp("revoked_at"),
|
||||
acceptedAt: timestamp("accepted_at"),
|
||||
createdAt: timestamp("created_at").defaultNow().notNull(),
|
||||
updatedAt: timestamp("updated_at")
|
||||
.defaultNow()
|
||||
.$onUpdate(() => /* @__PURE__ */ new Date())
|
||||
.notNull(),
|
||||
},
|
||||
(table) => [
|
||||
index("user_invitation_created_by_user_id_idx").on(table.createdByUserId),
|
||||
index("user_invitation_accepted_user_id_idx").on(table.acceptedUserId),
|
||||
index("user_invitation_created_at_idx").on(table.createdAt),
|
||||
],
|
||||
);
|
||||
|
||||
export const userInvitationRole = pgTable(
|
||||
"user_invitation_role",
|
||||
{
|
||||
invitationId: text("invitation_id")
|
||||
.notNull()
|
||||
.references(() => userInvitation.id, { onDelete: "cascade" }),
|
||||
roleId: text("role_id")
|
||||
.notNull()
|
||||
.references(() => role.id, { onDelete: "cascade" }),
|
||||
createdAt: timestamp("created_at").defaultNow().notNull(),
|
||||
},
|
||||
(table) => [
|
||||
primaryKey({ columns: [table.invitationId, table.roleId] }),
|
||||
index("user_invitation_role_invitation_id_idx").on(table.invitationId),
|
||||
index("user_invitation_role_role_id_idx").on(table.roleId),
|
||||
],
|
||||
);
|
||||
|
||||
export const userRelations = relations(user, ({ many }) => ({
|
||||
sessions: many(session),
|
||||
accounts: many(account),
|
||||
roles: many(userRole),
|
||||
createdInvitations: many(userInvitation, {
|
||||
relationName: "invitationCreator",
|
||||
}),
|
||||
acceptedInvitations: many(userInvitation, {
|
||||
relationName: "invitationRecipient",
|
||||
}),
|
||||
}));
|
||||
|
||||
export const sessionRelations = relations(session, ({ one }) => ({
|
||||
|
|
@ -181,3 +241,34 @@ export const userRoleRelations = relations(userRole, ({ one }) => ({
|
|||
references: [role.id],
|
||||
}),
|
||||
}));
|
||||
|
||||
export const userInvitationRelations = relations(
|
||||
userInvitation,
|
||||
({ one, many }) => ({
|
||||
createdBy: one(user, {
|
||||
fields: [userInvitation.createdByUserId],
|
||||
references: [user.id],
|
||||
relationName: "invitationCreator",
|
||||
}),
|
||||
acceptedUser: one(user, {
|
||||
fields: [userInvitation.acceptedUserId],
|
||||
references: [user.id],
|
||||
relationName: "invitationRecipient",
|
||||
}),
|
||||
roles: many(userInvitationRole),
|
||||
}),
|
||||
);
|
||||
|
||||
export const userInvitationRoleRelations = relations(
|
||||
userInvitationRole,
|
||||
({ one }) => ({
|
||||
invitation: one(userInvitation, {
|
||||
fields: [userInvitationRole.invitationId],
|
||||
references: [userInvitation.id],
|
||||
}),
|
||||
role: one(role, {
|
||||
fields: [userInvitationRole.roleId],
|
||||
references: [role.id],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -4,25 +4,13 @@ dotenv.config({
|
|||
path: new URL("../../../apps/server/.env", import.meta.url).pathname,
|
||||
});
|
||||
|
||||
import { db } from "./index";
|
||||
import { seed, seedRolesAndPermissions } from "./seed";
|
||||
import { seedRolesAndPermissions } from "./seed";
|
||||
|
||||
async function seedIfEmpty() {
|
||||
const existingUser = await db.query.user.findFirst({
|
||||
columns: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (existingUser) {
|
||||
await seedRolesAndPermissions(existingUser.id);
|
||||
console.info("Database already has users; ensured default roles and permissions.");
|
||||
return;
|
||||
}
|
||||
|
||||
await seed();
|
||||
console.info("Seeded auth admin and monitoring dashboard sample data.");
|
||||
console.info("Admin login: admin@minmon.local / admin12345");
|
||||
await seedRolesAndPermissions();
|
||||
console.info(
|
||||
"Ensured default roles and permissions. First-run setup will create the administrator.",
|
||||
);
|
||||
}
|
||||
|
||||
seedIfEmpty()
|
||||
|
|
|
|||
|
|
@ -7,8 +7,21 @@ dotenv.config({
|
|||
});
|
||||
|
||||
import { db } from "./index";
|
||||
import { account, permission, role, rolePermission, user, userRole } from "./schema/auth";
|
||||
import { domain, domainCheckHistory, note, server, service } from "./schema/monitoring";
|
||||
import {
|
||||
account,
|
||||
permission,
|
||||
role,
|
||||
rolePermission,
|
||||
user,
|
||||
userRole,
|
||||
} from "./schema/auth";
|
||||
import {
|
||||
domain,
|
||||
domainCheckHistory,
|
||||
note,
|
||||
server,
|
||||
service,
|
||||
} from "./schema/monitoring";
|
||||
|
||||
const now = new Date();
|
||||
const earlierToday = new Date(now.getTime() - 45 * 60 * 1000);
|
||||
|
|
@ -30,7 +43,8 @@ const servers = [
|
|||
operatingSystem: "Ubuntu 24.04 LTS",
|
||||
location: "Singapore",
|
||||
provider: "DigitalOcean",
|
||||
description: "Main production server hosting the dashboard web app, API, and reverse proxy.",
|
||||
description:
|
||||
"Main production server hosting the dashboard web app, API, and reverse proxy.",
|
||||
status: "active" as const,
|
||||
},
|
||||
{
|
||||
|
|
@ -52,7 +66,8 @@ const servers = [
|
|||
operatingSystem: "Ubuntu 22.04 LTS",
|
||||
location: "Campus Lab",
|
||||
provider: "University Lab",
|
||||
description: "Used for student practice and lecturer demonstration in class.",
|
||||
description:
|
||||
"Used for student practice and lecturer demonstration in class.",
|
||||
status: "inactive" as const,
|
||||
},
|
||||
];
|
||||
|
|
@ -67,7 +82,8 @@ const services = [
|
|||
externalPort: 443,
|
||||
protocol: "https" as const,
|
||||
status: "active" as const,
|
||||
description: "Frontend application for the private server management dashboard.",
|
||||
description:
|
||||
"Frontend application for the private server management dashboard.",
|
||||
},
|
||||
{
|
||||
id: "service_dashboard_api",
|
||||
|
|
@ -89,7 +105,8 @@ const services = [
|
|||
externalPort: 25,
|
||||
protocol: "tcp" as const,
|
||||
status: "maintenance" as const,
|
||||
description: "Mail service used as a sample SMTP gateway for the assignment.",
|
||||
description:
|
||||
"Mail service used as a sample SMTP gateway for the assignment.",
|
||||
},
|
||||
{
|
||||
id: "service_lab_proxy",
|
||||
|
|
@ -100,7 +117,8 @@ const services = [
|
|||
externalPort: 80,
|
||||
protocol: "http" as const,
|
||||
status: "down" as const,
|
||||
description: "Reverse proxy for local practice deployments in the campus lab.",
|
||||
description:
|
||||
"Reverse proxy for local practice deployments in the campus lab.",
|
||||
},
|
||||
];
|
||||
|
||||
|
|
@ -151,7 +169,8 @@ const domains = [
|
|||
resolutionStatus: "UNRESOLVED" as const,
|
||||
lastCheckedAt: yesterday,
|
||||
remarks: "Lab VM is powered off outside teaching hours.",
|
||||
lastCheckMessage: "DNS lookup failed because the host could not be resolved.",
|
||||
lastCheckMessage:
|
||||
"DNS lookup failed because the host could not be resolved.",
|
||||
},
|
||||
];
|
||||
|
||||
|
|
@ -160,7 +179,8 @@ const notes = [
|
|||
id: "note_prod_backup",
|
||||
serverId: "server_prod_1",
|
||||
title: "Weekly backup reminder",
|
||||
content: "Verify the PostgreSQL backup every Friday before the lecturer demo session.",
|
||||
content:
|
||||
"Verify the PostgreSQL backup every Friday before the lecturer demo session.",
|
||||
category: "maintenance",
|
||||
},
|
||||
{
|
||||
|
|
@ -175,14 +195,16 @@ const notes = [
|
|||
id: "note_mail_dns",
|
||||
serverId: "server_mail_1",
|
||||
title: "Update stale A record",
|
||||
content: "Point mail.minmon.dev to the current mail server before final presentation week.",
|
||||
content:
|
||||
"Point mail.minmon.dev to the current mail server before final presentation week.",
|
||||
category: "todo",
|
||||
},
|
||||
{
|
||||
id: "note_lab_status",
|
||||
serverId: "server_lab_1",
|
||||
title: "Lab VM inactive",
|
||||
content: "The campus lab VM is intentionally inactive outside class hours, so related checks may fail.",
|
||||
content:
|
||||
"The campus lab VM is intentionally inactive outside class hours, so related checks may fail.",
|
||||
category: "incident",
|
||||
},
|
||||
];
|
||||
|
|
@ -202,7 +224,8 @@ async function seedAuthAdmin() {
|
|||
id: adminUser.id,
|
||||
name: adminUser.name,
|
||||
email: adminUser.email,
|
||||
emailVerified: true,
|
||||
emailVerified: false,
|
||||
mustChangePassword: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
|
@ -221,42 +244,54 @@ async function seedAuthAdmin() {
|
|||
}
|
||||
|
||||
export async function seedRolesAndPermissions(adminUserId?: string) {
|
||||
await db.insert(permission).values(
|
||||
permissions.map((name) => ({
|
||||
id: name,
|
||||
name,
|
||||
description: `Allows ${name.replace(".", " ")}`,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})),
|
||||
).onConflictDoNothing();
|
||||
|
||||
await db.insert(role).values(
|
||||
roleDefinitions.map((item) => ({
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
description: item.description,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})),
|
||||
).onConflictDoNothing();
|
||||
|
||||
await db.insert(rolePermission).values(
|
||||
roleDefinitions.flatMap((item) =>
|
||||
item.permissions.map((permissionName) => ({
|
||||
roleId: item.id,
|
||||
permissionId: permissionName,
|
||||
await db
|
||||
.insert(permission)
|
||||
.values(
|
||||
permissions.map((name) => ({
|
||||
id: name,
|
||||
name,
|
||||
description: `Allows ${name.replace(".", " ")}`,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})),
|
||||
),
|
||||
).onConflictDoNothing();
|
||||
)
|
||||
.onConflictDoNothing();
|
||||
|
||||
await db
|
||||
.insert(role)
|
||||
.values(
|
||||
roleDefinitions.map((item) => ({
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
description: item.description,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})),
|
||||
)
|
||||
.onConflictDoNothing();
|
||||
|
||||
await db
|
||||
.insert(rolePermission)
|
||||
.values(
|
||||
roleDefinitions.flatMap((item) =>
|
||||
item.permissions.map((permissionName) => ({
|
||||
roleId: item.id,
|
||||
permissionId: permissionName,
|
||||
createdAt: now,
|
||||
})),
|
||||
),
|
||||
)
|
||||
.onConflictDoNothing();
|
||||
|
||||
if (adminUserId) {
|
||||
await db.insert(userRole).values({
|
||||
userId: adminUserId,
|
||||
roleId: "role_admin",
|
||||
createdAt: now,
|
||||
}).onConflictDoNothing();
|
||||
await db
|
||||
.insert(userRole)
|
||||
.values({
|
||||
userId: adminUserId,
|
||||
roleId: "role_admin",
|
||||
createdAt: now,
|
||||
})
|
||||
.onConflictDoNothing();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
79
packages/ui/src/components/alert.tsx
Normal file
79
packages/ui/src/components/alert.tsx
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
import * as React from "react";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "@minmon/ui/lib/utils";
|
||||
|
||||
const alertVariants = cva(
|
||||
"group/alert relative grid w-full gap-0.5 rounded-none border px-2.5 py-2 text-left text-xs has-data-[slot=alert-action]:relative has-data-[slot=alert-action]:pr-18 has-[>svg]:grid-cols-[auto_1fr] has-[>svg]:gap-x-2 *:[svg]:row-span-2 *:[svg]:translate-y-0 *:[svg]:text-current *:[svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-card text-card-foreground",
|
||||
destructive:
|
||||
"bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 *:[svg]:text-current",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
function Alert({
|
||||
className,
|
||||
variant,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert"
|
||||
role="alert"
|
||||
className={cn(alertVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-title"
|
||||
className={cn(
|
||||
"font-medium group-has-[>svg]/alert:col-start-2 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AlertDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-description"
|
||||
className={cn(
|
||||
"text-xs/relaxed text-balance text-muted-foreground md:text-pretty [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground [&_p:not(:last-child)]:mb-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AlertAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-action"
|
||||
className={cn(
|
||||
"absolute top-[calc(--spacing(1.25))] right-[calc(--spacing(1.25))]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Alert, AlertTitle, AlertDescription, AlertAction };
|
||||
|
|
@ -4,7 +4,7 @@ import { cva, type VariantProps } from "class-variance-authority";
|
|||
import { Loader2Icon } from "lucide-react";
|
||||
|
||||
const buttonVariants = cva(
|
||||
"group/button relative inline-flex shrink-0 items-center justify-center rounded-none border border-transparent bg-clip-padding text-xs font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50 active:scale-[0.98] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
"group/button relative inline-flex shrink-0 items-center justify-center rounded-none border border-transparent bg-clip-padding text-xs font-medium whitespace-nowrap transition-[color,background-color,border-color,box-shadow,transform,opacity] outline-none select-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50 active:scale-[0.96] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
|
|
@ -64,7 +64,7 @@ function Button({
|
|||
aria-hidden="true"
|
||||
className="absolute inset-0 inline-flex items-center justify-center"
|
||||
>
|
||||
<Loader2Icon className="size-4 animate-spin" />
|
||||
<Loader2Icon className="animate-spin" />
|
||||
</span>
|
||||
) : null}
|
||||
<span
|
||||
|
|
|
|||
238
packages/ui/src/components/field.tsx
Normal file
238
packages/ui/src/components/field.tsx
Normal file
|
|
@ -0,0 +1,238 @@
|
|||
"use client";
|
||||
|
||||
import { useMemo } from "react";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "@minmon/ui/lib/utils";
|
||||
import { Label } from "@minmon/ui/components/label";
|
||||
import { Separator } from "@minmon/ui/components/separator";
|
||||
|
||||
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
|
||||
return (
|
||||
<fieldset
|
||||
data-slot="field-set"
|
||||
className={cn(
|
||||
"flex flex-col gap-4 has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FieldLegend({
|
||||
className,
|
||||
variant = "legend",
|
||||
...props
|
||||
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
|
||||
return (
|
||||
<legend
|
||||
data-slot="field-legend"
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"mb-2.5 font-medium data-[variant=label]:text-xs data-[variant=legend]:text-sm",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="field-group"
|
||||
className={cn(
|
||||
"group/field-group @container/field-group flex w-full flex-col gap-5 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const fieldVariants = cva(
|
||||
"group/field flex w-full gap-2 data-[invalid=true]:text-destructive",
|
||||
{
|
||||
variants: {
|
||||
orientation: {
|
||||
vertical: "flex-col *:w-full [&>.sr-only]:w-auto",
|
||||
horizontal:
|
||||
"flex-row items-center has-[>[data-slot=field-content]]:items-start *:data-[slot=field-label]:flex-auto has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
|
||||
responsive:
|
||||
"flex-col *:w-full @md/field-group:flex-row @md/field-group:items-center @md/field-group:*:w-auto @md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:*:data-[slot=field-label]:flex-auto [&>.sr-only]:w-auto @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
orientation: "vertical",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
function Field({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
data-slot="field"
|
||||
data-orientation={orientation}
|
||||
className={cn(fieldVariants({ orientation }), className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="field-content"
|
||||
className={cn(
|
||||
"group/field-content flex flex-1 flex-col gap-0.5 leading-snug",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FieldLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Label>) {
|
||||
return (
|
||||
<Label
|
||||
data-slot="field-label"
|
||||
className={cn(
|
||||
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50 has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:rounded-none has-[>[data-slot=field]]:border *:data-[slot=field]:p-2 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10",
|
||||
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="field-label"
|
||||
className={cn(
|
||||
"flex w-fit items-center gap-2 text-xs/relaxed group-data-[disabled=true]/field:opacity-50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||
return (
|
||||
<p
|
||||
data-slot="field-description"
|
||||
className={cn(
|
||||
"text-left text-xs/relaxed leading-normal font-normal text-muted-foreground group-has-data-horizontal/field:text-balance [[data-variant=legend]+&]:-mt-1.5",
|
||||
"last:mt-0 nth-last-2:-mt-1",
|
||||
"[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FieldSeparator({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
children?: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
data-slot="field-separator"
|
||||
data-content={!!children}
|
||||
className={cn(
|
||||
"relative -my-2 h-5 text-xs group-data-[variant=outline]/field-group:-mb-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<Separator className="absolute inset-0 top-1/2" />
|
||||
{children && (
|
||||
<span
|
||||
className="relative mx-auto block w-fit bg-background px-2 text-muted-foreground"
|
||||
data-slot="field-separator-content"
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FieldError({
|
||||
className,
|
||||
children,
|
||||
errors,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
errors?: Array<{ message?: string } | undefined>;
|
||||
}) {
|
||||
const content = useMemo(() => {
|
||||
if (children) {
|
||||
return children;
|
||||
}
|
||||
|
||||
if (!errors?.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const uniqueErrors = [
|
||||
...new Map(errors.map((error) => [error?.message, error])).values(),
|
||||
];
|
||||
|
||||
if (uniqueErrors?.length == 1) {
|
||||
return uniqueErrors[0]?.message;
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className="ml-4 flex list-disc flex-col gap-1">
|
||||
{uniqueErrors.map(
|
||||
(error, index) =>
|
||||
error?.message && <li key={index}>{error.message}</li>,
|
||||
)}
|
||||
</ul>
|
||||
);
|
||||
}, [children, errors]);
|
||||
|
||||
if (!content) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
data-slot="field-error"
|
||||
className={cn("text-xs font-normal text-destructive", className)}
|
||||
{...props}
|
||||
>
|
||||
{content}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Field,
|
||||
FieldLabel,
|
||||
FieldDescription,
|
||||
FieldError,
|
||||
FieldGroup,
|
||||
FieldLegend,
|
||||
FieldSeparator,
|
||||
FieldSet,
|
||||
FieldContent,
|
||||
FieldTitle,
|
||||
};
|
||||
23
packages/ui/src/components/separator.tsx
Normal file
23
packages/ui/src/components/separator.tsx
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import { Separator as SeparatorPrimitive } from "@base-ui/react/separator";
|
||||
|
||||
import { cn } from "@minmon/ui/lib/utils";
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
...props
|
||||
}: SeparatorPrimitive.Props) {
|
||||
return (
|
||||
<SeparatorPrimitive
|
||||
data-slot="separator"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Separator };
|
||||
87
packages/ui/src/components/toggle-group.tsx
Normal file
87
packages/ui/src/components/toggle-group.tsx
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
import * as React from "react";
|
||||
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle";
|
||||
import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-group";
|
||||
import { type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "@minmon/ui/lib/utils";
|
||||
import { toggleVariants } from "@minmon/ui/components/toggle";
|
||||
|
||||
const ToggleGroupContext = React.createContext<
|
||||
VariantProps<typeof toggleVariants> & {
|
||||
spacing?: number;
|
||||
orientation?: "horizontal" | "vertical";
|
||||
}
|
||||
>({
|
||||
size: "default",
|
||||
variant: "default",
|
||||
spacing: 2,
|
||||
orientation: "horizontal",
|
||||
});
|
||||
|
||||
function ToggleGroup({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
spacing = 2,
|
||||
orientation = "horizontal",
|
||||
children,
|
||||
...props
|
||||
}: ToggleGroupPrimitive.Props &
|
||||
VariantProps<typeof toggleVariants> & {
|
||||
spacing?: number;
|
||||
orientation?: "horizontal" | "vertical";
|
||||
}) {
|
||||
return (
|
||||
<ToggleGroupPrimitive
|
||||
data-slot="toggle-group"
|
||||
data-variant={variant}
|
||||
data-size={size}
|
||||
data-spacing={spacing}
|
||||
data-orientation={orientation}
|
||||
style={{ "--gap": spacing } as React.CSSProperties}
|
||||
className={cn(
|
||||
"group/toggle-group flex w-fit flex-row items-center gap-[--spacing(var(--gap))] rounded-none data-[size=sm]:rounded-none data-vertical:flex-col data-vertical:items-stretch",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ToggleGroupContext.Provider
|
||||
value={{ variant, size, spacing, orientation }}
|
||||
>
|
||||
{children}
|
||||
</ToggleGroupContext.Provider>
|
||||
</ToggleGroupPrimitive>
|
||||
);
|
||||
}
|
||||
|
||||
function ToggleGroupItem({
|
||||
className,
|
||||
children,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
...props
|
||||
}: TogglePrimitive.Props & VariantProps<typeof toggleVariants>) {
|
||||
const context = React.useContext(ToggleGroupContext);
|
||||
|
||||
return (
|
||||
<TogglePrimitive
|
||||
data-slot="toggle-group-item"
|
||||
data-variant={context.variant || variant}
|
||||
data-size={context.size || size}
|
||||
data-spacing={context.spacing}
|
||||
className={cn(
|
||||
"shrink-0 group-data-[spacing=0]/toggle-group:rounded-none group-data-[spacing=0]/toggle-group:px-2 focus:z-10 focus-visible:z-10 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-end]:pr-1.5 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-start]:pl-1.5 group-data-horizontal/toggle-group:data-[spacing=0]:first:rounded-none group-data-vertical/toggle-group:data-[spacing=0]:first:rounded-none group-data-horizontal/toggle-group:data-[spacing=0]:last:rounded-none group-data-vertical/toggle-group:data-[spacing=0]:last:rounded-none group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:border-l-0 group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:border-t-0 group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-l group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-t",
|
||||
toggleVariants({
|
||||
variant: context.variant || variant,
|
||||
size: context.size || size,
|
||||
}),
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</TogglePrimitive>
|
||||
);
|
||||
}
|
||||
|
||||
export { ToggleGroup, ToggleGroupItem };
|
||||
43
packages/ui/src/components/toggle.tsx
Normal file
43
packages/ui/src/components/toggle.tsx
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "@minmon/ui/lib/utils";
|
||||
|
||||
const toggleVariants = cva(
|
||||
"group/toggle inline-flex items-center justify-center gap-1 rounded-none text-xs font-medium whitespace-nowrap transition-[color,background-color,border-color,box-shadow,transform,opacity] outline-none hover:bg-muted hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 active:scale-[0.96] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 aria-pressed:bg-muted data-[state=on]:bg-muted dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-transparent",
|
||||
outline: "border border-input bg-transparent hover:bg-muted",
|
||||
},
|
||||
size: {
|
||||
default:
|
||||
"h-8 min-w-8 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
||||
sm: "h-7 min-w-7 rounded-none px-2.5 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5",
|
||||
lg: "h-9 min-w-9 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
function Toggle({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
...props
|
||||
}: TogglePrimitive.Props & VariantProps<typeof toggleVariants>) {
|
||||
return (
|
||||
<TogglePrimitive
|
||||
data-slot="toggle"
|
||||
className={cn(toggleVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Toggle, toggleVariants };
|
||||
|
|
@ -194,6 +194,6 @@
|
|||
letter-spacing: var(--tracking-normal);
|
||||
}
|
||||
html {
|
||||
@apply font-sans;
|
||||
@apply font-sans antialiased;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue