blob: 27af76dd9f3b53a9bb93d620cf1e96527357677f [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 */
12 create : function (name) {
13 var obj = Object.create(this);
14 if (name === undefined)
15 name = 'korap';
16 obj._name = name.toLowerCase();
17 obj._hash = {};
18 obj._parse();
19 return obj;
20 },
Nils Diewald58141332015-04-07 16:18:45 +000021
Nils Diewald0e6992a2015-04-14 20:13:52 +000022 /**
23 * Get a value based on a key.
24 * The value can be complex, as the value is stored as JSON.
25 */
26 get : function (key) {
27 return this._hash[key.toLowerCase()];
28 },
Nils Diewald58141332015-04-07 16:18:45 +000029
Nils Diewald0e6992a2015-04-14 20:13:52 +000030 /**
31 * Set a value based on a key.
32 * The value can be complex, as the value is stored as JSON.
33 */
34 set : function (key, value) {
35 this._hash[key] = value;
36 this._store();
37 },
Nils Diewald58141332015-04-07 16:18:45 +000038
Nils Diewald0e6992a2015-04-14 20:13:52 +000039 /**
40 * Clears the session by removing the cookie
41 */
42 clear : function () {
43 document.cookie = this._name + '=; expires=-1';
44 },
Nils Diewald58141332015-04-07 16:18:45 +000045
Nils Diewald0e6992a2015-04-14 20:13:52 +000046 /* Store cookie */
47 _store : function () {
48 /*
49 var date = new Date();
50 date.setYear(date.getFullYear() + 1);
51 */
52 document.cookie =
53 this._name + '=' + encodeURIComponent(JSON.stringify(this._hash)) + ';';
54 },
Nils Diewald58141332015-04-07 16:18:45 +000055
Nils Diewald0e6992a2015-04-14 20:13:52 +000056 /* Parse cookie */
57 _parse : function () {
58 var c = document.cookie;
59 var part = document.cookie.split(';');
60 for(var i = 0; i < part.length; i++) {
61 var pair = part[i].split('=');
62 var name = pair[0].trim().toLowerCase();
63 if (name === this._name) {
Akron0b489ad2018-02-02 16:49:32 +010064 if (pair.length === 1 || pair[1].length === 0)
65 return;
Nils Diewald0e6992a2015-04-14 20:13:52 +000066 this._hash = JSON.parse(decodeURIComponent(pair[1]));
Akron0b489ad2018-02-02 16:49:32 +010067 return;
Nils Diewald58141332015-04-07 16:18:45 +000068 };
Nils Diewald0e6992a2015-04-14 20:13:52 +000069 };
Nils Diewald58141332015-04-07 16:18:45 +000070 }
Nils Diewald0e6992a2015-04-14 20:13:52 +000071});