This repository has been archived by the owner on Dec 5, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
simple-auth-cookie-store.js
448 lines (381 loc) · 13.8 KB
/
simple-auth-cookie-store.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
(function(global) {
Ember.libraries.register('Ember Simple Auth Cookie Store', '0.8.0');
var define, requireModule;
(function() {
var registry = {}, seen = {};
define = function(name, deps, callback) {
registry[name] = { deps: deps, callback: callback };
};
requireModule = function(name) {
if (seen.hasOwnProperty(name)) { return seen[name]; }
seen[name] = {};
if (!registry[name]) {
throw new Error("Could not find module " + name);
}
var mod = registry[name],
deps = mod.deps,
callback = mod.callback,
reified = [],
exports;
for (var i=0, l=deps.length; i<l; i++) {
if (deps[i] === 'exports') {
reified.push(exports = {});
} else {
reified.push(requireModule(resolve(deps[i])));
}
}
var value = callback.apply(this, reified);
return seen[name] = exports || value;
function resolve(child) {
if (child.charAt(0) !== '.') { return child; }
var parts = child.split("/");
var parentBase = name.split("/").slice(0, -1);
for (var i=0, l=parts.length; i<l; i++) {
var part = parts[i];
if (part === '..') { parentBase.pop(); }
else if (part === '.') { continue; }
else { parentBase.push(part); }
}
return parentBase.join("/");
}
};
requireModule.registry = registry;
})();
define("simple-auth-cookie-store/configuration",
["simple-auth/utils/load-config","exports"],
function(__dependency1__, __exports__) {
"use strict";
var loadConfig = __dependency1__["default"];
var defaults = {
cookieName: 'ember_simple_auth:session',
cookieDomain: null,
cookieExpirationTime: null
};
/**
Ember Simple Auth Cookie Store's configuration object.
To change any of these values, set them on the application's environment
object:
```js
ENV['simple-auth-cookie-store'] = {
cookieName: 'my_app_auth_session'
}
```
@class CookieStore
@namespace SimpleAuth.Configuration
@module simple-auth/configuration
*/
__exports__["default"] = {
/**
The domain to use for the cookie, e.g., "example.com", ".example.com"
(includes all subdomains) or "subdomain.example.com". If not configured the
cookie domain defaults to the domain the session was authneticated on.
This value can be configured via
[`SimpleAuth.Configuration.CookieStore#cookieDomain`](#SimpleAuth-Configuration-CookieStore-cookieDomain).
@property cookieDomain
@type String
@default null
*/
cookieDomain: defaults.cookieDomain,
/**
The name of the cookie the store stores its data in.
@property cookieName
@readOnly
@static
@type String
@default 'ember_simple_auth:'
*/
cookieName: defaults.cookieName,
/**
The expiration time in seconds to use for the cookie. A value of `null`
will make the cookie a session cookie that expires when the browser is
closed.
@property cookieExpirationTime
@readOnly
@static
@type Integer
@default null
*/
cookieExpirationTime: defaults.cookieExpirationTime,
/**
@method load
@private
*/
load: loadConfig(defaults)
};
});
define("simple-auth-cookie-store/ember",
["./initializer"],
function(__dependency1__) {
"use strict";
var initializer = __dependency1__["default"];
Ember.onLoad('Ember.Application', function(Application) {
Application.initializer(initializer);
});
});
define("simple-auth-cookie-store/initializer",
["./configuration","simple-auth/utils/get-global-config","simple-auth-cookie-store/stores/cookie","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var Configuration = __dependency1__["default"];
var getGlobalConfig = __dependency2__["default"];
var Store = __dependency3__["default"];
__exports__["default"] = {
name: 'simple-auth-cookie-store',
before: 'simple-auth',
initialize: function(container, application) {
var config = getGlobalConfig('simple-auth-cookie-store');
Configuration.load(container, config);
application.register('simple-auth-session-store:cookie', Store);
}
};
});
define("simple-auth-cookie-store/stores/cookie",
["simple-auth/stores/base","simple-auth/utils/objects-are-equal","./../configuration","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var Base = __dependency1__["default"];
var objectsAreEqual = __dependency2__["default"];
var Configuration = __dependency3__["default"];
/**
Store that saves its data in a cookie.
__In order to keep multiple tabs/windows of an application in sync, this
store has to periodically (every 500ms) check the cookie__ for changes as
there are no events that notify of changes in cookies. The recommended
alternative is `Stores.LocalStorage` that also persistently stores data but
instead of cookies relies on the `localStorage` API and does not need to poll
for external changes.
By default the cookie store will use a session cookie that expires and is
deleted when the browser is closed. The cookie expiration period can be
configured via setting
[`Stores.Cooke#cookieExpirationTime`](#SimpleAuth-Stores-Cookie-cookieExpirationTime)
though. This can also be used to implement "remember me" functionality that
will either store the session persistently or in a session cookie depending
whether the user opted in or not:
```js
// app/controllers/login.js
export default Ember.Controller.extend({
rememberMe: false,
rememberMeChanged: function() {
this.get('session.store').cookieExpirationTime = this.get('rememberMe') ? (14 * 24 * 60 * 60) : null;
}.observes('rememberMe')
});
```
_The factory for this store is registered as
`'simple-auth-session-store:cookie'` in Ember's container._
@class Cookie
@namespace SimpleAuth.Stores
@module simple-auth-cookie-store/stores/cookie
@extends Stores.Base
*/
__exports__["default"] = Base.extend({
/**
The domain to use for the cookie, e.g., "example.com", ".example.com"
(includes all subdomains) or "subdomain.example.com". If not configured the
cookie domain defaults to the domain the session was authneticated on.
This value can be configured via
[`SimpleAuth.Configuration.CookieStore#cookieDomain`](#SimpleAuth-Configuration-CookieStore-cookieDomain).
@property cookieDomain
@type String
@default null
*/
cookieDomain: null,
/**
The name of the cookie the store stores its data in.
This value can be configured via
[`SimpleAuth.Configuration.CookieStore#cookieName`](#SimpleAuth-Configuration-CookieStore-cookieName).
@property cookieName
@readOnly
@type String
*/
cookieName: 'ember_simple_auth:session',
/**
The expiration time in seconds to use for the cookie. A value of `null`
will make the cookie a session cookie that expires when the browser is
closed.
This value can be configured via
[`SimpleAuth.Configuration.CookieStore#cookieExpirationTime`](#SimpleAuth-Configuration-CookieStore-cookieExpirationTime).
@property cookieExpirationTime
@readOnly
@type Integer
*/
cookieExpirationTime: null,
/**
@property _secureCookies
@private
*/
_secureCookies: window.location.protocol === 'https:',
/**
@property _syncDataTimeout
@private
*/
_syncDataTimeout: null,
/**
@property renewExpirationTimeout
@private
*/
renewExpirationTimeout: null,
/**
@property isPageVisible
@private
*/
isPageVisible: null,
/**
@method init
@private
*/
init: function() {
this.cookieName = Configuration.cookieName;
this.cookieExpirationTime = Configuration.cookieExpirationTime;
this.cookieDomain = Configuration.cookieDomain;
this.isPageVisible = this.initPageVisibility();
this.syncData();
this.renewExpiration();
},
/**
Persists the `data` in session cookies.
@method persist
@param {Object} data The data to persist
*/
persist: function(data) {
data = JSON.stringify(data || {});
var expiration = this.calculateExpirationTime();
this.write(data, expiration);
this._lastData = this.restore();
},
/**
Restores all data currently saved in the cookie as a plain object.
@method restore
@return {Object} All data currently persisted in the cookie
*/
restore: function() {
var data = this.read(this.cookieName);
if (Ember.isEmpty(data)) {
return {};
} else {
return JSON.parse(data);
}
},
/**
Clears the store by deleting all session cookies prefixed with the
`cookieName` (see
[`SimpleAuth.Stores.Cookie#cookieName`](#SimpleAuth-Stores-Cookie-cookieName)).
@method clear
*/
clear: function() {
this.write(null, 0);
this._lastData = {};
},
/**
@method read
@private
*/
read: function(name) {
var value = document.cookie.match(new RegExp(name + '=([^;]+)')) || [];
return decodeURIComponent(value[1] || '');
},
/**
@method calculateExpirationTime
@private
*/
calculateExpirationTime: function() {
var cachedExpirationTime = this.read(this.cookieName + ':expiration_time');
cachedExpirationTime = !!cachedExpirationTime ? new Date().getTime() + cachedExpirationTime * 1000 : null;
return !!this.cookieExpirationTime ? new Date().getTime() + this.cookieExpirationTime * 1000 : cachedExpirationTime;
},
/**
@method write
@private
*/
write: function(value, expiration) {
var path = '; path=/';
var domain = Ember.isEmpty(this.cookieDomain) ? '' : '; domain=' + this.cookieDomain;
var expires = Ember.isEmpty(expiration) ? '' : '; expires=' + new Date(expiration).toUTCString();
var secure = !!this._secureCookies ? ';secure' : '';
document.cookie = this.cookieName + '=' + encodeURIComponent(value) + domain + path + expires + secure;
if(expiration !== null) {
var cachedExpirationTime = this.read(this.cookieName + ':expiration_time');
document.cookie = this.cookieName + ':expiration_time=' + encodeURIComponent(this.cookieExpirationTime || cachedExpirationTime) + domain + path + expires + secure;
}
},
/**
@method syncData
@private
*/
syncData: function() {
var data = this.restore();
if (!objectsAreEqual(data, this._lastData)) {
this._lastData = data;
this.trigger('sessionDataUpdated', data);
}
if (!Ember.testing) {
Ember.run.cancel(this._syncDataTimeout);
this._syncDataTimeout = Ember.run.later(this, this.syncData, 500);
}
},
/**
@method initPageVisibility
@private
*/
initPageVisibility: function(){
var keys = {
hidden: 'visibilitychange',
webkitHidden: 'webkitvisibilitychange',
mozHidden: 'mozvisibilitychange',
msHidden: 'msvisibilitychange'
};
for (var stateKey in keys) {
if (stateKey in document) {
var eventKey = keys[stateKey];
break;
}
}
return function() {
return !document[stateKey];
};
},
/**
@method renew
@private
*/
renew: function() {
var data = this.restore();
if (!Ember.isEmpty(data) && data !== {}) {
data = Ember.typeOf(data) === 'string' ? data : JSON.stringify(data || {});
var expiration = this.calculateExpirationTime();
this.write(data, expiration);
}
},
/**
@method renewExpiration
@private
*/
renewExpiration: function() {
if (this.isPageVisible()) {
this.renew();
}
if (!Ember.testing) {
Ember.run.cancel(this.renewExpirationTimeout);
this.renewExpirationTimeout = Ember.run.later(this, this.renewExpiration, 60000);
}
}
});
});
define('simple-auth/stores/base', ['exports'], function(__exports__) {
__exports__['default'] = global.SimpleAuth.Stores.Base;
});
define('simple-auth/utils/objects-are-equal', ['exports'], function(__exports__) {
__exports__['default'] = global.SimpleAuth.Utils.objectsAreEqual;
});
define('simple-auth/utils/get-global-config', ['exports'], function(__exports__) {
__exports__['default'] = global.SimpleAuth.Utils.getGlobalConfig;
});
define('simple-auth/utils/load-config', ['exports'], function(__exports__) {
__exports__['default'] = global.SimpleAuth.Utils.loadConfig;
});
var initializer = requireModule('simple-auth-cookie-store/initializer')['default'];
var Configuration = requireModule('simple-auth-cookie-store/configuration')['default'];
var Cookie = requireModule('simple-auth-cookie-store/stores/cookie')['default'];
global.SimpleAuth.Configuration.CookieStore = Configuration;
global.SimpleAuth.Stores.Cookie = Cookie;
requireModule('simple-auth-cookie-store/ember');
})((typeof global !== 'undefined') ? global : window);