all files / src/shared/ CookieManager.js

87.5% Statements 14/16
100% Branches 4/4
66.67% Functions 4/6
86.67% Lines 13/15
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                      12×   12×                   90×                                    
import Cookies from 'js-cookie';
import { getCookieDomain } from './utils';
 
class CookieManager {
    constructor(cookies) {
        this.domain = getCookieDomain(window.location.hostname);
        this.sessionCookies = cookies.map((cookie) => ({
            ...cookie,
            value: this.getSessionCookiesValue(cookie.name, cookie.addTimestamp)
        }));
    }
 
    getSessionCookiesValue(name, addTimestamp) {
        const resultValue = Cookies.get(name);
 
        if (!resultValue) {
            return this.generateValue(addTimestamp);
        }
 
        return resultValue;
    }
 
    generateValue(withTimestamp) {
        // for users from GDPR countries if they did not give consent for tracking
        // we assign random values to session cookies; should match results of:
        // https://developer.fastly.com/reference/vcl/functions/randomness/randomstr/
        const validCharacters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-';
 
        let resultValue = '';
        while(resultValue.length < 10) {
            resultValue += validCharacters[(Math.random() * validCharacters.length) | 0];
        }
 
        if (withTimestamp) {
            resultValue += '.' + Date.now();
        }
 
        return resultValue;
    }
 
    setSessionCookiesOnAccept() {
        this.sessionCookies.forEach(({ name, value, extendTime }) => {
            Cookies.set(name, value, {
                expires: extendTime,
                domain: this.domain
            });
        });
    };
}
 
export default CookieManager;