Nils Diewald | 5814133 | 2015-04-07 16:18:45 +0000 | [diff] [blame] | 1 | /** |
| 2 | * Simple cookie based session library that stores |
| 3 | * values in JSON encoded cookies. |
| 4 | * |
| 5 | * @author Nils Diewald |
| 6 | */ |
| 7 | var KorAP = KorAP || {}; |
| 8 | |
| 9 | (function (KorAP) { |
| 10 | "use strict"; |
| 11 | |
| 12 | |
| 13 | KorAP.Session = { |
| 14 | |
| 15 | /** |
| 16 | * Create a new session. |
| 17 | * Expects a name or defaults to 'korap' |
| 18 | */ |
| 19 | create : function (name) { |
| 20 | var obj = Object.create(KorAP.Session); |
| 21 | if (name === undefined) |
| 22 | name = 'korap'; |
| 23 | obj._name = name.toLowerCase(); |
| 24 | obj._hash = {}; |
| 25 | obj._parse(); |
| 26 | return obj; |
| 27 | }, |
| 28 | |
| 29 | /** |
| 30 | * Get a value based on a key. |
| 31 | * The value can be complex, as the value is stored as JSON. |
| 32 | */ |
| 33 | get : function (key) { |
| 34 | return this._hash[key.toLowerCase()]; |
| 35 | }, |
| 36 | |
| 37 | /** |
| 38 | * Set a value based on a key. |
| 39 | * The value can be complex, as the value is stored as JSON. |
| 40 | */ |
| 41 | set : function (key, value) { |
| 42 | this._hash[key] = value; |
| 43 | this._store(); |
| 44 | }, |
| 45 | |
| 46 | /** |
| 47 | * Clears the session by removing the cookie |
| 48 | */ |
| 49 | clear : function () { |
| 50 | document.cookie = this._name + '=; expires=-1'; |
| 51 | }, |
| 52 | |
| 53 | /* Store cookie */ |
| 54 | _store : function () { |
| 55 | /* |
| 56 | var date = new Date(); |
| 57 | date.setYear(date.getFullYear() + 1); |
| 58 | */ |
| 59 | document.cookie = |
| 60 | this._name + '=' + encodeURIComponent(JSON.stringify(this._hash)) + ';'; |
| 61 | }, |
| 62 | |
| 63 | /* Parse cookie */ |
| 64 | _parse : function () { |
| 65 | var c = document.cookie; |
| 66 | var part = document.cookie.split(';'); |
| 67 | for(var i = 0; i < part.length; i++) { |
| 68 | var pair = part[i].split('='); |
| 69 | var name = pair[0].trim().toLowerCase(); |
| 70 | if (name === this._name) { |
| 71 | if (pair.length === 1 || pair[1].length === 0) |
| 72 | return; |
| 73 | this._hash = JSON.parse(decodeURIComponent(pair[1])); |
| 74 | return; |
| 75 | }; |
| 76 | }; |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | }(this.KorAP)); |