-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
RestWrite.js
1833 lines (1689 loc) · 59.6 KB
/
RestWrite.js
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
// A RestWrite encapsulates everything we need to run an operation
// that writes to the database.
// This could be either a "create" or an "update".
var SchemaController = require('./Controllers/SchemaController');
var deepcopy = require('deepcopy');
const Auth = require('./Auth');
const Utils = require('./Utils');
var cryptoUtils = require('./cryptoUtils');
var passwordCrypto = require('./password');
var Parse = require('parse/node');
var triggers = require('./triggers');
var ClientSDK = require('./ClientSDK');
const util = require('util');
import RestQuery from './RestQuery';
import _ from 'lodash';
import logger from './logger';
import { requiredColumns } from './Controllers/SchemaController';
// query and data are both provided in REST API format. So data
// types are encoded by plain old objects.
// If query is null, this is a "create" and the data in data should be
// created.
// Otherwise this is an "update" - the object matching the query
// should get updated with data.
// RestWrite will handle objectId, createdAt, and updatedAt for
// everything. It also knows to use triggers and special modifications
// for the _User class.
function RestWrite(config, auth, className, query, data, originalData, clientSDK, context, action) {
if (auth.isReadOnly) {
throw new Parse.Error(
Parse.Error.OPERATION_FORBIDDEN,
'Cannot perform a write operation when using readOnlyMasterKey'
);
}
this.config = config;
this.auth = auth;
this.className = className;
this.clientSDK = clientSDK;
this.storage = {};
this.runOptions = {};
this.context = context || {};
if (action) {
this.runOptions.action = action;
}
if (!query) {
if (this.config.allowCustomObjectId) {
if (Object.prototype.hasOwnProperty.call(data, 'objectId') && !data.objectId) {
throw new Parse.Error(
Parse.Error.MISSING_OBJECT_ID,
'objectId must not be empty, null or undefined'
);
}
} else {
if (data.objectId) {
throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, 'objectId is an invalid field name.');
}
if (data.id) {
throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, 'id is an invalid field name.');
}
}
}
// When the operation is complete, this.response may have several
// fields.
// response: the actual data to be returned
// status: the http status code. if not present, treated like a 200
// location: the location header. if not present, no location header
this.response = null;
// Processing this operation may mutate our data, so we operate on a
// copy
this.query = deepcopy(query);
this.data = deepcopy(data);
// We never change originalData, so we do not need a deep copy
this.originalData = originalData;
// The timestamp we'll use for this whole operation
this.updatedAt = Parse._encode(new Date()).iso;
// Shared SchemaController to be reused to reduce the number of loadSchema() calls per request
// Once set the schemaData should be immutable
this.validSchemaController = null;
this.pendingOps = {
operations: null,
identifier: null,
};
}
// A convenient method to perform all the steps of processing the
// write, in order.
// Returns a promise for a {response, status, location} object.
// status and location are optional.
RestWrite.prototype.execute = function () {
return Promise.resolve()
.then(() => {
return this.getUserAndRoleACL();
})
.then(() => {
return this.validateClientClassCreation();
})
.then(() => {
return this.handleInstallation();
})
.then(() => {
return this.handleSession();
})
.then(() => {
return this.validateAuthData();
})
.then(() => {
return this.checkRestrictedFields();
})
.then(() => {
return this.runBeforeSaveTrigger();
})
.then(() => {
return this.ensureUniqueAuthDataId();
})
.then(() => {
return this.deleteEmailResetTokenIfNeeded();
})
.then(() => {
return this.validateSchema();
})
.then(schemaController => {
this.validSchemaController = schemaController;
return this.setRequiredFieldsIfNeeded();
})
.then(() => {
return this.transformUser();
})
.then(() => {
return this.expandFilesForExistingObjects();
})
.then(() => {
return this.destroyDuplicatedSessions();
})
.then(() => {
return this.runDatabaseOperation();
})
.then(() => {
return this.createSessionTokenIfNeeded();
})
.then(() => {
return this.handleFollowup();
})
.then(() => {
return this.runAfterSaveTrigger();
})
.then(() => {
return this.cleanUserAuthData();
})
.then(() => {
// Append the authDataResponse if exists
if (this.authDataResponse) {
if (this.response && this.response.response) {
this.response.response.authDataResponse = this.authDataResponse;
}
}
if (this.storage.rejectSignup && this.config.preventSignupWithUnverifiedEmail) {
throw new Parse.Error(Parse.Error.EMAIL_NOT_FOUND, 'User email is not verified.');
}
return this.response;
});
};
// Uses the Auth object to get the list of roles, adds the user id
RestWrite.prototype.getUserAndRoleACL = function () {
if (this.auth.isMaster || this.auth.isMaintenance) {
return Promise.resolve();
}
this.runOptions.acl = ['*'];
if (this.auth.user) {
return this.auth.getUserRoles().then(roles => {
this.runOptions.acl = this.runOptions.acl.concat(roles, [this.auth.user.id]);
return;
});
} else {
return Promise.resolve();
}
};
// Validates this operation against the allowClientClassCreation config.
RestWrite.prototype.validateClientClassCreation = function () {
if (
this.config.allowClientClassCreation === false &&
!this.auth.isMaster &&
!this.auth.isMaintenance &&
SchemaController.systemClasses.indexOf(this.className) === -1
) {
return this.config.database
.loadSchema()
.then(schemaController => schemaController.hasClass(this.className))
.then(hasClass => {
if (hasClass !== true) {
throw new Parse.Error(
Parse.Error.OPERATION_FORBIDDEN,
'This user is not allowed to access ' + 'non-existent class: ' + this.className
);
}
});
} else {
return Promise.resolve();
}
};
// Validates this operation against the schema.
RestWrite.prototype.validateSchema = function () {
return this.config.database.validateObject(
this.className,
this.data,
this.query,
this.runOptions,
this.auth.isMaintenance
);
};
// Runs any beforeSave triggers against this operation.
// Any change leads to our data being mutated.
RestWrite.prototype.runBeforeSaveTrigger = function () {
if (this.response || this.runOptions.many) {
return;
}
// Avoid doing any setup for triggers if there is no 'beforeSave' trigger for this class.
if (
!triggers.triggerExists(this.className, triggers.Types.beforeSave, this.config.applicationId)
) {
return Promise.resolve();
}
const { originalObject, updatedObject } = this.buildParseObjects();
const identifier = updatedObject._getStateIdentifier();
const stateController = Parse.CoreManager.getObjectStateController();
const [pending] = stateController.getPendingOps(identifier);
this.pendingOps = {
operations: { ...pending },
identifier,
};
return Promise.resolve()
.then(() => {
// Before calling the trigger, validate the permissions for the save operation
let databasePromise = null;
if (this.query) {
// Validate for updating
databasePromise = this.config.database.update(
this.className,
this.query,
this.data,
this.runOptions,
true,
true
);
} else {
// Validate for creating
databasePromise = this.config.database.create(
this.className,
this.data,
this.runOptions,
true
);
}
// In the case that there is no permission for the operation, it throws an error
return databasePromise.then(result => {
if (!result || result.length <= 0) {
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Object not found.');
}
});
})
.then(() => {
return triggers.maybeRunTrigger(
triggers.Types.beforeSave,
this.auth,
updatedObject,
originalObject,
this.config,
this.context
);
})
.then(response => {
if (response && response.object) {
this.storage.fieldsChangedByTrigger = _.reduce(
response.object,
(result, value, key) => {
if (!_.isEqual(this.data[key], value)) {
result.push(key);
}
return result;
},
[]
);
this.data = response.object;
// We should delete the objectId for an update write
if (this.query && this.query.objectId) {
delete this.data.objectId;
}
}
try {
Utils.checkProhibitedKeywords(this.config, this.data);
} catch (error) {
throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, error);
}
});
};
RestWrite.prototype.runBeforeLoginTrigger = async function (userData) {
// Avoid doing any setup for triggers if there is no 'beforeLogin' trigger
if (
!triggers.triggerExists(this.className, triggers.Types.beforeLogin, this.config.applicationId)
) {
return;
}
// Cloud code gets a bit of extra data for its objects
const extraData = { className: this.className };
// Expand file objects
await this.config.filesController.expandFilesInObject(this.config, userData);
const user = triggers.inflate(extraData, userData);
// no need to return a response
await triggers.maybeRunTrigger(
triggers.Types.beforeLogin,
this.auth,
user,
null,
this.config,
this.context
);
};
RestWrite.prototype.setRequiredFieldsIfNeeded = function () {
if (this.data) {
return this.validSchemaController.getAllClasses().then(allClasses => {
const schema = allClasses.find(oneClass => oneClass.className === this.className);
const setRequiredFieldIfNeeded = (fieldName, setDefault) => {
if (
this.data[fieldName] === undefined ||
this.data[fieldName] === null ||
this.data[fieldName] === '' ||
(typeof this.data[fieldName] === 'object' && this.data[fieldName].__op === 'Delete')
) {
if (
setDefault &&
schema.fields[fieldName] &&
schema.fields[fieldName].defaultValue !== null &&
schema.fields[fieldName].defaultValue !== undefined &&
(this.data[fieldName] === undefined ||
(typeof this.data[fieldName] === 'object' && this.data[fieldName].__op === 'Delete'))
) {
this.data[fieldName] = schema.fields[fieldName].defaultValue;
this.storage.fieldsChangedByTrigger = this.storage.fieldsChangedByTrigger || [];
if (this.storage.fieldsChangedByTrigger.indexOf(fieldName) < 0) {
this.storage.fieldsChangedByTrigger.push(fieldName);
}
} else if (schema.fields[fieldName] && schema.fields[fieldName].required === true) {
throw new Parse.Error(Parse.Error.VALIDATION_ERROR, `${fieldName} is required`);
}
}
};
// Add default fields
if (!this.query) {
// allow customizing createdAt and updatedAt when using maintenance key
if (
this.auth.isMaintenance &&
this.data.createdAt &&
this.data.createdAt.__type === 'Date'
) {
this.data.createdAt = this.data.createdAt.iso;
if (this.data.updatedAt && this.data.updatedAt.__type === 'Date') {
const createdAt = new Date(this.data.createdAt);
const updatedAt = new Date(this.data.updatedAt.iso);
if (updatedAt < createdAt) {
throw new Parse.Error(
Parse.Error.VALIDATION_ERROR,
'updatedAt cannot occur before createdAt'
);
}
this.data.updatedAt = this.data.updatedAt.iso;
}
// if no updatedAt is provided, set it to createdAt to match default behavior
else {
this.data.updatedAt = this.data.createdAt;
}
} else {
this.data.updatedAt = this.updatedAt;
this.data.createdAt = this.updatedAt;
}
// Only assign new objectId if we are creating new object
if (!this.data.objectId) {
this.data.objectId = cryptoUtils.newObjectId(this.config.objectIdSize);
}
if (schema) {
Object.keys(schema.fields).forEach(fieldName => {
setRequiredFieldIfNeeded(fieldName, true);
});
}
} else if (schema) {
this.data.updatedAt = this.updatedAt;
Object.keys(this.data).forEach(fieldName => {
setRequiredFieldIfNeeded(fieldName, false);
});
}
});
}
return Promise.resolve();
};
// Transforms auth data for a user object.
// Does nothing if this isn't a user object.
// Returns a promise for when we're done if it can't finish this tick.
RestWrite.prototype.validateAuthData = function () {
if (this.className !== '_User') {
return;
}
const authData = this.data.authData;
const hasUsernameAndPassword =
typeof this.data.username === 'string' && typeof this.data.password === 'string';
if (!this.query && !authData) {
if (typeof this.data.username !== 'string' || _.isEmpty(this.data.username)) {
throw new Parse.Error(Parse.Error.USERNAME_MISSING, 'bad or missing username');
}
if (typeof this.data.password !== 'string' || _.isEmpty(this.data.password)) {
throw new Parse.Error(Parse.Error.PASSWORD_MISSING, 'password is required');
}
}
if (
(authData && !Object.keys(authData).length) ||
!Object.prototype.hasOwnProperty.call(this.data, 'authData')
) {
// Nothing to validate here
return;
} else if (Object.prototype.hasOwnProperty.call(this.data, 'authData') && !this.data.authData) {
// Handle saving authData to null
throw new Parse.Error(
Parse.Error.UNSUPPORTED_SERVICE,
'This authentication method is unsupported.'
);
}
var providers = Object.keys(authData);
if (providers.length > 0) {
const canHandleAuthData = providers.some(provider => {
var providerAuthData = authData[provider];
var hasToken = providerAuthData && providerAuthData.id;
return hasToken || providerAuthData === null;
});
if (canHandleAuthData || hasUsernameAndPassword || this.auth.isMaster || this.getUserId()) {
return this.handleAuthData(authData);
}
}
throw new Parse.Error(
Parse.Error.UNSUPPORTED_SERVICE,
'This authentication method is unsupported.'
);
};
RestWrite.prototype.filteredObjectsByACL = function (objects) {
if (this.auth.isMaster || this.auth.isMaintenance) {
return objects;
}
return objects.filter(object => {
if (!object.ACL) {
return true; // legacy users that have no ACL field on them
}
// Regular users that have been locked out.
return object.ACL && Object.keys(object.ACL).length > 0;
});
};
RestWrite.prototype.getUserId = function () {
if (this.query && this.query.objectId && this.className === '_User') {
return this.query.objectId;
} else if (this.auth && this.auth.user && this.auth.user.id) {
return this.auth.user.id;
}
};
// Developers are allowed to change authData via before save trigger
// we need after before save to ensure that the developer
// is not currently duplicating auth data ID
RestWrite.prototype.ensureUniqueAuthDataId = async function () {
if (this.className !== '_User' || !this.data.authData) {
return;
}
const hasAuthDataId = Object.keys(this.data.authData).some(
key => this.data.authData[key] && this.data.authData[key].id
);
if (!hasAuthDataId) { return; }
const r = await Auth.findUsersWithAuthData(this.config, this.data.authData);
const results = this.filteredObjectsByACL(r);
if (results.length > 1) {
throw new Parse.Error(Parse.Error.ACCOUNT_ALREADY_LINKED, 'this auth is already used');
}
// use data.objectId in case of login time and found user during handle validateAuthData
const userId = this.getUserId() || this.data.objectId;
if (results.length === 1 && userId !== results[0].objectId) {
throw new Parse.Error(Parse.Error.ACCOUNT_ALREADY_LINKED, 'this auth is already used');
}
};
RestWrite.prototype.handleAuthData = async function (authData) {
const r = await Auth.findUsersWithAuthData(this.config, authData);
const results = this.filteredObjectsByACL(r);
const userId = this.getUserId();
const userResult = results[0];
const foundUserIsNotCurrentUser = userId && userResult && userId !== userResult.objectId;
if (results.length > 1 || foundUserIsNotCurrentUser) {
// To avoid https://github.com/parse-community/parse-server/security/advisories/GHSA-8w3j-g983-8jh5
// Let's run some validation before throwing
await Auth.handleAuthDataValidation(authData, this, userResult);
throw new Parse.Error(Parse.Error.ACCOUNT_ALREADY_LINKED, 'this auth is already used');
}
// No user found with provided authData we need to validate
if (!results.length) {
const { authData: validatedAuthData, authDataResponse } = await Auth.handleAuthDataValidation(
authData,
this
);
this.authDataResponse = authDataResponse;
// Replace current authData by the new validated one
this.data.authData = validatedAuthData;
return;
}
// User found with provided authData
if (results.length === 1) {
this.storage.authProvider = Object.keys(authData).join(',');
const { hasMutatedAuthData, mutatedAuthData } = Auth.hasMutatedAuthData(
authData,
userResult.authData
);
const isCurrentUserLoggedOrMaster =
(this.auth && this.auth.user && this.auth.user.id === userResult.objectId) ||
this.auth.isMaster;
const isLogin = !userId;
if (isLogin || isCurrentUserLoggedOrMaster) {
// no user making the call
// OR the user making the call is the right one
// Login with auth data
delete results[0].password;
// need to set the objectId first otherwise location has trailing undefined
this.data.objectId = userResult.objectId;
if (!this.query || !this.query.objectId) {
this.response = {
response: userResult,
location: this.location(),
};
// Run beforeLogin hook before storing any updates
// to authData on the db; changes to userResult
// will be ignored.
await this.runBeforeLoginTrigger(deepcopy(userResult));
// If we are in login operation via authData
// we need to be sure that the user has provided
// required authData
Auth.checkIfUserHasProvidedConfiguredProvidersForLogin(
{ config: this.config, auth: this.auth },
authData,
userResult.authData,
this.config
);
}
// Prevent validating if no mutated data detected on update
if (!hasMutatedAuthData && isCurrentUserLoggedOrMaster) {
return;
}
// Force to validate all provided authData on login
// on update only validate mutated ones
if (hasMutatedAuthData || !this.config.allowExpiredAuthDataToken) {
const res = await Auth.handleAuthDataValidation(
isLogin ? authData : mutatedAuthData,
this,
userResult
);
this.data.authData = res.authData;
this.authDataResponse = res.authDataResponse;
}
// IF we are in login we'll skip the database operation / beforeSave / afterSave etc...
// we need to set it up there.
// We are supposed to have a response only on LOGIN with authData, so we skip those
// If we're not logging in, but just updating the current user, we can safely skip that part
if (this.response) {
// Assign the new authData in the response
Object.keys(mutatedAuthData).forEach(provider => {
this.response.response.authData[provider] = mutatedAuthData[provider];
});
// Run the DB update directly, as 'master' only if authData contains some keys
// authData could not contains keys after validation if the authAdapter
// uses the `doNotSave` option. Just update the authData part
// Then we're good for the user, early exit of sorts
if (Object.keys(this.data.authData).length) {
await this.config.database.update(
this.className,
{ objectId: this.data.objectId },
{ authData: this.data.authData },
{}
);
}
}
}
}
};
RestWrite.prototype.checkRestrictedFields = async function () {
if (this.className !== '_User') {
return;
}
if (!this.auth.isMaintenance && !this.auth.isMaster && 'emailVerified' in this.data) {
const error = `Clients aren't allowed to manually update email verification.`;
throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, error);
}
};
// The non-third-party parts of User transformation
RestWrite.prototype.transformUser = async function () {
var promise = Promise.resolve();
if (this.className !== '_User') {
return promise;
}
// Do not cleanup session if objectId is not set
if (this.query && this.objectId()) {
// If we're updating a _User object, we need to clear out the cache for that user. Find all their
// session tokens, and remove them from the cache.
const query = await RestQuery({
method: RestQuery.Method.find,
config: this.config,
auth: Auth.master(this.config),
className: '_Session',
runBeforeFind: false,
restWhere: {
user: {
__type: 'Pointer',
className: '_User',
objectId: this.objectId(),
},
},
});
promise = query.execute().then(results => {
results.results.forEach(session =>
this.config.cacheController.user.del(session.sessionToken)
);
});
}
return promise
.then(() => {
// Transform the password
if (this.data.password === undefined) {
// ignore only if undefined. should proceed if empty ('')
return Promise.resolve();
}
if (this.query) {
this.storage['clearSessions'] = true;
// Generate a new session only if the user requested
if (!this.auth.isMaster && !this.auth.isMaintenance) {
this.storage['generateNewSession'] = true;
}
}
return this._validatePasswordPolicy().then(() => {
return passwordCrypto.hash(this.data.password).then(hashedPassword => {
this.data._hashed_password = hashedPassword;
delete this.data.password;
});
});
})
.then(() => {
return this._validateUserName();
})
.then(() => {
return this._validateEmail();
});
};
RestWrite.prototype._validateUserName = function () {
// Check for username uniqueness
if (!this.data.username) {
if (!this.query) {
this.data.username = cryptoUtils.randomString(25);
this.responseShouldHaveUsername = true;
}
return Promise.resolve();
}
/*
Usernames should be unique when compared case insensitively
Users should be able to make case sensitive usernames and
login using the case they entered. I.e. 'Snoopy' should preclude
'snoopy' as a valid username.
*/
return this.config.database
.find(
this.className,
{
username: this.data.username,
objectId: { $ne: this.objectId() },
},
{ limit: 1, caseInsensitive: true },
{},
this.validSchemaController
)
.then(results => {
if (results.length > 0) {
throw new Parse.Error(
Parse.Error.USERNAME_TAKEN,
'Account already exists for this username.'
);
}
return;
});
};
/*
As with usernames, Parse should not allow case insensitive collisions of email.
unlike with usernames (which can have case insensitive collisions in the case of
auth adapters), emails should never have a case insensitive collision.
This behavior can be enforced through a properly configured index see:
https://docs.mongodb.com/manual/core/index-case-insensitive/#create-a-case-insensitive-index
which could be implemented instead of this code based validation.
Given that this lookup should be a relatively low use case and that the case sensitive
unique index will be used by the db for the query, this is an adequate solution.
*/
RestWrite.prototype._validateEmail = function () {
if (!this.data.email || this.data.email.__op === 'Delete') {
return Promise.resolve();
}
// Validate basic email address format
if (!this.data.email.match(/^.+@.+$/)) {
return Promise.reject(
new Parse.Error(Parse.Error.INVALID_EMAIL_ADDRESS, 'Email address format is invalid.')
);
}
// Case insensitive match, see note above function.
return this.config.database
.find(
this.className,
{
email: this.data.email,
objectId: { $ne: this.objectId() },
},
{ limit: 1, caseInsensitive: true },
{},
this.validSchemaController
)
.then(results => {
if (results.length > 0) {
throw new Parse.Error(
Parse.Error.EMAIL_TAKEN,
'Account already exists for this email address.'
);
}
if (
!this.data.authData ||
!Object.keys(this.data.authData).length ||
(Object.keys(this.data.authData).length === 1 &&
Object.keys(this.data.authData)[0] === 'anonymous')
) {
// We updated the email, send a new validation
const { originalObject, updatedObject } = this.buildParseObjects();
const request = {
original: originalObject,
object: updatedObject,
master: this.auth.isMaster,
ip: this.config.ip,
installationId: this.auth.installationId,
};
return this.config.userController.setEmailVerifyToken(this.data, request, this.storage);
}
});
};
RestWrite.prototype._validatePasswordPolicy = function () {
if (!this.config.passwordPolicy) { return Promise.resolve(); }
return this._validatePasswordRequirements().then(() => {
return this._validatePasswordHistory();
});
};
RestWrite.prototype._validatePasswordRequirements = function () {
// check if the password conforms to the defined password policy if configured
// If we specified a custom error in our configuration use it.
// Example: "Passwords must include a Capital Letter, Lowercase Letter, and a number."
//
// This is especially useful on the generic "password reset" page,
// as it allows the programmer to communicate specific requirements instead of:
// a. making the user guess whats wrong
// b. making a custom password reset page that shows the requirements
const policyError = this.config.passwordPolicy.validationError
? this.config.passwordPolicy.validationError
: 'Password does not meet the Password Policy requirements.';
const containsUsernameError = 'Password cannot contain your username.';
// check whether the password meets the password strength requirements
if (
(this.config.passwordPolicy.patternValidator &&
!this.config.passwordPolicy.patternValidator(this.data.password)) ||
(this.config.passwordPolicy.validatorCallback &&
!this.config.passwordPolicy.validatorCallback(this.data.password))
) {
return Promise.reject(new Parse.Error(Parse.Error.VALIDATION_ERROR, policyError));
}
// check whether password contain username
if (this.config.passwordPolicy.doNotAllowUsername === true) {
if (this.data.username) {
// username is not passed during password reset
if (this.data.password.indexOf(this.data.username) >= 0)
{ return Promise.reject(new Parse.Error(Parse.Error.VALIDATION_ERROR, containsUsernameError)); }
} else {
// retrieve the User object using objectId during password reset
return this.config.database.find('_User', { objectId: this.objectId() }).then(results => {
if (results.length != 1) {
throw undefined;
}
if (this.data.password.indexOf(results[0].username) >= 0)
{ return Promise.reject(
new Parse.Error(Parse.Error.VALIDATION_ERROR, containsUsernameError)
); }
return Promise.resolve();
});
}
}
return Promise.resolve();
};
RestWrite.prototype._validatePasswordHistory = function () {
// check whether password is repeating from specified history
if (this.query && this.config.passwordPolicy.maxPasswordHistory) {
return this.config.database
.find(
'_User',
{ objectId: this.objectId() },
{ keys: ['_password_history', '_hashed_password'] },
Auth.maintenance(this.config)
)
.then(results => {
if (results.length != 1) {
throw undefined;
}
const user = results[0];
let oldPasswords = [];
if (user._password_history)
{ oldPasswords = _.take(
user._password_history,
this.config.passwordPolicy.maxPasswordHistory - 1
); }
oldPasswords.push(user.password);
const newPassword = this.data.password;
// compare the new password hash with all old password hashes
const promises = oldPasswords.map(function (hash) {
return passwordCrypto.compare(newPassword, hash).then(result => {
if (result)
// reject if there is a match
{ return Promise.reject('REPEAT_PASSWORD'); }
return Promise.resolve();
});
});
// wait for all comparisons to complete
return Promise.all(promises)
.then(() => {
return Promise.resolve();
})
.catch(err => {
if (err === 'REPEAT_PASSWORD')
// a match was found
{ return Promise.reject(
new Parse.Error(
Parse.Error.VALIDATION_ERROR,
`New password should not be the same as last ${this.config.passwordPolicy.maxPasswordHistory} passwords.`
)
); }
throw err;
});
});
}
return Promise.resolve();
};
RestWrite.prototype.createSessionTokenIfNeeded = async function () {
if (this.className !== '_User') {
return;
}
// Don't generate session for updating user (this.query is set) unless authData exists
if (this.query && !this.data.authData) {
return;
}
// Don't generate new sessionToken if linking via sessionToken
if (this.auth.user && this.data.authData) {
return;
}
// If sign-up call
if (!this.storage.authProvider) {
// Create request object for verification functions
const { originalObject, updatedObject } = this.buildParseObjects();
const request = {
original: originalObject,
object: updatedObject,
master: this.auth.isMaster,
ip: this.config.ip,
installationId: this.auth.installationId,
};
// Get verification conditions which can be booleans or functions; the purpose of this async/await
// structure is to avoid unnecessarily executing subsequent functions if previous ones fail in the
// conditional statement below, as a developer may decide to execute expensive operations in them
const verifyUserEmails = async () => this.config.verifyUserEmails === true || (typeof this.config.verifyUserEmails === 'function' && await Promise.resolve(this.config.verifyUserEmails(request)) === true);
const preventLoginWithUnverifiedEmail = async () => this.config.preventLoginWithUnverifiedEmail === true || (typeof this.config.preventLoginWithUnverifiedEmail === 'function' && await Promise.resolve(this.config.preventLoginWithUnverifiedEmail(request)) === true);
// If verification is required
if (await verifyUserEmails() && await preventLoginWithUnverifiedEmail()) {
this.storage.rejectSignup = true;
return;
}
}
return this.createSessionToken();
};
RestWrite.prototype.createSessionToken = async function () {
// cloud installationId from Cloud Code,
// never create session tokens from there.
if (this.auth.installationId && this.auth.installationId === 'cloud') {
return;
}
if (this.storage.authProvider == null && this.data.authData) {
this.storage.authProvider = Object.keys(this.data.authData).join(',');
}
const { sessionData, createSession } = RestWrite.createSession(this.config, {
userId: this.objectId(),
createdWith: {
action: this.storage.authProvider ? 'login' : 'signup',
authProvider: this.storage.authProvider || 'password',
},
installationId: this.auth.installationId,
});
if (this.response && this.response.response) {
this.response.response.sessionToken = sessionData.sessionToken;
}
return createSession();
};
RestWrite.createSession = function (
config,
{ userId, createdWith, installationId, additionalSessionData }
) {
const token = 'r:' + cryptoUtils.newToken();
const expiresAt = config.generateSessionExpiresAt();
const sessionData = {
sessionToken: token,
user: {
__type: 'Pointer',
className: '_User',
objectId: userId,
},
createdWith,
expiresAt: Parse._encode(expiresAt),
};
if (installationId) {