forked from MrSwitch/hello.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhello.all.js
5395 lines (4445 loc) · 125 KB
/
hello.all.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
/**
* @hello.js
*
* HelloJS is a client side Javascript SDK for making OAuth2 logins and subsequent REST calls.
*
* @author Andrew Dodson
* @company Knarly
*
* @copyright Andrew Dodson, 2012 - 2013
* @license MIT: You are free to use and modify this code for any use, on the condition that this copyright notice remains.
*/
// Can't use strict with arguments.callee
//"use strict";
//
// Setup
// Initiates the construction of the library
var hello = function(name){
return hello.use(name);
};
hello.utils = {
//
// Extend the first object with the properties and methods of the second
extend : function(r /*, a[, b[, ...]] */){
// Get the arguments as an array but ommit the initial item
var args = Array.prototype.slice.call(arguments,1);
for(var i=0;i<args.length;i++){
var a = args[i];
if( r instanceof Object && a instanceof Object && r !== a ){
for(var x in a){
//if(a.hasOwnProperty(x)){
r[x] = hello.utils.extend( r[x], a[x] );
//}
}
}
else{
r = a;
}
}
return r;
}
};
/////////////////////////////////////////////////
// Core library
// This contains the following methods
// ----------------------------------------------
// init
// login
// logout
// getAuthRequest
/////////////////////////////////////////////////
hello.utils.extend( hello, {
//
// Options
settings : {
//
// OAuth 2 authentication defaults
redirect_uri : window.location.href.split('#')[0],
response_type : 'token',
display : 'popup',
state : '',
//
// OAuth 1 shim
// The path to the OAuth1 server for signing user requests
// Wanna recreate your own? checkout https://github.com/MrSwitch/node-oauth-shim
oauth_proxy : 'https://auth-server.herokuapp.com/proxy',
//
// API Timeout, milliseconds
timeout : 20000,
//
// Default Network
default_service : null,
//
// Force signin
// When hello.login is fired, ignore current session expiry and continue with login
force : true
},
//
// Service
// Get/Set the default service
//
service : function(service){
//this.utils.warn("`hello.service` is deprecated");
if(typeof (service) !== 'undefined' ){
return this.utils.store( 'sync_service', service );
}
return this.utils.store( 'sync_service' );
},
//
// Services
// Collection of objects which define services configurations
services : {},
//
// Use
// Define a new instance of the Hello library with a default service
//
use : function(service){
// Create self, which inherits from its parent
var self = this.utils.objectCreate(this);
// Inherit the prototype from its parent
self.settings = this.utils.objectCreate(this.settings);
// Define the default service
if(service){
self.settings.default_service = service;
}
// Create an instance of Events
self.utils.Event.call(self);
return self;
},
//
// init
// Define the clientId's for the endpoint services
// @param object o, contains a key value pair, service => clientId
// @param object opts, contains a key value pair of options used for defining the authentication defaults
// @param number timeout, timeout in seconds
//
init : function(services,options){
var utils = this.utils;
if(!services){
return this.services;
}
// Define provider credentials
// Reformat the ID field
for( var x in services ){if(services.hasOwnProperty(x)){
if( typeof(services[x]) !== 'object' ){
services[x] = {id : services[x]};
}
}}
//
// merge services if there already exists some
utils.extend(this.services, services);
//
// Format the incoming
for( x in this.services ){if(this.services.hasOwnProperty(x)){
this.services[x].scope = this.services[x].scope || {};
}}
//
// Update the default settings with this one.
if(options){
utils.extend(this.settings, options);
// Do this immediatly incase the browser changes the current path.
if("redirect_uri" in options){
this.settings.redirect_uri = utils.url(options.redirect_uri).href;
}
}
return this;
},
//
// Login
// Using the endpoint
// @param network stringify name to connect to
// @param options object (optional) {display mode, is either none|popup(default)|page, scope: email,birthday,publish, .. }
// @param callback function (optional) fired on signin
//
login : function(){
// Create self
// An object which inherits its parent as the prototype.
// And constructs a new event chain.
var self = this.use(),
utils = self.utils;
// Get parameters
var p = utils.args({network:'s', options:'o', callback:'f'}, arguments);
// Apply the args
self.args = p;
// Local vars
var url;
// merge/override options with app defaults
var opts = p.options = utils.merge(self.settings, p.options || {} );
// Network
p.network = self.settings.default_service = p.network || self.settings.default_service;
//
// Bind listener
self.on('complete', p.callback);
// Is our service valid?
if( typeof(p.network) !== 'string' || !( p.network in self.services ) ){
// trigger the default login.
// ahh we dont have one.
self.emitAfter('error complete', {error:{
code : 'invalid_network',
message : 'The provided network was not recognized'
}});
return self;
}
//
var provider = self.services[p.network];
//
// Callback
// Save the callback until state comes back.
//
var responded = false;
//
// Create a global listener to capture events triggered out of scope
var callback_id = utils.globalEvent(function(str){
// Save this locally
// responseHandler returns a string, lets save this locally
var obj;
if ( str ){
obj = JSON.parse(str);
}
else {
obj = {
error : {
code : 'cancelled',
message : 'The authentication was not completed'
}
};
}
//
// Cancel the popup close listener
responded = true;
//
// Handle these response using the local
// Trigger on the parent
if(!obj.error){
// Save on the parent window the new credentials
// This fixes an IE10 bug i think... atleast it does for me.
utils.store(obj.network,obj);
// Trigger local complete events
self.emit("complete success login auth.login auth", {
network : obj.network,
authResponse : obj
});
}
else{
// Trigger local complete events
self.emit("complete error failed auth.failed", {
error : obj.error
});
}
});
//
// REDIRECT_URI
// Is the redirect_uri root?
//
var redirect_uri = utils.url(opts.redirect_uri).href;
//
// Response Type
//
var response_type = provider.oauth.response_type || opts.response_type;
// Fallback to token if the module hasn't defined a grant url
if( response_type === 'code' && !provider.oauth.grant ){
response_type = 'token';
}
//
// QUERY STRING
// querystring parameters, we may pass our own arguments to form the querystring
//
p.qs = {
client_id : provider.id,
response_type : response_type,
redirect_uri : redirect_uri,
display : opts.display,
scope : 'basic',
state : {
client_id : provider.id,
network : p.network,
display : opts.display,
callback : callback_id,
state : opts.state,
redirect_uri: redirect_uri,
}
};
//
// SESSION
// Get current session for merging scopes, and for quick auth response
var session = utils.store(p.network);
//
// SCOPES
// Authentication permisions
//
// convert any array, or falsy value to a string.
var scope = (opts.scope||'').toString();
scope = (scope ? scope + ',' : '') + p.qs.scope;
// Append scopes from a previous session
// This helps keep app credentials constant,
// Avoiding having to keep tabs on what scopes are authorized
if(session && "scope" in session && session.scope instanceof String){
scope += ","+ session.scope;
}
// Save in the State
// Convert to a string because IE, has a problem moving Arrays between windows
p.qs.state.scope = utils.unique( scope.split(/[,\s]+/) ).join(',');
// Map replace each scope with the providers default scopes
p.qs.scope = scope.replace(/[^,\s]+/ig, function(m){
// Does this have a mapping?
if (m in provider.scope){
return provider.scope[m];
}else{
// Loop through all services and determine whether the scope is generic
for(var x in self.services){
var _scopes = self.services[x].scope;
if(_scopes && m in _scopes){
// found an instance of this scope, so lets not assume its special
return '';
}
}
// this is a unique scope to this service so lets in it.
return m;
}
}).replace(/[,\s]+/ig, ',');
// remove duplication and empty spaces
p.qs.scope = utils.unique(p.qs.scope.split(/,+/)).join( provider.scope_delim || ',');
//
// FORCE
// Is the user already signed in with the appropriate scopes, valid access_token?
//
if(opts.force===false){
if( session && "access_token" in session && session.access_token && "expires" in session && session.expires > ((new Date()).getTime()/1e3) ){
// What is different about the scopes in the session vs the scopes in the new login?
var diff = utils.diff( session.scope || [], p.qs.state.scope || [] );
if(diff.length===0){
// Ok trigger the callback
self.emitAfter("complete success login", {
unchanged : true,
network : p.network,
authResponse : session
});
// Nothing has changed
return self;
}
}
}
// Bespoke
// Override login querystrings from auth_options
if("login" in provider && typeof(provider.login) === 'function'){
// Format the paramaters according to the providers formatting function
provider.login(p);
}
// Add OAuth to state
// Where the service is going to take advantage of the oauth_proxy
if( response_type !== "token" ||
parseInt(provider.oauth.version,10) < 2 ||
( opts.display === 'none' && provider.oauth.grant && session && session.refresh_token ) ){
// Add the oauth endpoints
p.qs.state.oauth = provider.oauth;
// Add the proxy url
p.qs.state.oauth_proxy = opts.oauth_proxy;
}
// Convert state to a string
p.qs.state = JSON.stringify(p.qs.state);
//
// URL
//
if( parseInt(provider.oauth.version,10) === 1 ){
// Turn the request to the OAuth Proxy for 3-legged auth
url = utils.qs( opts.oauth_proxy, p.qs );
}
// Refresh token
else if( opts.display === 'none' && provider.oauth.grant && session && session.refresh_token ){
// Add the refresh_token to the request
p.qs.refresh_token = session.refresh_token;
// Define the request path
url = utils.qs( opts.oauth_proxy, p.qs );
}
//
else{
url = utils.qs( provider.oauth.auth, p.qs );
}
self.emit("notice", "Authorization URL " + url );
//
// Execute
// Trigger how we want self displayed
// Calling Quietly?
//
if( opts.display === 'none' ){
// signin in the background, iframe
utils.iframe(url);
}
// Triggering popup?
else if( opts.display === 'popup'){
var popup = utils.popup( url, redirect_uri, opts.window_width || 500, opts.window_height || 550 );
var timer = setInterval(function(){
if(!popup||popup.closed){
clearInterval(timer);
if(!responded){
var error = {
code:"cancelled",
message:"Login has been cancelled"
};
if(!popup){
error = {
code:'blocked',
message :'Popup was blocked'
};
}
self.emit("complete failed error", {error:error, network:p.network });
}
}
}, 100);
}
else {
window.location = url;
}
return self;
},
//
// Logout
// Remove any data associated with a given service
// @param string name of the service
// @param function callback
//
logout : function(){
// Create self
// An object which inherits its parent as the prototype.
// And constructs a new event chain.
var self = this.use();
var utils = self.utils;
var p = utils.args({name:'s', options: 'o', callback:"f" }, arguments);
p.options = p.options || {};
// Add callback to events
self.on('complete', p.callback);
// Netowrk
p.name = p.name || self.settings.default_service;
if( p.name && !( p.name in self.services ) ){
self.emitAfter("complete error", {error:{
code : 'invalid_network',
message : 'The network was unrecognized'
}});
}
else if(p.name && utils.store(p.name)){
// Define the callback
var callback = function(opts){
// Remove from the store
self.utils.store(p.name,'');
// Emit events by default
self.emitAfter("complete logout success auth.logout auth", hello.utils.merge( {network:p.name}, opts || {} ) );
};
//
// Run an async operation to remove the users session
//
var _opts = {};
if(p.options.force){
var logout = self.services[p.name].logout;
if( logout ){
// Convert logout to URL string,
// If no string is returned, then this function will handle the logout async style
if(typeof(logout) === 'function' ){
logout = logout(callback);
}
// If logout is a string then assume URL and open in iframe.
if(typeof(logout)==='string'){
utils.iframe( logout );
_opts.force = null;
_opts.message = "Logout success on providers site was indeterminate";
}
else if(logout === undefined){
// the callback function will handle the response.
return self;
}
}
}
//
// Remove local credentials
callback(_opts);
}
else if(!p.name){
for(var x in self.services){if(self.services.hasOwnProperty(x)){
self.logout(x);
}}
// remove the default
self.service(false);
// trigger callback
}
else{
self.emitAfter("complete error", {error:{
code : 'invalid_session',
message : 'There was no session to remove'
}});
}
return self;
},
//
// getAuthResponse
// Returns all the sessions that are subscribed too
// @param string optional, name of the service to get information about.
//
getAuthResponse : function(service){
// If the service doesn't exist
service = service || this.settings.default_service;
if( !service || !( service in this.services ) ){
this.emit("complete error", {error:{
code : 'invalid_network',
message : 'The network was unrecognized'
}});
return null;
}
return this.utils.store(service) || null;
},
//
// Events
// Define placeholder for the events
events : {}
});
///////////////////////////////////
// Core Utilities
///////////////////////////////////
hello.utils.extend( hello.utils, {
// Append the querystring to a url
// @param string url
// @param object parameters
qs : function(url, params){
if(params){
var reg;
for(var x in params){
if(url.indexOf(x)>-1){
var str = "[\\?\\&]"+x+"=[^\\&]*";
reg = new RegExp(str);
url = url.replace(reg,'');
}
}
}
return url + (!this.isEmpty(params) ? ( url.indexOf('?') > -1 ? "&" : "?" ) + this.param(params) : '');
},
//
// Param
// Explode/Encode the parameters of an URL string/object
// @param string s, String to decode
//
param : function(s){
var b,
a = {},
m;
if(typeof(s)==='string'){
m = s.replace(/^[\#\?]/,'').match(/([^=\/\&]+)=([^\&]+)/g);
if(m){
for(var i=0;i<m.length;i++){
b = m[i].match(/([^=]+)=(.*)/);
a[b[1]] = decodeURIComponent( b[2] );
}
}
return a;
}
else {
var o = s;
a = [];
for( var x in o ){if(o.hasOwnProperty(x)){
if( o.hasOwnProperty(x) ){
a.push( [x, o[x] === '?' ? '?' : encodeURIComponent(o[x]) ].join('=') );
}
}}
return a.join('&');
}
},
//
// Local Storage Facade
store : (function(localStorage){
//
// LocalStorage
var a = [localStorage,window.sessionStorage],
i=0;
// Set LocalStorage
localStorage = a[i++];
while(localStorage){
try{
localStorage.setItem(i,i);
localStorage.removeItem(i);
break;
}
catch(e){
localStorage = a[i++];
}
}
if(!localStorage){
localStorage = {
getItem : function(prop){
prop = prop +'=';
var m = document.cookie.split(";");
for(var i=0;i<m.length;i++){
var _m = m[i].replace(/(^\s+|\s+$)/,'');
if(_m && _m.indexOf(prop)===0){
return _m.substr(prop.length);
}
}
return null;
},
setItem : function(prop, value){
document.cookie = prop + '=' + value;
}
};
}
function get(){
var json = {};
try{
json = JSON.parse(localStorage.getItem('hello')) || {};
}catch(e){}
return json;
}
function set(json){
localStorage.setItem('hello', JSON.stringify(json));
}
// Does this browser support localStorage?
return function (name,value,days) {
// Local storage
var json = get();
if(name && value === undefined){
return json[name] || null;
}
else if(name && value === null){
try{
delete json[name];
}
catch(e){
json[name]=null;
}
}
else if(name){
json[name] = value;
}
else {
return json;
}
set(json);
return json || null;
};
})(window.localStorage),
//
// Create and Append new Dom elements
// @param node string
// @param attr object literal
// @param dom/string
//
append : function(node,attr,target){
var n = typeof(node)==='string' ? document.createElement(node) : node;
if(typeof(attr)==='object' ){
if( "tagName" in attr ){
target = attr;
}
else{
for(var x in attr){if(attr.hasOwnProperty(x)){
if(typeof(attr[x])==='object'){
for(var y in attr[x]){if(attr[x].hasOwnProperty(y)){
n[x][y] = attr[x][y];
}}
}
else if(x==="html"){
n.innerHTML = attr[x];
}
// IE doesn't like us setting methods with setAttribute
else if(!/^on/.test(x)){
n.setAttribute( x, attr[x]);
}
else{
n[x] = attr[x];
}
}}
}
}
if(target==='body'){
(function self(){
if(document.body){
document.body.appendChild(n);
}
else{
setTimeout( self, 16 );
}
})();
}
else if(typeof(target)==='object'){
target.appendChild(n);
}
else if(typeof(target)==='string'){
document.getElementsByTagName(target)[0].appendChild(n);
}
return n;
},
//
// create IFRAME
// An easy way to create a hidden iframe
// @param string src
//
iframe : function(src){
this.append('iframe', { src : src, style : {position:'absolute',left:"-1000px",bottom:0,height:'1px',width:'1px'} }, 'body');
},
//
// merge
// recursive merge two objects into one, second parameter overides the first
// @param a array
//
merge : function(/*a,b,c,..n*/){
var args = Array.prototype.slice.call(arguments);
args.unshift({});
return this.extend.apply(null, args);
},
//
// Args utility
// Makes it easier to assign parameters, where some are optional
// @param o object
// @param a arguments
//
args : function(o,args){
var p = {},
i = 0,
t = null,
x = null;
// define x
// x is the first key in the list of object parameters
for(x in o){if(o.hasOwnProperty(x)){
break;
}}
// Passing in hash object of arguments?
// Where the first argument can't be an object
if((args.length===1)&&(typeof(args[0])==='object')&&o[x]!='o!'){
// Could this object still belong to a property?
// Check the object keys if they match any of the property keys
for(x in args[0]){if(o.hasOwnProperty(x)){
// Does this key exist in the property list?
if( x in o ){
// Yes this key does exist so its most likely this function has been invoked with an object parameter
// return first argument as the hash of all arguments
return args[0];
}
}}
}
// else loop through and account for the missing ones.
for(x in o){if(o.hasOwnProperty(x)){
t = typeof( args[i] );
if( ( typeof( o[x] ) === 'function' && o[x].test(args[i]) ) || ( typeof( o[x] ) === 'string' && (
( o[x].indexOf('s')>-1 && t === 'string' ) ||
( o[x].indexOf('o')>-1 && t === 'object' ) ||
( o[x].indexOf('i')>-1 && t === 'number' ) ||
( o[x].indexOf('a')>-1 && t === 'object' ) ||
( o[x].indexOf('f')>-1 && t === 'function' )
) )
){
p[x] = args[i++];
}
else if( typeof( o[x] ) === 'string' && o[x].indexOf('!')>-1 ){
// ("Whoops! " + x + " not defined");
return false;
}
}}
return p;
},
//
// URL
// Returns a URL instance
//
url : function(path){
// If the path is empty
if(!path){
return window.location;
}
// Chrome and FireFox support new URL() to extract URL objects
else if( window.URL && URL instanceof Function && URL.length !== 0){
return new URL(path, window.location);
}
else{
// ugly shim, it works!
var a = document.createElement('a');
a.href = path;
return a;
}
},
//
// diff
diff : function(a,b){
var r = [];
for(var i=0;i<b.length;i++){
if(this.indexOf(a,b[i])===-1){
r.push(b[i]);
}
}
return r;
},
//
// indexOf
// IE hack Array.indexOf doesn't exist prior to IE9
indexOf : function(a,s){
// Do we need the hack?
if(a.indexOf){
return a.indexOf(s);
}
for(var j=0;j<a.length;j++){
if(a[j]===s){
return j;
}
}
return -1;
},
//
// unique
// remove duplicate and null values from an array
// @param a array
//
unique : function(a){
if(typeof(a)!=='object'){ return []; }
var r = [];
for(var i=0;i<a.length;i++){
if(!a[i]||a[i].length===0||this.indexOf(r, a[i])!==-1){
continue;
}
else{
r.push(a[i]);
}
}
return r;
},
// isEmpty
isEmpty : function (obj){
// scalar?
if(!obj){
return true;
}