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.
Files changed (82) hide show
  1. package/README.md +108 -2
  2. package/index.js +399 -0
  3. package/package.json +36 -4
  4. package/template/AGENTS.md +9 -0
  5. package/template/Dockerfile +48 -0
  6. package/template/README.md +262 -0
  7. package/template/_dockerignore +13 -0
  8. package/template/_env.example +11 -0
  9. package/template/_gitignore +42 -0
  10. package/template/_prettierignore +11 -0
  11. package/template/_prettierrc +9 -0
  12. package/template/components.json +25 -0
  13. package/template/docker-compose.yml +33 -0
  14. package/template/eslint.config.mjs +21 -0
  15. package/template/next.config.ts +45 -0
  16. package/template/package.json +53 -0
  17. package/template/public/robots.txt +6 -0
  18. package/template/src/app/(app)/admin/page.tsx +53 -0
  19. package/template/src/app/(app)/dashboard/page.tsx +127 -0
  20. package/template/src/app/(app)/error.tsx +28 -0
  21. package/template/src/app/(app)/layout.tsx +35 -0
  22. package/template/src/app/(app)/loading.tsx +5 -0
  23. package/template/src/app/(app)/reports/page.tsx +109 -0
  24. package/template/src/app/(auth)/layout.tsx +22 -0
  25. package/template/src/app/(auth)/login/page.tsx +18 -0
  26. package/template/src/app/(auth)/register/page.tsx +20 -0
  27. package/template/src/app/api/admin/users/[id]/route.ts +40 -0
  28. package/template/src/app/api/admin/users/route.ts +18 -0
  29. package/template/src/app/api/auth/login/route.ts +26 -0
  30. package/template/src/app/api/auth/logout/route.ts +21 -0
  31. package/template/src/app/api/auth/me/route.ts +19 -0
  32. package/template/src/app/api/auth/register/route.ts +40 -0
  33. package/template/src/app/api/health/route.ts +27 -0
  34. package/template/src/app/favicon.ico +0 -0
  35. package/template/src/app/forbidden/page.tsx +49 -0
  36. package/template/src/app/globals.css +142 -0
  37. package/template/src/app/layout.tsx +52 -0
  38. package/template/src/app/not-found.tsx +18 -0
  39. package/template/src/app/page.tsx +187 -0
  40. package/template/src/components/admin/users-table.tsx +162 -0
  41. package/template/src/components/auth/auth-card.tsx +41 -0
  42. package/template/src/components/auth/can.tsx +34 -0
  43. package/template/src/components/auth/form-field.tsx +32 -0
  44. package/template/src/components/auth/login-form.tsx +82 -0
  45. package/template/src/components/auth/register-form.tsx +114 -0
  46. package/template/src/components/auth/session-refresher.tsx +44 -0
  47. package/template/src/components/layout/logout-button.tsx +34 -0
  48. package/template/src/components/layout/navbar.tsx +67 -0
  49. package/template/src/components/layout/page-header.tsx +21 -0
  50. package/template/src/components/layout/skeletons.tsx +35 -0
  51. package/template/src/components/logo.tsx +19 -0
  52. package/template/src/components/motion/fade-in.tsx +19 -0
  53. package/template/src/components/providers/user-provider.tsx +60 -0
  54. package/template/src/components/reports/animated-bar.tsx +28 -0
  55. package/template/src/components/role-badge.tsx +17 -0
  56. package/template/src/components/theme-toggle.tsx +25 -0
  57. package/template/src/components/ui/badge.tsx +44 -0
  58. package/template/src/components/ui/button.tsx +66 -0
  59. package/template/src/components/ui/card.tsx +87 -0
  60. package/template/src/components/ui/input.tsx +18 -0
  61. package/template/src/components/ui/label.tsx +20 -0
  62. package/template/src/components/ui/native-select.tsx +54 -0
  63. package/template/src/components/ui/skeleton.tsx +13 -0
  64. package/template/src/config/rbac.ts +140 -0
  65. package/template/src/config/site.ts +4 -0
  66. package/template/src/lib/api.ts +143 -0
  67. package/template/src/lib/auth.ts +42 -0
  68. package/template/src/lib/dal.ts +60 -0
  69. package/template/src/lib/db.ts +35 -0
  70. package/template/src/lib/env.ts +36 -0
  71. package/template/src/lib/http.ts +57 -0
  72. package/template/src/lib/redirect.ts +21 -0
  73. package/template/src/lib/session.ts +67 -0
  74. package/template/src/lib/theme.ts +8 -0
  75. package/template/src/lib/users.ts +159 -0
  76. package/template/src/lib/utils.ts +1 -0
  77. package/template/src/lib/validations/auth.ts +44 -0
  78. package/template/src/lib/validations/user.ts +13 -0
  79. package/template/src/models/user.ts +30 -0
  80. package/template/src/proxy.ts +57 -0
  81. package/template/src/types/user.ts +10 -0
  82. package/template/tsconfig.json +34 -0
