create-mohit-next 0.0.0-stage → 2.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 (202) hide show
  1. package/README.md +139 -2
  2. package/index.js +399 -0
  3. package/lib/features.js +358 -0
  4. package/lib/scaffold.js +471 -0
  5. package/package.json +40 -4
  6. package/templates/common/_editorconfig +12 -0
  7. package/templates/common/_gitattributes +5 -0
  8. package/templates/common/_github/dependabot.yml +14 -0
  9. package/templates/common/_github/workflows/ci.yml +66 -0
  10. package/templates/common/_husky/commit-msg +1 -0
  11. package/templates/common/_husky/pre-commit +1 -0
  12. package/templates/common/_nvmrc +1 -0
  13. package/templates/common/_prettierignore +15 -0
  14. package/templates/common/commitlint.config.mjs +10 -0
  15. package/templates/next/AGENTS.md +9 -0
  16. package/templates/next/Dockerfile +48 -0
  17. package/templates/next/README.md +328 -0
  18. package/templates/next/_dockerignore +13 -0
  19. package/templates/next/_env.example +20 -0
  20. package/templates/next/_gitignore +50 -0
  21. package/templates/next/docker-compose.yml +33 -0
  22. package/templates/next/e2e/rbac.spec.ts +69 -0
  23. package/templates/next/e2e/server.mjs +35 -0
  24. package/templates/next/eslint.config.mjs +33 -0
  25. package/templates/next/next.config.ts +47 -0
  26. package/templates/next/package.json +68 -0
  27. package/templates/next/playwright.config.ts +30 -0
  28. package/templates/next/public/robots.txt +6 -0
  29. package/templates/next/scripts/seed.ts +111 -0
  30. package/templates/next/src/app/(app)/admin/audit/page.tsx +99 -0
  31. package/templates/next/src/app/(app)/admin/page.tsx +92 -0
  32. package/templates/next/src/app/(app)/dashboard/page.tsx +120 -0
  33. package/templates/next/src/app/(app)/error.tsx +28 -0
  34. package/templates/next/src/app/(app)/layout.tsx +58 -0
  35. package/templates/next/src/app/(app)/loading.tsx +5 -0
  36. package/templates/next/src/app/(app)/reports/page.tsx +128 -0
  37. package/templates/next/src/app/(app)/settings/page.tsx +66 -0
  38. package/templates/next/src/app/(auth)/forgot-password/page.tsx +17 -0
  39. package/templates/next/src/app/(auth)/layout.tsx +18 -0
  40. package/templates/next/src/app/(auth)/login/page.tsx +18 -0
  41. package/templates/next/src/app/(auth)/register/page.tsx +18 -0
  42. package/templates/next/src/app/(auth)/reset-password/page.tsx +18 -0
  43. package/templates/next/src/app/api/account/password/route.ts +45 -0
  44. package/templates/next/src/app/api/account/route.ts +25 -0
  45. package/templates/next/src/app/api/account/sessions/route.ts +12 -0
  46. package/templates/next/src/app/api/admin/audit/route.ts +13 -0
  47. package/templates/next/src/app/api/admin/users/[id]/route.ts +61 -0
  48. package/templates/next/src/app/api/admin/users/route.ts +18 -0
  49. package/templates/next/src/app/api/auth/forgot-password/route.ts +47 -0
  50. package/templates/next/src/app/api/auth/login/route.ts +43 -0
  51. package/templates/next/src/app/api/auth/logout/route.ts +21 -0
  52. package/templates/next/src/app/api/auth/me/route.ts +21 -0
  53. package/templates/next/src/app/api/auth/register/route.ts +74 -0
  54. package/templates/next/src/app/api/auth/resend-verification/route.ts +25 -0
  55. package/templates/next/src/app/api/auth/reset-password/route.ts +43 -0
  56. package/templates/next/src/app/api/auth/verify-email/route.ts +29 -0
  57. package/templates/next/src/app/api/health/route.ts +27 -0
  58. package/templates/next/src/app/favicon.ico +0 -0
  59. package/templates/next/src/app/forbidden/page.tsx +47 -0
  60. package/templates/next/src/app/layout.tsx +55 -0
  61. package/templates/next/src/app/not-found.tsx +20 -0
  62. package/templates/next/src/app/opengraph-image.tsx +49 -0
  63. package/templates/next/src/app/page.tsx +165 -0
  64. package/templates/next/src/app/robots.ts +15 -0
  65. package/templates/next/src/app/sitemap.ts +13 -0
  66. package/templates/next/src/app/verify-email/page.tsx +23 -0
  67. package/templates/next/src/components/admin/user-actions.tsx +124 -0
  68. package/templates/next/src/components/admin/users-data-table.tsx +221 -0
  69. package/templates/next/src/components/admin/users-table.tsx +67 -0
  70. package/templates/next/src/components/auth/auth-card.tsx +41 -0
  71. package/templates/next/src/components/auth/can.tsx +34 -0
  72. package/templates/next/src/components/auth/forgot-password-form.tsx +76 -0
  73. package/templates/next/src/components/auth/form-field.tsx +40 -0
  74. package/templates/next/src/components/auth/login-form.tsx +87 -0
  75. package/templates/next/src/components/auth/password-input.tsx +43 -0
  76. package/templates/next/src/components/auth/register-form.tsx +117 -0
  77. package/templates/next/src/components/auth/reset-password-form.tsx +80 -0
  78. package/templates/next/src/components/auth/session-refresher.tsx +44 -0
  79. package/templates/next/src/components/auth/verify-email-banner.tsx +43 -0
  80. package/templates/next/src/components/auth/verify-email-status.tsx +44 -0
  81. package/templates/next/src/components/layout/nav-links.tsx +37 -0
  82. package/templates/next/src/components/layout/navbar.tsx +27 -0
  83. package/templates/next/src/components/layout/page-header.tsx +21 -0
  84. package/templates/next/src/components/layout/sidebar.tsx +83 -0
  85. package/templates/next/src/components/layout/skeletons.tsx +57 -0
  86. package/templates/next/src/components/layout/user-menu.tsx +118 -0
  87. package/templates/next/src/components/logo.tsx +16 -0
  88. package/templates/next/src/components/motion/fade-in.tsx +19 -0
  89. package/templates/next/src/components/providers/user-provider.tsx +60 -0
  90. package/templates/next/src/components/reports/animated-bar.tsx +24 -0
  91. package/templates/next/src/components/reports/role-chart.tsx +61 -0
  92. package/templates/next/src/components/reports/signups-chart.tsx +64 -0
  93. package/templates/next/src/components/role-badge.tsx +11 -0
  94. package/templates/next/src/components/settings/password-form.tsx +80 -0
  95. package/templates/next/src/components/settings/profile-form.tsx +63 -0
  96. package/templates/next/src/components/settings/sessions-card.tsx +70 -0
  97. package/templates/next/src/components/theme-toggle.tsx +61 -0
  98. package/templates/next/src/config/rbac.test.ts +89 -0
  99. package/templates/next/src/config/rbac.ts +170 -0
  100. package/templates/next/src/config/site.ts +4 -0
  101. package/templates/next/src/lib/api.ts +179 -0
  102. package/templates/next/src/lib/audit.ts +66 -0
  103. package/templates/next/src/lib/auth.ts +50 -0
  104. package/templates/next/src/lib/dal.ts +63 -0
  105. package/templates/next/src/lib/db.ts +35 -0
  106. package/templates/next/src/lib/email-templates.ts +55 -0
  107. package/templates/next/src/lib/email.ts +53 -0
  108. package/templates/next/src/lib/env.ts +90 -0
  109. package/templates/next/src/lib/http.ts +57 -0
  110. package/templates/next/src/lib/password-strength.test.ts +20 -0
  111. package/templates/next/src/lib/password-strength.ts +24 -0
  112. package/templates/next/src/lib/rate-limit.test.ts +47 -0
  113. package/templates/next/src/lib/rate-limit.ts +70 -0
  114. package/templates/next/src/lib/redirect.test.ts +23 -0
  115. package/templates/next/src/lib/redirect.ts +21 -0
  116. package/templates/next/src/lib/session.ts +71 -0
  117. package/templates/next/src/lib/theme.ts +32 -0
  118. package/templates/next/src/lib/tokens.ts +63 -0
  119. package/templates/next/src/lib/users.ts +196 -0
  120. package/templates/next/src/lib/validations/account.ts +20 -0
  121. package/templates/next/src/lib/validations/auth.test.ts +39 -0
  122. package/templates/next/src/lib/validations/auth.ts +66 -0
  123. package/templates/next/src/lib/validations/user.ts +13 -0
  124. package/templates/next/src/models/audit-log.ts +33 -0
  125. package/templates/next/src/models/auth-token.ts +26 -0
  126. package/templates/next/src/models/user.ts +35 -0
  127. package/templates/next/src/proxy.ts +57 -0
  128. package/templates/next/src/styles/app.css +1092 -0
  129. package/templates/next/src/types/user.ts +13 -0
  130. package/templates/next/tsconfig.json +34 -0
  131. package/templates/next/vitest.config.mts +13 -0
  132. package/templates/styles/css.css +580 -0
  133. package/templates/styles/shadcn.css +142 -0
  134. package/templates/styles/tailwind.css +140 -0
  135. package/templates/ui/css/components/alert-dialog.tsx +172 -0
  136. package/templates/ui/css/components/avatar.tsx +17 -0
  137. package/templates/ui/css/components/badge.tsx +18 -0
  138. package/templates/ui/css/components/button.tsx +41 -0
  139. package/templates/ui/css/components/card.tsx +33 -0
  140. package/templates/ui/css/components/dropdown-menu.tsx +230 -0
  141. package/templates/ui/css/components/input.tsx +7 -0
  142. package/templates/ui/css/components/label.tsx +7 -0
  143. package/templates/ui/css/components/native-select.tsx +23 -0
  144. package/templates/ui/css/components/skeleton.tsx +7 -0
  145. package/templates/ui/css/components/slot.tsx +30 -0
  146. package/templates/ui/css/components/table.tsx +31 -0
  147. package/templates/ui/css/utils.ts +16 -0
  148. package/templates/ui/shadcn/components/alert-dialog.tsx +199 -0
  149. package/templates/ui/shadcn/components/avatar.tsx +111 -0
  150. package/templates/ui/shadcn/components/badge.tsx +44 -0
  151. package/templates/ui/shadcn/components/button.tsx +66 -0
  152. package/templates/ui/shadcn/components/card.tsx +87 -0
  153. package/templates/ui/shadcn/components/dropdown-menu.tsx +268 -0
  154. package/templates/ui/shadcn/components/input.tsx +18 -0
  155. package/templates/ui/shadcn/components/label.tsx +20 -0
  156. package/templates/ui/shadcn/components/native-select.tsx +54 -0
  157. package/templates/ui/shadcn/components/skeleton.tsx +13 -0
  158. package/templates/ui/shadcn/components/table.tsx +115 -0
  159. package/templates/ui/shadcn/utils.ts +1 -0
  160. package/templates/ui/tailwind/components/alert-dialog.tsx +177 -0
  161. package/templates/ui/tailwind/components/avatar.tsx +36 -0
  162. package/templates/ui/tailwind/components/badge.tsx +29 -0
  163. package/templates/ui/tailwind/components/button.tsx +65 -0
  164. package/templates/ui/tailwind/components/card.tsx +70 -0
  165. package/templates/ui/tailwind/components/dropdown-menu.tsx +236 -0
  166. package/templates/ui/tailwind/components/input.tsx +17 -0
  167. package/templates/ui/tailwind/components/label.tsx +16 -0
  168. package/templates/ui/tailwind/components/native-select.tsx +32 -0
  169. package/templates/ui/tailwind/components/skeleton.tsx +13 -0
  170. package/templates/ui/tailwind/components/slot.tsx +34 -0
  171. package/templates/ui/tailwind/components/table.tsx +56 -0
  172. package/templates/ui/tailwind/utils.ts +1 -0
  173. package/templates/vite/Dockerfile +29 -0
  174. package/templates/vite/README.md +142 -0
  175. package/templates/vite/_dockerignore +14 -0
  176. package/templates/vite/_env.example +8 -0
  177. package/templates/vite/_gitignore +37 -0
  178. package/templates/vite/e2e/app.spec.ts +41 -0
  179. package/templates/vite/index.html +32 -0
  180. package/templates/vite/nginx.conf +26 -0
  181. package/templates/vite/package.json +61 -0
  182. package/templates/vite/playwright.config.ts +27 -0
  183. package/templates/vite/public/favicon.svg +1 -0
  184. package/templates/vite/src/App.test.tsx +28 -0
  185. package/templates/vite/src/App.tsx +26 -0
  186. package/templates/vite/src/components/home.tsx +121 -0
  187. package/templates/vite/src/components/layout/root-layout.tsx +18 -0
  188. package/templates/vite/src/components/layout/site-footer.tsx +10 -0
  189. package/templates/vite/src/components/layout/site-header.tsx +49 -0
  190. package/templates/vite/src/components/theme-toggle.tsx +90 -0
  191. package/templates/vite/src/env.ts +36 -0
  192. package/templates/vite/src/lib/theme.ts +26 -0
  193. package/templates/vite/src/main.tsx +13 -0
  194. package/templates/vite/src/pages/about.tsx +52 -0
  195. package/templates/vite/src/pages/not-found.tsx +33 -0
  196. package/templates/vite/src/router.ts +24 -0
  197. package/templates/vite/src/styles/app.css +281 -0
  198. package/templates/vite/src/test/setup.ts +21 -0
  199. package/templates/vite/tsconfig.app.json +31 -0
  200. package/templates/vite/tsconfig.json +7 -0
  201. package/templates/vite/tsconfig.node.json +23 -0
  202. package/templates/vite/vite.config.ts +30 -0
