-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetupAuth.js
More file actions
282 lines (258 loc) · 8.4 KB
/
Copy pathsetupAuth.js
File metadata and controls
282 lines (258 loc) · 8.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import express from "express";
import helmet from "helmet";
import { setupSession } from "./modules/auth/session.js";
import { createUserModel } from "./modules/utils/userModel.js";
import { validatePassword } from "./modules/utils/validators.js";
import { callHook } from "./modules/utils/hookUtils.js";
import {
registerRoute,
loginRoute,
logoutRoute
} from "./modules/routes/authRoutes.js";
import {
authenticate,
authorize
} from "./modules/middleware/authMiddleware.js";
import { setupEmailRoutes } from "./modules/email/routes/emailRoutes.js";
import { defaultSendMail } from "./modules/email/services/emailService.js";
import { setupOAuthRoutes } from "./modules/oauth/oauthRoutes.js";
import { setupSwaggerDocs } from "./modules/docs/swagger.js";
/**
* Sets up authentication, session, and email verification routes for the app.
* Deep-merges config, validates requirements, and wires up all middleware.
* @param {import('express').Application} app - Express app instance.
* @param {Object} config - Auth configuration object.
* @returns {Promise<{auth: {authenticate: Function, authorize: Function}, models: {User: any}}>} Auth middleware and models.
*/
export async function setupAuth(app, config) {
// 1. Define default config
const defaults = {
route: "/auth",
useSession: false,
roles: ["user"],
passwordPolicy: { minLength: 8 },
rateLimiting: {
login: {
windowMs: 15 * 60 * 1000,
max: 5,
message: "Too many login attempts.",
store: null
},
register: {
windowMs: 60 * 60 * 1000,
max: 5,
message: "Too many registration attempts.",
store: null
}
},
sessionConfig: {
resave: false,
saveUninitialized: false,
cookie: { secure: false, httpOnly: true, sameSite: "lax" },
store: null
},
jwtConfig: { expiresIn: "1h" },
security: { helmet: true },
User: null,
emailVerification: null,
forgotPassword: null,
hooks: {},
hashing: { algorithm: "bcrypt" },
oauth: { providers: {} },
enableDocs: process.env.NODE_ENV !== "production"
};
// 2. Deep-merge user config with defaults
const merged = {
...defaults,
...config,
passwordPolicy: {
...defaults.passwordPolicy,
...(config.passwordPolicy || {})
},
rateLimiting: {
login: {
...defaults.rateLimiting.login,
...(config.rateLimiting?.login || {})
},
register: {
...defaults.rateLimiting.register,
...(config.rateLimiting?.register || {})
}
},
sessionConfig: {
...defaults.sessionConfig,
...(config.sessionConfig || {}),
cookie: {
...defaults.sessionConfig.cookie,
...(config.sessionConfig?.cookie || {})
}
},
jwtConfig: {
...defaults.jwtConfig,
...(config.jwtConfig || {})
},
security: {
...defaults.security,
...(config.security || {})
},
hooks: {
...defaults.hooks,
...(config.hooks || {})
},
hashing: {
...defaults.hashing,
...(config.hashing || {})
},
oauth: {
...defaults.oauth,
...(config.oauth || {})
},
enableDocs: config.enableDocs !== undefined ? config.enableDocs : defaults.enableDocs
};
// 3. Destructure merged config
const {
db,
route,
jwtSecret,
useSession,
roles,
passwordPolicy,
rateLimiting,
sessionConfig,
jwtConfig,
security,
emailVerification,
forgotPassword,
hashing,
oauth,
enableDocs
} = merged;
// 3.1 Startup Banner & Feature Logging
console.log("\n==================================================");
console.log("Initializing Light-Auth...");
console.log("==================================================");
console.log(`[OK] Auth Mode: ${useSession ? "Session-based" : "JWT-based"}`);
console.log(`[OK] Base Route: ${route}`);
console.log(`[OK] Roles: ${roles.join(", ")}`);
if (security?.helmet) console.log(`[OK] Security: Helmet Enabled`);
if (hashing?.algorithm !== "bcrypt") console.log(`[OK] Hashing: ${hashing.algorithm}`);
if (oauth && Object.keys(oauth.providers || {}).length > 0) {
console.log(`[OK] OAuth2: ${Object.keys(oauth.providers).join(", ")}`);
}
if (enableDocs) console.log(`[OK] Swagger Docs: Enabled at ${route}/docs`);
if (emailVerification?.enabled) console.log(`[OK] Email Verify: Enabled`);
if (forgotPassword?.enabled) console.log(`[OK] Forgot Pass: Enabled`);
console.log("==================================================\n");
// 4. Validate critical requirements
if (!jwtSecret || typeof jwtSecret !== "string" || jwtSecret.length < 16) {
const error = new Error("[setupAuth] jwtSecret is required and must be a strong, non-default string (min 16 chars).");
await callHook(merged.hooks?.onError, { type: "setup", error });
throw error;
}
if (!db || !db.model) {
const error = new Error("[setupAuth] Mongoose DB connection required.");
await callHook(merged.hooks?.onError, { type: "setup", error });
throw error;
}
if (!merged.User) {
const error = new Error("[setupAuth] User model is required. Pass a Mongoose model or set User: 'default' to auto-generate one.");
await callHook(merged.hooks?.onError, { type: "setup", error });
throw error;
}
// 5. Create or load User model
const UserModel = merged.User === "default"
? await createUserModel(merged, roles, db)
: merged.User;
// 6. Register security middleware
if (security?.helmet) {
app.use(helmet());
}
// 7. Only initialize session middleware once per app
if (useSession && !app._sessionInitialized) {
if (process.env.NODE_ENV === "production" && !sessionConfig.store) {
console.warn(
"[light-auth] WARNING: No session store provided in production. Defaulting to MemoryStore, which will not persist across restarts or work in distributed environments."
);
}
setupSession(app, jwtSecret, sessionConfig);
app._sessionInitialized = true;
}
// 8. Create router and register core auth routes
const router = express.Router();
router.use(express.json());
// 8.1 Register route: user registration
registerRoute(
router,
UserModel,
roles,
validatePassword(passwordPolicy),
rateLimiting.register,
merged
);
// 8.2 Register route: user login
const requireEmailVerified = !!(
emailVerification && emailVerification.requiredToLogin
);
loginRoute(
router,
UserModel,
jwtSecret,
jwtConfig,
useSession,
rateLimiting.login,
requireEmailVerified,
merged
);
// 8.3 Register route: user logout
logoutRoute(router, useSession, merged, jwtSecret);
// 9. Mount router on app
app.use(route, router);
// 10. Email verification + forgot password support
const emailFeaturesEnabled =
emailVerification?.enabled || forgotPassword?.enabled;
if (emailFeaturesEnabled) {
const isProd = process.env.NODE_ENV === "production";
const allowMock = process.env.ALLOW_MOCK_EMAILS === "true";
// 10.1 Provide default sendMail if not set
if (emailVerification?.enabled && !emailVerification.sendMail) {
if (isProd && !allowMock) {
const error = new Error(
"[setupAuth] Email verification is enabled but no sendMail function provided. Use a real mailer or set ALLOW_MOCK_EMAILS=true."
);
await callHook(merged.hooks?.onError, { type: "setup", error });
throw error;
}
merged.emailVerification.sendMail = defaultSendMail;
}
if (forgotPassword?.enabled && !forgotPassword.sendMail) {
if (isProd && !allowMock) {
const error = new Error(
"[setupAuth] Forgot password is enabled but no sendMail function provided. Use a real mailer or set ALLOW_MOCK_EMAILS=true."
);
await callHook(merged.hooks?.onError, { type: "setup", error });
throw error;
}
merged.forgotPassword.sendMail = defaultSendMail;
}
// 10.2 Register email routes
setupEmailRoutes(app, UserModel, merged);
}
// 11. OAuth2 support
if (oauth && Object.keys(oauth.providers || {}).length > 0) {
setupOAuthRoutes(app, UserModel, merged);
}
// 12. Swagger Docs
if (enableDocs) {
setupSwaggerDocs(app, merged);
}
// 13. Export auth middleware + models
return {
auth: {
authenticate: authenticate(useSession, jwtSecret),
authorize
},
models: {
User: UserModel
}
};
}