@aventoapp/framework 0.2.0 → 0.2.2
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 +281 -0
- package/dist/index.js.map +1 -1
- package/dist/native/index.js.map +1 -1
- package/dist/offline/index.js.map +1 -1
- package/dist/server/index.js +69 -6
- package/dist/server/index.js.map +2 -2
- package/dist/server/workflow/index.js.map +1 -1
- package/dist/shared/index.js.map +1 -1
- package/dist/web/index.js.map +1 -1
- package/package.json +84 -79
- package/schemas/Workflow.json +14 -14
- package/schemas/WorkflowHistory.json +22 -22
- package/schemas/WorkflowInstance.json +16 -16
- package/schemas/WorkflowState.json +18 -18
- package/schemas/WorkflowTransition.json +27 -27
- package/src/index.js +8 -8
- package/src/native/components/NativeAuthProvider.jsx +249 -249
- package/src/native/components/NativeDetail.jsx +270 -270
- package/src/native/components/NativeForm.jsx +543 -543
- package/src/native/components/NativeGrid.jsx +90 -90
- package/src/native/components/NativeJsonGrid.jsx +213 -213
- package/src/native/components/NativeJsonView.jsx +454 -454
- package/src/native/components/NativeJsonViewContext.js +17 -17
- package/src/native/components/NativeShell.jsx +68 -68
- package/src/native/components/NativeViewComponent.jsx +351 -351
- package/src/native/extensions/NativeExtensionRegistry.js +81 -81
- package/src/native/hooks/useNativeStore.js +72 -72
- package/src/native/index.js +15 -15
- package/src/native/layouts/NativeStackLayout.jsx +30 -30
- package/src/native/layouts/NativeTabLayout.jsx +96 -96
- package/src/native/storage.js +13 -13
- package/src/native/stores/NativeBaseStore.js +348 -348
- package/src/native/stores/NativeStoreContext.jsx +53 -53
- package/src/offline/index.js +1 -1
- package/src/server/ai/capabilities-routes.js +106 -106
- package/src/server/ai/index.js +1 -1
- package/src/server/cache/MemoryCache.js +153 -153
- package/src/server/cache/index.js +2 -2
- package/src/server/cache/middleware.js +12 -12
- package/src/server/db/index.js +14 -14
- package/src/server/db/mongo.js +137 -137
- package/src/server/db/postgres.js +144 -144
- package/src/server/index.js +42 -42
- package/src/server/middleware/auth.js +682 -682
- package/src/server/middleware/can-flags.js +132 -132
- package/src/server/middleware/entityRoles.js +105 -105
- package/src/server/middleware/index.js +58 -58
- package/src/server/middleware/permissions.js +240 -240
- package/src/server/middleware/tenant.js +203 -203
- package/src/server/offline/field-lww.js +98 -6
- package/src/server/realtime/EventBus.js +45 -45
- package/src/server/realtime/WebSocketServer.js +105 -105
- package/src/server/realtime/index.js +3 -3
- package/src/server/realtime/middleware.js +18 -18
- package/src/server/services/email-templates.js +157 -157
- package/src/server/services/email.js +78 -78
- package/src/server/services/index.js +15 -15
- package/src/server/services/storage.js +119 -119
- package/src/server/utils/index.js +16 -16
- package/src/server/utils/paginate.js +65 -65
- package/src/server/utils/query-builder.js +293 -293
- package/src/server/utils/route-loader.js +61 -61
- package/src/server/workflow/WorkflowEngine.js +494 -494
- package/src/server/workflow/index.js +2 -2
- package/src/server/workflow/workflow-routes.js +174 -174
- package/src/shared/index.js +10 -10
- package/src/shared/utils/field-accessor.js +108 -108
- package/src/shared/utils/index.js +7 -7
- package/src/shared/utils/validation-utils.js +83 -83
- package/src/web/components/AppRouter/AppRouter.jsx +130 -130
- package/src/web/components/AppRouter/index.js +1 -1
- package/src/web/components/AppShell/AppShell.jsx +101 -101
- package/src/web/components/AppShell/DefaultUserMenu.jsx +54 -54
- package/src/web/components/AppShell/ShellConfig.js +53 -53
- package/src/web/components/AppShell/index.js +3 -3
- package/src/web/components/AuthProvider.jsx +426 -426
- package/src/web/components/CardList/CardList.jsx +272 -272
- package/src/web/components/CardList/index.js +2 -2
- package/src/web/components/DetailView/DetailView.jsx +281 -281
- package/src/web/components/DetailView/index.js +2 -2
- package/src/web/components/Form/Form.jsx +300 -300
- package/src/web/components/Form/FormField.jsx +226 -226
- package/src/web/components/Form/index.js +3 -3
- package/src/web/components/Grid/Grid.jsx +304 -304
- package/src/web/components/Grid/index.js +2 -2
- package/src/web/components/IconRegistry/IconRegistry.jsx +127 -127
- package/src/web/components/IconRegistry/index.js +1 -1
- package/src/web/components/JsonView/JsonView.jsx +647 -647
- package/src/web/components/JsonView/ViewComponent.jsx +1045 -1045
- package/src/web/components/JsonView/ViewToolbar.jsx +141 -141
- package/src/web/components/JsonView/index.js +14 -14
- package/src/web/components/JsonView/layouts/SingleLayout.jsx +41 -41
- package/src/web/components/JsonView/layouts/SplitLayout.jsx +122 -122
- package/src/web/components/JsonView/layouts/TabLayout.jsx +112 -112
- package/src/web/components/JsonView/layouts/index.js +8 -8
- package/src/web/components/Layout.jsx +265 -265
- package/src/web/components/MobileLayout/MobileLayout.jsx +385 -385
- package/src/web/components/MobileLayout/index.js +1 -1
- package/src/web/components/Navigation/Navigation.jsx +248 -248
- package/src/web/components/Navigation/index.js +1 -1
- package/src/web/components/NotificationProvider.jsx +55 -55
- package/src/web/components/Pagination/InfiniteScroll.jsx +82 -82
- package/src/web/components/Pagination/Pagination.jsx +73 -73
- package/src/web/components/Pagination/index.js +8 -8
- package/src/web/components/SimpleList/SimpleList.jsx +177 -177
- package/src/web/components/SimpleList/index.js +2 -2
- package/src/web/components/TenantProvider.jsx +121 -121
- package/src/web/components/WorkflowActions/WorkflowActions.jsx +71 -71
- package/src/web/components/WorkflowActions/index.js +1 -1
- package/src/web/components/WorkflowField/WorkflowField.jsx +176 -176
- package/src/web/components/WorkflowField/index.js +2 -2
- package/src/web/components/WorkflowField/workflowColors.js +32 -32
- package/src/web/components/auth/DevTenantSelector.jsx +90 -90
- package/src/web/components/auth/ForgotPasswordForm.jsx +94 -94
- package/src/web/components/auth/RegisterForm.jsx +168 -168
- package/src/web/components/auth/ResetPasswordForm.jsx +121 -121
- package/src/web/components/auth/VerifyEmailView.jsx +85 -85
- package/src/web/components/auth/index.js +5 -5
- package/src/web/components/index.js +39 -39
- package/src/web/components/layouts/CardListLayout.jsx +68 -68
- package/src/web/components/layouts/FullscreenLayout.jsx +30 -30
- package/src/web/components/layouts/MobileStackLayout.jsx +28 -28
- package/src/web/components/layouts/WizardLayout.jsx +86 -86
- package/src/web/components/layouts/index.js +4 -4
- package/src/web/components/mobile/Badge.jsx +105 -105
- package/src/web/components/mobile/BadgeThemeEditor.jsx +104 -104
- package/src/web/components/mobile/EmptyState.jsx +30 -30
- package/src/web/components/mobile/QuickActionButton.jsx +77 -77
- package/src/web/components/mobile/ServerAutocomplete.jsx +123 -123
- package/src/web/components/mobile/StarRating.jsx +42 -42
- package/src/web/components/mobile/StatCard.jsx +65 -65
- package/src/web/components/mobile/index.js +7 -7
- package/src/web/extensions/ExtensionRegistry.js +79 -79
- package/src/web/extensions/index.js +7 -7
- package/src/web/hooks/index.js +15 -15
- package/src/web/hooks/useApi.js +76 -76
- package/src/web/hooks/useAuth.js +37 -37
- package/src/web/hooks/useDebouncedSave.js +158 -158
- package/src/web/hooks/useIsMobile.js +14 -14
- package/src/web/hooks/useOfflineQueue.js +99 -99
- package/src/web/hooks/useSelectionModel.js +143 -143
- package/src/web/hooks/useServerAutocomplete.js +146 -146
- package/src/web/hooks/useStore.js +107 -107
- package/src/web/hooks/useSubscription.js +130 -130
- package/src/web/hooks/useTenant.js +39 -39
- package/src/web/hooks/useTenantResolver.js +65 -65
- package/src/web/hooks/useUndoRedo.js +77 -77
- package/src/web/hooks/useViews.js +113 -113
- package/src/web/hooks/useWorkflow.js +190 -190
- package/src/web/index.js +117 -117
- package/src/web/stores/BaseStore.js +439 -439
- package/src/web/stores/StoreContext.jsx +93 -93
- package/src/web/stores/index.js +3 -3
- package/src/web/theme/index.js +3 -3
- package/src/web/theme/mui-theme.js +228 -228
- package/src/web/utils/formatTimeAgo.js +22 -22
- package/src/web/utils/index.js +1 -1
- package/src/web/views/ViewRegistry.js +235 -235
- package/src/web/views/index.js +2 -2
|
@@ -1,682 +1,682 @@
|
|
|
1
|
-
import passport from 'passport';
|
|
2
|
-
import passportJwt from 'passport-jwt';
|
|
3
|
-
import jwt from 'jsonwebtoken';
|
|
4
|
-
import bcrypt from 'bcrypt';
|
|
5
|
-
import crypto from 'crypto';
|
|
6
|
-
import { emailVerificationEmail, passwordResetEmail } from '../services/email-templates.js';
|
|
7
|
-
|
|
8
|
-
const { Strategy: JwtStrategy, ExtractJwt } = passportJwt;
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Default JWT options
|
|
12
|
-
*/
|
|
13
|
-
const DEFAULT_OPTIONS = {
|
|
14
|
-
jwtSecret: process.env.JWT_SECRET || 'avento-secret-change-me',
|
|
15
|
-
jwtExpiry: process.env.JWT_EXPIRY || '24h',
|
|
16
|
-
refreshExpiry: process.env.JWT_REFRESH_EXPIRY || '7d',
|
|
17
|
-
saltRounds: 10
|
|
18
|
-
};
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* Configure Passport JWT strategy
|
|
22
|
-
*/
|
|
23
|
-
export function configurePassport(options = {}) {
|
|
24
|
-
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
25
|
-
|
|
26
|
-
const jwtOptions = {
|
|
27
|
-
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
|
28
|
-
secretOrKey: opts.jwtSecret,
|
|
29
|
-
passReqToCallback: true
|
|
30
|
-
};
|
|
31
|
-
|
|
32
|
-
passport.use(new JwtStrategy(jwtOptions, async (req, payload, done) => {
|
|
33
|
-
try {
|
|
34
|
-
// The payload contains user info from the token
|
|
35
|
-
// In a real app, you might want to fetch fresh user data from DB
|
|
36
|
-
|
|
37
|
-
if (!payload.user_id) {
|
|
38
|
-
return done(null, false, { message: 'Invalid token payload' });
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
// Check token expiration (jwt.verify handles this, but double-check)
|
|
42
|
-
if (payload.exp && Date.now() >= payload.exp * 1000) {
|
|
43
|
-
return done(null, false, { message: 'Token expired' });
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// Attach user to request
|
|
47
|
-
const user = {
|
|
48
|
-
id: payload.user_id,
|
|
49
|
-
email: payload.email,
|
|
50
|
-
roles: payload.roles || [],
|
|
51
|
-
tenant_id: payload.tenant_id,
|
|
52
|
-
tenant_name: payload.tenant_name
|
|
53
|
-
};
|
|
54
|
-
|
|
55
|
-
return done(null, user);
|
|
56
|
-
} catch (err) {
|
|
57
|
-
return done(err, false);
|
|
58
|
-
}
|
|
59
|
-
}));
|
|
60
|
-
|
|
61
|
-
return passport;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/**
|
|
65
|
-
* Initialize auth middleware
|
|
66
|
-
*/
|
|
67
|
-
export function initAuth(app, options = {}) {
|
|
68
|
-
configurePassport(options);
|
|
69
|
-
app.use(passport.initialize());
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/**
|
|
73
|
-
* Middleware to require authentication
|
|
74
|
-
*/
|
|
75
|
-
export function requireAuth() {
|
|
76
|
-
return (req, res, next) => {
|
|
77
|
-
passport.authenticate('jwt', { session: false }, (err, user, info) => {
|
|
78
|
-
if (err) {
|
|
79
|
-
return res.status(500).json({
|
|
80
|
-
error: 'Authentication error',
|
|
81
|
-
message: err.message
|
|
82
|
-
});
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
if (!user) {
|
|
86
|
-
return res.status(401).json({
|
|
87
|
-
error: 'Unauthorized',
|
|
88
|
-
message: info?.message || 'Authentication required'
|
|
89
|
-
});
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
req.user = user;
|
|
93
|
-
|
|
94
|
-
// Also set tenant context from JWT if available
|
|
95
|
-
if (user.tenant_id && !req.tenant) {
|
|
96
|
-
req.tenant = {
|
|
97
|
-
id: user.tenant_id,
|
|
98
|
-
name: user.tenant_name
|
|
99
|
-
};
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
next();
|
|
103
|
-
})(req, res, next);
|
|
104
|
-
};
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
/**
|
|
108
|
-
* Middleware to optionally authenticate (doesn't fail if no token)
|
|
109
|
-
*/
|
|
110
|
-
export function optionalAuth() {
|
|
111
|
-
return (req, res, next) => {
|
|
112
|
-
passport.authenticate('jwt', { session: false }, (err, user) => {
|
|
113
|
-
if (user) {
|
|
114
|
-
req.user = user;
|
|
115
|
-
if (user.tenant_id && !req.tenant) {
|
|
116
|
-
req.tenant = {
|
|
117
|
-
id: user.tenant_id,
|
|
118
|
-
name: user.tenant_name
|
|
119
|
-
};
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
next();
|
|
123
|
-
})(req, res, next);
|
|
124
|
-
};
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
/**
|
|
128
|
-
* Generate JWT token for a user
|
|
129
|
-
*/
|
|
130
|
-
export function generateToken(user, tenantId, tenantName, options = {}) {
|
|
131
|
-
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
132
|
-
|
|
133
|
-
const payload = {
|
|
134
|
-
user_id: user.id,
|
|
135
|
-
email: user.email,
|
|
136
|
-
roles: user.roles || [],
|
|
137
|
-
tenant_id: tenantId,
|
|
138
|
-
tenant_name: tenantName
|
|
139
|
-
};
|
|
140
|
-
|
|
141
|
-
return jwt.sign(payload, opts.jwtSecret, {
|
|
142
|
-
expiresIn: opts.jwtExpiry
|
|
143
|
-
});
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
/**
|
|
147
|
-
* Generate refresh token
|
|
148
|
-
*/
|
|
149
|
-
export function generateRefreshToken(userId, options = {}) {
|
|
150
|
-
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
151
|
-
|
|
152
|
-
return jwt.sign(
|
|
153
|
-
{ user_id: userId, type: 'refresh' },
|
|
154
|
-
opts.jwtSecret,
|
|
155
|
-
{ expiresIn: opts.refreshExpiry }
|
|
156
|
-
);
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
/**
|
|
160
|
-
* Verify and decode a token
|
|
161
|
-
*/
|
|
162
|
-
export function verifyToken(token, options = {}) {
|
|
163
|
-
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
164
|
-
|
|
165
|
-
try {
|
|
166
|
-
return jwt.verify(token, opts.jwtSecret);
|
|
167
|
-
} catch (err) {
|
|
168
|
-
return null;
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
/**
|
|
173
|
-
* Hash a password
|
|
174
|
-
*/
|
|
175
|
-
export async function hashPassword(password, options = {}) {
|
|
176
|
-
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
177
|
-
return bcrypt.hash(password, opts.saltRounds);
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* Compare password with hash
|
|
182
|
-
*/
|
|
183
|
-
export async function comparePassword(password, hash) {
|
|
184
|
-
return bcrypt.compare(password, hash);
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
/**
|
|
188
|
-
* Create login handler
|
|
189
|
-
*/
|
|
190
|
-
export function createLoginHandler(findUserByEmail, options = {}) {
|
|
191
|
-
const { getTenantSettings } = options;
|
|
192
|
-
|
|
193
|
-
return async (req, res) => {
|
|
194
|
-
try {
|
|
195
|
-
const { email, password, tenant_id } = req.body;
|
|
196
|
-
|
|
197
|
-
if (!email || !password) {
|
|
198
|
-
return res.status(400).json({
|
|
199
|
-
error: 'Validation error',
|
|
200
|
-
message: 'Email and password are required'
|
|
201
|
-
});
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
// Find user
|
|
205
|
-
const user = await findUserByEmail(email, tenant_id);
|
|
206
|
-
|
|
207
|
-
if (!user) {
|
|
208
|
-
return res.status(401).json({
|
|
209
|
-
error: 'Authentication failed',
|
|
210
|
-
message: 'Invalid email or password'
|
|
211
|
-
});
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
// Verify password
|
|
215
|
-
const isValid = await comparePassword(password, user.password_hash);
|
|
216
|
-
|
|
217
|
-
if (!isValid) {
|
|
218
|
-
return res.status(401).json({
|
|
219
|
-
error: 'Authentication failed',
|
|
220
|
-
message: 'Invalid email or password'
|
|
221
|
-
});
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
// Check email verification if required
|
|
225
|
-
if (getTenantSettings && !user.email_verified_at) {
|
|
226
|
-
try {
|
|
227
|
-
const settings = await getTenantSettings(user.tenant_id);
|
|
228
|
-
if (settings?.requireEmailVerification) {
|
|
229
|
-
return res.status(403).json({
|
|
230
|
-
error: 'Email not verified',
|
|
231
|
-
message: 'Please verify your email address before logging in'
|
|
232
|
-
});
|
|
233
|
-
}
|
|
234
|
-
} catch (err) {
|
|
235
|
-
console.error('[Auth] Error checking tenant settings:', err);
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
// Generate tokens
|
|
240
|
-
const token = generateToken(user, user.tenant_id, user.tenant_name, options);
|
|
241
|
-
const refreshToken = generateRefreshToken(user.id, options);
|
|
242
|
-
|
|
243
|
-
res.json({
|
|
244
|
-
token,
|
|
245
|
-
refreshToken,
|
|
246
|
-
user: {
|
|
247
|
-
id: user.id,
|
|
248
|
-
email: user.email,
|
|
249
|
-
roles: user.roles
|
|
250
|
-
},
|
|
251
|
-
tenant: {
|
|
252
|
-
id: user.tenant_id,
|
|
253
|
-
name: user.tenant_name
|
|
254
|
-
}
|
|
255
|
-
});
|
|
256
|
-
} catch (err) {
|
|
257
|
-
console.error('[Auth] Login error:', err);
|
|
258
|
-
res.status(500).json({
|
|
259
|
-
error: 'Login failed',
|
|
260
|
-
message: 'An unexpected error occurred'
|
|
261
|
-
});
|
|
262
|
-
}
|
|
263
|
-
};
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
/**
|
|
267
|
-
* Generate a cryptographically secure token
|
|
268
|
-
*/
|
|
269
|
-
export function generateSecureToken(bytes = 32) {
|
|
270
|
-
return crypto.randomBytes(bytes).toString('hex');
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
/**
|
|
274
|
-
* Generate a token expiry date (as UTC ISO string for consistent DB storage)
|
|
275
|
-
*/
|
|
276
|
-
export function generateTokenExpiry(hours = 1) {
|
|
277
|
-
return new Date(Date.now() + hours * 60 * 60 * 1000).toISOString();
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
/**
|
|
281
|
-
* Create refresh token handler
|
|
282
|
-
*/
|
|
283
|
-
export function createRefreshHandler(findUserById, options = {}) {
|
|
284
|
-
return async (req, res) => {
|
|
285
|
-
try {
|
|
286
|
-
const { refreshToken } = req.body;
|
|
287
|
-
|
|
288
|
-
if (!refreshToken) {
|
|
289
|
-
return res.status(400).json({
|
|
290
|
-
error: 'Validation error',
|
|
291
|
-
message: 'Refresh token is required'
|
|
292
|
-
});
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
const decoded = verifyToken(refreshToken, options);
|
|
296
|
-
|
|
297
|
-
if (!decoded || decoded.type !== 'refresh') {
|
|
298
|
-
return res.status(401).json({
|
|
299
|
-
error: 'Invalid token',
|
|
300
|
-
message: 'Invalid or expired refresh token'
|
|
301
|
-
});
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
const user = await findUserById(decoded.user_id);
|
|
305
|
-
|
|
306
|
-
if (!user) {
|
|
307
|
-
return res.status(401).json({
|
|
308
|
-
error: 'User not found',
|
|
309
|
-
message: 'User no longer exists'
|
|
310
|
-
});
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
const token = generateToken(user, user.tenant_id, user.tenant_name, options);
|
|
314
|
-
|
|
315
|
-
res.json({ token });
|
|
316
|
-
} catch (err) {
|
|
317
|
-
console.error('[Auth] Refresh error:', err);
|
|
318
|
-
res.status(500).json({
|
|
319
|
-
error: 'Refresh failed',
|
|
320
|
-
message: 'An unexpected error occurred'
|
|
321
|
-
});
|
|
322
|
-
}
|
|
323
|
-
};
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
/**
|
|
327
|
-
* Validate email format
|
|
328
|
-
*/
|
|
329
|
-
function isValidEmail(email) {
|
|
330
|
-
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
/**
|
|
334
|
-
* Create register handler
|
|
335
|
-
*/
|
|
336
|
-
export function createRegisterHandler(callbacks, options = {}) {
|
|
337
|
-
const {
|
|
338
|
-
findUserByEmail,
|
|
339
|
-
createUser,
|
|
340
|
-
getTenantSettings,
|
|
341
|
-
createToken
|
|
342
|
-
} = callbacks;
|
|
343
|
-
|
|
344
|
-
const {
|
|
345
|
-
emailService,
|
|
346
|
-
appUrl = '',
|
|
347
|
-
passwordMinLength = 8,
|
|
348
|
-
emailBranding
|
|
349
|
-
} = options;
|
|
350
|
-
|
|
351
|
-
return async (req, res) => {
|
|
352
|
-
try {
|
|
353
|
-
const { email, password, first_name, last_name } = req.body;
|
|
354
|
-
const tenantId = req.tenant?.id;
|
|
355
|
-
|
|
356
|
-
// Validate required fields
|
|
357
|
-
if (!email || !password || !first_name || !last_name) {
|
|
358
|
-
return res.status(400).json({
|
|
359
|
-
error: 'Validation error',
|
|
360
|
-
message: 'Email, password, first name, and last name are required'
|
|
361
|
-
});
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
if (!isValidEmail(email)) {
|
|
365
|
-
return res.status(400).json({
|
|
366
|
-
error: 'Validation error',
|
|
367
|
-
message: 'Invalid email format'
|
|
368
|
-
});
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
if (password.length < passwordMinLength) {
|
|
372
|
-
return res.status(400).json({
|
|
373
|
-
error: 'Validation error',
|
|
374
|
-
message: `Password must be at least ${passwordMinLength} characters`
|
|
375
|
-
});
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
if (!tenantId) {
|
|
379
|
-
return res.status(400).json({
|
|
380
|
-
error: 'Validation error',
|
|
381
|
-
message: 'Tenant context is required for registration'
|
|
382
|
-
});
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
// Check tenant settings
|
|
386
|
-
const settings = await getTenantSettings(tenantId);
|
|
387
|
-
if (!settings?.allowSelfRegistration) {
|
|
388
|
-
return res.status(403).json({
|
|
389
|
-
error: 'Registration disabled',
|
|
390
|
-
message: 'Self-registration is not allowed for this tenant'
|
|
391
|
-
});
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
// Check for existing user
|
|
395
|
-
const existingUser = await findUserByEmail(email, tenantId);
|
|
396
|
-
if (existingUser) {
|
|
397
|
-
return res.status(409).json({
|
|
398
|
-
error: 'User exists',
|
|
399
|
-
message: 'An account with this email already exists'
|
|
400
|
-
});
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
// Create user
|
|
404
|
-
const passwordHash = await hashPassword(password);
|
|
405
|
-
const user = await createUser({
|
|
406
|
-
email,
|
|
407
|
-
password_hash: passwordHash,
|
|
408
|
-
first_name,
|
|
409
|
-
last_name,
|
|
410
|
-
tenant_id: tenantId,
|
|
411
|
-
roles: ['user']
|
|
412
|
-
});
|
|
413
|
-
|
|
414
|
-
// Handle email verification
|
|
415
|
-
if (settings.requireEmailVerification) {
|
|
416
|
-
const tokenValue = generateSecureToken();
|
|
417
|
-
await createToken({
|
|
418
|
-
tenant_id: tenantId,
|
|
419
|
-
user_id: user.id,
|
|
420
|
-
token: tokenValue,
|
|
421
|
-
type: 'email_verification',
|
|
422
|
-
expires_at: generateTokenExpiry(24)
|
|
423
|
-
});
|
|
424
|
-
|
|
425
|
-
if (emailService) {
|
|
426
|
-
const verifyUrl = `${appUrl}/verify-email?token=${tokenValue}`;
|
|
427
|
-
|
|
428
|
-
if (emailBranding) {
|
|
429
|
-
const { html, text } = emailVerificationEmail(emailBranding, { verifyUrl });
|
|
430
|
-
await emailService.sendMail({
|
|
431
|
-
to: email,
|
|
432
|
-
subject: 'Verify your email address',
|
|
433
|
-
html,
|
|
434
|
-
text,
|
|
435
|
-
});
|
|
436
|
-
} else {
|
|
437
|
-
await emailService.sendMail({
|
|
438
|
-
to: email,
|
|
439
|
-
subject: 'Verify your email address',
|
|
440
|
-
html: `<p>Welcome! Please verify your email by clicking the link below:</p><p><a href="${verifyUrl}">${verifyUrl}</a></p>`,
|
|
441
|
-
text: `Welcome! Please verify your email by visiting: ${verifyUrl}`
|
|
442
|
-
});
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
return res.status(201).json({
|
|
447
|
-
success: true,
|
|
448
|
-
message: 'Registration successful. Please check your email to verify your account.',
|
|
449
|
-
requiresVerification: true
|
|
450
|
-
});
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
// Auto-login (no verification required)
|
|
454
|
-
const token = generateToken(user, tenantId, req.tenant?.name, options);
|
|
455
|
-
const refreshTokenValue = generateRefreshToken(user.id, options);
|
|
456
|
-
|
|
457
|
-
res.status(201).json({
|
|
458
|
-
success: true,
|
|
459
|
-
token,
|
|
460
|
-
refreshToken: refreshTokenValue,
|
|
461
|
-
user: {
|
|
462
|
-
id: user.id,
|
|
463
|
-
email: user.email,
|
|
464
|
-
roles: user.roles,
|
|
465
|
-
first_name: user.first_name || first_name || '',
|
|
466
|
-
last_name: user.last_name || last_name || '',
|
|
467
|
-
},
|
|
468
|
-
tenant: {
|
|
469
|
-
id: tenantId,
|
|
470
|
-
name: req.tenant?.name
|
|
471
|
-
}
|
|
472
|
-
});
|
|
473
|
-
} catch (err) {
|
|
474
|
-
console.error('[Auth] Register error:', err);
|
|
475
|
-
res.status(500).json({
|
|
476
|
-
error: 'Registration failed',
|
|
477
|
-
message: 'An unexpected error occurred'
|
|
478
|
-
});
|
|
479
|
-
}
|
|
480
|
-
};
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
/**
|
|
484
|
-
* Create forgot password handler
|
|
485
|
-
*/
|
|
486
|
-
export function createForgotPasswordHandler(callbacks, options = {}) {
|
|
487
|
-
const {
|
|
488
|
-
findUserByEmail,
|
|
489
|
-
createToken,
|
|
490
|
-
invalidateExistingTokens
|
|
491
|
-
} = callbacks;
|
|
492
|
-
|
|
493
|
-
const {
|
|
494
|
-
emailService,
|
|
495
|
-
appUrl = '',
|
|
496
|
-
tokenExpiryHours = 1,
|
|
497
|
-
emailBranding
|
|
498
|
-
} = options;
|
|
499
|
-
|
|
500
|
-
return async (req, res) => {
|
|
501
|
-
try {
|
|
502
|
-
const { email } = req.body;
|
|
503
|
-
const tenantId = req.tenant?.id;
|
|
504
|
-
|
|
505
|
-
if (!email) {
|
|
506
|
-
return res.status(400).json({
|
|
507
|
-
error: 'Validation error',
|
|
508
|
-
message: 'Email is required'
|
|
509
|
-
});
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
// Always return the same response to prevent enumeration
|
|
513
|
-
const genericResponse = {
|
|
514
|
-
success: true,
|
|
515
|
-
message: 'If an account exists with that email, a password reset link has been sent'
|
|
516
|
-
};
|
|
517
|
-
|
|
518
|
-
if (!tenantId) {
|
|
519
|
-
return res.json(genericResponse);
|
|
520
|
-
}
|
|
521
|
-
|
|
522
|
-
const user = await findUserByEmail(email, tenantId);
|
|
523
|
-
if (!user) {
|
|
524
|
-
return res.json(genericResponse);
|
|
525
|
-
}
|
|
526
|
-
|
|
527
|
-
// Invalidate existing reset tokens
|
|
528
|
-
if (invalidateExistingTokens) {
|
|
529
|
-
await invalidateExistingTokens(user.id, 'password_reset');
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
// Generate and store reset token
|
|
533
|
-
const tokenValue = generateSecureToken();
|
|
534
|
-
await createToken({
|
|
535
|
-
tenant_id: tenantId,
|
|
536
|
-
user_id: user.id,
|
|
537
|
-
token: tokenValue,
|
|
538
|
-
type: 'password_reset',
|
|
539
|
-
expires_at: generateTokenExpiry(tokenExpiryHours)
|
|
540
|
-
});
|
|
541
|
-
|
|
542
|
-
if (emailService) {
|
|
543
|
-
const resetUrl = `${appUrl}/reset-password?token=${tokenValue}`;
|
|
544
|
-
|
|
545
|
-
if (emailBranding) {
|
|
546
|
-
const { html, text } = passwordResetEmail(emailBranding, { resetUrl, expiryHours: tokenExpiryHours });
|
|
547
|
-
await emailService.sendMail({
|
|
548
|
-
to: email,
|
|
549
|
-
subject: 'Reset your password',
|
|
550
|
-
html,
|
|
551
|
-
text,
|
|
552
|
-
});
|
|
553
|
-
} else {
|
|
554
|
-
await emailService.sendMail({
|
|
555
|
-
to: email,
|
|
556
|
-
subject: 'Reset your password',
|
|
557
|
-
html: `<p>You requested a password reset. Click the link below to set a new password:</p><p><a href="${resetUrl}">${resetUrl}</a></p><p>This link expires in ${tokenExpiryHours} hour(s).</p>`,
|
|
558
|
-
text: `You requested a password reset. Visit this link to set a new password: ${resetUrl}\n\nThis link expires in ${tokenExpiryHours} hour(s).`
|
|
559
|
-
});
|
|
560
|
-
}
|
|
561
|
-
}
|
|
562
|
-
|
|
563
|
-
res.json(genericResponse);
|
|
564
|
-
} catch (err) {
|
|
565
|
-
console.error('[Auth] Forgot password error:', err);
|
|
566
|
-
res.status(500).json({
|
|
567
|
-
error: 'Request failed',
|
|
568
|
-
message: 'An unexpected error occurred'
|
|
569
|
-
});
|
|
570
|
-
}
|
|
571
|
-
};
|
|
572
|
-
}
|
|
573
|
-
|
|
574
|
-
/**
|
|
575
|
-
* Create reset password handler
|
|
576
|
-
*/
|
|
577
|
-
export function createResetPasswordHandler(callbacks, options = {}) {
|
|
578
|
-
const {
|
|
579
|
-
findValidToken,
|
|
580
|
-
updateUserPassword,
|
|
581
|
-
markTokenUsed
|
|
582
|
-
} = callbacks;
|
|
583
|
-
|
|
584
|
-
const { passwordMinLength = 8 } = options;
|
|
585
|
-
|
|
586
|
-
return async (req, res) => {
|
|
587
|
-
try {
|
|
588
|
-
const { token, password } = req.body;
|
|
589
|
-
|
|
590
|
-
if (!token || !password) {
|
|
591
|
-
return res.status(400).json({
|
|
592
|
-
error: 'Validation error',
|
|
593
|
-
message: 'Token and new password are required'
|
|
594
|
-
});
|
|
595
|
-
}
|
|
596
|
-
|
|
597
|
-
if (password.length < passwordMinLength) {
|
|
598
|
-
return res.status(400).json({
|
|
599
|
-
error: 'Validation error',
|
|
600
|
-
message: `Password must be at least ${passwordMinLength} characters`
|
|
601
|
-
});
|
|
602
|
-
}
|
|
603
|
-
|
|
604
|
-
// Find and validate token
|
|
605
|
-
const tokenRecord = await findValidToken(token, 'password_reset');
|
|
606
|
-
if (!tokenRecord) {
|
|
607
|
-
return res.status(400).json({
|
|
608
|
-
error: 'Invalid token',
|
|
609
|
-
message: 'This reset link is invalid or has expired'
|
|
610
|
-
});
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
// Update password
|
|
614
|
-
const passwordHash = await hashPassword(password);
|
|
615
|
-
await updateUserPassword(tokenRecord.user_id, passwordHash);
|
|
616
|
-
|
|
617
|
-
// Mark token as used
|
|
618
|
-
await markTokenUsed(tokenRecord.id);
|
|
619
|
-
|
|
620
|
-
res.json({
|
|
621
|
-
success: true,
|
|
622
|
-
message: 'Password has been reset successfully'
|
|
623
|
-
});
|
|
624
|
-
} catch (err) {
|
|
625
|
-
console.error('[Auth] Reset password error:', err);
|
|
626
|
-
res.status(500).json({
|
|
627
|
-
error: 'Reset failed',
|
|
628
|
-
message: 'An unexpected error occurred'
|
|
629
|
-
});
|
|
630
|
-
}
|
|
631
|
-
};
|
|
632
|
-
}
|
|
633
|
-
|
|
634
|
-
/**
|
|
635
|
-
* Create verify email handler
|
|
636
|
-
*/
|
|
637
|
-
export function createVerifyEmailHandler(callbacks) {
|
|
638
|
-
const {
|
|
639
|
-
findValidToken,
|
|
640
|
-
markUserEmailVerified,
|
|
641
|
-
markTokenUsed
|
|
642
|
-
} = callbacks;
|
|
643
|
-
|
|
644
|
-
return async (req, res) => {
|
|
645
|
-
try {
|
|
646
|
-
const token = req.body.token || req.query.token;
|
|
647
|
-
|
|
648
|
-
if (!token) {
|
|
649
|
-
return res.status(400).json({
|
|
650
|
-
error: 'Validation error',
|
|
651
|
-
message: 'Verification token is required'
|
|
652
|
-
});
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
// Find and validate token
|
|
656
|
-
const tokenRecord = await findValidToken(token, 'email_verification');
|
|
657
|
-
if (!tokenRecord) {
|
|
658
|
-
return res.status(400).json({
|
|
659
|
-
error: 'Invalid token',
|
|
660
|
-
message: 'This verification link is invalid or has expired'
|
|
661
|
-
});
|
|
662
|
-
}
|
|
663
|
-
|
|
664
|
-
// Mark user as verified
|
|
665
|
-
await markUserEmailVerified(tokenRecord.user_id);
|
|
666
|
-
|
|
667
|
-
// Mark token as used
|
|
668
|
-
await markTokenUsed(tokenRecord.id);
|
|
669
|
-
|
|
670
|
-
res.json({
|
|
671
|
-
success: true,
|
|
672
|
-
message: 'Email verified successfully. You can now log in.'
|
|
673
|
-
});
|
|
674
|
-
} catch (err) {
|
|
675
|
-
console.error('[Auth] Verify email error:', err);
|
|
676
|
-
res.status(500).json({
|
|
677
|
-
error: 'Verification failed',
|
|
678
|
-
message: 'An unexpected error occurred'
|
|
679
|
-
});
|
|
680
|
-
}
|
|
681
|
-
};
|
|
682
|
-
}
|
|
1
|
+
import passport from 'passport';
|
|
2
|
+
import passportJwt from 'passport-jwt';
|
|
3
|
+
import jwt from 'jsonwebtoken';
|
|
4
|
+
import bcrypt from 'bcrypt';
|
|
5
|
+
import crypto from 'crypto';
|
|
6
|
+
import { emailVerificationEmail, passwordResetEmail } from '../services/email-templates.js';
|
|
7
|
+
|
|
8
|
+
const { Strategy: JwtStrategy, ExtractJwt } = passportJwt;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Default JWT options
|
|
12
|
+
*/
|
|
13
|
+
const DEFAULT_OPTIONS = {
|
|
14
|
+
jwtSecret: process.env.JWT_SECRET || 'avento-secret-change-me',
|
|
15
|
+
jwtExpiry: process.env.JWT_EXPIRY || '24h',
|
|
16
|
+
refreshExpiry: process.env.JWT_REFRESH_EXPIRY || '7d',
|
|
17
|
+
saltRounds: 10
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Configure Passport JWT strategy
|
|
22
|
+
*/
|
|
23
|
+
export function configurePassport(options = {}) {
|
|
24
|
+
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
25
|
+
|
|
26
|
+
const jwtOptions = {
|
|
27
|
+
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
|
28
|
+
secretOrKey: opts.jwtSecret,
|
|
29
|
+
passReqToCallback: true
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
passport.use(new JwtStrategy(jwtOptions, async (req, payload, done) => {
|
|
33
|
+
try {
|
|
34
|
+
// The payload contains user info from the token
|
|
35
|
+
// In a real app, you might want to fetch fresh user data from DB
|
|
36
|
+
|
|
37
|
+
if (!payload.user_id) {
|
|
38
|
+
return done(null, false, { message: 'Invalid token payload' });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Check token expiration (jwt.verify handles this, but double-check)
|
|
42
|
+
if (payload.exp && Date.now() >= payload.exp * 1000) {
|
|
43
|
+
return done(null, false, { message: 'Token expired' });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Attach user to request
|
|
47
|
+
const user = {
|
|
48
|
+
id: payload.user_id,
|
|
49
|
+
email: payload.email,
|
|
50
|
+
roles: payload.roles || [],
|
|
51
|
+
tenant_id: payload.tenant_id,
|
|
52
|
+
tenant_name: payload.tenant_name
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
return done(null, user);
|
|
56
|
+
} catch (err) {
|
|
57
|
+
return done(err, false);
|
|
58
|
+
}
|
|
59
|
+
}));
|
|
60
|
+
|
|
61
|
+
return passport;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Initialize auth middleware
|
|
66
|
+
*/
|
|
67
|
+
export function initAuth(app, options = {}) {
|
|
68
|
+
configurePassport(options);
|
|
69
|
+
app.use(passport.initialize());
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Middleware to require authentication
|
|
74
|
+
*/
|
|
75
|
+
export function requireAuth() {
|
|
76
|
+
return (req, res, next) => {
|
|
77
|
+
passport.authenticate('jwt', { session: false }, (err, user, info) => {
|
|
78
|
+
if (err) {
|
|
79
|
+
return res.status(500).json({
|
|
80
|
+
error: 'Authentication error',
|
|
81
|
+
message: err.message
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (!user) {
|
|
86
|
+
return res.status(401).json({
|
|
87
|
+
error: 'Unauthorized',
|
|
88
|
+
message: info?.message || 'Authentication required'
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
req.user = user;
|
|
93
|
+
|
|
94
|
+
// Also set tenant context from JWT if available
|
|
95
|
+
if (user.tenant_id && !req.tenant) {
|
|
96
|
+
req.tenant = {
|
|
97
|
+
id: user.tenant_id,
|
|
98
|
+
name: user.tenant_name
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
next();
|
|
103
|
+
})(req, res, next);
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Middleware to optionally authenticate (doesn't fail if no token)
|
|
109
|
+
*/
|
|
110
|
+
export function optionalAuth() {
|
|
111
|
+
return (req, res, next) => {
|
|
112
|
+
passport.authenticate('jwt', { session: false }, (err, user) => {
|
|
113
|
+
if (user) {
|
|
114
|
+
req.user = user;
|
|
115
|
+
if (user.tenant_id && !req.tenant) {
|
|
116
|
+
req.tenant = {
|
|
117
|
+
id: user.tenant_id,
|
|
118
|
+
name: user.tenant_name
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
next();
|
|
123
|
+
})(req, res, next);
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Generate JWT token for a user
|
|
129
|
+
*/
|
|
130
|
+
export function generateToken(user, tenantId, tenantName, options = {}) {
|
|
131
|
+
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
132
|
+
|
|
133
|
+
const payload = {
|
|
134
|
+
user_id: user.id,
|
|
135
|
+
email: user.email,
|
|
136
|
+
roles: user.roles || [],
|
|
137
|
+
tenant_id: tenantId,
|
|
138
|
+
tenant_name: tenantName
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
return jwt.sign(payload, opts.jwtSecret, {
|
|
142
|
+
expiresIn: opts.jwtExpiry
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Generate refresh token
|
|
148
|
+
*/
|
|
149
|
+
export function generateRefreshToken(userId, options = {}) {
|
|
150
|
+
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
151
|
+
|
|
152
|
+
return jwt.sign(
|
|
153
|
+
{ user_id: userId, type: 'refresh' },
|
|
154
|
+
opts.jwtSecret,
|
|
155
|
+
{ expiresIn: opts.refreshExpiry }
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Verify and decode a token
|
|
161
|
+
*/
|
|
162
|
+
export function verifyToken(token, options = {}) {
|
|
163
|
+
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
164
|
+
|
|
165
|
+
try {
|
|
166
|
+
return jwt.verify(token, opts.jwtSecret);
|
|
167
|
+
} catch (err) {
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Hash a password
|
|
174
|
+
*/
|
|
175
|
+
export async function hashPassword(password, options = {}) {
|
|
176
|
+
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
177
|
+
return bcrypt.hash(password, opts.saltRounds);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Compare password with hash
|
|
182
|
+
*/
|
|
183
|
+
export async function comparePassword(password, hash) {
|
|
184
|
+
return bcrypt.compare(password, hash);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Create login handler
|
|
189
|
+
*/
|
|
190
|
+
export function createLoginHandler(findUserByEmail, options = {}) {
|
|
191
|
+
const { getTenantSettings } = options;
|
|
192
|
+
|
|
193
|
+
return async (req, res) => {
|
|
194
|
+
try {
|
|
195
|
+
const { email, password, tenant_id } = req.body;
|
|
196
|
+
|
|
197
|
+
if (!email || !password) {
|
|
198
|
+
return res.status(400).json({
|
|
199
|
+
error: 'Validation error',
|
|
200
|
+
message: 'Email and password are required'
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// Find user
|
|
205
|
+
const user = await findUserByEmail(email, tenant_id);
|
|
206
|
+
|
|
207
|
+
if (!user) {
|
|
208
|
+
return res.status(401).json({
|
|
209
|
+
error: 'Authentication failed',
|
|
210
|
+
message: 'Invalid email or password'
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Verify password
|
|
215
|
+
const isValid = await comparePassword(password, user.password_hash);
|
|
216
|
+
|
|
217
|
+
if (!isValid) {
|
|
218
|
+
return res.status(401).json({
|
|
219
|
+
error: 'Authentication failed',
|
|
220
|
+
message: 'Invalid email or password'
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Check email verification if required
|
|
225
|
+
if (getTenantSettings && !user.email_verified_at) {
|
|
226
|
+
try {
|
|
227
|
+
const settings = await getTenantSettings(user.tenant_id);
|
|
228
|
+
if (settings?.requireEmailVerification) {
|
|
229
|
+
return res.status(403).json({
|
|
230
|
+
error: 'Email not verified',
|
|
231
|
+
message: 'Please verify your email address before logging in'
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
} catch (err) {
|
|
235
|
+
console.error('[Auth] Error checking tenant settings:', err);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Generate tokens
|
|
240
|
+
const token = generateToken(user, user.tenant_id, user.tenant_name, options);
|
|
241
|
+
const refreshToken = generateRefreshToken(user.id, options);
|
|
242
|
+
|
|
243
|
+
res.json({
|
|
244
|
+
token,
|
|
245
|
+
refreshToken,
|
|
246
|
+
user: {
|
|
247
|
+
id: user.id,
|
|
248
|
+
email: user.email,
|
|
249
|
+
roles: user.roles
|
|
250
|
+
},
|
|
251
|
+
tenant: {
|
|
252
|
+
id: user.tenant_id,
|
|
253
|
+
name: user.tenant_name
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
} catch (err) {
|
|
257
|
+
console.error('[Auth] Login error:', err);
|
|
258
|
+
res.status(500).json({
|
|
259
|
+
error: 'Login failed',
|
|
260
|
+
message: 'An unexpected error occurred'
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Generate a cryptographically secure token
|
|
268
|
+
*/
|
|
269
|
+
export function generateSecureToken(bytes = 32) {
|
|
270
|
+
return crypto.randomBytes(bytes).toString('hex');
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Generate a token expiry date (as UTC ISO string for consistent DB storage)
|
|
275
|
+
*/
|
|
276
|
+
export function generateTokenExpiry(hours = 1) {
|
|
277
|
+
return new Date(Date.now() + hours * 60 * 60 * 1000).toISOString();
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Create refresh token handler
|
|
282
|
+
*/
|
|
283
|
+
export function createRefreshHandler(findUserById, options = {}) {
|
|
284
|
+
return async (req, res) => {
|
|
285
|
+
try {
|
|
286
|
+
const { refreshToken } = req.body;
|
|
287
|
+
|
|
288
|
+
if (!refreshToken) {
|
|
289
|
+
return res.status(400).json({
|
|
290
|
+
error: 'Validation error',
|
|
291
|
+
message: 'Refresh token is required'
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const decoded = verifyToken(refreshToken, options);
|
|
296
|
+
|
|
297
|
+
if (!decoded || decoded.type !== 'refresh') {
|
|
298
|
+
return res.status(401).json({
|
|
299
|
+
error: 'Invalid token',
|
|
300
|
+
message: 'Invalid or expired refresh token'
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const user = await findUserById(decoded.user_id);
|
|
305
|
+
|
|
306
|
+
if (!user) {
|
|
307
|
+
return res.status(401).json({
|
|
308
|
+
error: 'User not found',
|
|
309
|
+
message: 'User no longer exists'
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const token = generateToken(user, user.tenant_id, user.tenant_name, options);
|
|
314
|
+
|
|
315
|
+
res.json({ token });
|
|
316
|
+
} catch (err) {
|
|
317
|
+
console.error('[Auth] Refresh error:', err);
|
|
318
|
+
res.status(500).json({
|
|
319
|
+
error: 'Refresh failed',
|
|
320
|
+
message: 'An unexpected error occurred'
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Validate email format
|
|
328
|
+
*/
|
|
329
|
+
function isValidEmail(email) {
|
|
330
|
+
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* Create register handler
|
|
335
|
+
*/
|
|
336
|
+
export function createRegisterHandler(callbacks, options = {}) {
|
|
337
|
+
const {
|
|
338
|
+
findUserByEmail,
|
|
339
|
+
createUser,
|
|
340
|
+
getTenantSettings,
|
|
341
|
+
createToken
|
|
342
|
+
} = callbacks;
|
|
343
|
+
|
|
344
|
+
const {
|
|
345
|
+
emailService,
|
|
346
|
+
appUrl = '',
|
|
347
|
+
passwordMinLength = 8,
|
|
348
|
+
emailBranding
|
|
349
|
+
} = options;
|
|
350
|
+
|
|
351
|
+
return async (req, res) => {
|
|
352
|
+
try {
|
|
353
|
+
const { email, password, first_name, last_name } = req.body;
|
|
354
|
+
const tenantId = req.tenant?.id;
|
|
355
|
+
|
|
356
|
+
// Validate required fields
|
|
357
|
+
if (!email || !password || !first_name || !last_name) {
|
|
358
|
+
return res.status(400).json({
|
|
359
|
+
error: 'Validation error',
|
|
360
|
+
message: 'Email, password, first name, and last name are required'
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
if (!isValidEmail(email)) {
|
|
365
|
+
return res.status(400).json({
|
|
366
|
+
error: 'Validation error',
|
|
367
|
+
message: 'Invalid email format'
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
if (password.length < passwordMinLength) {
|
|
372
|
+
return res.status(400).json({
|
|
373
|
+
error: 'Validation error',
|
|
374
|
+
message: `Password must be at least ${passwordMinLength} characters`
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
if (!tenantId) {
|
|
379
|
+
return res.status(400).json({
|
|
380
|
+
error: 'Validation error',
|
|
381
|
+
message: 'Tenant context is required for registration'
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// Check tenant settings
|
|
386
|
+
const settings = await getTenantSettings(tenantId);
|
|
387
|
+
if (!settings?.allowSelfRegistration) {
|
|
388
|
+
return res.status(403).json({
|
|
389
|
+
error: 'Registration disabled',
|
|
390
|
+
message: 'Self-registration is not allowed for this tenant'
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// Check for existing user
|
|
395
|
+
const existingUser = await findUserByEmail(email, tenantId);
|
|
396
|
+
if (existingUser) {
|
|
397
|
+
return res.status(409).json({
|
|
398
|
+
error: 'User exists',
|
|
399
|
+
message: 'An account with this email already exists'
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// Create user
|
|
404
|
+
const passwordHash = await hashPassword(password);
|
|
405
|
+
const user = await createUser({
|
|
406
|
+
email,
|
|
407
|
+
password_hash: passwordHash,
|
|
408
|
+
first_name,
|
|
409
|
+
last_name,
|
|
410
|
+
tenant_id: tenantId,
|
|
411
|
+
roles: ['user']
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
// Handle email verification
|
|
415
|
+
if (settings.requireEmailVerification) {
|
|
416
|
+
const tokenValue = generateSecureToken();
|
|
417
|
+
await createToken({
|
|
418
|
+
tenant_id: tenantId,
|
|
419
|
+
user_id: user.id,
|
|
420
|
+
token: tokenValue,
|
|
421
|
+
type: 'email_verification',
|
|
422
|
+
expires_at: generateTokenExpiry(24)
|
|
423
|
+
});
|
|
424
|
+
|
|
425
|
+
if (emailService) {
|
|
426
|
+
const verifyUrl = `${appUrl}/verify-email?token=${tokenValue}`;
|
|
427
|
+
|
|
428
|
+
if (emailBranding) {
|
|
429
|
+
const { html, text } = emailVerificationEmail(emailBranding, { verifyUrl });
|
|
430
|
+
await emailService.sendMail({
|
|
431
|
+
to: email,
|
|
432
|
+
subject: 'Verify your email address',
|
|
433
|
+
html,
|
|
434
|
+
text,
|
|
435
|
+
});
|
|
436
|
+
} else {
|
|
437
|
+
await emailService.sendMail({
|
|
438
|
+
to: email,
|
|
439
|
+
subject: 'Verify your email address',
|
|
440
|
+
html: `<p>Welcome! Please verify your email by clicking the link below:</p><p><a href="${verifyUrl}">${verifyUrl}</a></p>`,
|
|
441
|
+
text: `Welcome! Please verify your email by visiting: ${verifyUrl}`
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
return res.status(201).json({
|
|
447
|
+
success: true,
|
|
448
|
+
message: 'Registration successful. Please check your email to verify your account.',
|
|
449
|
+
requiresVerification: true
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// Auto-login (no verification required)
|
|
454
|
+
const token = generateToken(user, tenantId, req.tenant?.name, options);
|
|
455
|
+
const refreshTokenValue = generateRefreshToken(user.id, options);
|
|
456
|
+
|
|
457
|
+
res.status(201).json({
|
|
458
|
+
success: true,
|
|
459
|
+
token,
|
|
460
|
+
refreshToken: refreshTokenValue,
|
|
461
|
+
user: {
|
|
462
|
+
id: user.id,
|
|
463
|
+
email: user.email,
|
|
464
|
+
roles: user.roles,
|
|
465
|
+
first_name: user.first_name || first_name || '',
|
|
466
|
+
last_name: user.last_name || last_name || '',
|
|
467
|
+
},
|
|
468
|
+
tenant: {
|
|
469
|
+
id: tenantId,
|
|
470
|
+
name: req.tenant?.name
|
|
471
|
+
}
|
|
472
|
+
});
|
|
473
|
+
} catch (err) {
|
|
474
|
+
console.error('[Auth] Register error:', err);
|
|
475
|
+
res.status(500).json({
|
|
476
|
+
error: 'Registration failed',
|
|
477
|
+
message: 'An unexpected error occurred'
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* Create forgot password handler
|
|
485
|
+
*/
|
|
486
|
+
export function createForgotPasswordHandler(callbacks, options = {}) {
|
|
487
|
+
const {
|
|
488
|
+
findUserByEmail,
|
|
489
|
+
createToken,
|
|
490
|
+
invalidateExistingTokens
|
|
491
|
+
} = callbacks;
|
|
492
|
+
|
|
493
|
+
const {
|
|
494
|
+
emailService,
|
|
495
|
+
appUrl = '',
|
|
496
|
+
tokenExpiryHours = 1,
|
|
497
|
+
emailBranding
|
|
498
|
+
} = options;
|
|
499
|
+
|
|
500
|
+
return async (req, res) => {
|
|
501
|
+
try {
|
|
502
|
+
const { email } = req.body;
|
|
503
|
+
const tenantId = req.tenant?.id;
|
|
504
|
+
|
|
505
|
+
if (!email) {
|
|
506
|
+
return res.status(400).json({
|
|
507
|
+
error: 'Validation error',
|
|
508
|
+
message: 'Email is required'
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// Always return the same response to prevent enumeration
|
|
513
|
+
const genericResponse = {
|
|
514
|
+
success: true,
|
|
515
|
+
message: 'If an account exists with that email, a password reset link has been sent'
|
|
516
|
+
};
|
|
517
|
+
|
|
518
|
+
if (!tenantId) {
|
|
519
|
+
return res.json(genericResponse);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
const user = await findUserByEmail(email, tenantId);
|
|
523
|
+
if (!user) {
|
|
524
|
+
return res.json(genericResponse);
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// Invalidate existing reset tokens
|
|
528
|
+
if (invalidateExistingTokens) {
|
|
529
|
+
await invalidateExistingTokens(user.id, 'password_reset');
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// Generate and store reset token
|
|
533
|
+
const tokenValue = generateSecureToken();
|
|
534
|
+
await createToken({
|
|
535
|
+
tenant_id: tenantId,
|
|
536
|
+
user_id: user.id,
|
|
537
|
+
token: tokenValue,
|
|
538
|
+
type: 'password_reset',
|
|
539
|
+
expires_at: generateTokenExpiry(tokenExpiryHours)
|
|
540
|
+
});
|
|
541
|
+
|
|
542
|
+
if (emailService) {
|
|
543
|
+
const resetUrl = `${appUrl}/reset-password?token=${tokenValue}`;
|
|
544
|
+
|
|
545
|
+
if (emailBranding) {
|
|
546
|
+
const { html, text } = passwordResetEmail(emailBranding, { resetUrl, expiryHours: tokenExpiryHours });
|
|
547
|
+
await emailService.sendMail({
|
|
548
|
+
to: email,
|
|
549
|
+
subject: 'Reset your password',
|
|
550
|
+
html,
|
|
551
|
+
text,
|
|
552
|
+
});
|
|
553
|
+
} else {
|
|
554
|
+
await emailService.sendMail({
|
|
555
|
+
to: email,
|
|
556
|
+
subject: 'Reset your password',
|
|
557
|
+
html: `<p>You requested a password reset. Click the link below to set a new password:</p><p><a href="${resetUrl}">${resetUrl}</a></p><p>This link expires in ${tokenExpiryHours} hour(s).</p>`,
|
|
558
|
+
text: `You requested a password reset. Visit this link to set a new password: ${resetUrl}\n\nThis link expires in ${tokenExpiryHours} hour(s).`
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
res.json(genericResponse);
|
|
564
|
+
} catch (err) {
|
|
565
|
+
console.error('[Auth] Forgot password error:', err);
|
|
566
|
+
res.status(500).json({
|
|
567
|
+
error: 'Request failed',
|
|
568
|
+
message: 'An unexpected error occurred'
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* Create reset password handler
|
|
576
|
+
*/
|
|
577
|
+
export function createResetPasswordHandler(callbacks, options = {}) {
|
|
578
|
+
const {
|
|
579
|
+
findValidToken,
|
|
580
|
+
updateUserPassword,
|
|
581
|
+
markTokenUsed
|
|
582
|
+
} = callbacks;
|
|
583
|
+
|
|
584
|
+
const { passwordMinLength = 8 } = options;
|
|
585
|
+
|
|
586
|
+
return async (req, res) => {
|
|
587
|
+
try {
|
|
588
|
+
const { token, password } = req.body;
|
|
589
|
+
|
|
590
|
+
if (!token || !password) {
|
|
591
|
+
return res.status(400).json({
|
|
592
|
+
error: 'Validation error',
|
|
593
|
+
message: 'Token and new password are required'
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
if (password.length < passwordMinLength) {
|
|
598
|
+
return res.status(400).json({
|
|
599
|
+
error: 'Validation error',
|
|
600
|
+
message: `Password must be at least ${passwordMinLength} characters`
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
// Find and validate token
|
|
605
|
+
const tokenRecord = await findValidToken(token, 'password_reset');
|
|
606
|
+
if (!tokenRecord) {
|
|
607
|
+
return res.status(400).json({
|
|
608
|
+
error: 'Invalid token',
|
|
609
|
+
message: 'This reset link is invalid or has expired'
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// Update password
|
|
614
|
+
const passwordHash = await hashPassword(password);
|
|
615
|
+
await updateUserPassword(tokenRecord.user_id, passwordHash);
|
|
616
|
+
|
|
617
|
+
// Mark token as used
|
|
618
|
+
await markTokenUsed(tokenRecord.id);
|
|
619
|
+
|
|
620
|
+
res.json({
|
|
621
|
+
success: true,
|
|
622
|
+
message: 'Password has been reset successfully'
|
|
623
|
+
});
|
|
624
|
+
} catch (err) {
|
|
625
|
+
console.error('[Auth] Reset password error:', err);
|
|
626
|
+
res.status(500).json({
|
|
627
|
+
error: 'Reset failed',
|
|
628
|
+
message: 'An unexpected error occurred'
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/**
|
|
635
|
+
* Create verify email handler
|
|
636
|
+
*/
|
|
637
|
+
export function createVerifyEmailHandler(callbacks) {
|
|
638
|
+
const {
|
|
639
|
+
findValidToken,
|
|
640
|
+
markUserEmailVerified,
|
|
641
|
+
markTokenUsed
|
|
642
|
+
} = callbacks;
|
|
643
|
+
|
|
644
|
+
return async (req, res) => {
|
|
645
|
+
try {
|
|
646
|
+
const token = req.body.token || req.query.token;
|
|
647
|
+
|
|
648
|
+
if (!token) {
|
|
649
|
+
return res.status(400).json({
|
|
650
|
+
error: 'Validation error',
|
|
651
|
+
message: 'Verification token is required'
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
// Find and validate token
|
|
656
|
+
const tokenRecord = await findValidToken(token, 'email_verification');
|
|
657
|
+
if (!tokenRecord) {
|
|
658
|
+
return res.status(400).json({
|
|
659
|
+
error: 'Invalid token',
|
|
660
|
+
message: 'This verification link is invalid or has expired'
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
// Mark user as verified
|
|
665
|
+
await markUserEmailVerified(tokenRecord.user_id);
|
|
666
|
+
|
|
667
|
+
// Mark token as used
|
|
668
|
+
await markTokenUsed(tokenRecord.id);
|
|
669
|
+
|
|
670
|
+
res.json({
|
|
671
|
+
success: true,
|
|
672
|
+
message: 'Email verified successfully. You can now log in.'
|
|
673
|
+
});
|
|
674
|
+
} catch (err) {
|
|
675
|
+
console.error('[Auth] Verify email error:', err);
|
|
676
|
+
res.status(500).json({
|
|
677
|
+
error: 'Verification failed',
|
|
678
|
+
message: 'An unexpected error occurred'
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
};
|
|
682
|
+
}
|