forked from geturbackend/urBackend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuserAuth.controller.js
More file actions
1869 lines (1573 loc) · 69.2 KB
/
Copy pathuserAuth.controller.js
File metadata and controls
1869 lines (1573 loc) · 69.2 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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { z } = require('zod');
const mongoose = require('mongoose');
const crypto = require('crypto');
const {redis} = require('@urbackend/common');
const {Project} = require('@urbackend/common');
const { authEmailQueue } = require('@urbackend/common');
const { checkLockout, recordFailedAttempt, clearLockout } = require('@urbackend/common');
const { AppError } = require('@urbackend/common');
const { getRefreshSession, persistRefreshSession, revokeSessionChain } = require('@urbackend/common');
const { loginSchema, userSignupSchema, resetPasswordSchema, onlyEmailSchema, verifyOtpSchema, changePasswordSchema, sanitize } = require('@urbackend/common');
const { getConnection } = require('@urbackend/common');
const { getCompiledModel } = require('@urbackend/common');
const { decrypt } = require('@urbackend/common');
const {
assertRefreshRateLimits,
clearRefreshCookie,
hashRefreshToken,
issueAuthTokens,
parseRefreshToken,
readRefreshTokenFromRequest,
shouldExposeRefreshToken
} = require('../utils/refreshToken');
const checkUserSoftDeleted = (user) => {
if (user && user.isDeleted) {
const dateStr = user.deletedAt
? new Date(new Date(user.deletedAt).getTime() + 30 * 24 * 60 * 60 * 1000).toDateString()
: 'soon';
return `Your account is scheduled for deletion on ${dateStr}. Please contact the administrator to recover it.`;
}
return null;
};
const SOCIAL_PROVIDER_KEYS = ['github', 'google'];
const SOCIAL_STATE_TTL_SECONDS = 600;
const SOCIAL_REFRESH_EXCHANGE_TTL_SECONDS = 60;
/**
* Checks if a public OTP cooldown is active for this email.
* @param {string} projectId
* @param {string} email
* @param {string} type
*/
const checkPublicOtpCooldown = async (projectId, email, type = 'verification') => {
const cooldownKey = `project:${projectId}:otp:cooldown:${type}:${email}`;
const exists = await redis.get(cooldownKey);
if (exists) {
const ttl = await redis.ttl(cooldownKey);
const err = new Error(`Please wait ${ttl} seconds before requesting another code.`);
err.statusCode = 429;
throw err;
}
};
/**
* Sets a 60s cooldown for OTP requests to prevent spam.
*/
const setPublicOtpCooldown = async (projectId, email, type = 'verification') => {
const cooldownKey = `project:${projectId}:otp:cooldown:${type}:${email}`;
await redis.set(cooldownKey, '1', 'EX', 60);
};
/**
* Returns the base URL for the public API, used for redirect URI construction.
* @returns {string}
*/
const getPublicApiBaseUrl = () => {
const configured = process.env.PUBLIC_API_URL?.trim();
if (configured) return configured.replace(/\/$/, '');
const port = process.env.USER_PORT || 1235;
return `http://localhost:${port}`;
};
/**
* Returns the Redis key for storing OAuth state.
* @param {string} state - CSRF state token
* @returns {string}
*/
const getSocialStateKey = (state) => `project:auth:oauth:state:${state}`;
/**
* Returns the Redis key for storing the temporary social refresh exchange code.
* @param {string} rtCode - Exchange code
* @returns {string}
*/
const getSocialRefreshExchangeKey = (rtCode) => `project:social-auth:refresh-exchange:${rtCode}`;
/**
* Returns the frontend OAuth callback URL for a project.
* Falls back to FRONTEND_URL env or localhost when siteUrl is not set.
* @param {Object} project - Project document
* @returns {string}
*/
const getFrontendCallbackBaseUrl = (project) => {
const configured = String(project?.siteUrl || '').trim();
const base = configured || process.env.FRONTEND_URL || '';
if (!base) {
console.warn('[social-auth] getFrontendCallbackBaseUrl: siteUrl is not set on the project and FRONTEND_URL env is not configured. Falling back to http://localhost:5173. Set siteUrl in Project Settings or configure FRONTEND_URL.');
}
return `${(base || 'http://localhost:5173').replace(/\/$/, '')}/auth/callback`;
};
/**
* Decodes a base64url-encoded string into a Buffer.
* @param {string} input - Base64url encoded string
* @returns {Buffer}
*/
const toBase64UrlBuffer = (input) => Buffer.from(input.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(input.length / 4) * 4, '='), 'base64');
/**
* In-memory cache for Google's public JWK keys.
* Keys are refreshed when the cache expires (based on Cache-Control max-age).
* An in-flight promise is stored to prevent redundant concurrent fetches (single-flight).
*/
const googleJwkCache = { keys: null, expiresAt: 0, inflight: null };
/**
* Fetches Google's public JWK keys, using an in-memory cache keyed by Cache-Control max-age.
* Uses a single-flight pattern so that concurrent requests share one fetch instead of many.
* @returns {Promise<Array>} Array of JWK key objects
*/
const getGooglePublicKeys = async () => {
const now = Date.now();
if (googleJwkCache.keys && now < googleJwkCache.expiresAt) {
return googleJwkCache.keys;
}
// Single-flight: reuse in-flight promise if a fetch is already in progress.
if (googleJwkCache.inflight) {
return googleJwkCache.inflight;
}
googleJwkCache.inflight = (async () => {
try {
const certsResponse = await fetch('https://www.googleapis.com/oauth2/v3/certs');
if (!certsResponse.ok) {
throw new Error('Unable to fetch Google JWK keys');
}
const certsPayload = await certsResponse.json();
const keys = certsPayload.keys || [];
// Parse Cache-Control max-age from response headers to determine TTL.
const cacheControl = (typeof certsResponse.headers?.get === 'function')
? (certsResponse.headers.get('cache-control') || '')
: '';
const maxAgeMatch = cacheControl.match(/max-age=(\d+)/);
const ttlMs = maxAgeMatch ? parseInt(maxAgeMatch[1], 10) * 1000 : 3600 * 1000;
googleJwkCache.keys = keys;
googleJwkCache.expiresAt = Date.now() + ttlMs;
return keys;
} finally {
googleJwkCache.inflight = null;
}
})();
return googleJwkCache.inflight;
};
/**
* Asserts that a project has auth enabled and a valid users collection schema.
* Throws with an appropriate statusCode on failure.
* @param {Object} project - Lean project document
* @returns {Object} The users collection config
*/
const assertAuthProjectReady = (project) => {
if (!project?.isAuthEnabled) {
const err = new Error('Authentication service is disabled');
err.statusCode = 403;
throw err;
}
const usersCollection = project.collections?.find(c => c.name === 'users');
if (!usersCollection) {
const err = new Error("User Schema Missing");
err.statusCode = 403;
err.publicMessage = "Authentication is enabled, but the 'users' collection has not been defined.";
throw err;
}
const hasEmail = usersCollection.model.find(f => f.key === 'email' && f.type === 'String' && f.required);
const hasPassword = usersCollection.model.find(f => f.key === 'password' && f.type === 'String' && f.required);
if (!hasEmail || !hasPassword) {
const err = new Error('Invalid Users Schema');
err.statusCode = 422;
err.publicMessage = "The 'users' collection must contain required 'email' and 'password' String fields.";
throw err;
}
return usersCollection;
};
/**
* Loads and decrypts a social provider's config for a project.
* @param {string} projectId - Project ObjectId
* @param {string} provider - 'github' or 'google'
* @returns {Promise<{project: Object, providerConfig: Object|null}|null>}
*/
const getSocialProviderConfig = async (projectId, provider) => {
const selectClause = [
'name',
'resources',
'collections',
'jwtSecret',
'isAuthEnabled',
`authProviders.${provider}.enabled`,
`authProviders.${provider}.clientId`,
`authProviders.${provider}.redirectUri`,
`+authProviders.${provider}.clientSecret.encrypted`,
`+authProviders.${provider}.clientSecret.iv`,
`+authProviders.${provider}.clientSecret.tag`,
].join(' ');
const project = await Project.findById(projectId).select(selectClause).lean();
if (!project) return null;
const providerConfig = project.authProviders?.[provider];
if (!providerConfig?.enabled || !providerConfig.clientId || !providerConfig.clientSecret) {
return { project, providerConfig: null };
}
const decryptedSecret = decrypt(providerConfig.clientSecret);
if (!decryptedSecret) {
return { project, providerConfig: null };
}
return {
project,
providerConfig: {
enabled: true,
clientId: providerConfig.clientId,
clientSecret: decryptedSecret,
redirectUri: `${getPublicApiBaseUrl()}/api/userAuth/social/${provider}/callback`
}
};
};
/**
* Builds the GitHub OAuth authorization URL.
* @param {Object} params
* @param {string} params.clientId
* @param {string} params.redirectUri
* @param {string} params.state - CSRF state token
* @returns {string}
*/
const buildGithubAuthorizeUrl = ({ clientId, redirectUri, state }) => {
const params = new URLSearchParams({
client_id: clientId,
redirect_uri: redirectUri,
scope: 'read:user user:email',
state,
});
return `https://github.com/login/oauth/authorize?${params.toString()}`;
};
/**
* Builds the Google OAuth authorization URL.
* @param {Object} params
* @param {string} params.clientId
* @param {string} params.redirectUri
* @param {string} params.state - CSRF state token
* @returns {string}
*/
const buildGoogleAuthorizeUrl = ({ clientId, redirectUri, state }) => {
const params = new URLSearchParams({
client_id: clientId,
redirect_uri: redirectUri,
response_type: 'code',
scope: 'openid email profile',
state,
access_type: 'offline',
prompt: 'consent',
});
return `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;
};
/**
* Exchanges a GitHub OAuth authorization code for an access token.
* @param {Object} params
* @param {string} params.code
* @param {string} params.clientId
* @param {string} params.clientSecret
* @param {string} params.redirectUri
* @returns {Promise<{accessToken: string, tokenType: string}>}
*/
const exchangeGithubCodeForToken = async ({ code, clientId, clientSecret, redirectUri }) => {
const response = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
client_id: clientId,
client_secret: clientSecret,
code,
redirect_uri: redirectUri,
}),
});
const payload = await response.json();
if (!response.ok || payload.error || !payload.access_token) {
throw new Error(payload.error_description || payload.error || 'GitHub token exchange failed');
}
return {
accessToken: payload.access_token,
tokenType: payload.token_type || 'bearer',
};
};
/**
* Exchanges a Google OAuth authorization code for tokens including an id_token.
* @param {Object} params
* @param {string} params.code
* @param {string} params.clientId
* @param {string} params.clientSecret
* @param {string} params.redirectUri
* @returns {Promise<Object>} Google token response including id_token
*/
const exchangeGoogleCodeForToken = async ({ code, clientId, clientSecret, redirectUri }) => {
const params = new URLSearchParams({
code,
client_id: clientId,
client_secret: clientSecret,
redirect_uri: redirectUri,
grant_type: 'authorization_code',
});
const response = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: params.toString(),
});
const payload = await response.json();
if (!response.ok || payload.error || !payload.id_token) {
throw new Error(payload.error_description || payload.error || 'Google token exchange failed');
}
return payload;
};
/**
* Fetches the user profile from GitHub using an access token.
* Includes user email fetching as a secondary step.
* @param {string} accessToken
* @returns {Promise<Object>} Normalized profile
*/
const fetchGithubProfile = async (accessToken) => {
const headers = {
'Authorization': `Bearer ${accessToken}`,
'Accept': 'application/vnd.github+json',
'User-Agent': 'urBackend-social-auth',
};
const [profileResponse, emailsResponse] = await Promise.all([
fetch('https://api.github.com/user', { headers }),
fetch('https://api.github.com/user/emails', { headers }),
]);
const profile = await profileResponse.json();
const emails = await emailsResponse.json();
if (!profileResponse.ok) {
throw new Error(profile.message || 'Failed to fetch GitHub profile');
}
if (!emailsResponse.ok || !Array.isArray(emails)) {
throw new Error('Failed to fetch GitHub email addresses');
}
const verifiedEmail = emails.find((entry) => entry.primary && entry.verified) || emails.find((entry) => entry.verified);
return {
providerUserId: String(profile.id || ''),
email: verifiedEmail?.email || profile.email || '',
emailVerified: !!verifiedEmail?.verified,
username: profile.login || '',
name: profile.name || profile.login || '',
avatarUrl: profile.avatar_url || '',
rawProfile: profile,
};
};
/**
* Verifies a Google id_token using Google's public JWK keys.
* @param {Object} params
* @param {string} params.idToken - Google JWT id_token
* @param {string} params.clientId - OAuth client ID for audience validation
* @returns {Promise<Object>} Decoded JWT claims
*/
const verifyGoogleIdToken = async ({ idToken, clientId }) => {
const parts = String(idToken || '').split('.');
if (parts.length !== 3) {
throw new Error('Invalid Google id_token format');
}
const [encodedHeader, encodedPayload, encodedSignature] = parts;
const header = JSON.parse(toBase64UrlBuffer(encodedHeader).toString('utf8'));
const payload = JSON.parse(toBase64UrlBuffer(encodedPayload).toString('utf8'));
if (header.alg !== 'RS256' || !header.kid) {
throw new Error('Unsupported Google id_token signature');
}
const certsKeys = await getGooglePublicKeys();
const signingKey = certsKeys.find((key) => key.kid === header.kid);
if (!signingKey) {
throw new Error('Unable to verify Google id_token signing key');
}
const publicKey = crypto.createPublicKey({ key: signingKey, format: 'jwk' });
const verified = crypto.verify(
'RSA-SHA256',
Buffer.from(`${encodedHeader}.${encodedPayload}`),
publicKey,
toBase64UrlBuffer(encodedSignature)
);
if (!verified) {
throw new Error('Invalid Google id_token signature');
}
const validIssuers = new Set(['accounts.google.com', 'https://accounts.google.com']);
const nowSeconds = Math.floor(Date.now() / 1000);
const audienceMatches = Array.isArray(payload.aud)
? payload.aud.includes(clientId)
: payload.aud === clientId;
if (!audienceMatches) {
throw new Error('Google id_token audience mismatch');
}
if (!validIssuers.has(payload.iss)) {
throw new Error('Google id_token issuer mismatch');
}
if (!payload.exp || Number(payload.exp) <= nowSeconds) {
throw new Error('Google id_token has expired');
}
return payload;
};
/**
* Verifies a Google ID token and returns the normalized user profile.
* @param {Object} params
* @param {string} params.idToken
* @param {string} params.clientId
* @returns {Promise<Object>} Normalized profile
*/
const fetchGoogleProfile = async ({ idToken, clientId }) => {
const claims = await verifyGoogleIdToken({ idToken, clientId });
return {
providerUserId: String(claims.sub || ''),
email: claims.email || '',
emailVerified: !!claims.email_verified,
username: claims.email ? String(claims.email).split('@')[0] : '',
name: claims.name || '',
avatarUrl: claims.picture || '',
rawProfile: claims,
};
};
const socialProviders = {
github: {
buildAuthorizeUrl: buildGithubAuthorizeUrl,
exchangeCodeForToken: exchangeGithubCodeForToken,
fetchProfile: async ({ tokenResponse }) => fetchGithubProfile(tokenResponse.accessToken),
},
google: {
buildAuthorizeUrl: buildGoogleAuthorizeUrl,
exchangeCodeForToken: exchangeGoogleCodeForToken,
fetchProfile: async ({ tokenResponse, providerConfig }) => fetchGoogleProfile({
idToken: tokenResponse.id_token,
clientId: providerConfig.clientId,
}),
},
};
/**
* Builds a new user document payload for a social-auth-created user.
* Generates a random hashed password to satisfy the users schema contract.
* @param {Object} usersColConfig - Users collection config from project
* @param {Object} profile - Normalized social profile
* @returns {Promise<Object>} User document fields
*/
const buildSocialAuthUserPayload = async (usersColConfig, profile) => {
const randomPassword = crypto.randomBytes(24).toString('hex');
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(randomPassword, salt);
return buildAuthUserPayload(
usersColConfig,
{
email: profile.email,
password: randomPassword,
username: profile.username,
name: profile.name,
avatarUrl: profile.avatarUrl,
},
hashedPassword,
profile.emailVerified
);
};
/**
* Finds an existing user by provider ID or verified email, or creates a new user.
* Only links by email when profile.emailVerified is true to prevent account takeover.
* @param {Object} params
* @param {Object} params.project - Project document
* @param {Object} params.usersColConfig - Users collection config
* @param {Object} params.Model - Mongoose model for the users collection
* @param {string} params.provider - 'github' or 'google'
* @param {Object} params.profile - Normalized social profile
* @returns {Promise<{user: Object, isNewUser: boolean, linkedByEmail: boolean}>}
*/
const findOrCreateSocialUser = async ({ project, usersColConfig, Model, provider, profile }) => {
const providerIdField = `${provider}Id`;
const providerName = provider;
let user = await Model.findOne({ [providerIdField]: profile.providerUserId });
if (user) {
const deletedMsg = checkUserSoftDeleted(user);
if (deletedMsg) {
const err = new Error(deletedMsg);
err.statusCode = 403;
throw err;
}
return { user, isNewUser: false, linkedByEmail: false };
}
if (!profile.email) {
const err = new Error(`${providerName} did not return an email address for this account.`);
err.statusCode = 422;
throw err;
}
user = await Model.findOne({ email: profile.email });
if (user) {
const deletedMsg = checkUserSoftDeleted(user);
if (deletedMsg) {
const err = new Error(deletedMsg);
err.statusCode = 403;
throw err;
}
// P1: Only link if provider email is verified; reject if unverified to prevent account takeover
if (!profile.emailVerified) {
const err = new Error(`Cannot link ${providerName} account: the provider email is not verified. Please verify your email with ${providerName} first.`);
err.statusCode = 403;
err.code = 'SOCIAL_AUTH_EMAIL_NOT_VERIFIED';
throw err;
}
const update = {
$set: {
[providerIdField]: profile.providerUserId,
...(profile.avatarUrl ? { avatarUrl: profile.avatarUrl } : {}),
},
$addToSet: { authProviders: providerName },
};
const verificationField = getVerificationField(usersColConfig);
if (verificationField) {
update.$set[verificationField] = true;
}
await Model.updateOne({ _id: user._id }, update);
user = await Model.findOne({ _id: user._id });
return { user, isNewUser: false, linkedByEmail: true };
}
const newUserPayload = await buildSocialAuthUserPayload(usersColConfig, profile);
newUserPayload[providerIdField] = profile.providerUserId;
newUserPayload.authProviders = [providerName];
if (profile.avatarUrl && newUserPayload.avatarUrl === undefined) {
newUserPayload.avatarUrl = profile.avatarUrl;
}
try {
user = await Model.create(newUserPayload);
} catch (err) {
if (err.name === "ValidationError") {
try {
if (typeof Model === "function") {
const doc = new Model(newUserPayload);
await doc.save({ validateBeforeSave: false });
user = doc;
} else {
user = await Model.create(newUserPayload);
}
} catch (saveErr) {
if (saveErr.code === 11000) {
throw new AppError(409, "User already exists.");
}
throw new AppError(500, "Failed to complete social signup.");
}
} else {
if (err.code === 11000) {
throw new AppError(409, "User already exists.");
}
throw new AppError(500, "Failed to complete social signup.");
}
}
return { user, isNewUser: true, linkedByEmail: false };
};
/**
* Loads the compiled Mongoose model for the users collection.
* @param {Object} project - Lean project document
* @returns {Promise<{usersColConfig: Object|null, Model: Object|null}>}
*/
const getUsersModel = async (project) => {
const usersColConfig = project.collections.find(c => c.name === 'users');
if (!usersColConfig) return { usersColConfig: null, Model: null };
const connection = await getConnection(project._id);
const Model = getCompiledModel(connection, usersColConfig, project._id, project.resources.db.isExternal);
return { usersColConfig, Model };
};
/**
* Checks whether a required field key exists in the users collection schema.
* @param {Object} usersColConfig - Users collection config
* @param {string} fieldKey - Field key to check
* @returns {boolean}
*/
const hasRequiredField = (usersColConfig, fieldKey) => {
const model = usersColConfig?.model || [];
return model.some((f) => f?.key === fieldKey && !!f?.required);
};
/**
* Returns the name of the email verification field in the users schema, if it exists.
* @param {Object} usersColConfig - Users collection config
* @returns {string|null}
*/
const getVerificationField = (usersColConfig) => {
const modelKeys = (usersColConfig?.model || []).map((f) => f?.key);
if (modelKeys.includes('emailVerified')) return 'emailVerified';
if (modelKeys.includes('isVerified')) return 'isVerified';
if (modelKeys.includes('isverified')) return 'isverified';
return null;
};
/**
* Builds a user payload for registration or social login, mapping flat data to the users collection schema.
* @param {Object} usersColConfig - Users collection config
* @param {Object} parsedData - Raw user data (email, name, etc.)
* @param {string} hashedPassword - Hashed password string
* @param {boolean} verifiedValue - Default value for the verification field
* @returns {Object} Mongoose-ready user document payload
*/
const buildAuthUserPayload = (usersColConfig, parsedData, hashedPassword, verifiedValue) => {
const { email, password: _password, username, ...otherData } = parsedData;
const payload = {
email,
password: hashedPassword,
...otherData,
createdAt: new Date()
};
if (username !== undefined) {
payload.username = username;
}
const verificationField = getVerificationField(usersColConfig);
if (verificationField !== null) {
payload[verificationField] = verifiedValue;
}
if (hasRequiredField(usersColConfig, 'name') && (payload.name === undefined || payload.name === null || payload.name === '')) {
const generatedName = username || email.split('@')[0];
payload.name = generatedName.length >= 3 ? generatedName : generatedName.padEnd(3, '0');
}
if (hasRequiredField(usersColConfig, 'username') && (payload.username === undefined || payload.username === null || payload.username === '')) {
const baseUsername = typeof payload.name === 'string' ? payload.name : email.split('@')[0];
const generatedUsername = baseUsername;
payload.username = generatedUsername.length >= 3 ? generatedUsername : generatedUsername.padEnd(3, '0');
}
return payload;
};
const SENSITIVE_PROFILE_KEYS = [
'password',
'email',
'token',
'otp',
'secret',
'session',
'refresh'
];
/**
* Strips sensitive fields (password, provider secrets) from a user document for API responses.
* @param {Object} userDoc - Raw user document
* @param {Object} usersColConfig - Users collection config
* @returns {Object} Sanitized user object safe for public exposure
*/
const sanitizePublicProfile = (userDoc, usersColConfig) => {
const result = { _id: userDoc._id };
const schemaKeys = (usersColConfig?.model || []).map((f) => f?.key).filter(Boolean);
for (const key of schemaKeys) {
const lowered = String(key).toLowerCase();
const isSensitive = SENSITIVE_PROFILE_KEYS.some((needle) => lowered.includes(needle));
if (isSensitive) continue;
if (userDoc[key] !== undefined) {
result[key] = userDoc[key];
}
}
if (userDoc.createdAt) result.createdAt = userDoc.createdAt;
if (userDoc.updatedAt) result.updatedAt = userDoc.updatedAt;
return result;
};
/**
* Initiates the social authentication flow for a given provider.
* Generates a secure state, stores it in Redis, and redirects the user to the provider's OAuth page.
* Requires x-api-key header or ?key query param and auth enabled on the project.
* @route GET /api/userAuth/social/:provider/start
*/
module.exports.startSocialAuth = async (req, res) => {
try {
const provider = String(req.params.provider || '').trim().toLowerCase();
if (!SOCIAL_PROVIDER_KEYS.includes(provider)) {
return res.status(404).json({ error: 'Unsupported social auth provider' });
}
assertAuthProjectReady(req.project);
const { project, providerConfig } = await getSocialProviderConfig(req.project._id, provider);
if (!project || !providerConfig) {
return res.status(422).json({
error: 'Provider not configured',
message: `${provider} social auth is disabled or incomplete for this project.`,
});
}
const state = crypto.randomBytes(24).toString('hex');
await redis.set(
getSocialStateKey(state),
JSON.stringify({
projectId: String(project._id),
provider,
callbackUrl: getFrontendCallbackBaseUrl(project),
}),
'EX',
SOCIAL_STATE_TTL_SECONDS
);
const authUrl = socialProviders[provider].buildAuthorizeUrl({
clientId: providerConfig.clientId,
redirectUri: providerConfig.redirectUri,
state,
});
return res.redirect(authUrl);
} catch (err) {
return res.status(err.statusCode || 500).json({
error: err.publicMessage || err.message,
});
}
};
/**
* Handles the OAuth provider callback. Validates state, exchanges code, resolves/creates user,
* issues auth tokens, and redirects to the frontend callback URL.
* @route GET /api/userAuth/social/:provider/callback
*/
module.exports.handleSocialAuthCallback = async (req, res) => {
// Helper to redirect error to frontend instead of returning JSON
const redirectWithError = (callbackUrl, errorMessage) => {
try {
const url = new URL(callbackUrl);
url.searchParams.set('error', errorMessage);
return res.redirect(url.toString());
} catch {
// Fallback if URL is malformed
return res.status(400).json({ error: errorMessage });
}
};
// P2: Check for provider-side OAuth errors first and forward them
const providerError = String(req.query.error || '').trim();
const providerErrorDesc = String(req.query.error_description || '').trim();
let parsedState = null;
let callbackUrl = null;
// Try to parse state to get callback URL (even if there's an error)
const state = String(req.query.state || '').trim();
if (state) {
const stateKey = getSocialStateKey(state);
const rawState = await redis.get(stateKey);
if (rawState) {
try {
parsedState = JSON.parse(rawState);
callbackUrl = parsedState.callbackUrl || getFrontendCallbackBaseUrl({ siteUrl: '' });
} catch {
// Ignore parse errors here
}
// Cleanup state even on error
await redis.del(stateKey);
}
}
// If provider returned an error, redirect it to frontend
if (providerError) {
const errorMsg = providerErrorDesc || providerError || 'OAuth provider returned an error';
if (callbackUrl) {
return redirectWithError(callbackUrl, errorMsg);
}
// No callback URL available - return JSON as fallback
return res.status(400).json({ error: errorMsg });
}
try {
const provider = String(req.params.provider || '').trim().toLowerCase();
if (!SOCIAL_PROVIDER_KEYS.includes(provider)) {
return res.status(404).json({ error: 'Unsupported social auth provider' });
}
const code = String(req.query.code || '').trim();
if (!code || !state) {
const errorMsg = 'Missing code or state';
if (callbackUrl) return redirectWithError(callbackUrl, errorMsg);
return res.status(400).json({ error: errorMsg });
}
if (!parsedState) {
return res.status(400).json({ error: 'Invalid or expired OAuth state' });
}
if (parsedState.provider !== provider || !parsedState.projectId) {
const errorMsg = 'OAuth state mismatch';
if (callbackUrl) return redirectWithError(callbackUrl, errorMsg);
return res.status(400).json({ error: errorMsg });
}
// Update callbackUrl from parsed state
callbackUrl = parsedState.callbackUrl || callbackUrl;
const { project, providerConfig } = await getSocialProviderConfig(parsedState.projectId, provider);
if (!project || !providerConfig) {
const errorMsg = `${provider} social auth is disabled or incomplete for this project.`;
if (callbackUrl) return redirectWithError(callbackUrl, errorMsg);
return res.status(422).json({ error: 'Provider not configured', message: errorMsg });
}
// Use project's callback URL
callbackUrl = parsedState.callbackUrl || getFrontendCallbackBaseUrl(project);
const usersColConfig = assertAuthProjectReady(project);
const connection = await getConnection(project._id);
const Model = getCompiledModel(connection, usersColConfig, project._id, project.resources.db.isExternal);
const tokenResponse = await socialProviders[provider].exchangeCodeForToken({
code,
clientId: providerConfig.clientId,
clientSecret: providerConfig.clientSecret,
redirectUri: providerConfig.redirectUri,
});
const profile = await socialProviders[provider].fetchProfile({
tokenResponse,
providerConfig,
});
const { user, isNewUser, linkedByEmail } = await findOrCreateSocialUser({
project,
usersColConfig,
Model,
provider,
profile,
});
const issuedTokens = await issueAuthTokens({
project,
userId: user._id,
req,
res,
});
const rtCode = crypto.randomBytes(16).toString('hex');
await redis.set(
getSocialRefreshExchangeKey(rtCode),
JSON.stringify({
token: issuedTokens.accessToken,
refreshToken: issuedTokens.refreshToken,
}),
'EX',
SOCIAL_REFRESH_EXCHANGE_TTL_SECONDS
);
const successUrl = new URL(callbackUrl);
const fragmentParams = new URLSearchParams(
successUrl.hash.startsWith('#') ? successUrl.hash.slice(1) : successUrl.hash
);
fragmentParams.set('token', issuedTokens.accessToken);
successUrl.searchParams.set('rtCode', rtCode);
successUrl.searchParams.set('provider', provider);
successUrl.searchParams.set('userId', String(user._id));
successUrl.searchParams.set('projectId', String(project._id));
successUrl.searchParams.set('isNewUser', String(isNewUser));
successUrl.searchParams.set('linkedByEmail', String(linkedByEmail));
successUrl.hash = fragmentParams.toString();
return res.redirect(successUrl.toString());
} catch (err) {
const errorMsg = err.publicMessage || err.message || 'Social authentication failed';
if (callbackUrl) return redirectWithError(callbackUrl, errorMsg);
return res.status(err.statusCode || 500).json({ error: errorMsg });
}
};
/**
* Exchanges a one-time rtCode (from social auth callback) for a refresh token.
* Completes the OAuth token flow initiated by handleSocialAuthCallback.
* @route POST /api/userAuth/social/exchange
*/
module.exports.exchangeSocialRefreshToken = async (req, res) => {
try {
const rtCode = String(req.body?.rtCode || '').trim();
const token = String(req.body?.token || '').trim();
if (!rtCode || !token) {
return res.status(400).json({
success: false,
data: {},
message: 'rtCode and token are required',
});
}
const exchangeKey = getSocialRefreshExchangeKey(rtCode);
const rawExchange = await redis.getdel(exchangeKey);
if (!rawExchange) {
return res.status(400).json({
success: false,
data: {},
message: 'Invalid or expired refresh token exchange code',
});
}
let parsedExchange;
try {
parsedExchange = JSON.parse(rawExchange);
} catch (err) {
return res.status(400).json({
success: false,
data: {},
message: 'Invalid or expired refresh token exchange code',
});
}
if (parsedExchange.token !== token || !parsedExchange.refreshToken) {
return res.status(403).json({
success: false,
data: {},
message: 'Invalid refresh token exchange payload',
});
}
return res.status(200).json({
success: true,
data: {
refreshToken: parsedExchange.refreshToken,
},
message: 'Refresh token exchanged successfully',
});
} catch (err) {
return res.status(500).json({
success: false,
data: {},
message: 'Internal server error',
});
}
};
/**
* Handles traditional email/password user registration.
* Hashes the password and triggers a verification email if mandatory.
* @route POST /api/userAuth/signup
*/
module.exports.signup = async (req, res) => {
try {
const project = req.project;
const { email, password, username, ...otherData } = userSignupSchema.parse(req.body);
const normalizedEmail = email.toLowerCase().trim();
// Get Mongoose Model
const usersColConfig = project.collections.find(c => c.name === 'users');
if (!usersColConfig) return res.status(404).json({ error: "Auth collection not found" });