-
-
Notifications
You must be signed in to change notification settings - Fork 594
/
Copy pathParseUser.js
1276 lines (1170 loc) · 39.5 KB
/
ParseUser.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
/**
* @flow
*/
import CoreManager from './CoreManager';
import isRevocableSession from './isRevocableSession';
import ParseError from './ParseError';
import ParseObject from './ParseObject';
import ParseSession from './ParseSession';
import Storage from './Storage';
import type { AttributeMap } from './ObjectStateMutations';
import type { RequestOptions, FullOptions } from './RESTController';
export type AuthData = ?{ [key: string]: mixed };
const CURRENT_USER_KEY = 'currentUser';
let canUseCurrentUser = !CoreManager.get('IS_NODE');
let currentUserCacheMatchesDisk = false;
let currentUserCache = null;
const authProviders = {};
/**
* <p>A Parse.User object is a local representation of a user persisted to the
* Parse cloud. This class is a subclass of a Parse.Object, and retains the
* same functionality of a Parse.Object, but also extends it with various
* user specific methods, like authentication, signing up, and validation of
* uniqueness.</p>
*
* @alias Parse.User
* @augments Parse.Object
*/
class ParseUser extends ParseObject {
/**
* @param {object} attributes The initial set of data to store in the user.
*/
constructor(attributes: ?AttributeMap) {
super('_User');
if (attributes && typeof attributes === 'object') {
if (!this.set(attributes || {})) {
throw new Error("Can't create an invalid Parse User");
}
}
}
/**
* Request a revocable session token to replace the older style of token.
*
* @param {object} options
* @returns {Promise} A promise that is resolved when the replacement
* token has been fetched.
*/
_upgradeToRevocableSession(options: RequestOptions): Promise<void> {
options = options || {};
const upgradeOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
upgradeOptions.useMasterKey = options.useMasterKey;
}
const controller = CoreManager.getUserController();
return controller.upgradeToRevocableSession(this, upgradeOptions);
}
/**
* Parse allows you to link your users with {@link https://docs.parseplatform.org/parse-server/guide/#oauth-and-3rd-party-authentication 3rd party authentication}, enabling
* your users to sign up or log into your application using their existing identities.
* Since 2.9.0
*
* @see {@link https://docs.parseplatform.org/js/guide/#linking-users Linking Users}
* @param {string | AuthProvider} provider Name of auth provider or {@link https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html AuthProvider}
* @param {object} options
* <ul>
* <li>If provider is string, options is {@link http://docs.parseplatform.org/parse-server/guide/#supported-3rd-party-authentications authData}
* <li>If provider is AuthProvider, options is saveOpts
* </ul>
* @param {object} saveOpts useMasterKey / sessionToken
* @returns {Promise} A promise that is fulfilled with the user is linked
*/
linkWith(
provider: any,
options: { authData?: AuthData },
saveOpts?: FullOptions = {}
): Promise<ParseUser> {
saveOpts.sessionToken = saveOpts.sessionToken || this.getSessionToken() || '';
let authType;
if (typeof provider === 'string') {
authType = provider;
if (authProviders[provider]) {
provider = authProviders[provider];
} else {
const authProvider = {
restoreAuthentication() {
return true;
},
getAuthType() {
return authType;
},
};
authProviders[authProvider.getAuthType()] = authProvider;
provider = authProvider;
}
} else {
authType = provider.getAuthType();
}
if (options && options.hasOwnProperty('authData')) {
const authData = this.get('authData') || {};
if (typeof authData !== 'object') {
throw new Error('Invalid type: authData field should be an object');
}
authData[authType] = options.authData;
const oldAnonymousData = authData.anonymous;
this.stripAnonymity();
const controller = CoreManager.getUserController();
return controller.linkWith(this, authData, saveOpts).catch((e) => {
delete authData[authType];
this.restoreAnonimity(oldAnonymousData);
throw e;
});
} else {
return new Promise((resolve, reject) => {
provider.authenticate({
success: (provider, result) => {
const opts = {};
opts.authData = result;
this.linkWith(provider, opts, saveOpts).then(
() => {
resolve(this);
},
error => {
reject(error);
}
);
},
error: (provider, error) => {
reject(error);
},
});
});
}
}
/**
* @param provider
* @param options
* @param saveOpts
* @deprecated since 2.9.0 see {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#linkWith linkWith}
* @returns {Promise}
*/
_linkWith(
provider: any,
options: { authData?: AuthData },
saveOpts?: FullOptions = {}
): Promise<ParseUser> {
return this.linkWith(provider, options, saveOpts);
}
/**
* Synchronizes auth data for a provider (e.g. puts the access token in the
* right place to be used by the Facebook SDK).
*
* @param provider
*/
_synchronizeAuthData(provider: string) {
if (!this.isCurrent() || !provider) {
return;
}
let authType;
if (typeof provider === 'string') {
authType = provider;
provider = authProviders[authType];
} else {
authType = provider.getAuthType();
}
const authData = this.get('authData');
if (!provider || !authData || typeof authData !== 'object') {
return;
}
const success = provider.restoreAuthentication(authData[authType]);
if (!success) {
this._unlinkFrom(provider);
}
}
/**
* Synchronizes authData for all providers.
*/
_synchronizeAllAuthData() {
const authData = this.get('authData');
if (typeof authData !== 'object') {
return;
}
for (const key in authData) {
this._synchronizeAuthData(key);
}
}
/**
* Removes null values from authData (which exist temporarily for unlinking)
*/
_cleanupAuthData() {
if (!this.isCurrent()) {
return;
}
const authData = this.get('authData');
if (typeof authData !== 'object') {
return;
}
for (const key in authData) {
if (!authData[key]) {
delete authData[key];
}
}
}
/**
* Unlinks a user from a service.
*
* @param {string | AuthProvider} provider Name of auth provider or {@link https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html AuthProvider}
* @param {object} options MasterKey / SessionToken
* @returns {Promise} A promise that is fulfilled when the unlinking
* finishes.
*/
_unlinkFrom(provider: any, options?: FullOptions): Promise<ParseUser> {
return this.linkWith(provider, { authData: null }, options).then(() => {
this._synchronizeAuthData(provider);
return Promise.resolve(this);
});
}
/**
* Checks whether a user is linked to a service.
*
* @param {object} provider service to link to
* @returns {boolean} true if link was successful
*/
_isLinked(provider: any): boolean {
let authType;
if (typeof provider === 'string') {
authType = provider;
} else {
authType = provider.getAuthType();
}
const authData = this.get('authData') || {};
if (typeof authData !== 'object') {
return false;
}
return !!authData[authType];
}
/**
* Deauthenticates all providers.
*/
_logOutWithAll() {
const authData = this.get('authData');
if (typeof authData !== 'object') {
return;
}
for (const key in authData) {
this._logOutWith(key);
}
}
/**
* Deauthenticates a single provider (e.g. removing access tokens from the
* Facebook SDK).
*
* @param {object} provider service to logout of
*/
_logOutWith(provider: any) {
if (!this.isCurrent()) {
return;
}
if (typeof provider === 'string') {
provider = authProviders[provider];
}
if (provider && provider.deauthenticate) {
provider.deauthenticate();
}
}
/**
* Class instance method used to maintain specific keys when a fetch occurs.
* Used to ensure that the session token is not lost.
*
* @returns {object} sessionToken
*/
_preserveFieldsOnFetch(): AttributeMap {
return {
sessionToken: this.get('sessionToken'),
};
}
/**
* Returns true if <code>current</code> would return this user.
*
* @returns {boolean} true if user is cached on disk
*/
isCurrent(): boolean {
const current = ParseUser.current();
return !!current && current.id === this.id;
}
/**
* Returns true if <code>current</code> would return this user.
*
* @returns {Promise<boolean>} true if user is cached on disk
*/
async isCurrentAsync(): Promise<boolean> {
const current = await ParseUser.currentAsync();
return !!current && current.id === this.id;
}
stripAnonymity() {
const authData = this.get('authData');
if (authData && typeof authData === 'object' && authData.hasOwnProperty('anonymous')) {
// We need to set anonymous to null instead of deleting it in order to remove it from Parse.
authData.anonymous = null;
}
}
restoreAnonimity(anonymousData: any) {
if (anonymousData) {
const authData = this.get('authData');
authData.anonymous = anonymousData;
}
}
/**
* Returns get("username").
*
* @returns {string}
*/
getUsername(): ?string {
const username = this.get('username');
if (username == null || typeof username === 'string') {
return username;
}
return '';
}
/**
* Calls set("username", username, options) and returns the result.
*
* @param {string} username
*/
setUsername(username: string) {
this.stripAnonymity();
this.set('username', username);
}
/**
* Calls set("password", password, options) and returns the result.
*
* @param {string} password User's Password
*/
setPassword(password: string) {
this.set('password', password);
}
/**
* Returns get("email").
*
* @returns {string} User's Email
*/
getEmail(): ?string {
const email = this.get('email');
if (email == null || typeof email === 'string') {
return email;
}
return '';
}
/**
* Calls set("email", email) and returns the result.
*
* @param {string} email
* @returns {boolean}
*/
setEmail(email: string) {
return this.set('email', email);
}
/**
* Returns the session token for this user, if the user has been logged in,
* or if it is the result of a query with the master key. Otherwise, returns
* undefined.
*
* @returns {string} the session token, or undefined
*/
getSessionToken(): ?string {
const token = this.get('sessionToken');
if (token == null || typeof token === 'string') {
return token;
}
return '';
}
/**
* Checks whether this user is the current user and has been authenticated.
*
* @returns {boolean} whether this user is the current user and is logged in.
*/
authenticated(): boolean {
const current = ParseUser.current();
return !!this.get('sessionToken') && !!current && current.id === this.id;
}
/**
* Signs up a new user. You should call this instead of save for
* new Parse.Users. This will create a new Parse.User on the server, and
* also persist the session on disk so that you can access the user using
* <code>current</code>.
*
* <p>A username and password must be set before calling signUp.</p>
*
* @param {object} attrs Extra fields to set on the new user, or null.
* @param {object} options
* @returns {Promise} A promise that is fulfilled when the signup
* finishes.
*/
signUp(attrs: AttributeMap, options?: FullOptions): Promise<ParseUser> {
options = options || {};
const signupOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
signupOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('installationId')) {
signupOptions.installationId = options.installationId;
}
if (
options.hasOwnProperty('context') &&
Object.prototype.toString.call(options.context) === '[object Object]'
) {
signupOptions.context = options.context;
}
const controller = CoreManager.getUserController();
return controller.signUp(this, attrs, signupOptions);
}
/**
* Logs in a Parse.User. On success, this saves the session to disk,
* so you can retrieve the currently logged in user using
* <code>current</code>.
*
* <p>A username and password must be set before calling logIn.</p>
*
* @param {object} options
* @returns {Promise} A promise that is fulfilled with the user when
* the login is complete.
*/
logIn(options?: FullOptions): Promise<ParseUser> {
options = options || {};
const loginOptions = { usePost: true };
if (options.hasOwnProperty('useMasterKey')) {
loginOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('installationId')) {
loginOptions.installationId = options.installationId;
}
if (options.hasOwnProperty('usePost')) {
loginOptions.usePost = options.usePost;
}
if (
options.hasOwnProperty('context') &&
Object.prototype.toString.call(options.context) === '[object Object]'
) {
loginOptions.context = options.context;
}
const controller = CoreManager.getUserController();
return controller.logIn(this, loginOptions);
}
/**
* Wrap the default save behavior with functionality to save to local
* storage if this is current user.
*
* @param {...any} args
* @returns {Promise}
*/
async save(...args: Array<any>): Promise<ParseUser> {
await super.save.apply(this, args);
const current = await this.isCurrentAsync();
if (current) {
return CoreManager.getUserController().updateUserOnDisk(this);
}
return this;
}
/**
* Wrap the default destroy behavior with functionality that logs out
* the current user when it is destroyed
*
* @param {...any} args
* @returns {Parse.User}
*/
async destroy(...args: Array<any>): Promise<ParseUser> {
await super.destroy.apply(this, args);
const current = await this.isCurrentAsync();
if (current) {
return CoreManager.getUserController().removeUserFromDisk();
}
return this;
}
/**
* Wrap the default fetch behavior with functionality to save to local
* storage if this is current user.
*
* @param {...any} args
* @returns {Parse.User}
*/
async fetch(...args: Array<any>): Promise<ParseUser> {
await super.fetch.apply(this, args);
const current = await this.isCurrentAsync();
if (current) {
return CoreManager.getUserController().updateUserOnDisk(this);
}
return this;
}
/**
* Wrap the default fetchWithInclude behavior with functionality to save to local
* storage if this is current user.
*
* @param {...any} args
* @returns {Parse.User}
*/
async fetchWithInclude(...args: Array<any>): Promise<ParseUser> {
await super.fetchWithInclude.apply(this, args);
const current = await this.isCurrentAsync();
if (current) {
return CoreManager.getUserController().updateUserOnDisk(this);
}
return this;
}
/**
* Verify whether a given password is the password of the current user.
*
* @param {string} password A password to be verified
* @param {object} options
* @returns {Promise} A promise that is fulfilled with a user
* when the password is correct.
*/
verifyPassword(password: string, options?: RequestOptions): Promise<ParseUser> {
const username = this.getUsername() || '';
return ParseUser.verifyPassword(username, password, options);
}
static readOnlyAttributes() {
return ['sessionToken'];
}
/**
* Adds functionality to the existing Parse.User class.
*
* @param {object} protoProps A set of properties to add to the prototype
* @param {object} classProps A set of static properties to add to the class
* @static
* @returns {Parse.User} The newly extended Parse.User class
*/
static extend(protoProps: { [prop: string]: any }, classProps: { [prop: string]: any }) {
if (protoProps) {
for (const prop in protoProps) {
if (prop !== 'className') {
Object.defineProperty(ParseUser.prototype, prop, {
value: protoProps[prop],
enumerable: false,
writable: true,
configurable: true,
});
}
}
}
if (classProps) {
for (const prop in classProps) {
if (prop !== 'className') {
Object.defineProperty(ParseUser, prop, {
value: classProps[prop],
enumerable: false,
writable: true,
configurable: true,
});
}
}
}
return ParseUser;
}
/**
* Retrieves the currently logged in ParseUser with a valid session,
* either from memory or localStorage, if necessary.
*
* @static
* @returns {Parse.Object} The currently logged in Parse.User.
*/
static current(): ?ParseUser {
if (!canUseCurrentUser) {
return null;
}
const controller = CoreManager.getUserController();
return controller.currentUser();
}
/**
* Retrieves the currently logged in ParseUser from asynchronous Storage.
*
* @static
* @returns {Promise} A Promise that is resolved with the currently
* logged in Parse User
*/
static currentAsync(): Promise<?ParseUser> {
if (!canUseCurrentUser) {
return Promise.resolve(null);
}
const controller = CoreManager.getUserController();
return controller.currentUserAsync();
}
/**
* Signs up a new user with a username (or email) and password.
* This will create a new Parse.User on the server, and also persist the
* session in localStorage so that you can access the user using
* {@link #current}.
*
* @param {string} username The username (or email) to sign up with.
* @param {string} password The password to sign up with.
* @param {object} attrs Extra fields to set on the new user.
* @param {object} options
* @static
* @returns {Promise} A promise that is fulfilled with the user when
* the signup completes.
*/
static signUp(username: string, password: string, attrs: AttributeMap, options?: FullOptions) {
attrs = attrs || {};
attrs.username = username;
attrs.password = password;
const user = new this(attrs);
return user.signUp({}, options);
}
/**
* Logs in a user with a username (or email) and password. On success, this
* saves the session to disk, so you can retrieve the currently logged in
* user using <code>current</code>.
*
* @param {string} username The username (or email) to log in with.
* @param {string} password The password to log in with.
* @param {object} options
* @static
* @returns {Promise} A promise that is fulfilled with the user when
* the login completes.
*/
static logIn(username: string, password: string, options?: FullOptions) {
if (typeof username !== 'string') {
return Promise.reject(new ParseError(ParseError.OTHER_CAUSE, 'Username must be a string.'));
} else if (typeof password !== 'string') {
return Promise.reject(new ParseError(ParseError.OTHER_CAUSE, 'Password must be a string.'));
}
const user = new this();
user._finishFetch({ username: username, password: password });
return user.logIn(options);
}
/**
* Logs in a user with a username (or email) and password, and authData. On success, this
* saves the session to disk, so you can retrieve the currently logged in
* user using <code>current</code>.
*
* @param {string} username The username (or email) to log in with.
* @param {string} password The password to log in with.
* @param {object} authData The authData to log in with.
* @param {object} options
* @static
* @returns {Promise} A promise that is fulfilled with the user when
* the login completes.
*/
static logInWithAdditionalAuth(username: string, password: string, authData: AuthData, options?: FullOptions) {
if (typeof username !== 'string') {
return Promise.reject(new ParseError(ParseError.OTHER_CAUSE, 'Username must be a string.'));
}
if (typeof password !== 'string') {
return Promise.reject(new ParseError(ParseError.OTHER_CAUSE, 'Password must be a string.'));
}
if (Object.prototype.toString.call(authData) !== '[object Object]') {
return Promise.reject(new ParseError(ParseError.OTHER_CAUSE, 'Auth must be an object.'));
}
const user = new this();
user._finishFetch({ username: username, password: password, authData });
return user.logIn(options);
}
/**
* Logs in a user with an objectId. On success, this saves the session
* to disk, so you can retrieve the currently logged in user using
* <code>current</code>.
*
* @param {string} userId The objectId for the user.
* @static
* @returns {Promise} A promise that is fulfilled with the user when
* the login completes.
*/
static loginAs(userId: string) {
if (!userId) {
throw new ParseError(ParseError.USERNAME_MISSING, 'Cannot log in as user with an empty user id');
}
const controller = CoreManager.getUserController();
const user = new this();
return controller.loginAs(user, userId);
}
/**
* Logs in a user with a session token. On success, this saves the session
* to disk, so you can retrieve the currently logged in user using
* <code>current</code>.
*
* @param {string} sessionToken The sessionToken to log in with.
* @param {object} options
* @static
* @returns {Promise} A promise that is fulfilled with the user when
* the login completes.
*/
static become(sessionToken: string, options?: RequestOptions) {
if (!canUseCurrentUser) {
throw new Error('It is not memory-safe to become a user in a server environment');
}
options = options || {};
const becomeOptions: RequestOptions = {
sessionToken: sessionToken,
};
if (options.hasOwnProperty('useMasterKey')) {
becomeOptions.useMasterKey = options.useMasterKey;
}
const controller = CoreManager.getUserController();
const user = new this();
return controller.become(user, becomeOptions);
}
/**
* Retrieves a user with a session token.
*
* @param {string} sessionToken The sessionToken to get user with.
* @param {object} options
* @static
* @returns {Promise} A promise that is fulfilled with the user is fetched.
*/
static me(sessionToken: string, options?: RequestOptions = {}) {
const controller = CoreManager.getUserController();
const meOptions: RequestOptions = {
sessionToken: sessionToken,
};
if (options.useMasterKey) {
meOptions.useMasterKey = options.useMasterKey;
}
const user = new this();
return controller.me(user, meOptions);
}
/**
* Logs in a user with a session token. On success, this saves the session
* to disk, so you can retrieve the currently logged in user using
* <code>current</code>. If there is no session token the user will not logged in.
*
* @param {object} userJSON The JSON map of the User's data
* @static
* @returns {Promise} A promise that is fulfilled with the user when
* the login completes.
*/
static hydrate(userJSON: AttributeMap) {
const controller = CoreManager.getUserController();
const user = new this();
return controller.hydrate(user, userJSON);
}
/**
* Static version of {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#linkWith linkWith}
*
* @param provider
* @param options
* @param saveOpts
* @static
* @returns {Promise}
*/
static logInWith(
provider: any,
options: { authData?: AuthData },
saveOpts?: FullOptions
): Promise<ParseUser> {
const user = new this();
return user.linkWith(provider, options, saveOpts);
}
/**
* Logs out the currently logged in user session. This will remove the
* session from disk, log out of linked services, and future calls to
* <code>current</code> will return <code>null</code>.
*
* @param {object} options
* @static
* @returns {Promise} A promise that is resolved when the session is
* destroyed on the server.
*/
static logOut(options: RequestOptions = {}) {
const controller = CoreManager.getUserController();
return controller.logOut(options);
}
/**
* Requests a password reset email to be sent to the specified email address
* associated with the user account. This email allows the user to securely
* reset their password on the Parse site.
*
* @param {string} email The email address associated with the user that
* forgot their password.
* @param {object} options
* @static
* @returns {Promise}
*/
static requestPasswordReset(email: string, options?: RequestOptions) {
options = options || {};
const requestOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
requestOptions.useMasterKey = options.useMasterKey;
}
const controller = CoreManager.getUserController();
return controller.requestPasswordReset(email, requestOptions);
}
/**
* Request an email verification.
*
* @param {string} email The email address associated with the user that
* needs to verify their email.
* @param {object} options
* @static
* @returns {Promise}
*/
static requestEmailVerification(email: string, options?: RequestOptions) {
options = options || {};
const requestOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
requestOptions.useMasterKey = options.useMasterKey;
}
const controller = CoreManager.getUserController();
return controller.requestEmailVerification(email, requestOptions);
}
/**
* Verify whether a given password is the password of the current user.
*
* @param {string} username A username to be used for identificaiton
* @param {string} password A password to be verified
* @param {object} options
* @static
* @returns {Promise} A promise that is fulfilled with a user
* when the password is correct.
*/
static verifyPassword(username: string, password: string, options?: RequestOptions) {
if (typeof username !== 'string') {
return Promise.reject(new ParseError(ParseError.OTHER_CAUSE, 'Username must be a string.'));
}
if (typeof password !== 'string') {
return Promise.reject(new ParseError(ParseError.OTHER_CAUSE, 'Password must be a string.'));
}
const controller = CoreManager.getUserController();
return controller.verifyPassword(username, password, options || {});
}
/**
* Allow someone to define a custom User class without className
* being rewritten to _User. The default behavior is to rewrite
* User to _User for legacy reasons. This allows developers to
* override that behavior.
*
* @param {boolean} isAllowed Whether or not to allow custom User class
* @static
*/
static allowCustomUserClass(isAllowed: boolean) {
CoreManager.set('PERFORM_USER_REWRITE', !isAllowed);
}
/**
* Allows a legacy application to start using revocable sessions. If the
* current session token is not revocable, a request will be made for a new,
* revocable session.
* It is not necessary to call this method from cloud code unless you are
* handling user signup or login from the server side. In a cloud code call,
* this function will not attempt to upgrade the current token.
*
* @param {object} options
* @static
* @returns {Promise} A promise that is resolved when the process has
* completed. If a replacement session token is requested, the promise
* will be resolved after a new token has been fetched.
*/
static enableRevocableSession(options?: RequestOptions) {
options = options || {};
CoreManager.set('FORCE_REVOCABLE_SESSION', true);
if (canUseCurrentUser) {
const current = ParseUser.current();
if (current) {
return current._upgradeToRevocableSession(options);
}
}
return Promise.resolve();
}
/**
* Enables the use of become or the current user in a server
* environment. These features are disabled by default, since they depend on
* global objects that are not memory-safe for most servers.
*
* @static
*/
static enableUnsafeCurrentUser() {
canUseCurrentUser = true;
}
/**
* Disables the use of become or the current user in any environment.
* These features are disabled on servers by default, since they depend on
* global objects that are not memory-safe for most servers.
*
* @static
*/
static disableUnsafeCurrentUser() {
canUseCurrentUser = false;
}
/**
* When registering users with {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#linkWith linkWith} a basic auth provider
* is automatically created for you.
*
* For advanced authentication, you can register an Auth provider to
* implement custom authentication, deauthentication.
*
* @param provider
* @see {@link https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html AuthProvider}
* @see {@link https://docs.parseplatform.org/js/guide/#custom-authentication-module Custom Authentication Module}
* @static
*/
static _registerAuthenticationProvider(provider: any) {
authProviders[provider.getAuthType()] = provider;
// Synchronize the current user with the auth provider.
ParseUser.currentAsync().then(current => {
if (current) {
current._synchronizeAuthData(provider.getAuthType());
}
});
}
/**
* @param provider
* @param options
* @param saveOpts
* @deprecated since 2.9.0 see {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#logInWith logInWith}
* @static
* @returns {Promise}
*/
static _logInWith(provider: any, options: { authData?: AuthData }, saveOpts?: FullOptions) {
const user = new this();
return user.linkWith(provider, options, saveOpts);
}
static _clearCache() {
currentUserCache = null;
currentUserCacheMatchesDisk = false;
}
static _setCurrentUserCache(user: ParseUser) {
currentUserCache = user;
}
}
ParseObject.registerSubclass('_User', ParseUser);
const DefaultController = {
updateUserOnDisk(user) {
const path = Storage.generatePath(CURRENT_USER_KEY);
const json = user.toJSON();