@@ -0,0 +1,196 @@
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
+ // @feature email
18
+ emailVerifiedAt?: Date | null;
19
+ // @end email
20
+ };
21
+
22
+ export function toPublicUser(user: UserLike): PublicUser {
23
+ return {
24
+ id: String(user._id),
25
+ name: user.name,
26
+ email: user.email,
27
+ role: user.role as Role,
28
+ createdAt: new Date(user.createdAt ?? Date.now()).toISOString(),
29
+ // @feature email
30
+ emailVerified: Boolean(user.emailVerifiedAt),
31
+ // @end email
32
+ };
33
+ }
34
+
35
+ export function isValidId(id: string): boolean {
36
+ return mongoose.isValidObjectId(id) && /^[a-f0-9]{24}$/i.test(id);
37
+ }
38
+
39
+ export async function findUserById(id: string): Promise<PublicUser | null> {
40
+ if (!isValidId(id)) return null;
41
+ await connectDB();
42
+ const user = await User.findById(id).lean();
43
+ return user ? toPublicUser(user) : null;
44
+ }
45
+
46
+ /** The user plus their current token version (for validating sessions). */
47
+ export async function findSessionUser(
48
+ id: string,
49
+ ): Promise<{ user: PublicUser; tokenVersion: number } | null> {
50
+ if (!isValidId(id)) return null;
51
+ await connectDB();
52
+ const doc = await User.findById(id).lean();
53
+ return doc ? { user: toPublicUser(doc), tokenVersion: doc.tokenVersion ?? 0 } : null;
54
+ }
55
+
56
+ /** Invalidates every session of the user. Returns the new token version. */
57
+ export async function bumpTokenVersion(id: string): Promise<number> {
58
+ await connectDB();
59
+ const doc = await User.findByIdAndUpdate(
60
+ id,
61
+ { $inc: { tokenVersion: 1 } },
62
+ { returnDocument: "after" },
63
+ ).lean();
64
+ return doc?.tokenVersion ?? 0;
65
+ }
66
+
67
+ export async function listUsers({ page = 1, limit = 50 } = {}): Promise<{
68
+ users: PublicUser[];
69
+ total: number;
70
+ }> {
71
+ await connectDB();
72
+ const [docs, total] = await Promise.all([
73
+ User.find()
74
+ .sort({ createdAt: -1 })
75
+ .skip((page - 1) * limit)
76
+ .limit(limit)
77
+ .lean(),
78
+ User.countDocuments(),
79
+ ]);
80
+ return { users: docs.map(toPublicUser), total };
81
+ }
82
+
83
+ /** Changes a user's role. Returns the updated user and their previous role, or null if not found. */
84
+ export async function updateUserRole(
85
+ id: string,
86
+ role: Role,
87
+ ): Promise<{ user: PublicUser; previousRole: Role } | null> {
88
+ if (!isValidId(id)) return null;
89
+ await connectDB();
90
+ const before = await User.findByIdAndUpdate(
91
+ id,
92
+ { role },
93
+ { returnDocument: "before", runValidators: true },
94
+ ).lean();
95
+ if (!before) return null;
96
+ return { user: { ...toPublicUser(before), role }, previousRole: before.role as Role };
97
+ }
98
+
99
+ /** Deletes a user. Returns the deleted user, or null if not found. */
100
+ export async function deleteUser(id: string): Promise<PublicUser | null> {
101
+ if (!isValidId(id)) return null;
102
+ await connectDB();
103
+ const deleted = await User.findByIdAndDelete(id).lean();
104
+ return deleted ? toPublicUser(deleted) : null;
105
+ }
106
+
107
+ export function isDuplicateKeyError(error: unknown): boolean {
108
+ return (
109
+ typeof error === "object" && error !== null && (error as { code?: unknown }).code === 11000
110
+ );
111
+ }
112
+
113
+ // ---------------------------------------------------------------------------
114
+ // First-user bootstrap
115
+ // ---------------------------------------------------------------------------
116
+
117
+ const META_COLLECTION = "app_meta";
118
+ const FIRST_ADMIN_KEY = "first-admin-claimed";
119
+
120
+ /**
121
+ * Atomically claims the "first user becomes admin" slot. Returns true for
122
+ * exactly one registration, even if several sign-ups race on an empty DB,
123
+ * because the insert of a fixed _id can only succeed once.
124
+ */
125
+ export async function claimFirstAdmin(): Promise<boolean> {
126
+ await connectDB();
127
+ if (await User.exists({})) return false;
128
+ try {
129
+ await mongoose.connection
130
+ .collection<{ _id: string; claimedAt: Date }>(META_COLLECTION)
131
+ .insertOne({ _id: FIRST_ADMIN_KEY, claimedAt: new Date() });
132
+ return true;
133
+ } catch (error) {
134
+ if (isDuplicateKeyError(error)) return false;
135
+ throw error;
136
+ }
137
+ }
138
+
139
+ /** Gives the claim back if creating the first user failed. */
140
+ export async function releaseFirstAdmin(): Promise<void> {
141
+ await connectDB();
142
+ await mongoose.connection
143
+ .collection<{ _id: string }>(META_COLLECTION)
144
+ .deleteOne({ _id: FIRST_ADMIN_KEY });
145
+ }
146
+
147
+ /** Number of days shown in the sign-ups report. */
148
+ export const SIGNUP_DAYS = 14;
149
+
150
+ export type UserStats = {
151
+ total: number;
152
+ byRole: Record<Role, number>;
153
+ /** Sign-ups in the last SIGNUP_DAYS days. */
154
+ newInPeriod: number;
155
+ signupsByDay: { date: string; count: number }[];
156
+ };
157
+
158
+ export async function getUserStats(): Promise<UserStats> {
159
+ await connectDB();
160
+ const since = new Date();
161
+ since.setUTCHours(0, 0, 0, 0);
162
+ since.setUTCDate(since.getUTCDate() - (SIGNUP_DAYS - 1));
163
+
164
+ const [roleCounts, daily] = await Promise.all([
165
+ User.aggregate<{ _id: Role; count: number }>([
166
+ { $group: { _id: "$role", count: { $sum: 1 } } },
167
+ ]),
168
+ User.aggregate<{ _id: string; count: number }>([
169
+ { $match: { createdAt: { $gte: since } } },
170
+ {
171
+ $group: {
172
+ _id: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt", timezone: "UTC" } },
173
+ count: { $sum: 1 },
174
+ },
175
+ },
176
+ ]),
177
+ ]);
178
+
179
+ const byRole = Object.fromEntries(ROLES.map((role) => [role, 0])) as Record<Role, number>;
180
+ for (const { _id, count } of roleCounts) if (_id in byRole) byRole[_id] = count;
181
+
182
+ const dailyMap = new Map(daily.map((d) => [d._id, d.count]));
183
+ const signupsByDay = Array.from({ length: SIGNUP_DAYS }, (_, i) => {
184
+ const day = new Date(since);
185
+ day.setUTCDate(since.getUTCDate() + i);
186
+ const key = day.toISOString().slice(0, 10);
187
+ return { date: key, count: dailyMap.get(key) ?? 0 };
188
+ });
189
+
190
+ return {
191
+ total: Object.values(byRole).reduce((a, b) => a + b, 0),
192
+ byRole,
193
+ newInPeriod: signupsByDay.reduce((a, d) => a + d.count, 0),
194
+ signupsByDay,
195
+ };
196
+ }
@@ -0,0 +1,20 @@
1
+ import { z } from "zod";
2
+
3
+ import { passwordSchema, registerSchema } from "@/lib/validations/auth";
4
+
5
+ export const updateProfileSchema = registerSchema.pick({ name: true });
6
+ export type UpdateProfileInput = z.infer<typeof updateProfileSchema>;
7
+
8
+ export const changePasswordSchema = z.object({
9
+ currentPassword: z.string().min(1, "Enter your current password"),
10
+ newPassword: passwordSchema,
11
+ });
12
+ export type ChangePasswordInput = z.infer<typeof changePasswordSchema>;
13
+
14
+ /** Client-only extension with a confirmation field. */
15
+ export const changePasswordFormSchema = changePasswordSchema
16
+ .extend({ confirmPassword: z.string().min(1, "Please confirm your new password") })
17
+ .refine((data) => data.newPassword === data.confirmPassword, {
18
+ message: "Passwords do not match",
19
+ path: ["confirmPassword"],
20
+ });
@@ -0,0 +1,39 @@
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ import { loginSchema, registerFormSchema, registerSchema } from "./auth";
4
+
5
+ describe("auth schemas", () => {
6
+ it("normalizes emails", () => {
7
+ const result = loginSchema.parse({ email: " Ada@Example.COM ", password: "x" });
8
+ expect(result.email).toBe("ada@example.com");
9
+ });
10
+
11
+ it("rejects short passwords and names", () => {
12
+ const result = registerSchema.safeParse({ name: "A", email: "a@b.co", password: "short" });
13
+ expect(result.success).toBe(false);
14
+ if (!result.success) {
15
+ const fields = result.error.issues.map((i) => i.path[0]);
16
+ expect(fields).toContain("name");
17
+ expect(fields).toContain("password");
18
+ }
19
+ });
20
+
21
+ it("rejects passwords longer than bcrypt can use (72 bytes)", () => {
22
+ const result = registerSchema.safeParse({
23
+ name: "Ada",
24
+ email: "ada@example.com",
25
+ password: "a".repeat(73),
26
+ });
27
+ expect(result.success).toBe(false);
28
+ });
29
+
30
+ it("requires matching confirmation on the register form", () => {
31
+ const result = registerFormSchema.safeParse({
32
+ name: "Ada",
33
+ email: "ada@example.com",
34
+ password: "correct-horse",
35
+ confirmPassword: "correct-horsf",
36
+ });
37
+ expect(result.success).toBe(false);
38
+ });
39
+ });
@@ -0,0 +1,66 @@
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
+ export const passwordSchema = 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: passwordSchema,
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>;
45
+ // @feature email
46
+
47
+ export const forgotPasswordSchema = z.object({ email });
48
+ export type ForgotPasswordInput = z.infer<typeof forgotPasswordSchema>;
49
+
50
+ export const resetPasswordSchema = z.object({
51
+ token: z.string().min(1, "Missing reset token"),
52
+ password: passwordSchema,
53
+ });
54
+ export type ResetPasswordInput = z.infer<typeof resetPasswordSchema>;
55
+
56
+ /** Client-only extension with a confirmation field. */
57
+ export const resetPasswordFormSchema = z
58
+ .object({
59
+ password: passwordSchema,
60
+ confirmPassword: z.string().min(1, "Please confirm your password"),
61
+ })
62
+ .refine((data) => data.password === data.confirmPassword, {
63
+ message: "Passwords do not match",
64
+ path: ["confirmPassword"],
65
+ });
66
+ // @end email
@@ -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,33 @@
1
+ import "server-only";
2
+
3
+ import mongoose, { Schema, type InferSchemaType, type Model } from "mongoose";
4
+
5
+ export const AUDIT_ACTIONS = ["user.role_changed", "user.deleted"] as const;
6
+ export type AuditAction = (typeof AUDIT_ACTIONS)[number];
7
+
8
+ const personSchema = new Schema(
9
+ { id: { type: String, required: true }, name: String, email: String },
10
+ { _id: false },
11
+ );
12
+
13
+ /** An append-only record of who did what to whom. */
14
+ const auditLogSchema = new Schema(
15
+ {
16
+ action: { type: String, enum: AUDIT_ACTIONS, required: true, index: true },
17
+ actor: { type: personSchema, required: true },
18
+ target: { type: personSchema, required: true },
19
+ details: { type: Schema.Types.Mixed, default: {} },
20
+ ip: { type: String, default: null },
21
+ },
22
+ { timestamps: { createdAt: true, updatedAt: false } },
23
+ );
24
+ auditLogSchema.index({ createdAt: -1 });
25
+
26
+ export type AuditLogDocument = InferSchemaType<typeof auditLogSchema> & {
27
+ _id: mongoose.Types.ObjectId;
28
+ createdAt: Date;
29
+ };
30
+
31
+ export const AuditLog: Model<AuditLogDocument> =
32
+ (mongoose.models.AuditLog as Model<AuditLogDocument> | undefined) ??
33
+ mongoose.model<AuditLogDocument>("AuditLog", auditLogSchema);
@@ -0,0 +1,26 @@
1
+ import "server-only";
2
+
3
+ import mongoose, { Schema, type InferSchemaType, type Model } from "mongoose";
4
+
5
+ export const AUTH_TOKEN_TYPES = ["password-reset", "email-verification"] as const;
6
+ export type AuthTokenType = (typeof AUTH_TOKEN_TYPES)[number];
7
+
8
+ /** One-time tokens for password resets and email verification. Only a hash is stored. */
9
+ const authTokenSchema = new Schema(
10
+ {
11
+ userId: { type: Schema.Types.ObjectId, ref: "User", required: true, index: true },
12
+ type: { type: String, enum: AUTH_TOKEN_TYPES, required: true },
13
+ tokenHash: { type: String, required: true, unique: true },
14
+ // MongoDB deletes the document automatically once this date passes.
15
+ expiresAt: { type: Date, required: true, expires: 0 },
16
+ },
17
+ { timestamps: { createdAt: true, updatedAt: false } },
18
+ );
19
+
20
+ export type AuthTokenDocument = InferSchemaType<typeof authTokenSchema> & {
21
+ _id: mongoose.Types.ObjectId;
22
+ };
23
+
24
+ export const AuthToken: Model<AuthTokenDocument> =
25
+ (mongoose.models.AuthToken as Model<AuthTokenDocument> | undefined) ??
26
+ mongoose.model<AuthTokenDocument>("AuthToken", authTokenSchema);
@@ -0,0 +1,35 @@
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
+ // Incremented to invalidate every existing session (password change, "sign out everywhere").
22
+ tokenVersion: { type: Number, default: 0, required: true },
23
+ // @feature email
24
+ emailVerifiedAt: { type: Date, default: null },
25
+ // @end email
26
+ },
27
+ { timestamps: true },
28
+ );
29
+
30
+ export type UserDocument = InferSchemaType<typeof userSchema> & { _id: mongoose.Types.ObjectId };
31
+
32
+ // Reuse the compiled model across hot reloads.
33
+ export const User: Model<UserDocument> =
34
+ (mongoose.models.User as Model<UserDocument> | undefined) ??
35
+ 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 (rule.permission && !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
+ };