forked from googlearchive/apigee-javascript-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapigee.js
3260 lines (3256 loc) · 115 KB
/
apigee.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
/*! apigee-javascript-sdk@2.0.5 2014-01-02 */
/*
* This module is a collection of classes designed to make working with
* the Apigee App Services API as easy as possible.
* Learn more at http://apigee.com/docs/usergrid
*
* Copyright 2012 Apigee Corporation
*
* 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.
*
* @author rod simpson (rod@apigee.com)
* @author matt dobson (matt@apigee.com)
* @author ryan bridges (rbridges@apigee.com)
*/
(function() {
var name = "Usergrid", global = global || this, overwrittenName = global[name];
//authentication type constants for Node.js
var AUTH_CLIENT_ID = "CLIENT_ID";
var AUTH_APP_USER = "APP_USER";
var AUTH_NONE = "NONE";
if ("undefined" === typeof console) {
global.console = {
log: function() {},
warn: function() {},
error: function() {},
dir: function() {}
};
}
function Usergrid() {}
Usergrid.Client = function(options) {
//usergrid enpoint
this.URI = options.URI || "https://api.usergrid.com";
//Find your Orgname and Appname in the Admin portal (http://apigee.com/usergrid)
if (options.orgName) {
this.set("orgName", options.orgName);
}
if (options.appName) {
this.set("appName", options.appName);
}
if (options.appVersion) {
this.set("appVersion", options.appVersion);
}
//authentication data
this.authType = options.authType || AUTH_NONE;
this.clientId = options.clientId;
this.clientSecret = options.clientSecret;
this.setToken(options.token || null);
//other options
this.buildCurl = options.buildCurl || false;
this.logging = options.logging || false;
//timeout and callbacks
this._callTimeout = options.callTimeout || 3e4;
//default to 30 seconds
this._callTimeoutCallback = options.callTimeoutCallback || null;
this.logoutCallback = options.logoutCallback || null;
};
/*
* Main function for making requests to the API using node.
* Use Usergrid.Client.prototype.request for cross-platform compatibility.
*
* options object:
* `method` - http method (GET, POST, PUT, or DELETE), defaults to GET
* `qs` - object containing querystring values to be appended to the uri
* `body` - object containing entity body for POST and PUT requests
* `endpoint` - API endpoint, for example 'users/fred'
* `mQuery` - boolean, set to true if running management query, defaults to false
*
* @method _request_node
* @public
* @params {object} options
* @param {function} callback
* @return {callback} callback(err, data)
*/
Usergrid.Client.prototype._request_node = function(options, callback) {
global.request = global.request || require("request");
var request = global.request;
var self = this;
var method = options.method || "GET";
var endpoint = options.endpoint;
var body = options.body || {};
var qs = options.qs || {};
var mQuery = options.mQuery || false;
//is this a query to the management endpoint?
var orgName = this.get("orgName");
var appName = this.get("appName");
if (!mQuery && !orgName && !appName) {
if (typeof this.logoutCallback === "function") {
return this.logoutCallback(true, "no_org_or_app_name_specified");
}
}
if (mQuery) {
uri = this.URI + "/" + endpoint;
} else {
uri = this.URI + "/" + orgName + "/" + appName + "/" + endpoint;
}
if (this.authType === AUTH_CLIENT_ID) {
qs.client_id = this.clientId;
qs.client_secret = this.clientSecret;
} else if (this.authType === AUTH_APP_USER) {
qs.access_token = self.getToken();
}
if (this.logging) {
console.log("calling: " + method + " " + uri);
}
this._start = new Date().getTime();
var callOptions = {
method: method,
uri: uri,
json: body,
qs: qs
};
request(callOptions, function(err, r, data) {
if (self.buildCurl) {
options.uri = r.request.uri.href;
self.buildCurlCall(options);
}
self._end = new Date().getTime();
if (r.statusCode === 200) {
if (self.logging) {
console.log("success (time: " + self.calcTimeDiff() + "): " + method + " " + uri);
}
callback(err, data);
} else {
err = true;
if (r.error === "auth_expired_session_token" || r.error === "auth_missing_credentials" || r.error == "auth_unverified_oath" || r.error === "expired_token" || r.error === "unauthorized" || r.error === "auth_invalid") {
//this error type means the user is not authorized. If a logout function is defined, call it
var error = r.body.error;
var errorDesc = r.body.error_description;
if (self.logging) {
console.log("Error (" + r.statusCode + ")(" + error + "): " + errorDesc);
}
//if the user has specified a logout callback:
if (typeof self.logoutCallback === "function") {
self.logoutCallback(err, data);
} else if (typeof callback === "function") {
callback(err, data);
}
} else {
var error = r.body.error;
var errorDesc = r.body.error_description;
if (self.logging) {
console.log("Error (" + r.statusCode + ")(" + error + "): " + errorDesc);
}
if (typeof callback === "function") {
callback(err, data);
}
}
}
});
};
/*
* Main function for making requests to the API using a browser.
* Use Usergrid.Client.prototype.request for cross-platform compatibility.
*
* options object:
* `method` - http method (GET, POST, PUT, or DELETE), defaults to GET
* `qs` - object containing querystring values to be appended to the uri
* `body` - object containing entity body for POST and PUT requests
* `endpoint` - API endpoint, for example 'users/fred'
* `mQuery` - boolean, set to true if running management query, defaults to false
*
* @method _request_node
* @public
* @params {object} options
* @param {function} callback
* @return {callback} callback(err, data)
*/
Usergrid.Client.prototype._request_xhr = function(options, callback) {
var self = this;
var method = options.method || "GET";
var endpoint = options.endpoint;
var body = options.body || {};
var qs = options.qs || {};
var mQuery = options.mQuery || false;
//is this a query to the management endpoint?
var orgName = this.get("orgName");
var appName = this.get("appName");
if (!mQuery && !orgName && !appName) {
if (typeof this.logoutCallback === "function") {
return this.logoutCallback(true, "no_org_or_app_name_specified");
}
}
var uri;
if (mQuery) {
uri = this.URI + "/" + endpoint;
} else {
uri = this.URI + "/" + orgName + "/" + appName + "/" + endpoint;
}
if (self.getToken()) {
qs.access_token = self.getToken();
}
//append params to the path
var encoded_params = encodeParams(qs);
if (encoded_params) {
uri += "?" + encoded_params;
}
//stringify the body object
body = JSON.stringify(body);
//so far so good, so run the query
var xhr = new XMLHttpRequest();
xhr.open(method, uri, true);
//add content type = json if there is a json payload
if (body) {
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
}
// Handle response.
xhr.onerror = function(response) {
self._end = new Date().getTime();
if (self.logging) {
console.log("success (time: " + self.calcTimeDiff() + "): " + method + " " + uri);
}
if (self.logging) {
console.log("Error: API call failed at the network level.");
}
//network error
clearTimeout(timeout);
var err = true;
if (typeof callback === "function") {
callback(err, response);
}
};
xhr.onload = function(response) {
//call timing, get time, then log the call
self._end = new Date().getTime();
if (self.logging) {
console.log("success (time: " + self.calcTimeDiff() + "): " + method + " " + uri);
}
//call completed
clearTimeout(timeout);
//decode the response
try {
response = JSON.parse(xhr.responseText);
} catch (e) {
response = {
error: "unhandled_error",
error_description: xhr.responseText
};
xhr.status = xhr.status === 200 ? 400 : xhr.status;
console.error(e);
}
if (xhr.status != 200) {
//there was an api error
var error = response.error;
var error_description = response.error_description;
if (self.logging) {
console.log("Error (" + xhr.status + ")(" + error + "): " + error_description);
}
if (error == "auth_expired_session_token" || error == "auth_missing_credentials" || error == "auth_unverified_oath" || error == "expired_token" || error == "unauthorized" || error == "auth_invalid") {
//these errors mean the user is not authorized for whatever reason. If a logout function is defined, call it
//if the user has specified a logout callback:
if (typeof self.logoutCallback === "function") {
return self.logoutCallback(true, response);
}
}
if (typeof callback === "function") {
callback(true, response);
}
} else {
if (typeof callback === "function") {
callback(false, response);
}
}
};
var timeout = setTimeout(function() {
xhr.abort();
if (self._callTimeoutCallback === "function") {
self._callTimeoutCallback("API CALL TIMEOUT");
} else {
self.callback("API CALL TIMEOUT");
}
}, self._callTimeout);
//set for 30 seconds
if (this.logging) {
console.log("calling: " + method + " " + uri);
}
if (this.buildCurl) {
var curlOptions = {
uri: uri,
body: body,
method: method
};
this.buildCurlCall(curlOptions);
}
this._start = new Date().getTime();
xhr.send(body);
};
/*
* Main function for making requests to the API using node. You may call this method directly
*
* options object:
* `method` - http method (GET, POST, PUT, or DELETE), defaults to GET
* `qs` - object containing querystring values to be appended to the uri
* `body` - object containing entity body for POST and PUT requests
* `endpoint` - API endpoint, for example 'users/fred'
* `mQuery` - boolean, set to true if running management query, defaults to false
*
* @method _request_node
* @public
* @params {object} options
* @param {function} callback
* @return {callback} callback(err, data)
*/
Usergrid.Client.prototype.request = function(options, callback) {
if ("undefined" !== typeof window) {
Usergrid.Client.prototype._request_xhr.apply(this, arguments);
} else {
Usergrid.Client.prototype._request_node.apply(this, arguments);
}
};
/*
* function for building asset urls
*
* @method buildAssetURL
* @public
* @params {string} uuid
* @return {string} assetURL
*/
Usergrid.Client.prototype.buildAssetURL = function(uuid) {
var self = this;
var qs = {};
var assetURL = this.URI + "/" + this.orgName + "/" + this.appName + "/assets/" + uuid + "/data";
if (self.getToken()) {
qs.access_token = self.getToken();
}
//append params to the path
var encoded_params = encodeParams(qs);
if (encoded_params) {
assetURL += "?" + encoded_params;
}
return assetURL;
};
/*
* Main function for creating new groups. Call this directly.
*
* @method createGroup
* @public
* @params {string} path
* @param {function} callback
* @return {callback} callback(err, data)
*/
Usergrid.Client.prototype.createGroup = function(options, callback) {
var getOnExist = options.getOnExist || false;
options = {
path: options.path,
client: this,
data: options
};
var group = new Usergrid.Group(options);
group.fetch(function(err, data) {
var okToSave = err && "service_resource_not_found" === data.error || "no_name_specified" === data.error || "null_pointer" === data.error || !err && getOnExist;
if (okToSave) {
group.save(function(err, data) {
if (typeof callback === "function") {
callback(err, group);
}
});
} else {
if (typeof callback === "function") {
callback(err, group);
}
}
});
};
/*
* Main function for creating new entities - should be called directly.
*
* options object: options {data:{'type':'collection_type', 'key':'value'}, uuid:uuid}}
*
* @method createEntity
* @public
* @params {object} options
* @param {function} callback
* @return {callback} callback(err, data)
*/
Usergrid.Client.prototype.createEntity = function(options, callback) {
// todo: replace the check for new / save on not found code with simple save
// when users PUT on no user fix is in place.
/*
options = {
client:this,
data:options
}
var entity = new Usergrid.Entity(options);
entity.save(function(err, data) {
if (typeof(callback) === 'function') {
callback(err, entity);
}
});
*/
var getOnExist = options.getOnExist || false;
//if true, will return entity if one already exists
options = {
client: this,
data: options
};
var entity = new Usergrid.Entity(options);
entity.fetch(function(err, data) {
//if the fetch doesn't find what we are looking for, or there is no error, do a save
var okToSave = err && "service_resource_not_found" === data.error || "no_name_specified" === data.error || "null_pointer" === data.error || !err && getOnExist;
if (okToSave) {
entity.set(options.data);
//add the data again just in case
entity.save(function(err, data) {
if (typeof callback === "function") {
callback(err, entity, data);
}
});
} else {
if (typeof callback === "function") {
callback(err, entity, data);
}
}
});
};
/*
* Main function for getting existing entities - should be called directly.
*
* You must supply a uuid or (username or name). Username only applies to users.
* Name applies to all custom entities
*
* options object: options {data:{'type':'collection_type', 'name':'value', 'username':'value'}, uuid:uuid}}
*
* @method createEntity
* @public
* @params {object} options
* @param {function} callback
* @return {callback} callback(err, data)
*/
Usergrid.Client.prototype.getEntity = function(options, callback) {
options = {
client: this,
data: options
};
var entity = new Usergrid.Entity(options);
entity.fetch(function(err, data) {
if (typeof callback === "function") {
callback(err, entity, data);
}
});
};
/*
* Main function for restoring an entity from serialized data.
*
* serializedObject should have come from entityObject.serialize();
*
* @method restoreEntity
* @public
* @param {string} serializedObject
* @return {object} Entity Object
*/
Usergrid.Client.prototype.restoreEntity = function(serializedObject) {
var data = JSON.parse(serializedObject);
options = {
client: this,
data: data
};
var entity = new Usergrid.Entity(options);
return entity;
};
/*
* Main function for creating new collections - should be called directly.
*
* options object: options {client:client, type: type, qs:qs}
*
* @method createCollection
* @public
* @params {object} options
* @param {function} callback
* @return {callback} callback(err, data)
*/
Usergrid.Client.prototype.createCollection = function(options, callback) {
options.client = this;
var collection = new Usergrid.Collection(options, function(err, data) {
if (typeof callback === "function") {
callback(err, collection, data);
}
});
};
/*
* Main function for restoring a collection from serialized data.
*
* serializedObject should have come from collectionObject.serialize();
*
* @method restoreCollection
* @public
* @param {string} serializedObject
* @return {object} Collection Object
*/
Usergrid.Client.prototype.restoreCollection = function(serializedObject) {
var data = JSON.parse(serializedObject);
data.client = this;
var collection = new Usergrid.Collection(data);
return collection;
};
/*
* Main function for retrieving a user's activity feed.
*
* @method getFeedForUser
* @public
* @params {string} username
* @param {function} callback
* @return {callback} callback(err, data, activities)
*/
Usergrid.Client.prototype.getFeedForUser = function(username, callback) {
var options = {
method: "GET",
endpoint: "users/" + username + "/feed"
};
this.request(options, function(err, data) {
if (typeof callback === "function") {
if (err) {
callback(err);
} else {
callback(err, data, data.entities);
}
}
});
};
/*
* Function for creating new activities for the current user - should be called directly.
*
* //user can be any of the following: "me", a uuid, a username
* Note: the "me" alias will reference the currently logged in user (e.g. 'users/me/activties')
*
* //build a json object that looks like this:
* var options =
* {
* "actor" : {
* "displayName" :"myusername",
* "uuid" : "myuserid",
* "username" : "myusername",
* "email" : "myemail",
* "picture": "http://path/to/picture",
* "image" : {
* "duration" : 0,
* "height" : 80,
* "url" : "http://www.gravatar.com/avatar/",
* "width" : 80
* },
* },
* "verb" : "post",
* "content" : "My cool message",
* "lat" : 48.856614,
* "lon" : 2.352222
* }
*
* @method createEntity
* @public
* @params {string} user // "me", a uuid, or a username
* @params {object} options
* @param {function} callback
* @return {callback} callback(err, data)
*/
Usergrid.Client.prototype.createUserActivity = function(user, options, callback) {
options.type = "users/" + user + "/activities";
options = {
client: this,
data: options
};
var entity = new Usergrid.Entity(options);
entity.save(function(err, data) {
if (typeof callback === "function") {
callback(err, entity);
}
});
};
/*
* Function for creating user activities with an associated user entity.
*
* user object:
* The user object passed into this function is an instance of Usergrid.Entity.
*
* @method createUserActivityWithEntity
* @public
* @params {object} user
* @params {string} content
* @param {function} callback
* @return {callback} callback(err, data)
*/
Usergrid.Client.prototype.createUserActivityWithEntity = function(user, content, callback) {
var username = user.get("username");
var options = {
actor: {
displayName: username,
uuid: user.get("uuid"),
username: username,
email: user.get("email"),
picture: user.get("picture"),
image: {
duration: 0,
height: 80,
url: user.get("picture"),
width: 80
}
},
verb: "post",
content: content
};
this.createUserActivity(username, options, callback);
};
/*
* A private method to get call timing of last call
*/
Usergrid.Client.prototype.calcTimeDiff = function() {
var seconds = 0;
var time = this._end - this._start;
try {
seconds = (time / 10 / 60).toFixed(2);
} catch (e) {
return 0;
}
return seconds;
};
/*
* A public method to store the OAuth token for later use - uses localstorage if available
*
* @method setToken
* @public
* @params {string} token
* @return none
*/
Usergrid.Client.prototype.setToken = function(token) {
this.set("token", token);
};
/*
* A public method to get the OAuth token
*
* @method getToken
* @public
* @return {string} token
*/
Usergrid.Client.prototype.getToken = function() {
return this.get("token");
};
Usergrid.Client.prototype.setObject = function(key, value) {
if (value) {
value = JSON.stringify(value);
}
this.set(key, value);
};
Usergrid.Client.prototype.set = function(key, value) {
var keyStore = "apigee_" + key;
this[key] = value;
if (typeof Storage !== "undefined") {
if (value) {
localStorage.setItem(keyStore, value);
} else {
localStorage.removeItem(keyStore);
}
}
};
Usergrid.Client.prototype.getObject = function(key) {
return JSON.parse(this.get(key));
};
Usergrid.Client.prototype.get = function(key) {
var keyStore = "apigee_" + key;
if (this[key]) {
return this[key];
} else if (typeof Storage !== "undefined") {
return localStorage.getItem(keyStore);
}
return null;
};
/*
* A public facing helper method for signing up users
*
* @method signup
* @public
* @params {string} username
* @params {string} password
* @params {string} email
* @params {string} name
* @param {function} callback
* @return {callback} callback(err, data)
*/
Usergrid.Client.prototype.signup = function(username, password, email, name, callback) {
var self = this;
var options = {
type: "users",
username: username,
password: password,
email: email,
name: name
};
this.createEntity(options, callback);
};
/*
*
* A public method to log in an app user - stores the token for later use
*
* @method login
* @public
* @params {string} username
* @params {string} password
* @param {function} callback
* @return {callback} callback(err, data)
*/
Usergrid.Client.prototype.login = function(username, password, callback) {
var self = this;
var options = {
method: "POST",
endpoint: "token",
body: {
username: username,
password: password,
grant_type: "password"
}
};
this.request(options, function(err, data) {
var user = {};
if (err && self.logging) {
console.log("error trying to log user in");
} else {
options = {
client: self,
data: data.user
};
user = new Usergrid.Entity(options);
self.setToken(data.access_token);
}
if (typeof callback === "function") {
callback(err, data, user);
}
});
};
Usergrid.Client.prototype.reAuthenticateLite = function(callback) {
var self = this;
var options = {
method: "GET",
endpoint: "management/me",
mQuery: true
};
this.request(options, function(err, response) {
if (err && self.logging) {
console.log("error trying to re-authenticate user");
} else {
//save the re-authed token and current email/username
self.setToken(response.access_token);
}
if (typeof callback === "function") {
callback(err);
}
});
};
Usergrid.Client.prototype.reAuthenticate = function(email, callback) {
var self = this;
var options = {
method: "GET",
endpoint: "management/users/" + email,
mQuery: true
};
this.request(options, function(err, response) {
var organizations = {};
var applications = {};
var user = {};
var data;
if (err && self.logging) {
console.log("error trying to full authenticate user");
} else {
data = response.data;
self.setToken(data.token);
self.set("email", data.email);
//delete next block and corresponding function when iframes are refactored
localStorage.setItem("accessToken", data.token);
localStorage.setItem("userUUID", data.uuid);
localStorage.setItem("userEmail", data.email);
//end delete block
var userData = {
username: data.username,
email: data.email,
name: data.name,
uuid: data.uuid
};
options = {
client: self,
data: userData
};
user = new Usergrid.Entity(options);
organizations = data.organizations;
var org = "";
try {
//if we have an org stored, then use that one. Otherwise, use the first one.
var existingOrg = self.get("orgName");
org = organizations[existingOrg] ? organizations[existingOrg] : organizations[Object.keys(organizations)[0]];
self.set("orgName", org.name);
} catch (e) {
err = true;
if (self.logging) {
console.log("error selecting org");
}
}
//should always be an org
applications = self.parseApplicationsArray(org);
self.selectFirstApp(applications);
self.setObject("organizations", organizations);
self.setObject("applications", applications);
}
if (typeof callback === "function") {
callback(err, data, user, organizations, applications);
}
});
};
/*
* A public method to log in an app user with facebook - stores the token for later use
*
* @method loginFacebook
* @public
* @params {string} username
* @params {string} password
* @param {function} callback
* @return {callback} callback(err, data)
*/
Usergrid.Client.prototype.loginFacebook = function(facebookToken, callback) {
var self = this;
var options = {
method: "GET",
endpoint: "auth/facebook",
qs: {
fb_access_token: facebookToken
}
};
this.request(options, function(err, data) {
var user = {};
if (err && self.logging) {
console.log("error trying to log user in");
} else {
var options = {
client: self,
data: data.user
};
user = new Usergrid.Entity(options);
self.setToken(data.access_token);
}
if (typeof callback === "function") {
callback(err, data, user);
}
});
};
/*
* A public method to get the currently logged in user entity
*
* @method getLoggedInUser
* @public
* @param {function} callback
* @return {callback} callback(err, data)
*/
Usergrid.Client.prototype.getLoggedInUser = function(callback) {
if (!this.getToken()) {
callback(true, null, null);
} else {
var self = this;
var options = {
method: "GET",
endpoint: "users/me"
};
this.request(options, function(err, data) {
if (err) {
if (self.logging) {
console.log("error trying to log user in");
}
if (typeof callback === "function") {
callback(err, data, null);
}
} else {
var options = {
client: self,
data: data.entities[0]
};
var user = new Usergrid.Entity(options);
if (typeof callback === "function") {
callback(err, data, user);
}
}
});
}
};
/*
* A public method to test if a user is logged in - does not guarantee that the token is still valid,
* but rather that one exists
*
* @method isLoggedIn
* @public
* @return {boolean} Returns true the user is logged in (has token and uuid), false if not
*/
Usergrid.Client.prototype.isLoggedIn = function() {
if (this.getToken() && this.getToken() != "null") {
return true;
}
return false;
};
/*
* A public method to log out an app user - clears all user fields from client
*
* @method logout
* @public
* @return none
*/
Usergrid.Client.prototype.logout = function() {
this.setToken(null);
};
/*
* A private method to build the curl call to display on the command line
*
* @method buildCurlCall
* @private
* @param {object} options
* @return {string} curl
*/
Usergrid.Client.prototype.buildCurlCall = function(options) {
var curl = "curl";
var method = (options.method || "GET").toUpperCase();
var body = options.body || {};
var uri = options.uri;
//curl - add the method to the command (no need to add anything for GET)
if (method === "POST") {
curl += " -X POST";
} else if (method === "PUT") {
curl += " -X PUT";
} else if (method === "DELETE") {
curl += " -X DELETE";
} else {
curl += " -X GET";
}
//curl - append the path
curl += " " + uri;
//curl - add the body
if ("undefined" !== typeof window) {
body = JSON.stringify(body);
}
//only in node module
if (body !== '"{}"' && method !== "GET" && method !== "DELETE") {
//curl - add in the json obj
curl += " -d '" + body + "'";
}
//log the curl command to the console
console.log(curl);
return curl;
};
Usergrid.Client.prototype.getDisplayImage = function(email, picture, size) {
try {
if (picture) {
return picture;
}
var size = size || 50;
if (email.length) {
return "https://secure.gravatar.com/avatar/" + MD5(email) + "?s=" + size + encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png");
} else {
return "https://apigee.com/usergrid/images/user_profile.png";
}
} catch (e) {
return "https://apigee.com/usergrid/images/user_profile.png";
}
};
/*
* A class to Model a Usergrid Entity.
* Set the type and uuid of entity in the 'data' json object
*
* @constructor
* @param {object} options {client:client, data:{'type':'collection_type', uuid:'uuid', 'key':'value'}}
*/
Usergrid.Entity = function(options) {
if (options) {
this._data = options.data || {};
this._client = options.client || {};
}
};
/*
* returns a serialized version of the entity object
*
* Note: use the client.restoreEntity() function to restore
*
* @method serialize
* @return {string} data
*/
Usergrid.Entity.prototype.serialize = function() {
return JSON.stringify(this._data);
};
/*
* gets a specific field or the entire data object. If null or no argument
* passed, will return all data, else, will return a specific field
*
* @method get
* @param {string} field
* @return {string} || {object} data
*/
Usergrid.Entity.prototype.get = function(field) {
if (field) {