All files / src/app/core/utils/cookies cookies.service.ts

77.94% Statements 53/68
66.66% Branches 34/51
66.66% Functions 8/12
77.94% Lines 53/68

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 173119x 119x   119x 119x   119x 119x                                 119x   11x 11x 11x 11x       1x       1x 1x         10x 10x                                                                                                     1x 1x           1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x           1x       11x 11x           11x 11x 11x     11x 11x 1x   11x 1x       11x       11x 11x 11x 11x     11x       11x   11x 11x         11x      
import { APP_BASE_HREF, DOCUMENT } from '@angular/common';
import { Inject, Injectable, TransferState } from '@angular/core';
 
import { COOKIE_CONSENT_OPTIONS } from 'ish-core/configurations/injection-keys';
import { COOKIE_CONSENT_VERSION } from 'ish-core/configurations/state-keys';
import { CookieConsentSettings } from 'ish-core/models/cookies/cookies.model';
import { browserNameVersion } from 'ish-core/utils/browser-detection';
import { InjectSingle } from 'ish-core/utils/injection';
 
interface CookiesOptions {
  path?: string;
  domain?: string;
  expires?: string | Date;
  secure?: boolean;
  httpOnly?: boolean;
  sameSite?: 'Lax' | 'Strict' | 'None';
}
 
/**
 * The Cookies Service handles any interaction of the PWA with cookies.
 * Implementation is mostly transferred from the 'ngx-utils-cookies-port' library (https://github.com/junekpavel/ngx-utils-cookies-port).
 * in addition it provides methods for the cookie consent handling.
 */
@Injectable({ providedIn: 'root' })
export class CookiesService {
  constructor(
    @Inject(COOKIE_CONSENT_OPTIONS) private cookieConsentOptions: InjectSingle<typeof COOKIE_CONSENT_OPTIONS>,
    private transferState: TransferState,
    @Inject(APP_BASE_HREF) private baseHref: string,
    @Inject(DOCUMENT) private document: Document
  ) {}
 
  get(key: string): string {
    return !SSR ? (this.cookiesReader()[key] as string) : undefined;
  }
 
  remove(key: string, options?: CookiesOptions) {
    if (!SSR) {
      this.cookiesWriter()(key, undefined, options);
    }
  }
 
  put(key: string, value: string, options?: CookiesOptions) {
    if (!SSR) {
      this.cookiesWriter()(key, value, options);
    }
  }
 
  /**
   * Saves the given cookie consent options settings together with the current cookie consent version
   * to a users cookie named 'cookieConsent' and reloads the PWA application with the new settings.
   *
   * @param options The selected cookie consent options that should be enabled.
   */
  setCookiesConsentFor(options: string[]) {
    const cookieConsentVersion = this.transferState.get<number>(COOKIE_CONSENT_VERSION, 1);
    this.deleteAllCookies();
    this.put('cookieConsent', JSON.stringify({ enabledOptions: options, version: cookieConsentVersion }), {
      expires: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
    });
    window.location.reload();
  }
 
  setCookiesConsentForAll() {
    this.setCookiesConsentFor(Object.keys(this.cookieConsentOptions.options));
  }
 
  /**
   * Check if consent was given for {option}.
   *
   * @param option The cookie consent option of interest.
   * @returns      'true' if the user has given the consent for the requested option, 'false' otherwise.
   */
  cookieConsentFor(option: string): boolean {
    if (!SSR) {
      const cookieConsentSettings = JSON.parse(this.get('cookieConsent') || 'null') as CookieConsentSettings;
      return cookieConsentSettings?.enabledOptions ? cookieConsentSettings.enabledOptions.includes(option) : false;
    } else {
      return false;
    }
  }
 
  /**
   * Deletes all cookies except for the ones configured as 'allowedCookies' in the environments cookie consent options.
   */
  private deleteAllCookies() {
    const allCookies = this.cookiesReader();
    for (const cookie in allCookies) {
      Iif (!this.cookieConsentOptions?.allowedCookies.includes(cookie)) {
        this.cookiesWriter()(cookie, undefined);
      }
    }
  }
 
  private cookiesReader(): { [key: string]: unknown } {
    let lastCookies: { [key: string]: unknown } = {};
    let lastCookieString = '';
    let cookiesArray: string[];
    let cookie: string;
    let i: number;
    let index: number;
    let name: string;
    const currentCookieString = this.document.cookie || '';
 
    if (currentCookieString !== lastCookieString) {
      lastCookieString = currentCookieString;
      cookiesArray = lastCookieString.split('; ');
      lastCookies = {};
      for (i = 0; i < cookiesArray.length; i++) {
        cookie = cookiesArray[i];
        index = cookie.indexOf('=');
        if (index > 0) {
          name = decodeURIComponent(cookie.substring(0, index));
          if (!lastCookies[name]) {
            const cookieValue = decodeURIComponent(cookie.substring(index + 1));
            if (cookieValue) {
              lastCookies[name] = cookieValue;
            }
          }
        }
      }
    }
    return lastCookies;
  }
 
  private cookiesWriter(): (name: string, value: string | undefined, options?: CookiesOptions) => void {
    return (name, value, options?) => {
      this.document.cookie = this.buildCookieString(name, value, options);
    };
  }
 
  // eslint-disable-next-line complexity
  private buildCookieString(name: string, value: string | undefined, opts: CookiesOptions = {}): string {
    let path = opts.path;
    if (!path) {
      path = this.baseHref;
    }
 
    let expires = opts.expires;
    if (!value) {
      expires = 'Thu, 01 Jan 1970 00:00:00 GMT';
    }
    if (typeof expires === 'string') {
      expires = new Date(expires);
    }
 
    // fix for Safari 14 not keeping 'SameSite=Strict' cookies when redirecting to a payment provider etc.
    Iif (browserNameVersion() === 'Safari 14' && opts.sameSite !== 'None') {
      opts.sameSite = 'Lax';
    }
 
    let str = `${encodeURIComponent(name)}=${encodeURIComponent(value || '')}`;
    str += `;path=${path}`;
    str += opts.domain ? `;domain=${opts.domain}` : '';
    str += expires ? `;expires=${expires.toUTCString()}` : '';
 
    // if in an iframe set cookies always with SameSite=None, otherwise set the given SameSite, default to SameSite=Strict
    str += `;SameSite=${window.parent !== window ? 'None' : opts.sameSite || 'Strict'}`;
 
    // if in http mode (should only be in development) or if explicitly set to false do not set the cookie secure, default to secure
    // eslint-disable-next-line @typescript-eslint/no-unnecessary-boolean-literal-compare
    str += window.location.protocol === 'http:' || opts.secure === false ? '' : ';secure';
 
    const cookiesLength = str.length + 1;
    Iif (cookiesLength > 4096) {
      // eslint-disable-next-line no-console
      console.log(`Cookie \'${name}\' possibly not set or overflowed because it was too
      large (${cookiesLength} > 4096 bytes)!`);
    }
    return str;
  }
}