forked from jebu/stackmob-js-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstackmob.js
2327 lines (2046 loc) · 84.3 KB
/
stackmob.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
/*
StackMob JS SDK Version 0.9.1
Copyright 2012-2013 StackMob Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
(function() {
var root = this;
//in case the JS SDK is being included in environments without window
var thisWindow = typeof window !== "undefined" ? window : { location: { hostname: 'api.stackmob.com', port: '443', protocol: 'https:' }};
/**
* The StackMob object is the core of the JS SDK. It holds static variables, methods, and configuration information.
*
* It is the only variable introduced globally.
*/
thisWindow.StackMob = root.StackMob = {
//Default API Version. Set to 0 for your Development API. Production APIs are 1, 2, 3+
DEFAULT_API_VERSION : 0,
/**
* StackMob provides an authentication capabilities out of the box. When you create your StackMob account, a default User schema `user` is created for you. The primary key field is what's used for login. The default primary key is `username`, and the default password field is `password`.
*/
DEFAULT_LOGIN_SCHEMA : 'user',
DEFAULT_LOGIN_FIELD : 'username',
DEFAULT_PASSWORD_FIELD : 'password',
// Radians are defined for use with the geospatial methods.
EARTH_RADIANS_MI : 3956.6,
EARTH_RADIANS_KM : 6367.5,
// Backbone.js will think you're updating an object if you provide an ID. This flag is used internally in the JS SDK to force a POST rather than a PUT if you provide an object ID.
FORCE_CREATE_REQUEST : 'stackmob_force_create_request',
// These constants are used internally in the JS SDK to help with queries involving arrays.
ARRAY_FIELDNAME : 'stackmob_array_fieldname',
ARRAY_VALUES : 'stackmob_array_values',
// This flag is used internally in the JS SDK to help with deletion of objects in relationships.
CASCADE_DELETE : 'stackmob_cascade_delete',
// These constants are intended for public use to help with deletion of objects in relationships.
HARD_DELETE : true,
SOFT_DELETE : false,
API_SERVER : 'api.stackmob.com',
RETRY_WAIT : 10000,
RETRY_ATTEMPTS : 3,
REFRESH_TOKEN_KEY : 'oauth2.refreshToken',
POST: 'POST',
PUT: 'PUT',
DELETE: 'DELETE',
CONTENT_TYPE_JSON: 'application/json',
// Use HTTPS for all requests
SECURE_ALWAYS: "ALWAYS",
// Use HTTPS for only authentication methods. Deteremind by StackMob.isAccessTokenMethod
SECURE_MIXED: "MIXED",
// Never use HTTPS
SECURE_NEVER: "NEVER",
// This specifies the server-side API this instance of the JS SDK should point to. It's set to the Development environment (0) by default. This should be over-ridden when the user initializes their StackMob instance.
apiVersion : 0,
// The current version of the JS SDK.
sdkVersion : "0.9.2",
// This holds the application public key when the JS SDK is initialized to connect to StackMob's services via OAuth 2.0.
publicKey : null,
/**
* Methods to help with api signing
*/
getProtocol: function() { return thisWindow.location.protocol; },
getHostname: function() { return thisWindow.location.hostname; },
getPort:function () { return thisWindow.location.port; },
/**
* The Storage object lives within the StackMob object and provides an abstraction layer for client storage. It's intended for internal use within the JS SDK. The JS SDK is currently using HTML5's Local Storage feature to persist key/value items.
*/
Storage : {
//Since the underlying client side storage implementation may not be name-spaced, we'll prefix our saved keys with `STORAGE_PREFIX`.
STORAGE_PREFIX : 'stackmob.',
//Use this to save things to local storage as a key/value pair.
persist : function(key, value) {
//If there's an HTML5 implementation of Local Storage available, then use it. Otherwise, there's no fallback at this point in time.
if(localStorage)
localStorage.setItem(this.STORAGE_PREFIX + key, value);
},
//Read a value from local storage given the `key`.
retrieve : function(key) {
if(localStorage)
return localStorage.getItem(this.STORAGE_PREFIX + key);
else
return null;
},
//Remove a value from local storage given the `key`.
remove : function(key) {
if(localStorage)
localStorage.removeItem(this.STORAGE_PREFIX + key);
}
},
/**
* Helper method to allow altering callback methods
**/
_generateCallbacks : function(options, methods){
options = options || {};
// Wrap yes/no methods with a success method
options['success'] = function(result){
if ( methods['isValidResult'](result) ){
if (typeof methods['yes'] === "function") methods['yes'](result);
} else {
if (typeof methods['no'] === "function") methods['no'](result);
}
};
// Set default error method if one is not provided
if ( !options['error'] && (typeof methods['error'] === "function") ) {
options['error'] = methods['error'];
}
return options;
},
/**
* Helper method that checks for callback methods in an options object
**/
_containsCallbacks : function(options, callbacks){
return ( typeof options === "object" ) &&
_.some(callbacks, function(callback){ return typeof options[callback] === "function"; });
},
/**
* Returns the current logged in user's login id: username (or your custom field if specified in StackMob.init), email, or whatever is defined as the primary key.
* Optionally accepts asynchronous callback methods in the options object.
*/
getLoggedInUser : function(options) {
var storedUser = ((!this.isOAuth2Mode() && this.Storage.retrieve(this.loggedInUserKey)) || this.Storage.retrieve('oauth2.user'));
//The logged in user's ID is saved in local storage until removed, so we need to check to make sure that the user has valid login credentials before returning the login ID.
if ( options && options['success'] ){
this.hasValidOAuth(options);
} else {
return (this.isLoggedIn(options) && storedUser) ? storedUser : null;
}
},
/**
* Without specifying the 'options' argument, this is a "dumb" method in that simply checks for the presence of login credentials, not if they're valid.
* The server checks the validity of the credentials on each API request, however. It's here for convenience.
*
* Optionally accepts asynchronous callback methods in the options object. When provided, this method will renew the refresh token if required.
*/
isLoggedIn : function(options) {
if ( this._containsCallbacks(options, ['yes', 'no']) ){
options = this._generateCallbacks(options, {
'isValidResult': function(result) {
return typeof result !== "undefined";
},
'yes': options['yes'],
'no': options['no'],
'error': options['no']
});
this.hasValidOAuth(options);
} else {
return (!this.isLoggedOut()) || this.hasValidOAuth(options);
}
},
/**
* Without specifying the 'options' argument, this is a "dumb" method in that simply checks if the given `username` is that of the logged in user without asking the server.
*
* Optionally accepts asynchronous callback methods in the options object. When provided, this method will renew the refresh token if required.
*/
isUserLoggedIn : function(username, options) {
if ( this._containsCallbacks(options, ['yes', 'no']) ){
options = this._generateCallbacks(options, {
'isValidResult': function(result) {
return result == username;
},
'yes': options['yes'],
'no': options['no'],
'error': options['no']
});
this.hasValidOAuth(options);
} else {
return username == this.getLoggedInUser(options);
}
},
/**
* Without specifying the 'options' argument, this is a "dumb" method in that checks to see if a user is logged out (doesn't have login credentials) without hitting the server.
*
* Optionally accepts asynchronous callback methods in the options object. When provided, this method will renew the refresh token if required.
*/
isLoggedOut : function(options) {
if ( this._containsCallbacks(options, ['yes', 'no']) ){
options = this._generateCallbacks(options, {
'isValidResult': function(result) {
return typeof result == "undefined";
},
'yes': options['yes'],
'no': options['no'],
'error': options['yes']
});
this.hasValidOAuth(options);
} else {
return !this.hasValidOAuth(options);
}
},
//This is an internally used method to get the API URL no matter what the context - development, production, etc. This envelopes `getDevAPIBase` and `getProdAPIBase` in that this method is smart enough to choose which of the URLs to use.
getBaseURL : function() {
if( StackMob['useRelativePathForAjax'] ){
// Build "relative path" (also used for OAuth signing)
return StackMob.apiDomain ? StackMob.apiDomain : (this.getHostname() + (this.getPort() ? ':' + this.getPort() : '')) + '/';
} else {
// Use absolute path and operate through CORS
return StackMob.apiDomain ? StackMob.apiDomain : (StackMob['API_SERVER'] + '/');
}
},
//The JS SDK calls this to throw an error.
throwError : function(msg) {
throw new Error(msg);
},
//The JS SDK calls this specifically when there's a URL error.
urlError : function() {
this.throwError('A "url" property or function must be specified');
},
//Some methods are OAuth 2.0 only. This is used internally in the JS SDK to throw an error if a public key is required in initialization.
requirePublicKey : function() {
if(!StackMob.publicKey)
this.throwError("Error: This requires that you initialize StackMob with a public key.");
},
//Checks to see if the JS SDK is in OAuth 2.0 mode or not.
isOAuth2Mode : function() {
return !isNaN(StackMob['publicKey'] && !StackMob['privateKey']);
},
prepareCredsForSaving : function(accessToken, refreshToken, macKey, expires, user, schemaInfo) {
var expireTime = (new Date()).getTime() + (this._stubbedExpireTime(expires) * 1000);
//For convenience, the JS SDK will save the expiration date of these credentials locally so that the developer can check for it if need be.
var creds = {
'oauth2.accessToken' : accessToken,
'oauth2.macKey' : macKey,
'oauth2.expires' : expireTime,
'oauth2.user' : user,
'oauth2.userSchemaInfo' : schemaInfo
};
creds[StackMob.REFRESH_TOKEN_KEY] = refreshToken;
return creds;
},
//Why have this? So that we can overwrite the expire time via _.extend(StackMob, { _stubbedExpireTime: ... }) for tests
_stubbedExpireTime: function(expires) {
return expires;
},
//Saves the OAuth 2.0 credentials (passed in as JSON) to client storage.
saveOAuthCredentials : function(creds) {
var accessToken = creds['oauth2.accessToken'];
var refreshToken = creds[StackMob.REFRESH_TOKEN_KEY];
//Because the server sends back how long the credentials are valid for and not the expiration date, we construct the expiration date on the client side. For the login scenario where we are using OAuth 2.0's redirect URL mechanism and where a user refreshes the logged-in redirected URL page, we don't want to incorrectly generate and save a new expiration date. If the access token is the same, then leave the expiration date as is.
//FIXME: don't even pass in the expires value if we dont' intend to save it. Move this logic out to handleOAuthCallback. This check is happening too late down the line.
if(this.Storage.retrieve('oauth2.accessToken') != accessToken) {
this.Storage.persist('oauth2.expires', creds['oauth2.expires']);
}
this.Storage.persist('oauth2.accessToken', accessToken);
this.Storage.persist(StackMob.REFRESH_TOKEN_KEY, refreshToken);
this.Storage.persist('oauth2.macKey', creds['oauth2.macKey']);
this.Storage.persist('oauth2.user', creds['oauth2.user']);
this.Storage.persist('oauth2.userSchemaInfo', JSON.stringify(creds['oauth2.userSchemaInfo']));
},
//StackMob validates OAuth 2.0 credentials upon each request and will send back a error message if the credentials have expired. To save the trip, developers can check to see if their user has valid OAuth 2.0 credentials that indicate the user is logged in.
hasValidOAuth : function(options) {
options = options || {};
//If we aren't running in OAuth 2.0 mode, then kick out early.
if(!this.isOAuth2Mode()){
if (options && options['error'])
options['error']();
return false;
}
//Check to see if we have all the necessary OAuth 2.0 credentials locally AND if the credentials have expired.
var creds = this.getOAuthCredentials();
var expires = (creds && creds['oauth2.expires']) || 0;
//If no accesstoken, mackey, or expires..
if ( !_.all([creds['oauth2.accessToken'], creds['oauth2.macKey'], expires], _.identity) ){
if (options && options['success']) options['success'](undefined);
return false;
}
if ( !StackMob.hasExpiredOAuth() ) {
//If not expired
if (options && options['success'] ){
options['success']( this.Storage.retrieve('oauth2.user') );
}
return this.Storage.retrieve('oauth2.user');
} else if ( options && options['success']) {
//If expired and async
var originalSuccess = options['success'];
options['success'] = function(input){
var creds = StackMob.getOAuthCredentials();
var loginField = (creds['oauth2.userSchemaInfo'] && creds['oauth2.userSchemaInfo']['loginField']) ?
creds['oauth2.userSchemaInfo']['loginField'] : this['loginField'];
originalSuccess( input[loginField]);
};
this.initiateRefreshSessionCall(options);
} else {
//If expired and sync
return false;
}
},
initiateRefreshSessionCall: function(options) {
StackMob.refreshSession.call(StackMob, options);
},
shouldSendRefreshToken : function() {
return this.hasExpiredOAuth() && this.hasRefreshToken() && this.shouldKeepLoggedIn();
},
keepLoggedIn : function(keep) {
StackMob.Storage.persist('oauth2.shouldKeepLoggedIn', keep === true);
},
shouldKeepLoggedIn : function() {
return StackMob.Storage.retrieve('oauth2.shouldKeepLoggedIn') === 'true';
},
hasRefreshToken : function() {
var creds = this.getOAuthCredentials();
return creds && ( typeof creds[StackMob.REFRESH_TOKEN_KEY] !== 'undefined') && creds[StackMob.REFRESH_TOKEN_KEY] !== null;
},
getRefreshToken : function() {
var creds = this.getOAuthCredentials();
return creds[StackMob.REFRESH_TOKEN_KEY];
},
hasExpiredOAuth : function() {
return this.isOAuth2Mode() && (this.getOAuthExpireTime() === null) || (this.getOAuthExpireTime() <= (new Date()).getTime());
},
clearOAuthCredentials : function() {
StackMob.Storage.remove(StackMob.loggedInUserKey);
StackMob.Storage.remove('oauth2.accessToken');
StackMob.Storage.remove(StackMob.REFRESH_TOKEN_KEY);
StackMob.Storage.remove('oauth2.macKey');
StackMob.Storage.remove('oauth2.expires');
StackMob.Storage.remove('oauth2.user');
StackMob.Storage.remove('oauth2.userSchemaInfo');
},
//Retrieve the OAuth 2.0 credentials from client storage.
getOAuthCredentials : function() {
var oauth_accessToken = StackMob.Storage.retrieve('oauth2.accessToken');
var oauth_macKey = StackMob.Storage.retrieve('oauth2.macKey');
var oauth_expires = StackMob.Storage.retrieve('oauth2.expires');
var oauth_refreshToken = StackMob.Storage.retrieve(StackMob.REFRESH_TOKEN_KEY);
var userSchemaInfo = StackMob.Storage.retrieve('oauth2.userSchemaInfo');
var oauth_schema = null;
try {
oauth_schema = JSON.parse(userSchemaInfo);
} catch (e) { /* Harmless if this fails (in theory!)*/ }
if (_.every([oauth_accessToken, oauth_macKey, oauth_expires, oauth_refreshToken, oauth_schema])) {
var creds = {
'oauth2.accessToken' : oauth_accessToken,
'oauth2.macKey' : oauth_macKey,
'oauth2.expires' : oauth_expires,
'oauth2.userSchemaInfo' : oauth_schema
};
creds[StackMob.REFRESH_TOKEN_KEY] = oauth_refreshToken;
return creds;
} else {
return {};
}
},
//Returns the date (in milliseconds) for when the current user's OAuth 2.0 credentials expire.
getOAuthExpireTime : function() {
var expires = this.Storage.retrieve('oauth2.expires');
return expires ? parseInt(expires, 10) : null;
},
//This is an internally used map that works with Backbone.js. It maps methods to HTTP Verbs used when making ajax calls.
METHOD_MAP : {
"create" : "POST",
"read" : "GET",
"update" : "PUT",
"delete" : "DELETE",
"post" : "POST",
"get" : "GET",
"put" : "PUT",
"addRelationship" : "POST",
"appendAndSave" : "PUT",
"deleteAndSave" : "DELETE",
"login" : "GET",
"accessToken" : "POST",
"refreshToken" : "POST",
"logout" : "GET",
"forgotPassword" : "POST",
"loginWithTempAndSetNewPassword" : "GET",
"resetPassword" : "POST",
"facebookAccessToken" : "POST",
"facebookAccessTokenWithCreate" : "POST",
"createUserWithFacebook" : "POST",
"linkUserWithFacebook" : "GET",
"unlinkUserFromFacebook" : "DELETE",
"gigyaAccessToken" : "POST",
"linkUserWithGigya" : "POST",
"unlinkUserFromGigya" : "DELETE"
},
/**
* Convenience method to retrieve the value of a key in an object. If it's a function, give its return value.
*/
getProperty : function(object, prop) {
if(!(object && object[prop]))
return null;
return _.isFunction(object[prop]) ? object[prop]() : object[prop];
},
/**
* Externally called by user to initialize their StackMob config.
*/
init : function(options) {
options = options || {};
// Run stuff before StackMob is initialized.
this.initStart(options);
/* DEPRECATED METHODS BELOW */
this.userSchema = options['userSchema']; // DEPRECATED: Use StackMob.User.extend({ schemaName: 'customschemaname' });
this.loginField = options['loginField']; // DEPRECATED: Use StackMob.User.extend({ loginField: 'customloginfield' });
this.passwordField = options['passwordField']; // DEPRECATED: Use StackMob.User.extend({ passwordField: 'custompasswordfield' });
/* DEPRECATED METHODS ABOVE */
this.newPasswordField = 'new_password';
this.publicKey = options['publicKey'];
this.apiVersion = options['apiVersion'] || this.DEFAULT_API_VERSION;
/*
* apiURL (DEPRECATED) - Advaanced Users Only. Use apiDomain instead.
* Used to redirect SDK requests to a different URL.
*
*/
if (typeof options['apiURL'] !== "undefined")
throw new Error("Error: apiURL is no longer supported. The API URL is now automatically set for PhoneGap users.");
/*
* apiDomain - Advanced Users Only. Only set apiDomain to redirect SDK
* requests to a different domain.
*
* Init variable 'apiDomain' should not contain a URL scheme (http:// or https://).
* Scheme will be prepended according to 'secure' init setting.
*/
var apiDomain = options['apiDomain'];
if (typeof apiDomain === "string"){
if (apiDomain.indexOf('http') === 0){
throw new Error("Error: apiDomain should not specify url scheme (http/https). For example, specify api.stackmob.com instead of http://api.stackmob.com. URL Scheme is determined by the 'secure' init variable.");
} else {
if (apiDomain.indexOf('/') == apiDomain.length - 1){
this.apiDomain = apiDomain;
} else {
this.apiDomain = apiDomain + '/';
}
}
}
/*
* useRelativePathForAjax - Advanced Users Only. Use to redirect SDK requests to a
* path relative to the current URL. Will only work for StackMob Hosts that can
* properly proxy requests to api.stackmob.com
*
* HTML5 apps hosted on stackmobapp.com will be set to `true` and use a relative path
* automatically.
*/
var isSMHosted = (this.getHostname().indexOf('.stackmobapp.com') > 0);
this.useRelativePathForAjax = (typeof options['useRelativePathForAjax'] === "boolean") ? options['useRelativePathForAjax'] : isSMHosted;
/*
* secure - Determine which requests should be done over SSL.
* Default the security mode to match the current URL scheme.
*
* If current page is HTTPS, set to SECURE_ALWAYS.
* If current page is HTTP, set to SECURE_NEVER.
* Otherwise, set to SECURE_MIXED.
* Can be overridden by manually specifying a security mode in init().
*/
if (options['secure']) {
this.secure = options['secure'];
} else if (this.getProtocol().indexOf("https:") == 0) {
this.secure = this.SECURE_ALWAYS;
} else if (this.getProtocol().indexOf("http:") == 0) {
this.secure = this.SECURE_NEVER;
} else {
this.secure = this.SECURE_MIXED;
}
this.ajax = options['ajax'] || this.ajax;
this.initEnd(options);
return this;
},
initStart : function(options) {
// Any actions a developer may want to implement via _extend should be done here
},
initEnd : function(options) {
},
/*
* Need to modify the options callbacks at all? do that here.
* These are placed in methods where Backbone wraps the success/error calls so that
* we also have an opportunity to modify/wrap the options if necessary.
*/
wrapStackMobCallbacks: function(options, callInfo) {}
};
}).call(this);
/**
* StackMob JS SDK
* BackBone.js-based
* Backbone.js Version 0.9.2
* No OAuth - for use with StackMob's HTML5 Product
*/
(function() {
var root = this;
var $ = root.jQuery || root.Ext || root.Zepto;
function createBaseString(ts, nonce, method, uri, host, port) {
var nl = '\u000A';
return ts + nl + nonce + nl + method + nl + uri + nl + host + nl + port + nl + nl;
}
function generateMAC(method, id, key, hostWithPort, url, host) {
var splitHost = hostWithPort.split(':');
var hostNoPort = splitHost.length > 1 ? splitHost[0] : hostWithPort;
var port = splitHost.length > 1 ? splitHost[1] : ((host.substring(0,5) == 'https') ? 443 : 80);
var ts = Math.round(new Date().getTime() / 1000);
var nonce = "n" + Math.round(Math.random() * 10000);
var base = createBaseString(ts, nonce, method, url, hostNoPort, port);
var hash = CryptoJS.HmacSHA1(base, key);
var mac = hash.toString(CryptoJS.enc.Base64);
return 'MAC id="' + id + '",ts="' + ts + '",nonce="' + nonce + '",mac="' + mac + '"';
}
function getAuthHeader(params){
var scheme = params['url'].match(/(^http|^https):\/\//g);
var host = scheme + StackMob.getBaseURL();
var path = params['url'].replace(new RegExp(host, 'g'), '/');
// Remove trailing slash from host for signing
var sighost = host.replace(new RegExp('^http://|^https://', 'g'), '').replace(new RegExp('/'), '');
var accessToken = StackMob.Storage.retrieve('oauth2.accessToken');
var macKey = StackMob.Storage.retrieve('oauth2.macKey');
var expires = StackMob.Storage.retrieve('oauth2.expires');
if(StackMob.isOAuth2Mode() && accessToken && macKey) {
var authHeader = generateMAC(params['type'], accessToken, macKey, sighost, path, host);
return authHeader;
}
}
function _getURLScheme(method, params){
params = params || {};
var scheme,
HTTP = 'http',
HTTPS = 'https';
if ( params['secureRequest'] === true ) {
scheme = HTTPS;
} else {
switch(StackMob.secure){
case StackMob.SECURE_ALWAYS:
scheme = HTTPS;
break;
case StackMob.SECURE_NEVER:
scheme = HTTP;
break;
default:
scheme = StackMob._isSecureMethod(method, params) ? HTTPS : HTTP;
break;
}
}
return scheme + '://';
}
function _prepareHeaders(method, params, options) {
options = options || {};
//Prepare Request Headers
params['headers'] = params['headers'] || {};
//Add API Version Number to Request Headers
//let users overwrite this if they know what they're doing
params['headers'] = _.extend(params['headers'], {
"Accept" : 'application/vnd.stackmob+json; version=' + StackMob['apiVersion']
});
//dont' let users overwrite the stackmob headers though..
_.extend(params['headers'], {
"X-StackMob-User-Agent" : "StackMob (JS; " + StackMob['sdkVersion'] + ")"
});
if(StackMob['publicKey'] && !StackMob['privateKey']) {
params['headers']['X-StackMob-API-Key'] = StackMob['publicKey'];
params['headers']['X-StackMob-Proxy-Plain'] = 'stackmob-api';
// CORS Support
// The value is set to something arbitrary because IE strips out
// headers with empty values.
params['headers']['X-StackMob-API-Key-' + StackMob['publicKey']] = "1";
} else {
params['headers']['X-StackMob-Proxy'] = 'stackmob-api';
}
//let users overwrite this if they know what they're doing
if(StackMob.isOAuth2Mode() && StackMob.isAccessTokenMethod(method)) {
params['contentType'] = 'application/x-www-form-urlencoded';
} else if(_.include(['PUT', 'POST'], StackMob.METHOD_MAP[method])) {
params['contentType'] = params['contentType'] || StackMob.CONTENT_TYPE_JSON;
}
if(!isNaN(options[StackMob.CASCADE_DELETE])) {
params['headers']['X-StackMob-CascadeDelete'] = options[StackMob.CASCADE_DELETE] === true;
}
// If this is an advanced query, check headers
if(options['query']) {
var queryObj = params['query'] || throwError("No StackMobQuery object provided to the query call.");
if(queryObj['selectFields']) {
if(queryObj['selectFields'].length > 0) {
params['headers']["X-StackMob-Select"] = queryObj['selectFields'].join();
}
}
//Add Range Headers
if(queryObj['range']) {
params['headers']['Range'] = 'objects=' + queryObj['range']['start'] + '-' + queryObj['range']['end'];
}
//Add Query Parameters to Parameter Map
_.extend(params['data'], queryObj['params']);
//Add OrderBy Headers
if(queryObj['orderBy'] && queryObj['orderBy'].length > 0) {
var orderList = queryObj['orderBy'];
var order = '';
var size = orderList.length;
for(var i = 0; i < size; i++) {
order += orderList[i];
if(i + 1 < size)
order += ',';
}
params['headers']["X-StackMob-OrderBy"] = order;
}
}
}
function _prepareAjaxClientParams(params) {
params = params || {};
//Prepare 3rd party ajax settings
params['processData'] = false;
//Put Accept into the header for jQuery
params['accepts'] = params['headers']["Accept"];
}
function _prepareAuth(method, params) {
if(StackMob.isAccessTokenMethod(method)) {
return;
//then don't add an Authorization Header
}
var authHeader = getAuthHeader(params);
if(authHeader) {
params['headers']['Authorization'] = authHeader;
}
}
_.extend(StackMob, {
isSencha : function() {
return root.Ext;
},
isZepto : function() {
return root.Zepto;
},
initEnd : function(options) {
createStackMobModel();
createStackMobCollection();
createStackMobUserModel();
},
cc : function(method, params, verb, options) {
this.customcode(method, params, verb, options);
},
customcode : function(method, params, verb, options) {
function isValidVerb(v) {
return v && !_.isUndefined(StackMob.METHOD_MAP[verb.toLowerCase()]);
}
// Verb is an optional parameter, so `options` may be passed into
// this slot instead of the verb string.
if(_.isObject(verb)) {
// If this is an object, assume it is the `options` param instead
options = verb || {};
var theVerb = options['httpVerb'];
options['httpVerb'] = isValidVerb(theVerb) ? theVerb : 'GET';
} else {
options = options || {};
if(_.isString(verb) && isValidVerb(verb))
options['httpVerb'] = verb.toUpperCase();
}
options['data'] = options['data'] || {};
if (verb !== 'GET') options['contentType'] = options['contentType'] || StackMob.CONTENT_TYPE_JSON;
_.extend(options['data'], params);
options['url'] = _getURLScheme(method, params) + this.getBaseURL();
this.sync.call(StackMob, method, null, options);
},
processLogin : function(result, options) {
if(StackMob.isOAuth2Mode()) {
var oauth2Creds = result;
var accessToken = oauth2Creds['access_token'];
var refreshToken = oauth2Creds['refresh_token'];
var macKey = oauth2Creds['mac_key'];
var expires = oauth2Creds['expires_in'];
try {
var savedCreds = StackMob.getOAuthCredentials();
/*
* processLogin can be called by the developer or automatically by refreshSession
* if by refreshSession, there is no user schema info passed from the options, so fetch it from the local storage if that's the case.'
*/
var userSchemaInfo = options['stackmob_userschemainfo'] || savedCreds['oauth2.userSchemaInfo']; //get schema info
var loginField = userSchemaInfo['loginField']; //so that we can determine the primary key/login field
var username = result['stackmob']['user'][loginField]; //figure out username
var creds = StackMob.prepareCredsForSaving(accessToken, refreshToken, macKey, expires, username, userSchemaInfo);
//...then let's save the OAuth credentials to local storage.
StackMob.saveOAuthCredentials(creds);
StackMob.Storage.persist(StackMob.loggedInUserKey, username);
} catch(err) {
if(console)
console.error('Problem saving OAuth 2.0 credentials and user: ' + err);
}
}
},
sync : function(method, model, options) {
options = options || {};
if(!StackMob.isAccessTokenMethod(method) && StackMob.shouldSendRefreshToken() && options['stackmob_attempted_refresh'] !== true) {
var originalMethod = method;
var originalOptions = options;
originalOptions['stackmob_attempted_refresh'] = true;
var originalModel = model;
var originalThis = this;
StackMob.refreshSession.call(StackMob, {
oncomplete : function() { // oncomplete because we don't care whether success or error
StackMob.sync.call(originalThis, originalMethod, originalModel, originalOptions);
}
});
return false;
}
//Override to allow 'Model#save' to force create even if the id (primary key) is set in the model and hence !isNew() in BackBone
var forceCreateRequest = options[StackMob.FORCE_CREATE_REQUEST] === true;
if(forceCreateRequest) {
method = 'create';
}
function _prepareBaseURL(model, method, params) {
params = params || {};
var scheme = _getURLScheme(method, params);
//User didn't override the URL so use the one defined in the model
if(!params['url'] && model) {
params['url'] = scheme + model.url();
}
var notCustomCode = method != 'cc';
var notNewModel = (model && model.isNew && !model.isNew());
var notForcedCreateRequest = !forceCreateRequest;
var isArrayMethod = (method == 'addRelationship' || method == 'appendAndSave' || method == 'deleteAndSave');
if(_isExtraMethodVerb(method)) { // Extra Method Verb? Add it to the model url. (e.g. /user/login)
var endpoint = method;
params['url'] += (params['url'].charAt(params['url'].length - 1) == '/' ? '' : '/') + endpoint;
} else if(isArrayMethod || notCustomCode && notNewModel && notForcedCreateRequest) {//append ID in URL if necessary
params['url'] += (params['url'].charAt(params['url'].length - 1) == '/' ? '' : '/') + encodeURIComponent(model.get(model.getPrimaryKeyField()));
if(isArrayMethod) {
params['url'] += '/' + options[StackMob.ARRAY_FIELDNAME];
}
if(method == 'deleteAndSave') {
var ids = '';
if(_.isArray(options[StackMob.ARRAY_VALUES])) {
ids = _.map(options[StackMob.ARRAY_VALUES], function(id) {
return encodeURIComponent(id);
}).join(',');
} else {
ids = encodeURIComponent(options[StackMob.ARRAY_VALUES]);
}
params['url'] += '/' + ids;
}
}
}
function _prepareRequestBody(method, params, options) {
options = options || {};
function toParams(obj) {
var params = _.map(_.keys(obj), function(key) {
return key + '=' + encodeURIComponent(obj[key]);
});
return params.join('&');
}
//Set the request body
if(StackMob.isOAuth2Mode() && StackMob.isAccessTokenMethod(method)) {
params['data'] = toParams(params['data']);
} else if(params['type'] == 'POST' || params['type'] == 'PUT') {
if(method == 'resetPassword' || method == 'forgotPassword') {
params['data'] = JSON.stringify(params['data']);
} else if(method == 'addRelationship' || method == 'appendAndSave') {
if(options && options[StackMob.ARRAY_VALUES])
params['data'] = JSON.stringify(options[StackMob.ARRAY_VALUES]);
} else if(model) {
var json = model.toJSON();
//Let developers ignore fields
var ignorefields = options['remote_ignore'] || [];
_.each(ignorefields, function(fieldname) {
delete json[fieldname];
});
delete json['lastmoddate'];
delete json['createddate'];
if(method == 'update') {
var userSchemaInfo = options['stackmob_userschemainfo'] || StackMob.getOAuthCredentials()['oauth2.userSchemaInfo'];
if (userSchemaInfo) {
var passwordField = userSchemaInfo['passwordField'];
delete json[passwordField];
}
_.each(model.getBinaryFields(), function(field) {
if (json[field] && json[field].indexOf('http') === 0) {
delete json[field];
}
});
}
if(StackMob.isOAuth2Mode())
delete json['sm_owner'];
params['data'] = JSON.stringify(_.extend(json, params['data']));
} else
params['data'] = JSON.stringify(params.data);
} else if(params['type'] == "GET" || params['type'] == "DELETE") {
if(!_.isEmpty(params['data'])) {
params['url'] += '?';
var path = toParams(params['data']);
params['url'] += path;
}
delete params['data'];
//we shouldn't be passing anything up as data in a GET call
} else {
delete params['data'];
}
}
function _isExtraMethodVerb(method) {
return !_.include(['create', 'update', 'delete', 'read', 'query', 'deleteAndSave', 'appendAndSave', 'addRelationship'], method);
}
//Determine what kind of call to make: GET, POST, PUT, DELETE
var type = options['httpVerb'] || StackMob.METHOD_MAP[method] || 'GET';
//Prepare query configuration
var params = _.extend({
type : type
}, options);
params['data'] = params['data'] || {};
_prepareBaseURL(model, method, params);
_prepareHeaders(method, params, options);
_prepareRequestBody(method, params, options);
_prepareAjaxClientParams(params);
_prepareAuth(method, params);
StackMob.makeAPICall(model, params, method, options);
},
refreshSession : function(options) {
//Make an ajax call here hitting the refreshToken access point and oncomplete, run whatever was passed in
var refreshOptions = {};
_.extend(refreshOptions, options);
if(StackMob.hasRefreshToken()) {
var userSchema = StackMob.getOAuthCredentials()['oauth2.userSchemaInfo'] ? StackMob.getOAuthCredentials()['oauth2.userSchemaInfo']['schemaName'] : StackMob['userSchema'];
//set request call details
refreshOptions['url'] = _getURLScheme('refreshToken') + this.getBaseURL() + userSchema;
refreshOptions['contentType'] = 'application/x-www-form-urlencoded';
refreshOptions['data'] = {
refresh_token : StackMob.getOAuthCredentials()[StackMob.REFRESH_TOKEN_KEY],
grant_type : 'refresh_token',
token_type : 'mac',
mac_algorithm : 'hmac-sha1'
};
//Set oncomplete callback
var originalOncomplete = options['oncomplete'];
if ( originalOncomplete ) {
refreshOptions['oncomplete'] = function() {
originalOncomplete();
};
}
if ( options && options['success'] ){
refreshOptions['success'] = options['success'];
}
refreshOptions['stackmob_onrefreshToken'] = StackMob.processLogin;
//Set onerror callback
refreshOptions['error'] = function() {
if ( options && options['error'] )
options['error']();
//invalidate the refresh token
StackMob.Storage.remove(StackMob.REFRESH_TOKEN_KEY);
};
(this.sync || Backbone.sync).call(this, 'refreshToken', this, refreshOptions);
} else {
if (options && options['error']) {
options['error']();
}
}
},