This repository has been archived by the owner on Feb 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathgeotrigger.js
444 lines (370 loc) · 12.5 KB
/
geotrigger.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
(function (root, factory) {
// Node.
if(typeof module === 'object' && typeof module.exports === 'object') {
XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
exports = module.exports = factory();
}
// Browser Global.
if(typeof window === "object") {
root.Geotrigger = factory();
}
}(this, function() {
var geotriggersUrl = "https://geotrigger.arcgis.com/";
var tokenUrl = "https://www.arcgis.com/sharing/oauth2/token";
var registerDeviceUrl = "https://www.arcgis.com/sharing/oauth2/registerDevice";
var exports = {};
var CORS = true;
if (typeof window === "object") {
CORS = !!(window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest());
}
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
FNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof FNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments)));
};
FNOP.prototype = this.prototype;
fBound.prototype = new FNOP();
return fBound;
};
}
function Session(options){
this._queue = [];
this._requestQueue = [];
this._events = {};
var defaults = {
preferLocalStorage: true,
persistSession: (typeof module !== 'undefined' && module.exports) ? false : true,
geotriggersUrl: geotriggersUrl,
tokenUrl: tokenUrl,
registerDeviceUrl: registerDeviceUrl,
automaticRegistation: true,
proxy: false,
ignoreCORS: false
};
// set application id
if(!options || !options.clientId) {
throw new Error("Geotrigger.Session requires an `clientId` or a `session` parameter.");
}
if(!options.proxy && !CORS) {
throw new Error("This browser does not support CORS and a proxy has not been set.");
}
// merge defaults and options into `this`
util.merge(this, util.merge(defaults, options));
this.authenticatedAs = (this.clientId && this.clientSecret) ? "application" : "device";
this.key = "geotriggers_" + this.authenticatedAs + "_" + this.clientId;
//restore a stored session if we have one
if(this.persistSession) {
if(this.preferLocalStorage && hasLocalStorage){
util.merge(this, localStorage.get(this.key));
} else if (hasCookies) {
util.merge(this, cookie.get(this.key));
}
}
// if there is an access token and it is after when the token expires or there is no access token
if((this.token && (Date.now() > new Date(this.expiresOn).getTime())) || !this.token){
// remove token to prevent queued functions from firing
delete this.token;
this.refresh();
}
// if token exists, is not expired, and session has been restored
else if (this.persistSession) {
this.emit("authentication:restored");
}
}
Session.prototype.authenticated = function(){
return !!this.token;
};
Session.prototype.refresh = function(){
if(this.refreshing){
return;
}
this.refreshing = true;
var url = this.tokenUrl;
var params = {
client_id: this.clientId,
f: "json"
};
if(this.clientSecret){
params.client_secret = this.clientSecret;
params.grant_type = "client_credentials";
} else if (this.refreshToken){
params.refresh_token = this.refreshToken;
params.grant_type = "refresh_token";
} else if (this.automaticRegistation) {
url = this.registerDeviceUrl;
}
this.request(url, params, function(error, response, xhr){
this.refreshing = false;
if (error) {
this.emit("authentication:error", error, response, xhr);
return;
}
this.expiresOn = new Date(new Date().getTime() + ((response.expires_in-(60*5)) *1000));
if(response.deviceToken){
this.refreshToken = response.deviceToken.refresh_token;
this.token = response.deviceToken.access_token;
this.deviceId = response.device.deviceId;
} else {
this.token = response.access_token;
}
if(this.persistSession){
this.persist();
}
while (this._queue.length) {
this._queue.shift().apply(this);
}
this.emit("authentication:success");
while (this._requestQueue.length) {
this.request.apply(this, this._requestQueue.shift());
}
}.bind(this));
};
Session.prototype.toJSON = function(){
var obj = {};
for (var key in this) {
if (this.hasOwnProperty(key) && this[key] && !key.match(/^_.+/)) {
obj[key] = this[key];
}
}
return obj;
};
Session.prototype.on = function(type, listener){
var types = type.split(' ');
for (var i=0; i < types.length; i++) {
if (typeof this._events[types[i]] === "undefined") {
this._events[types[i]] = [];
}
this._events[types[i]].push(listener);
}
};
Session.prototype.emit = function(type){
var args = [].splice.call(arguments,1);
if (this._events[type] instanceof Array){
var listeners = this._events[type];
for (var i=0, len=listeners.length; i < len; i++){
listeners[i].apply(this, args);
}
}
};
Session.prototype.off = function(type, listener){
if (this._events[type] instanceof Array){
var listeners = this._events[type];
for (var i=0, len=listeners.length; i < len; i++){
if (listeners[i] === listener){
listeners.splice(i, 1);
break;
}
}
}
};
Session.prototype.queue = function(fn) {
if (!this.token) {
this._queue.push(fn);
this.refresh();
return;
}
fn.apply(this);
};
Session.prototype.request = function(method, params, callback){
var args = Array.prototype.slice.apply(arguments);
var json;
var error;
var response;
var httpRequest;
// assume this is a request to geotriggers if it doesn't start with (http|https)://
var geotriggersRequest = !method.match(/^https?:\/\//);
// create the url for the request
var url = (geotriggersRequest) ? this.geotriggersUrl + method : method;
// use a proxy if CORS support isn't present, or developer wants to force it (to do something like pass through credentials)
if (this.proxy && (this.ignoreCORS || !CORS)) {
url = this.proxy + url;
}
if(typeof params === "function"){
callback = params;
params = {};
}
if(geotriggersRequest && !this.token){
this._requestQueue.push(args);
this.refresh();
return;
}
// callback for handling a successful request
var handleSuccessfulResponse = function(){
try {
json = JSON.parse(httpRequest.responseText);
response = (json.error) ? null : json;
error = (json.error) ? json.error : null;
} catch (e){
response = null;
error = {
type: "parse_error",
message: "could not parse response as JSON"
};
}
// did our token expire?
// if it didn't resolve or reject the callback
// if it did refresh the auth and run the request again
if(error && error.type === "invalidHeader" && error.headers.Authorization){
this._requestQueue.push(args);
this.refresh();
} else {
if (!error){
callback(null, response, httpRequest);
} else if (error){
callback(error, null, httpRequest);
} else {
var errorMessage = {
type: "unexpected_response",
message: "the api returned a non JSON or unexpected data"
};
callback(errorMessage, null, httpRequest);
}
}
}.bind(this);
// callback for handling an http error
var handleErrorResponse = function(){
var error = {
type: "http_error"
};
try {
error.message = JSON.parse(httpRequest.responseText);
} catch (e){
error.message = "http error and could not parse response as JSON";
}
callback(error, null, httpRequest);
}.bind(this);
// callback for handling state change
var handleStateChange = function(){
if(httpRequest.readyState === 4 && httpRequest.status < 400){
handleSuccessfulResponse();
} else if(httpRequest.readyState === 4 && httpRequest.status >= 400) {
handleErrorResponse();
}
}.bind(this);
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = handleStateChange;
var body;
if(geotriggersRequest){
body = JSON.stringify(params);
httpRequest.open("POST", url + "?token=" + this.token);
httpRequest.setRequestHeader('X-GT-Client-Name', 'geotrigger-js');
httpRequest.setRequestHeader('X-GT-Client-Version', '1.0.0');
httpRequest.setRequestHeader('Content-Type', 'application/json');
} else {
body = util.serialize(params);
httpRequest.open("POST", url);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
httpRequest.send(body);
};
Session.prototype.persist = function() {
var value = {};
if(this.clientId){ value.clientId = this.clientId; }
if(this.clientSecret){ value.clientSecret = this.clientSecret; }
if(this.token){ value.token = this.token; }
if(this.refreshToken){ value.refreshToken = this.refreshToken; }
if(this.deviceId){ value.deviceId = this.deviceId; }
if(this.preferLocalStorage && hasLocalStorage){
localStorage.set(this.key, value);
} else if (hasCookies) {
cookie.set(this.key, value);
}
};
Session.prototype.destroy = function() {
if(this.preferLocalStorage && hasLocalStorage) {
localStorage.erase(this.key);
} else if (hasCookies) {
cookie.erase(this.key);
}
};
exports.Session = Session;
/*
General Purpose Utilities
-----------------------------------
*/
var util = {
// Merge Object 1 and Object 2.
// Properties from Object 2 will override properties in Object 1.
// Returns Object 1
merge: function(target, obj){
for (var attr in obj) {
if(obj.hasOwnProperty(attr)){
target[attr] = obj[attr];
}
}
return target;
},
isObject: function(thing){
return Object.prototype.toString.call(thing) === '[object Object]';
},
serialize: function(obj, prefix) {
var enc = encodeURIComponent;
// make an array to hold each peice
var str = [];
// for every key in our object
for(var p in obj) {
if(obj.hasOwnProperty(p)){
var e;
var k = (prefix) ? prefix + "[" + p + "]" : p, v = obj[p];
e = (util.isObject(v)) ? util.serialize(v, k) : enc(k) + "=" + enc(v);
str.push(e);
}
}
// join with ampersands
return str.join("&");
}
};
/*
Utilities for manipulating sessions
-----------------------------------
*/
var hasLocalStorage = (typeof window === "object" && typeof window.localStorage === "object") ? true : false;
var hasCookies = (typeof document === "object" && typeof document.cookie === "string") ? true : false;
var localStorage = {
set:function(key, value){
window.localStorage.setItem(key, JSON.stringify(value));
},
get: function(key){
return JSON.parse(window.localStorage.getItem(key));
},
erase: function(key){
window.localStorage.removeItem(key);
}
};
var cookie = {
get: function(key) {
// Still not sure that "[a-zA-Z0-9.()=|%/_]+($|;)" match *all* allowed characters in cookies
var tmp = document.cookie.match((new RegExp(key +'=[a-zA-Z0-9.()=|%/_]+($|;)','g')));
if(!tmp || !tmp[0]){
return null;
} else {
return JSON.parse(tmp[0].substring(key.length+1,tmp[0].length).replace(';','')) || null;
}
},
set: function(key, value, secure) {
var cookie = [
key+'='+JSON.stringify(value),
'path=/',
'domain='+window.location.host
];
var expiration_date = new Date();
expiration_date.setFullYear(expiration_date.getFullYear() + 1);
cookie.push(expiration_date.toGMTString());
if (secure){
cookie.push('secure');
}
return document.cookie = cookie.join('; ');
},
erase: function(key) {
document.cookie = key + "; " + new Date(0).toUTCString();
}
};
return exports;
}));