blob: 178b83c362dd57866779b84326201b2bb978a20b [file] [log] [blame]
Nils Diewald58141332015-04-07 16:18:45 +00001/**
2 * Simple cookie based session library that stores
3 * values in JSON encoded cookies.
4 *
5 * @author Nils Diewald
6 */
Nils Diewald0e6992a2015-04-14 20:13:52 +00007define({
8 /**
9 * Create a new session.
10 * Expects a name or defaults to 'korap'
11 */
Akron3b253d32018-07-15 10:16:06 +020012 create : function (name = 'korap') {
Nils Diewald0e6992a2015-04-14 20:13:52 +000013 var obj = Object.create(this);
Nils Diewald0e6992a2015-04-14 20:13:52 +000014 obj._name = name.toLowerCase();
15 obj._hash = {};
16 obj._parse();
17 return obj;
18 },
Nils Diewald58141332015-04-07 16:18:45 +000019
Nils Diewald0e6992a2015-04-14 20:13:52 +000020 /**
21 * Get a value based on a key.
22 * The value can be complex, as the value is stored as JSON.
23 */
24 get : function (key) {
25 return this._hash[key.toLowerCase()];
26 },
Nils Diewald58141332015-04-07 16:18:45 +000027
Nils Diewald0e6992a2015-04-14 20:13:52 +000028 /**
29 * Set a value based on a key.
30 * The value can be complex, as the value is stored as JSON.
31 */
32 set : function (key, value) {
33 this._hash[key] = value;
34 this._store();
35 },
Nils Diewald58141332015-04-07 16:18:45 +000036
Nils Diewald0e6992a2015-04-14 20:13:52 +000037 /**
38 * Clears the session by removing the cookie
39 */
40 clear : function () {
41 document.cookie = this._name + '=; expires=-1';
42 },
Nils Diewald58141332015-04-07 16:18:45 +000043
Nils Diewald0e6992a2015-04-14 20:13:52 +000044 /* Store cookie */
45 _store : function () {
46 /*
47 var date = new Date();
48 date.setYear(date.getFullYear() + 1);
49 */
50 document.cookie =
51 this._name + '=' + encodeURIComponent(JSON.stringify(this._hash)) + ';';
52 },
Nils Diewald58141332015-04-07 16:18:45 +000053
Nils Diewald0e6992a2015-04-14 20:13:52 +000054 /* Parse cookie */
55 _parse : function () {
56 var c = document.cookie;
Akronb50964a2020-10-12 11:44:37 +020057 document.cookie.split(';').forEach(
58 function(i) {
59 var pair = i.split('=');
60 var name = pair[0].trim().toLowerCase();
61 if (name === this._name) {
62 if (pair.length === 1 || pair[1].length === 0)
63 return;
64 this._hash = JSON.parse(decodeURIComponent(pair[1]));
Akron0b489ad2018-02-02 16:49:32 +010065 return;
Akronb50964a2020-10-12 11:44:37 +020066 };
67 }
68 );
Nils Diewald58141332015-04-07 16:18:45 +000069 }
Nils Diewald0e6992a2015-04-14 20:13:52 +000070});