-
-
Notifications
You must be signed in to change notification settings - Fork 415
/
cookies.js
382 lines (314 loc) · 11 KB
/
cookies.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
import { globalObj } from '../core/global';
import { OPT_OUT_MODE, OPT_IN_MODE } from './constants';
import { manageExistingScripts } from './scripts';
import {
_log,
indexOf,
uuidv4,
getRemainingExpirationTimeMS,
getExpiresAfterDaysValue,
elContains,
deepCopy,
fireEvent,
arrayDiff
} from './general';
/**
* @param {boolean} [isFirstConsent]
*/
const getCategoriesWithCookies = (isFirstConsent) => {
const state = globalObj._state;
const categoriesToFilter = isFirstConsent
? state._allCategoryNames
: state._lastChangedCategoryNames;
/**
* Filter out categories with readOnly=true or don't have an autoClear object
*/
return categoriesToFilter.filter(categoryName => {
const currentCategoryObject = state._allDefinedCategories[categoryName];
return !!currentCategoryObject
&& !currentCategoryObject.readOnly
&& !!currentCategoryObject.autoClear;
});
};
/**
* @param {string[]} allCookies
* @param {string} cookieName
*/
const findMatchingCookies = (allCookies, cookieName) => {
if(cookieName instanceof RegExp) {
return allCookies.filter(cookie => cookieName.test(cookie));
}else{
const cookieIndex = indexOf(allCookies, cookieName);
return cookieIndex > -1
? [allCookies[cookieIndex]]
: [];
}
};
/**
* Delete all unused cookies
* @param {boolean} [isFirstConsent]
*/
export const autoclearCookiesHelper = (isFirstConsent) => {
const state = globalObj._state;
const allCookiesArray = getAllCookies();
const categoriesToClear = getCategoriesWithCookies(isFirstConsent);
/**
* Clear cookies for each disabled service
*/
for(const categoryName in state._lastChangedServices) {
for(const serviceName of state._lastChangedServices[categoryName]) {
const serviceCookies = state._allDefinedServices[categoryName][serviceName].cookies;
const serviceIsDisabled = !elContains(state._acceptedServices[categoryName], serviceName);
if(!serviceIsDisabled || !serviceCookies)
continue;
for(const cookieItem of serviceCookies) {
const foundCookies = findMatchingCookies(allCookiesArray, cookieItem.name);
eraseCookiesHelper(foundCookies, cookieItem.path, cookieItem.domain);
}
}
}
for(const currentCategoryName of categoriesToClear){
const category = state._allDefinedCategories[currentCategoryName];
const autoClear = category.autoClear;
const autoClearCookies = autoClear && autoClear.cookies || [];
const categoryWasJustChanged = elContains(state._lastChangedCategoryNames, currentCategoryName);
const categoryIsDisabled = !elContains(state._acceptedCategories, currentCategoryName);
const categoryWasJustDisabled = categoryWasJustChanged && categoryIsDisabled;
const shouldClearCookies = isFirstConsent
? categoryIsDisabled
: categoryWasJustDisabled;
if(!shouldClearCookies)
continue;
if(autoClear.reloadPage && categoryWasJustDisabled)
state._reloadPage = true;
for(const cookieItem of autoClearCookies){
const foundCookies = findMatchingCookies(allCookiesArray, cookieItem.name);
eraseCookiesHelper(foundCookies, cookieItem.path, cookieItem.domain);
}
}
};
export const saveCookiePreferences = () => {
const state = globalObj._state;
/**
* Determine if categories were changed from last state (saved in the cookie)
*/
state._lastChangedCategoryNames = globalObj._config.mode === OPT_OUT_MODE && state._invalidConsent
? arrayDiff(state._defaultEnabledCategories, state._acceptedCategories)
: arrayDiff(state._acceptedCategories, state._savedCookieContent.categories);
let categoriesWereChanged = state._lastChangedCategoryNames.length > 0;
let servicesWereChanged = false;
/**
* Determine if services were changed from last state
*/
for(const categoryName of state._allCategoryNames){
state._lastChangedServices[categoryName] = arrayDiff(
state._acceptedServices[categoryName],
state._lastEnabledServices[categoryName]
);
if(state._lastChangedServices[categoryName].length > 0)
servicesWereChanged = true;
}
//{{START: GUI}}
const categoryToggles = globalObj._dom._categoryCheckboxInputs;
/**
* If the category is accepted check checkbox,
* otherwise uncheck it
*/
for(const categoryName in categoryToggles){
categoryToggles[categoryName].checked = elContains(state._acceptedCategories, categoryName);
}
for(const categoryName of state._allCategoryNames){
const servicesToggles = globalObj._dom._serviceCheckboxInputs[categoryName];
const enabledServices = state._acceptedServices[categoryName];
for(const serviceName in servicesToggles){
const serviceInput = servicesToggles[serviceName];
serviceInput.checked = elContains(enabledServices, serviceName);
}
}
//{{END: GUI}}
if(!state._consentTimestamp)
state._consentTimestamp = new Date();
if(!state._consentId)
state._consentId = uuidv4();
state._savedCookieContent = {
categories: deepCopy(state._acceptedCategories),
revision: globalObj._config.revision,
data: state._cookieData,
consentTimestamp: state._consentTimestamp.toISOString(),
consentId: state._consentId,
services: deepCopy(state._acceptedServices)
};
let isFirstConsent = false;
const stateChanged = categoriesWereChanged || servicesWereChanged;
if(state._invalidConsent || stateChanged){
/**
* Set consent as valid
*/
if(state._invalidConsent) {
state._invalidConsent = false;
isFirstConsent = true;
}
state._lastConsentTimestamp = !state._lastConsentTimestamp
? state._consentTimestamp
: new Date();
state._savedCookieContent.lastConsentTimestamp = state._lastConsentTimestamp.toISOString();
setCookie();
const isAutoClearEnabled = globalObj._config.autoClearCookies;
const shouldClearCookies = isFirstConsent || stateChanged;
if(isAutoClearEnabled && shouldClearCookies)
autoclearCookiesHelper(isFirstConsent);
manageExistingScripts();
}
if(isFirstConsent){
fireEvent(globalObj._customEvents._onFirstConsent);
fireEvent(globalObj._customEvents._onConsent);
if(globalObj._config.mode === OPT_IN_MODE)
return;
}
if(stateChanged)
fireEvent(globalObj._customEvents._onChange);
/**
* Reload page if needed
*/
if(state._reloadPage) {
state._reloadPage = false;
location.reload();
}
};
/**
* Set plugin's cookie
* @param {boolean} [useRemainingExpirationTime]
*/
export const setCookie = (useRemainingExpirationTime) => {
const { hostname, protocol } = location;
const { name, path, domain, sameSite } = globalObj._config.cookie;
/**
* Encode value (RFC compliant)
*/
const cookieValue = encodeURIComponent(JSON.stringify(globalObj._state._savedCookieContent));
const expiresAfterMs = useRemainingExpirationTime
? getRemainingExpirationTimeMS()
: getExpiresAfterDaysValue()*86400000;
/**
* Expiration date
*/
const date = new Date();
date.setTime(date.getTime() + expiresAfterMs);
let cookieStr = name + '='
+ cookieValue
+ (expiresAfterMs !== 0 ? '; expires=' + date.toUTCString() : '')
+ '; Path=' + path
+ '; SameSite=' + sameSite;
/**
* Set "domain" only if hostname contains a dot (e.g domain.com)
* to ensure that cookie works with 'localhost'
*/
if(elContains(hostname, '.'))
cookieStr += '; Domain=' + domain;
if(protocol === 'https:')
cookieStr += '; Secure';
document.cookie = cookieStr;
_log('CookieConsent [SET_COOKIE]: ' + name + ':', globalObj._state._savedCookieContent);
};
/**
* Parse cookie value using JSON.parse
* @param {string} value
*/
export const parseCookie = (value) => {
let parsedValue;
try{
parsedValue = JSON.parse(decodeURIComponent(value));
}catch(e){
parsedValue = {}; // Cookie value is not valid
}
return parsedValue;
};
/**
* Delete cookie by name & path
* @param {string[]} cookies Array of cookie names
* @param {string} [customPath]
* @param {string} [customDomain]
*/
export const eraseCookiesHelper = (cookies, customPath, customDomain) => {
if(cookies.length === 0)
return;
const domain = customDomain || globalObj._config.cookie.domain;
const path = customPath || globalObj._config.cookie.path;
const isWwwSubdomain = domain.slice(0, 4) === 'www.';
const mainDomain = isWwwSubdomain && domain.substring(4);
/**
* Helper function to erase cookie
* @param {string} cookie
* @param {string} [domain]
*/
const erase = (cookie, domain) => {
document.cookie = cookie + '='
+ '; path=' + path
+ (domain ? '; domain=.' + domain : '')
+ '; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
for(const cookieName of cookies){
/**
* 2 attempts to erase the cookie:
* - without domain
* - with domain
*/
erase(cookieName);
erase(cookieName, domain);
/**
* If domain starts with 'www.',
* also erase the cookie for the
* main domain (without www)
*/
if(isWwwSubdomain)
erase(cookieName, mainDomain);
_log('CookieConsent [AUTOCLEAR]: deleting cookie: "' + cookieName + '" path: "' + path + '" domain:', domain);
}
};
/**
* Get plugin cookie
* @param {string} [customName]
* @returns {string} cookie value
*/
export const getPluginCookie = (customName) => {
return parseCookie(getSingleCookie(customName || globalObj._config.cookie.name, true));
};
/**
* Returns the cookie name/value, if it exists
* @param {string} name
* @param {boolean} getValue
* @returns {string}
*/
export const getSingleCookie = (name, getValue) => {
const found = document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)');
return found
? (getValue ? found.pop() : name)
: '';
};
/**
* Returns array with all the cookie names
* @param {RegExp} regex
* @returns {string[]}
*/
export const getAllCookies = (regex) => {
const allCookies = document.cookie.split(/;\s*/);
/**
* @type {string[]}
*/
const cookieNames = [];
/**
* Save only the cookie names
*/
for(const cookie of allCookies){
let name = cookie.split('=')[0];
if(regex){
try{
regex.test(name) && cookieNames.push(name);
// eslint-disable-next-line no-empty
}catch(e){}
}else{
cookieNames.push(name);
}
}
return cookieNames;
};