@@ -0,0 +1,35 @@
1
+ import "server-only";
2
+
3
+ import mongoose from "mongoose";
4
+
5
+ import { env } from "@/lib/env";
6
+
7
+ type MongooseCache = {
8
+ conn: typeof mongoose | null;
9
+ promise: Promise<typeof mongoose> | null;
10
+ };
11
+
12
+ /**
13
+ * Cache the connection on globalThis so hot reloads in development (and
14
+ * concurrent requests in production) reuse one connection pool instead of
15
+ * opening a new one each time.
16
+ */
17
+ const globalForMongoose = globalThis as typeof globalThis & { __mongoose?: MongooseCache };
18
+ const cached: MongooseCache = (globalForMongoose.__mongoose ??= { conn: null, promise: null });
19
+
20
+ export async function connectDB(): Promise<typeof mongoose> {
21
+ if (cached.conn) return cached.conn;
22
+
23
+ cached.promise ??= mongoose.connect(env().MONGODB_URI, {
24
+ bufferCommands: false,
25
+ serverSelectionTimeoutMS: 5_000,
26
+ });
27
+
28
+ try {
29
+ cached.conn = await cached.promise;
30
+ } catch (error) {
31
+ cached.promise = null; // allow the next request to retry
32
+ throw error;
33
+ }
34
+ return cached.conn;
35
+ }
@@ -0,0 +1,36 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * Server environment variables, validated with zod.
5
+ *
6
+ * Validation is lazy (on first use, not at import time) so `next build` and
7
+ * the Docker build work without any secrets present. Never import this from
8
+ * a Client Component: these values must stay on the server.
9
+ */
10
+ const envSchema = z.object({
11
+ NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
12
+ MONGODB_URI: z
13
+ .string({ error: "MONGODB_URI is required" })
14
+ .regex(/^mongodb(\+srv)?:\/\//, "MONGODB_URI must start with mongodb:// or mongodb+srv://"),
15
+ JWT_SECRET: z
16
+ .string({ error: "JWT_SECRET is required" })
17
+ .min(32, "JWT_SECRET must be at least 32 characters long"),
18
+ });
19
+
20
+ export type Env = z.infer<typeof envSchema>;
21
+
22
+ let cached: Env | undefined;
23
+
24
+ export function env(): Env {
25
+ if (cached) return cached;
26
+ const parsed = envSchema.safeParse(process.env);
27
+ if (!parsed.success) {
28
+ throw new Error(
29
+ `Invalid environment variables (check .env.local):\n${z.prettifyError(parsed.error)}`,
30
+ );
31
+ }
32
+ cached = parsed.data;
33
+ return cached;
34
+ }
35
+
36
+ export const isProduction = () => process.env.NODE_ENV === "production";
@@ -0,0 +1,57 @@
1
+ import type { ApiErrorBody } from "@/lib/api";
2
+
3
+ /** Error thrown by apiFetch for non-2xx responses, carrying the API's error shape. */
4
+ export class HttpError extends Error {
5
+ readonly status: number;
6
+ readonly code?: string;
7
+ readonly details?: unknown;
8
+
9
+ constructor(status: number, message: string, code?: string, details?: unknown) {
10
+ super(message);
11
+ this.name = "HttpError";
12
+ this.status = status;
13
+ this.code = code;
14
+ this.details = details;
15
+ }
16
+
17
+ /** Field errors from a 422 VALIDATION_ERROR response, if any. */
18
+ get fieldErrors(): Record<string, string[] | undefined> | undefined {
19
+ return this.code === "VALIDATION_ERROR" && this.details && typeof this.details === "object"
20
+ ? (this.details as Record<string, string[] | undefined>)
21
+ : undefined;
22
+ }
23
+ }
24
+
25
+ type ApiFetchInit = Omit<RequestInit, "body"> & { json?: unknown };
26
+
27
+ /** Small fetch wrapper for the app's JSON API (client or server). */
28
+ export async function apiFetch<T>(
29
+ url: string,
30
+ { json, headers, ...init }: ApiFetchInit = {},
31
+ ): Promise<T> {
32
+ const res = await fetch(url, {
33
+ ...init,
34
+ headers: {
35
+ Accept: "application/json",
36
+ ...(json !== undefined && { "Content-Type": "application/json" }),
37
+ ...headers,
38
+ },
39
+ body: json !== undefined ? JSON.stringify(json) : undefined,
40
+ });
41
+
42
+ const data = (await res.json().catch(() => null)) as (T & Partial<ApiErrorBody>) | null;
43
+ if (!res.ok) {
44
+ const error = data?.error;
45
+ throw new HttpError(
46
+ res.status,
47
+ error?.message ?? res.statusText ?? "Request failed",
48
+ error?.code,
49
+ error?.details,
50
+ );
51
+ }
52
+ return data as T;
53
+ }
54
+
55
+ export function getErrorMessage(error: unknown, fallback = "Something went wrong"): string {
56
+ return error instanceof Error && error.message ? error.message : fallback;
57
+ }
@@ -0,0 +1,21 @@
1
+ import { AFTER_LOGIN_PATH, isGuestOnlyRoute } from "@/config/rbac";
2
+
3
+ /**
4
+ * Validates a `?next=` redirect target. Only same-origin relative paths are
5
+ * allowed, which prevents open redirects like `?next=//evil.com`.
6
+ */
7
+ export function safeRedirectPath(
8
+ value: string | null | undefined,
9
+ fallback = AFTER_LOGIN_PATH,
10
+ ): string {
11
+ if (!value || !value.startsWith("/") || value.startsWith("//") || value.startsWith("/\\")) {
12
+ return fallback;
13
+ }
14
+ try {
15
+ const url = new URL(value, "http://localhost");
16
+ if (url.origin !== "http://localhost" || isGuestOnlyRoute(url.pathname)) return fallback;
17
+ return url.pathname + url.search + url.hash;
18
+ } catch {
19
+ return fallback;
20
+ }
21
+ }
@@ -0,0 +1,67 @@
1
+ import { jwtVerify, SignJWT } from "jose";
2
+ import { z } from "zod";
3
+
4
+ import { ROLES, type Role } from "@/config/rbac";
5
+ import { env, isProduction } from "@/lib/env";
6
+
7
+ /**
8
+ * Stateless session tokens (JWT, HS256) stored in an httpOnly cookie.
9
+ *
10
+ * Used by the proxy (optimistic checks) and the server. It has no Node-only or
11
+ * `server-only` imports so it can run anywhere server code runs.
12
+ */
13
+
14
+ export const SESSION_COOKIE = "session";
15
+ export const SESSION_MAX_AGE = 60 * 60 * 24 * 7; // 7 days, in seconds
16
+
17
+ const ALGORITHM = "HS256";
18
+
19
+ const payloadSchema = z.object({
20
+ sub: z.string().min(1),
21
+ role: z.enum(ROLES),
22
+ name: z.string(),
23
+ });
24
+
25
+ export type SessionPayload = {
26
+ /** User id */
27
+ sub: string;
28
+ role: Role;
29
+ name: string;
30
+ };
31
+
32
+ function getKey() {
33
+ return new TextEncoder().encode(env().JWT_SECRET);
34
+ }
35
+
36
+ export async function signSession(payload: SessionPayload): Promise<string> {
37
+ return new SignJWT({ role: payload.role, name: payload.name })
38
+ .setProtectedHeader({ alg: ALGORITHM })
39
+ .setSubject(payload.sub)
40
+ .setIssuedAt()
41
+ .setExpirationTime(`${SESSION_MAX_AGE}s`)
42
+ .sign(getKey());
43
+ }
44
+
45
+ /** Returns the session payload, or null if the token is missing, invalid or expired. */
46
+ export async function verifySession(
47
+ token: string | undefined | null,
48
+ ): Promise<SessionPayload | null> {
49
+ if (!token) return null;
50
+ try {
51
+ const { payload } = await jwtVerify(token, getKey(), { algorithms: [ALGORITHM] });
52
+ const parsed = payloadSchema.safeParse(payload);
53
+ return parsed.success ? parsed.data : null;
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+
59
+ export function sessionCookieOptions() {
60
+ return {
61
+ httpOnly: true,
62
+ secure: isProduction(),
63
+ sameSite: "lax" as const,
64
+ path: "/",
65
+ maxAge: SESSION_MAX_AGE,
66
+ };
67
+ }
@@ -0,0 +1,8 @@
1
+ export const THEME_STORAGE_KEY = "theme";
2
+
3
+ /**
4
+ * Runs in <head> before first paint so the page never flashes the wrong theme.
5
+ * Uses the saved choice, falling back to the OS preference.
6
+ * See node_modules/next/dist/docs/01-app/02-guides/preventing-flash-before-hydration.md
7
+ */
8
+ export const themeScript = `(function(){try{var t=localStorage.getItem("${THEME_STORAGE_KEY}");var d=t?t==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches;document.documentElement.classList.toggle("dark",d)}catch(e){}})()`;
@@ -0,0 +1,159 @@
1
+ import "server-only";
2
+
3
+ import mongoose from "mongoose";
4
+
5
+ import { ROLES, type Role } from "@/config/rbac";
6
+ import { connectDB } from "@/lib/db";
7
+ import { User, type UserDocument } from "@/models/user";
8
+ import type { PublicUser } from "@/types/user";
9
+
10
+ /**
11
+ * User data access. Authorization is NOT done here: callers (DAL helpers,
12
+ * withAuth route handlers) must check permissions before calling these.
13
+ */
14
+
15
+ type UserLike = Pick<UserDocument, "_id" | "name" | "email" | "role"> & {
16
+ createdAt?: Date | string;
17
+ };
18
+
19
+ export function toPublicUser(user: UserLike): PublicUser {
20
+ return {
21
+ id: String(user._id),
22
+ name: user.name,
23
+ email: user.email,
24
+ role: user.role as Role,
25
+ createdAt: new Date(user.createdAt ?? Date.now()).toISOString(),
26
+ };
27
+ }
28
+
29
+ export function isValidId(id: string): boolean {
30
+ return mongoose.isValidObjectId(id) && /^[a-f0-9]{24}$/i.test(id);
31
+ }
32
+
33
+ export async function findUserById(id: string): Promise<PublicUser | null> {
34
+ if (!isValidId(id)) return null;
35
+ await connectDB();
36
+ const user = await User.findById(id).lean();
37
+ return user ? toPublicUser(user) : null;
38
+ }
39
+
40
+ export async function listUsers({ page = 1, limit = 50 } = {}): Promise<{
41
+ users: PublicUser[];
42
+ total: number;
43
+ }> {
44
+ await connectDB();
45
+ const [docs, total] = await Promise.all([
46
+ User.find()
47
+ .sort({ createdAt: -1 })
48
+ .skip((page - 1) * limit)
49
+ .limit(limit)
50
+ .lean(),
51
+ User.countDocuments(),
52
+ ]);
53
+ return { users: docs.map(toPublicUser), total };
54
+ }
55
+
56
+ export async function updateUserRole(id: string, role: Role): Promise<PublicUser | null> {
57
+ if (!isValidId(id)) return null;
58
+ await connectDB();
59
+ const user = await User.findByIdAndUpdate(
60
+ id,
61
+ { role },
62
+ { returnDocument: "after", runValidators: true },
63
+ ).lean();
64
+ return user ? toPublicUser(user) : null;
65
+ }
66
+
67
+ export async function deleteUser(id: string): Promise<boolean> {
68
+ if (!isValidId(id)) return false;
69
+ await connectDB();
70
+ const result = await User.deleteOne({ _id: id });
71
+ return result.deletedCount === 1;
72
+ }
73
+
74
+ export function isDuplicateKeyError(error: unknown): boolean {
75
+ return (
76
+ typeof error === "object" && error !== null && (error as { code?: unknown }).code === 11000
77
+ );
78
+ }
79
+
80
+ // ---------------------------------------------------------------------------
81
+ // First-user bootstrap
82
+ // ---------------------------------------------------------------------------
83
+
84
+ const META_COLLECTION = "app_meta";
85
+ const FIRST_ADMIN_KEY = "first-admin-claimed";
86
+
87
+ /**
88
+ * Atomically claims the "first user becomes admin" slot. Returns true for
89
+ * exactly one registration, even if several sign-ups race on an empty DB,
90
+ * because the insert of a fixed _id can only succeed once.
91
+ */
92
+ export async function claimFirstAdmin(): Promise<boolean> {
93
+ await connectDB();
94
+ if (await User.exists({})) return false;
95
+ try {
96
+ await mongoose.connection
97
+ .collection<{ _id: string; claimedAt: Date }>(META_COLLECTION)
98
+ .insertOne({ _id: FIRST_ADMIN_KEY, claimedAt: new Date() });
99
+ return true;
100
+ } catch (error) {
101
+ if (isDuplicateKeyError(error)) return false;
102
+ throw error;
103
+ }
104
+ }
105
+
106
+ /** Gives the claim back if creating the first user failed. */
107
+ export async function releaseFirstAdmin(): Promise<void> {
108
+ await connectDB();
109
+ await mongoose.connection
110
+ .collection<{ _id: string }>(META_COLLECTION)
111
+ .deleteOne({ _id: FIRST_ADMIN_KEY });
112
+ }
113
+
114
+ export type UserStats = {
115
+ total: number;
116
+ byRole: Record<Role, number>;
117
+ newLast7Days: number;
118
+ signupsByDay: { date: string; count: number }[];
119
+ };
120
+
121
+ export async function getUserStats(): Promise<UserStats> {
122
+ await connectDB();
123
+ const since = new Date();
124
+ since.setUTCHours(0, 0, 0, 0);
125
+ since.setUTCDate(since.getUTCDate() - 6);
126
+
127
+ const [roleCounts, daily] = await Promise.all([
128
+ User.aggregate<{ _id: Role; count: number }>([
129
+ { $group: { _id: "$role", count: { $sum: 1 } } },
130
+ ]),
131
+ User.aggregate<{ _id: string; count: number }>([
132
+ { $match: { createdAt: { $gte: since } } },
133
+ {
134
+ $group: {
135
+ _id: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt", timezone: "UTC" } },
136
+ count: { $sum: 1 },
137
+ },
138
+ },
139
+ ]),
140
+ ]);
141
+
142
+ const byRole = Object.fromEntries(ROLES.map((role) => [role, 0])) as Record<Role, number>;
143
+ for (const { _id, count } of roleCounts) if (_id in byRole) byRole[_id] = count;
144
+
145
+ const dailyMap = new Map(daily.map((d) => [d._id, d.count]));
146
+ const signupsByDay = Array.from({ length: 7 }, (_, i) => {
147
+ const day = new Date(since);
148
+ day.setUTCDate(since.getUTCDate() + i);
149
+ const key = day.toISOString().slice(0, 10);
150
+ return { date: key, count: dailyMap.get(key) ?? 0 };
151
+ });
152
+
153
+ return {
154
+ total: Object.values(byRole).reduce((a, b) => a + b, 0),
155
+ byRole,
156
+ newLast7Days: signupsByDay.reduce((a, d) => a + d.count, 0),
157
+ signupsByDay,
158
+ };
159
+ }
@@ -0,0 +1 @@
1
+ export { cn } from "cn";
@@ -0,0 +1,44 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * Schemas shared by the client (react-hook-form) and the server (API routes),
5
+ * so validation rules live in one place.
6
+ */
7
+
8
+ const email = z
9
+ .string()
10
+ .trim()
11
+ .toLowerCase()
12
+ .pipe(z.email("Enter a valid email address").max(254, "Email is too long"));
13
+
14
+ // bcrypt only uses the first 72 bytes of a password.
15
+ const password = z
16
+ .string()
17
+ .min(8, "Password must be at least 8 characters")
18
+ .refine((value) => new TextEncoder().encode(value).length <= 72, "Password is too long");
19
+
20
+ export const loginSchema = z.object({
21
+ email,
22
+ password: z.string().min(1, "Password is required"),
23
+ });
24
+ export type LoginInput = z.infer<typeof loginSchema>;
25
+
26
+ export const registerSchema = z.object({
27
+ name: z
28
+ .string()
29
+ .trim()
30
+ .min(2, "Name must be at least 2 characters")
31
+ .max(80, "Name must be at most 80 characters"),
32
+ email,
33
+ password,
34
+ });
35
+ export type RegisterInput = z.infer<typeof registerSchema>;
36
+
37
+ /** Client-only extension: confirm the password before submitting. */
38
+ export const registerFormSchema = registerSchema
39
+ .extend({ confirmPassword: z.string().min(1, "Please confirm your password") })
40
+ .refine((data) => data.password === data.confirmPassword, {
41
+ message: "Passwords do not match",
42
+ path: ["confirmPassword"],
43
+ });
44
+ export type RegisterFormInput = z.infer<typeof registerFormSchema>;
@@ -0,0 +1,13 @@
1
+ import { z } from "zod";
2
+
3
+ import { ROLES } from "@/config/rbac";
4
+
5
+ export const updateRoleSchema = z.object({
6
+ role: z.enum(ROLES, { error: `Role must be one of: ${ROLES.join(", ")}` }),
7
+ });
8
+ export type UpdateRoleInput = z.infer<typeof updateRoleSchema>;
9
+
10
+ export const listUsersQuerySchema = z.object({
11
+ page: z.coerce.number().int().min(1).default(1),
12
+ limit: z.coerce.number().int().min(1).max(100).default(50),
13
+ });
@@ -0,0 +1,30 @@
1
+ import "server-only";
2
+
3
+ import mongoose, { Schema, type InferSchemaType, type Model } from "mongoose";
4
+
5
+ import { DEFAULT_ROLE, ROLES } from "@/config/rbac";
6
+
7
+ const userSchema = new Schema(
8
+ {
9
+ name: { type: String, required: true, trim: true, maxlength: 80 },
10
+ email: {
11
+ type: String,
12
+ required: true,
13
+ unique: true,
14
+ lowercase: true,
15
+ trim: true,
16
+ maxlength: 254,
17
+ },
18
+ // bcrypt hash. Excluded from queries unless explicitly selected with "+password".
19
+ password: { type: String, required: true, select: false },
20
+ role: { type: String, enum: ROLES, default: DEFAULT_ROLE, required: true, index: true },
21
+ },
22
+ { timestamps: true },
23
+ );
24
+
25
+ export type UserDocument = InferSchemaType<typeof userSchema> & { _id: mongoose.Types.ObjectId };
26
+
27
+ // Reuse the compiled model across hot reloads.
28
+ export const User: Model<UserDocument> =
29
+ (mongoose.models.User as Model<UserDocument> | undefined) ??
30
+ mongoose.model<UserDocument>("User", userSchema);
@@ -0,0 +1,57 @@
1
+ import { NextResponse, type NextRequest } from "next/server";
2
+
3
+ import {
4
+ AFTER_LOGIN_PATH,
5
+ FORBIDDEN_PATH,
6
+ getRouteRule,
7
+ hasPermission,
8
+ isGuestOnlyRoute,
9
+ LOGIN_PATH,
10
+ } from "@/config/rbac";
11
+ import { SESSION_COOKIE, verifySession } from "@/lib/session";
12
+
13
+ /**
14
+ * Proxy (formerly "middleware"): layer 1 of the RBAC model.
15
+ *
16
+ * An optimistic, fast check based only on the signed JWT: no database access.
17
+ * It handles redirects for UX; real authorization happens again on the server
18
+ * (src/lib/dal.ts for pages, withAuth() in src/lib/api.ts for API routes),
19
+ * because a token's role can be stale until it is re-issued.
20
+ */
21
+ export async function proxy(request: NextRequest) {
22
+ const { pathname, search } = request.nextUrl;
23
+ const token = request.cookies.get(SESSION_COOKIE)?.value;
24
+ const session = await verifySession(token);
25
+
26
+ // Signed-in users don't need /login or /register.
27
+ if (isGuestOnlyRoute(pathname)) {
28
+ return session
29
+ ? NextResponse.redirect(new URL(AFTER_LOGIN_PATH, request.url))
30
+ : NextResponse.next();
31
+ }
32
+
33
+ const rule = getRouteRule(pathname);
34
+ if (!rule) return NextResponse.next();
35
+
36
+ if (!session) {
37
+ const loginUrl = new URL(LOGIN_PATH, request.url);
38
+ loginUrl.searchParams.set("next", pathname + search);
39
+ const response = NextResponse.redirect(loginUrl);
40
+ // Drop an invalid/expired cookie so it isn't sent again.
41
+ if (token) response.cookies.delete(SESSION_COOKIE);
42
+ return response;
43
+ }
44
+
45
+ if (!hasPermission(session.role, rule.permission)) {
46
+ const forbiddenUrl = new URL(FORBIDDEN_PATH, request.url);
47
+ forbiddenUrl.searchParams.set("from", pathname);
48
+ return NextResponse.redirect(forbiddenUrl);
49
+ }
50
+
51
+ return NextResponse.next();
52
+ }
53
+
54
+ export const config = {
55
+ // Skip API routes (they use withAuth), Next.js internals and static files.
56
+ matcher: ["/((?!api|_next/static|_next/image|favicon.ico|robots.txt|.*\\.[\\w]+$).*)"],
57
+ };
@@ -0,0 +1,10 @@
1
+ import type { Role } from "@/config/rbac";
2
+
3
+ /** A user as it is safe to send to the client (never includes the password hash). */
4
+ export type PublicUser = {
5
+ id: string;
6
+ name: string;
7
+ email: string;
8
+ role: Role;
9
+ createdAt: string;
10
+ };
@@ -0,0 +1,34 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2017",
4
+ "lib": ["dom", "dom.iterable", "esnext"],
5
+ "allowJs": true,
6
+ "skipLibCheck": true,
7
+ "strict": true,
8
+ "noEmit": true,
9
+ "esModuleInterop": true,
10
+ "module": "esnext",
11
+ "moduleResolution": "bundler",
12
+ "resolveJsonModule": true,
13
+ "isolatedModules": true,
14
+ "jsx": "react-jsx",
15
+ "incremental": true,
16
+ "plugins": [
17
+ {
18
+ "name": "next"
19
+ }
20
+ ],
21
+ "paths": {
22
+ "@/*": ["./src/*"]
23
+ }
24
+ },
25
+ "include": [
26
+ "next-env.d.ts",
27
+ "**/*.ts",
28
+ "**/*.tsx",
29
+ ".next/types/**/*.ts",
30
+ ".next/dev/types/**/*.ts",
31
+ "**/*.mts"
32
+ ],
33
+ "exclude": ["node_modules"]
34
+ }