create-mohit-next 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +108 -2
- package/index.js +399 -0
- package/package.json +36 -4
- package/template/AGENTS.md +9 -0
- package/template/Dockerfile +48 -0
- package/template/README.md +262 -0
- package/template/_dockerignore +13 -0
- package/template/_env.example +11 -0
- package/template/_gitignore +42 -0
- package/template/_prettierignore +11 -0
- package/template/_prettierrc +9 -0
- package/template/components.json +25 -0
- package/template/docker-compose.yml +33 -0
- package/template/eslint.config.mjs +21 -0
- package/template/next.config.ts +45 -0
- package/template/package.json +53 -0
- package/template/public/robots.txt +6 -0
- package/template/src/app/(app)/admin/page.tsx +53 -0
- package/template/src/app/(app)/dashboard/page.tsx +127 -0
- package/template/src/app/(app)/error.tsx +28 -0
- package/template/src/app/(app)/layout.tsx +35 -0
- package/template/src/app/(app)/loading.tsx +5 -0
- package/template/src/app/(app)/reports/page.tsx +109 -0
- package/template/src/app/(auth)/layout.tsx +22 -0
- package/template/src/app/(auth)/login/page.tsx +18 -0
- package/template/src/app/(auth)/register/page.tsx +20 -0
- package/template/src/app/api/admin/users/[id]/route.ts +40 -0
- package/template/src/app/api/admin/users/route.ts +18 -0
- package/template/src/app/api/auth/login/route.ts +26 -0
- package/template/src/app/api/auth/logout/route.ts +21 -0
- package/template/src/app/api/auth/me/route.ts +19 -0
- package/template/src/app/api/auth/register/route.ts +40 -0
- package/template/src/app/api/health/route.ts +27 -0
- package/template/src/app/favicon.ico +0 -0
- package/template/src/app/forbidden/page.tsx +49 -0
- package/template/src/app/globals.css +142 -0
- package/template/src/app/layout.tsx +52 -0
- package/template/src/app/not-found.tsx +18 -0
- package/template/src/app/page.tsx +187 -0
- package/template/src/components/admin/users-table.tsx +162 -0
- package/template/src/components/auth/auth-card.tsx +41 -0
- package/template/src/components/auth/can.tsx +34 -0
- package/template/src/components/auth/form-field.tsx +32 -0
- package/template/src/components/auth/login-form.tsx +82 -0
- package/template/src/components/auth/register-form.tsx +114 -0
- package/template/src/components/auth/session-refresher.tsx +44 -0
- package/template/src/components/layout/logout-button.tsx +34 -0
- package/template/src/components/layout/navbar.tsx +67 -0
- package/template/src/components/layout/page-header.tsx +21 -0
- package/template/src/components/layout/skeletons.tsx +35 -0
- package/template/src/components/logo.tsx +19 -0
- package/template/src/components/motion/fade-in.tsx +19 -0
- package/template/src/components/providers/user-provider.tsx +60 -0
- package/template/src/components/reports/animated-bar.tsx +28 -0
- package/template/src/components/role-badge.tsx +17 -0
- package/template/src/components/theme-toggle.tsx +25 -0
- package/template/src/components/ui/badge.tsx +44 -0
- package/template/src/components/ui/button.tsx +66 -0
- package/template/src/components/ui/card.tsx +87 -0
- package/template/src/components/ui/input.tsx +18 -0
- package/template/src/components/ui/label.tsx +20 -0
- package/template/src/components/ui/native-select.tsx +54 -0
- package/template/src/components/ui/skeleton.tsx +13 -0
- package/template/src/config/rbac.ts +140 -0
- package/template/src/config/site.ts +4 -0
- package/template/src/lib/api.ts +143 -0
- package/template/src/lib/auth.ts +42 -0
- package/template/src/lib/dal.ts +60 -0
- package/template/src/lib/db.ts +35 -0
- package/template/src/lib/env.ts +36 -0
- package/template/src/lib/http.ts +57 -0
- package/template/src/lib/redirect.ts +21 -0
- package/template/src/lib/session.ts +67 -0
- package/template/src/lib/theme.ts +8 -0
- package/template/src/lib/users.ts +159 -0
- package/template/src/lib/utils.ts +1 -0
- package/template/src/lib/validations/auth.ts +44 -0
- package/template/src/lib/validations/user.ts +13 -0
- package/template/src/models/user.ts +30 -0
- package/template/src/proxy.ts +57 -0
- package/template/src/types/user.ts +10 -0
- package/template/tsconfig.json +34 -0
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import * as React from "react";
|
|
2
|
+
import { cva, type VariantProps } from "class-variance-authority";
|
|
3
|
+
import { cn } from "@/lib/utils";
|
|
4
|
+
import { Slot } from "radix-ui";
|
|
5
|
+
|
|
6
|
+
const buttonVariants = cva(
|
|
7
|
+
"group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 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",
|
|
8
|
+
{
|
|
9
|
+
variants: {
|
|
10
|
+
variant: {
|
|
11
|
+
default: "bg-primary text-primary-foreground hover:bg-primary/80",
|
|
12
|
+
outline:
|
|
13
|
+
"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
|
14
|
+
secondary:
|
|
15
|
+
"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
|
|
16
|
+
ghost:
|
|
17
|
+
"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
|
|
18
|
+
destructive:
|
|
19
|
+
"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
|
|
20
|
+
link: "text-primary underline-offset-4 hover:underline",
|
|
21
|
+
},
|
|
22
|
+
size: {
|
|
23
|
+
default:
|
|
24
|
+
"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
|
25
|
+
xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
|
|
26
|
+
sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
|
|
27
|
+
lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
|
28
|
+
icon: "size-8",
|
|
29
|
+
"icon-xs":
|
|
30
|
+
"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
|
|
31
|
+
"icon-sm":
|
|
32
|
+
"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
|
|
33
|
+
"icon-lg": "size-9",
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
defaultVariants: {
|
|
37
|
+
variant: "default",
|
|
38
|
+
size: "default",
|
|
39
|
+
},
|
|
40
|
+
},
|
|
41
|
+
);
|
|
42
|
+
|
|
43
|
+
function Button({
|
|
44
|
+
className,
|
|
45
|
+
variant = "default",
|
|
46
|
+
size = "default",
|
|
47
|
+
asChild = false,
|
|
48
|
+
...props
|
|
49
|
+
}: React.ComponentProps<"button"> &
|
|
50
|
+
VariantProps<typeof buttonVariants> & {
|
|
51
|
+
asChild?: boolean;
|
|
52
|
+
}) {
|
|
53
|
+
const Comp = asChild ? Slot.Root : "button";
|
|
54
|
+
|
|
55
|
+
return (
|
|
56
|
+
<Comp
|
|
57
|
+
data-slot="button"
|
|
58
|
+
data-variant={variant}
|
|
59
|
+
data-size={size}
|
|
60
|
+
className={cn(buttonVariants({ variant, size, className }))}
|
|
61
|
+
{...props}
|
|
62
|
+
/>
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export { Button, buttonVariants };
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import * as React from "react";
|
|
2
|
+
import { cn } from "@/lib/utils";
|
|
3
|
+
|
|
4
|
+
function Card({
|
|
5
|
+
className,
|
|
6
|
+
size = "default",
|
|
7
|
+
...props
|
|
8
|
+
}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {
|
|
9
|
+
return (
|
|
10
|
+
<div
|
|
11
|
+
data-slot="card"
|
|
12
|
+
data-size={size}
|
|
13
|
+
className={cn(
|
|
14
|
+
"group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl bg-card py-(--card-spacing) text-sm text-card-foreground ring-1 ring-foreground/10 [--card-spacing:--spacing(4)] has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
|
|
15
|
+
className,
|
|
16
|
+
)}
|
|
17
|
+
{...props}
|
|
18
|
+
/>
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
|
23
|
+
return (
|
|
24
|
+
<div
|
|
25
|
+
data-slot="card-header"
|
|
26
|
+
className={cn(
|
|
27
|
+
"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-(--card-spacing) has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-(--card-spacing)",
|
|
28
|
+
className,
|
|
29
|
+
)}
|
|
30
|
+
{...props}
|
|
31
|
+
/>
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
|
36
|
+
return (
|
|
37
|
+
<div
|
|
38
|
+
data-slot="card-title"
|
|
39
|
+
className={cn(
|
|
40
|
+
"font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",
|
|
41
|
+
className,
|
|
42
|
+
)}
|
|
43
|
+
{...props}
|
|
44
|
+
/>
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
|
49
|
+
return (
|
|
50
|
+
<div
|
|
51
|
+
data-slot="card-description"
|
|
52
|
+
className={cn("text-sm text-muted-foreground", className)}
|
|
53
|
+
{...props}
|
|
54
|
+
/>
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
|
59
|
+
return (
|
|
60
|
+
<div
|
|
61
|
+
data-slot="card-action"
|
|
62
|
+
className={cn("col-start-2 row-span-2 row-start-1 self-start justify-self-end", className)}
|
|
63
|
+
{...props}
|
|
64
|
+
/>
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
|
69
|
+
return (
|
|
70
|
+
<div data-slot="card-content" className={cn("px-(--card-spacing)", className)} {...props} />
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
|
75
|
+
return (
|
|
76
|
+
<div
|
|
77
|
+
data-slot="card-footer"
|
|
78
|
+
className={cn(
|
|
79
|
+
"flex items-center rounded-b-xl border-t bg-muted/50 p-(--card-spacing)",
|
|
80
|
+
className,
|
|
81
|
+
)}
|
|
82
|
+
{...props}
|
|
83
|
+
/>
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription, CardContent };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import * as React from "react";
|
|
2
|
+
import { cn } from "@/lib/utils";
|
|
3
|
+
|
|
4
|
+
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
|
5
|
+
return (
|
|
6
|
+
<input
|
|
7
|
+
type={type}
|
|
8
|
+
data-slot="input"
|
|
9
|
+
className={cn(
|
|
10
|
+
"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
|
|
11
|
+
className,
|
|
12
|
+
)}
|
|
13
|
+
{...props}
|
|
14
|
+
/>
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export { Input };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
import * as React from "react";
|
|
4
|
+
import { cn } from "@/lib/utils";
|
|
5
|
+
import { Label as LabelPrimitive } from "radix-ui";
|
|
6
|
+
|
|
7
|
+
function Label({ className, ...props }: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
|
8
|
+
return (
|
|
9
|
+
<LabelPrimitive.Root
|
|
10
|
+
data-slot="label"
|
|
11
|
+
className={cn(
|
|
12
|
+
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
|
13
|
+
className,
|
|
14
|
+
)}
|
|
15
|
+
{...props}
|
|
16
|
+
/>
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export { Label };
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import * as React from "react";
|
|
2
|
+
import { cn } from "@/lib/utils";
|
|
3
|
+
import { ChevronDownIcon } from "lucide-react";
|
|
4
|
+
|
|
5
|
+
type NativeSelectProps = Omit<React.ComponentProps<"select">, "size"> & {
|
|
6
|
+
size?: "sm" | "default";
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
function NativeSelect({ className, size = "default", ...props }: NativeSelectProps) {
|
|
10
|
+
return (
|
|
11
|
+
<div
|
|
12
|
+
className={cn(
|
|
13
|
+
"group/native-select relative w-fit has-[select:disabled]:opacity-50",
|
|
14
|
+
className,
|
|
15
|
+
)}
|
|
16
|
+
data-slot="native-select-wrapper"
|
|
17
|
+
data-size={size}
|
|
18
|
+
>
|
|
19
|
+
<select
|
|
20
|
+
data-slot="native-select"
|
|
21
|
+
data-size={size}
|
|
22
|
+
className="h-8 w-full min-w-0 appearance-none rounded-lg border border-input bg-transparent py-1 pr-8 pl-2.5 text-sm transition-colors outline-none select-none selection:bg-primary selection:text-primary-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] data-[size=sm]:py-0.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40"
|
|
23
|
+
{...props}
|
|
24
|
+
/>
|
|
25
|
+
<ChevronDownIcon
|
|
26
|
+
className="pointer-events-none absolute top-1/2 right-2.5 size-4 -translate-y-1/2 text-muted-foreground select-none"
|
|
27
|
+
aria-hidden="true"
|
|
28
|
+
data-slot="native-select-icon"
|
|
29
|
+
/>
|
|
30
|
+
</div>
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function NativeSelectOption({ className, ...props }: React.ComponentProps<"option">) {
|
|
35
|
+
return (
|
|
36
|
+
<option
|
|
37
|
+
data-slot="native-select-option"
|
|
38
|
+
className={cn("bg-[Canvas] text-[CanvasText]", className)}
|
|
39
|
+
{...props}
|
|
40
|
+
/>
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function NativeSelectOptGroup({ className, ...props }: React.ComponentProps<"optgroup">) {
|
|
45
|
+
return (
|
|
46
|
+
<optgroup
|
|
47
|
+
data-slot="native-select-optgroup"
|
|
48
|
+
className={cn("bg-[Canvas] text-[CanvasText]", className)}
|
|
49
|
+
{...props}
|
|
50
|
+
/>
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export { NativeSelect, NativeSelectOptGroup, NativeSelectOption };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { cn } from "@/lib/utils";
|
|
2
|
+
|
|
3
|
+
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
|
4
|
+
return (
|
|
5
|
+
<div
|
|
6
|
+
data-slot="skeleton"
|
|
7
|
+
className={cn("animate-pulse rounded-md bg-muted", className)}
|
|
8
|
+
{...props}
|
|
9
|
+
/>
|
|
10
|
+
);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export { Skeleton };
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Role-based access control: the single source of truth.
|
|
3
|
+
*
|
|
4
|
+
* This file is imported by the proxy, the server (DAL + API routes) AND the
|
|
5
|
+
* client (navbar, <Can>), so it must stay free of server-only imports.
|
|
6
|
+
*
|
|
7
|
+
* To add a role: add it to ROLES (lowest -> highest) and ROLE_PERMISSIONS.
|
|
8
|
+
* To add a permission: add it to PERMISSIONS and grant it in ROLE_PERMISSIONS.
|
|
9
|
+
* To protect a page: add a ROUTE_RULES entry + call requirePermission() in the page.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** Ordered from least to most privileged. */
|
|
13
|
+
export const ROLES = ["user", "manager", "admin"] as const;
|
|
14
|
+
export type Role = (typeof ROLES)[number];
|
|
15
|
+
|
|
16
|
+
/** Role given to every new account (except the very first one, which becomes admin). */
|
|
17
|
+
export const DEFAULT_ROLE: Role = "user";
|
|
18
|
+
/** Role given to the first registered account. */
|
|
19
|
+
export const FIRST_USER_ROLE: Role = "admin";
|
|
20
|
+
|
|
21
|
+
export const PERMISSIONS = [
|
|
22
|
+
"dashboard:view",
|
|
23
|
+
"reports:view",
|
|
24
|
+
"users:read",
|
|
25
|
+
"users:update-role",
|
|
26
|
+
"users:delete",
|
|
27
|
+
] as const;
|
|
28
|
+
export type Permission = (typeof PERMISSIONS)[number];
|
|
29
|
+
|
|
30
|
+
export const ROLE_PERMISSIONS: Record<Role, readonly Permission[]> = {
|
|
31
|
+
user: ["dashboard:view"],
|
|
32
|
+
manager: ["dashboard:view", "reports:view", "users:read"],
|
|
33
|
+
admin: ["dashboard:view", "reports:view", "users:read", "users:update-role", "users:delete"],
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export const ROLE_LABELS: Record<Role, string> = {
|
|
37
|
+
user: "User",
|
|
38
|
+
manager: "Manager",
|
|
39
|
+
admin: "Admin",
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export const PERMISSION_LABELS: Record<Permission, string> = {
|
|
43
|
+
"dashboard:view": "View the dashboard",
|
|
44
|
+
"reports:view": "View reports",
|
|
45
|
+
"users:read": "View all users",
|
|
46
|
+
"users:update-role": "Change user roles",
|
|
47
|
+
"users:delete": "Delete users",
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
export function isRole(value: unknown): value is Role {
|
|
51
|
+
return typeof value === "string" && (ROLES as readonly string[]).includes(value);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function hasPermission(role: Role | null | undefined, permission: Permission): boolean {
|
|
55
|
+
if (!role) return false;
|
|
56
|
+
return ROLE_PERMISSIONS[role]?.includes(permission) ?? false;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function getPermissions(role: Role): readonly Permission[] {
|
|
60
|
+
return ROLE_PERMISSIONS[role] ?? [];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Position of a role in the hierarchy (higher = more privileged). */
|
|
64
|
+
export function roleRank(role: Role): number {
|
|
65
|
+
return ROLES.indexOf(role);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function isRoleAtLeast(role: Role, minimum: Role): boolean {
|
|
69
|
+
return roleRank(role) >= roleRank(minimum);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ---------------------------------------------------------------------------
|
|
73
|
+
// Routes
|
|
74
|
+
// ---------------------------------------------------------------------------
|
|
75
|
+
|
|
76
|
+
export type RouteRule = {
|
|
77
|
+
/** Path prefix, matched on segment boundaries ("/admin" matches "/admin/x" but not "/administrator"). */
|
|
78
|
+
prefix: string;
|
|
79
|
+
permission: Permission;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Pages that require a permission. The longest matching prefix wins, so you can
|
|
84
|
+
* tighten sub-routes, e.g. { prefix: "/admin/billing", permission: "users:delete" }.
|
|
85
|
+
* API routes are protected separately with withAuth() (see src/lib/api.ts).
|
|
86
|
+
*/
|
|
87
|
+
export const ROUTE_RULES: readonly RouteRule[] = [
|
|
88
|
+
{ prefix: "/dashboard", permission: "dashboard:view" },
|
|
89
|
+
{ prefix: "/reports", permission: "reports:view" },
|
|
90
|
+
{ prefix: "/admin", permission: "users:read" },
|
|
91
|
+
];
|
|
92
|
+
|
|
93
|
+
/** Pages only for signed-out visitors; signed-in users are sent to AFTER_LOGIN_PATH. */
|
|
94
|
+
export const GUEST_ONLY_ROUTES: readonly string[] = ["/login", "/register"];
|
|
95
|
+
|
|
96
|
+
export const LOGIN_PATH = "/login";
|
|
97
|
+
export const AFTER_LOGIN_PATH = "/dashboard";
|
|
98
|
+
export const FORBIDDEN_PATH = "/forbidden";
|
|
99
|
+
|
|
100
|
+
function matchesPrefix(pathname: string, prefix: string): boolean {
|
|
101
|
+
return pathname === prefix || pathname.startsWith(prefix.endsWith("/") ? prefix : `${prefix}/`);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Returns the most specific rule protecting `pathname`, or null if the route is public. */
|
|
105
|
+
export function getRouteRule(pathname: string): RouteRule | null {
|
|
106
|
+
let match: RouteRule | null = null;
|
|
107
|
+
for (const rule of ROUTE_RULES) {
|
|
108
|
+
if (
|
|
109
|
+
matchesPrefix(pathname, rule.prefix) &&
|
|
110
|
+
(!match || rule.prefix.length > match.prefix.length)
|
|
111
|
+
) {
|
|
112
|
+
match = rule;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return match;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function isGuestOnlyRoute(pathname: string): boolean {
|
|
119
|
+
return GUEST_ONLY_ROUTES.some((route) => matchesPrefix(pathname, route));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// ---------------------------------------------------------------------------
|
|
123
|
+
// Navigation
|
|
124
|
+
// ---------------------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
export type NavItem = {
|
|
127
|
+
href: string;
|
|
128
|
+
label: string;
|
|
129
|
+
permission: Permission;
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
export const NAV_ITEMS: readonly NavItem[] = [
|
|
133
|
+
{ href: "/dashboard", label: "Dashboard", permission: "dashboard:view" },
|
|
134
|
+
{ href: "/reports", label: "Reports", permission: "reports:view" },
|
|
135
|
+
{ href: "/admin", label: "Admin", permission: "users:read" },
|
|
136
|
+
];
|
|
137
|
+
|
|
138
|
+
export function getNavItems(role: Role): NavItem[] {
|
|
139
|
+
return NAV_ITEMS.filter((item) => hasPermission(role, item.permission));
|
|
140
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
|
|
3
|
+
import { unstable_rethrow } from "next/navigation";
|
|
4
|
+
import { NextResponse, type NextRequest } from "next/server";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
|
|
7
|
+
import { hasPermission, type Permission } from "@/config/rbac";
|
|
8
|
+
import { getCurrentUser } from "@/lib/dal";
|
|
9
|
+
import type { PublicUser } from "@/types/user";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* API helpers: layer 3 of the RBAC model.
|
|
13
|
+
*
|
|
14
|
+
* Every error leaves the API in the same JSON shape:
|
|
15
|
+
* { "error": { "code": "FORBIDDEN", "message": "...", "details"?: ... } }
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
export type ApiErrorBody = {
|
|
19
|
+
error: { code: string; message: string; details?: unknown };
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export class ApiError extends Error {
|
|
23
|
+
readonly status: number;
|
|
24
|
+
readonly code: string;
|
|
25
|
+
readonly details?: unknown;
|
|
26
|
+
|
|
27
|
+
constructor(status: number, message: string, code = "BAD_REQUEST", details?: unknown) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.name = "ApiError";
|
|
30
|
+
this.status = status;
|
|
31
|
+
this.code = code;
|
|
32
|
+
this.details = details;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
static badRequest(message = "Bad request", code = "BAD_REQUEST", details?: unknown) {
|
|
36
|
+
return new ApiError(400, message, code, details);
|
|
37
|
+
}
|
|
38
|
+
static unauthorized(message = "Authentication required") {
|
|
39
|
+
return new ApiError(401, message, "UNAUTHENTICATED");
|
|
40
|
+
}
|
|
41
|
+
static forbidden(message = "You don't have permission to perform this action") {
|
|
42
|
+
return new ApiError(403, message, "FORBIDDEN");
|
|
43
|
+
}
|
|
44
|
+
static notFound(message = "Not found") {
|
|
45
|
+
return new ApiError(404, message, "NOT_FOUND");
|
|
46
|
+
}
|
|
47
|
+
static conflict(message: string) {
|
|
48
|
+
return new ApiError(409, message, "CONFLICT");
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function errorResponse(status: number, code: string, message: string, details?: unknown) {
|
|
53
|
+
const body: ApiErrorBody = {
|
|
54
|
+
error: { code, message, ...(details !== undefined && { details }) },
|
|
55
|
+
};
|
|
56
|
+
return NextResponse.json(body, { status });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function handleApiError(error: unknown): NextResponse<ApiErrorBody> {
|
|
60
|
+
if (error instanceof ApiError) {
|
|
61
|
+
return errorResponse(error.status, error.code, error.message, error.details);
|
|
62
|
+
}
|
|
63
|
+
if (error instanceof z.ZodError) {
|
|
64
|
+
return errorResponse(
|
|
65
|
+
422,
|
|
66
|
+
"VALIDATION_ERROR",
|
|
67
|
+
"Validation failed",
|
|
68
|
+
z.flattenError(error).fieldErrors,
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
console.error("[api] Unhandled error:", error);
|
|
72
|
+
return errorResponse(500, "INTERNAL_ERROR", "Something went wrong. Please try again.");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Parses and validates a JSON body. Throws ApiError (400 invalid JSON / 422 validation). */
|
|
76
|
+
export async function parseBody<S extends z.ZodType>(
|
|
77
|
+
req: Request,
|
|
78
|
+
schema: S,
|
|
79
|
+
): Promise<z.output<S>> {
|
|
80
|
+
let json: unknown;
|
|
81
|
+
try {
|
|
82
|
+
json = await req.json();
|
|
83
|
+
} catch {
|
|
84
|
+
throw ApiError.badRequest("Request body must be valid JSON", "INVALID_JSON");
|
|
85
|
+
}
|
|
86
|
+
const result = schema.safeParse(json);
|
|
87
|
+
if (!result.success) {
|
|
88
|
+
throw new ApiError(
|
|
89
|
+
422,
|
|
90
|
+
"Validation failed",
|
|
91
|
+
"VALIDATION_ERROR",
|
|
92
|
+
z.flattenError(result.error).fieldErrors,
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
return result.data;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
type Awaitable<T> = T | Promise<T>;
|
|
99
|
+
|
|
100
|
+
/** Wraps a public route handler so thrown errors become consistent JSON responses. */
|
|
101
|
+
export function apiHandler<Ctx = unknown>(
|
|
102
|
+
handler: (req: NextRequest, ctx: Ctx) => Awaitable<Response>,
|
|
103
|
+
) {
|
|
104
|
+
return async (req: NextRequest, ctx: Ctx): Promise<Response> => {
|
|
105
|
+
try {
|
|
106
|
+
return await handler(req, ctx);
|
|
107
|
+
} catch (error) {
|
|
108
|
+
// Let Next.js handle its own control-flow errors (redirect(), notFound(),
|
|
109
|
+
// and request-time APIs like cookies() bailing out of prerendering).
|
|
110
|
+
unstable_rethrow(error);
|
|
111
|
+
return handleApiError(error);
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export type WithAuthOptions = {
|
|
117
|
+
/** Required permission. Omit to only require a signed-in user. */
|
|
118
|
+
permission?: Permission;
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Protects a route handler. Loads the user from the DB (not just the JWT), then
|
|
123
|
+
* responds 401 if signed out or 403 if the role lacks `permission`.
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* export const DELETE = withAuth<RouteContext<"/api/posts/[id]">>(
|
|
127
|
+
* async (req, ctx, user) => { const { id } = await ctx.params; ... },
|
|
128
|
+
* { permission: "posts:delete" },
|
|
129
|
+
* );
|
|
130
|
+
*/
|
|
131
|
+
export function withAuth<Ctx = unknown>(
|
|
132
|
+
handler: (req: NextRequest, ctx: Ctx, user: PublicUser) => Awaitable<Response>,
|
|
133
|
+
options: WithAuthOptions = {},
|
|
134
|
+
) {
|
|
135
|
+
return apiHandler<Ctx>(async (req, ctx) => {
|
|
136
|
+
const user = await getCurrentUser();
|
|
137
|
+
if (!user) throw ApiError.unauthorized();
|
|
138
|
+
if (options.permission && !hasPermission(user.role, options.permission)) {
|
|
139
|
+
throw ApiError.forbidden();
|
|
140
|
+
}
|
|
141
|
+
return handler(req, ctx, user);
|
|
142
|
+
});
|
|
143
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
|
|
3
|
+
import bcrypt from "bcryptjs";
|
|
4
|
+
import { cookies } from "next/headers";
|
|
5
|
+
|
|
6
|
+
import {
|
|
7
|
+
SESSION_COOKIE,
|
|
8
|
+
sessionCookieOptions,
|
|
9
|
+
signSession,
|
|
10
|
+
type SessionPayload,
|
|
11
|
+
} from "@/lib/session";
|
|
12
|
+
|
|
13
|
+
export const BCRYPT_COST = 12;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* A valid bcrypt hash (cost 12) of a random string. When a login email doesn't
|
|
17
|
+
* exist we still compare against this, so the response takes the same time
|
|
18
|
+
* whether or not the account exists (prevents email enumeration via timing).
|
|
19
|
+
*/
|
|
20
|
+
const DUMMY_HASH = "$2b$12$3gk0gygzL252unva9MPTyOsJydBQd/B/bR7NtN/cfa4/RKniIXk1K";
|
|
21
|
+
|
|
22
|
+
export function hashPassword(password: string): Promise<string> {
|
|
23
|
+
return bcrypt.hash(password, BCRYPT_COST);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Constant-time-ish check: always runs one bcrypt comparison. */
|
|
27
|
+
export function verifyPassword(
|
|
28
|
+
password: string,
|
|
29
|
+
hash: string | null | undefined,
|
|
30
|
+
): Promise<boolean> {
|
|
31
|
+
return bcrypt.compare(password, hash ?? DUMMY_HASH).then((ok) => ok && Boolean(hash));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Signs a session JWT and stores it in the httpOnly cookie (Route Handlers / Server Actions only). */
|
|
35
|
+
export async function setSessionCookie(payload: SessionPayload): Promise<void> {
|
|
36
|
+
const token = await signSession(payload);
|
|
37
|
+
(await cookies()).set(SESSION_COOKIE, token, sessionCookieOptions());
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function clearSessionCookie(): Promise<void> {
|
|
41
|
+
(await cookies()).set(SESSION_COOKIE, "", { ...sessionCookieOptions(), maxAge: 0 });
|
|
42
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
|
|
3
|
+
import { cookies } from "next/headers";
|
|
4
|
+
import { redirect } from "next/navigation";
|
|
5
|
+
import { cache } from "react";
|
|
6
|
+
|
|
7
|
+
import { FORBIDDEN_PATH, hasPermission, LOGIN_PATH, type Permission } from "@/config/rbac";
|
|
8
|
+
import { SESSION_COOKIE, verifySession } from "@/lib/session";
|
|
9
|
+
import { findUserById } from "@/lib/users";
|
|
10
|
+
import type { PublicUser } from "@/types/user";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Data Access Layer: layer 2 of the RBAC model.
|
|
14
|
+
*
|
|
15
|
+
* The proxy only checks the JWT (fast but possibly stale). These helpers
|
|
16
|
+
* re-read the user from MongoDB, the source of truth, so role changes and
|
|
17
|
+
* deleted accounts take effect on the very next request.
|
|
18
|
+
*
|
|
19
|
+
* Call them from Server Components, Route Handlers and Server Actions. Any
|
|
20
|
+
* component that calls them must render inside a <Suspense> boundary
|
|
21
|
+
* (they read cookies, which is request-time data under Cache Components).
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** Visited when a token is valid but its user no longer exists: clears the cookie, then goes to /login. */
|
|
25
|
+
const STALE_SESSION_PATH = "/api/auth/logout";
|
|
26
|
+
|
|
27
|
+
/** Decoded JWT from the session cookie (not re-validated against the DB). Deduped per request. */
|
|
28
|
+
export const getSession = cache(async () => {
|
|
29
|
+
const token = (await cookies()).get(SESSION_COOKIE)?.value;
|
|
30
|
+
return verifySession(token);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
/** The signed-in user, freshly loaded from the database, or null. Deduped per request. */
|
|
34
|
+
export const getCurrentUser = cache(async (): Promise<PublicUser | null> => {
|
|
35
|
+
const session = await getSession();
|
|
36
|
+
if (!session) return null;
|
|
37
|
+
return findUserById(session.sub);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
/** Returns the current user or redirects to the login page. */
|
|
41
|
+
export async function requireUser(): Promise<PublicUser> {
|
|
42
|
+
const session = await getSession();
|
|
43
|
+
if (!session) redirect(LOGIN_PATH);
|
|
44
|
+
const user = await getCurrentUser();
|
|
45
|
+
if (!user) redirect(STALE_SESSION_PATH);
|
|
46
|
+
return user;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Returns the current user if they have `permission`, otherwise redirects to /forbidden. */
|
|
50
|
+
export async function requirePermission(permission: Permission): Promise<PublicUser> {
|
|
51
|
+
const user = await requireUser();
|
|
52
|
+
if (!hasPermission(user.role, permission)) redirect(FORBIDDEN_PATH);
|
|
53
|
+
return user;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** True when the JWT's role/name no longer match the database (e.g. an admin changed the role). */
|
|
57
|
+
export async function isSessionStale(user: PublicUser): Promise<boolean> {
|
|
58
|
+
const session = await getSession();
|
|
59
|
+
return !!session && (session.role !== user.role || session.name !== user.name);
|
|
60
|
+
}
|