UNPKG

7.76 kBJavaScriptView Raw
1import * as i0 from '@angular/core';
2import { PLATFORM_ID, Injectable, Inject } from '@angular/core';
3import { isPlatformBrowser, DOCUMENT } from '@angular/common';
4
5// This service is based on the `ng2-cookies` package which sadly is not a service and does
6class CookieService {
7 constructor(document,
8 // Get the `PLATFORM_ID` so we can check if we're in a browser.
9 platformId) {
10 this.document = document;
11 this.platformId = platformId;
12 this.documentIsAccessible = isPlatformBrowser(this.platformId);
13 }
14 /**
15 * Get cookie Regular Expression
16 *
17 * @param name Cookie name
18 * @returns property RegExp
19 *
20 * @author: Stepan Suvorov
21 * @since: 1.0.0
22 */
23 static getCookieRegExp(name) {
24 const escapedName = name.replace(/([\[\]\{\}\(\)\|\=\;\+\?\,\.\*\^\$])/gi, '\\$1');
25 return new RegExp('(?:^' + escapedName + '|;\\s*' + escapedName + ')=(.*?)(?:;|$)', 'g');
26 }
27 /**
28 * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI).
29 *
30 * @param encodedURIComponent A value representing an encoded URI component.
31 *
32 * @returns The unencoded version of an encoded component of a Uniform Resource Identifier (URI).
33 *
34 * @author: Stepan Suvorov
35 * @since: 1.0.0
36 */
37 static safeDecodeURIComponent(encodedURIComponent) {
38 try {
39 return decodeURIComponent(encodedURIComponent);
40 }
41 catch {
42 // probably it is not uri encoded. return as is
43 return encodedURIComponent;
44 }
45 }
46 /**
47 * Return `true` if {@link Document} is accessible, otherwise return `false`
48 *
49 * @param name Cookie name
50 * @returns boolean - whether cookie with specified name exists
51 *
52 * @author: Stepan Suvorov
53 * @since: 1.0.0
54 */
55 check(name) {
56 if (!this.documentIsAccessible) {
57 return false;
58 }
59 name = encodeURIComponent(name);
60 const regExp = CookieService.getCookieRegExp(name);
61 return regExp.test(this.document.cookie);
62 }
63 /**
64 * Get cookies by name
65 *
66 * @param name Cookie name
67 * @returns property value
68 *
69 * @author: Stepan Suvorov
70 * @since: 1.0.0
71 */
72 get(name) {
73 if (this.documentIsAccessible && this.check(name)) {
74 name = encodeURIComponent(name);
75 const regExp = CookieService.getCookieRegExp(name);
76 const result = regExp.exec(this.document.cookie);
77 return result[1] ? CookieService.safeDecodeURIComponent(result[1]) : '';
78 }
79 else {
80 return '';
81 }
82 }
83 /**
84 * Get all cookies in JSON format
85 *
86 * @returns all the cookies in json
87 *
88 * @author: Stepan Suvorov
89 * @since: 1.0.0
90 */
91 getAll() {
92 if (!this.documentIsAccessible) {
93 return {};
94 }
95 const cookies = {};
96 const document = this.document;
97 if (document.cookie && document.cookie !== '') {
98 document.cookie.split(';').forEach((currentCookie) => {
99 const [cookieName, cookieValue] = currentCookie.split('=');
100 cookies[CookieService.safeDecodeURIComponent(cookieName.replace(/^ /, ''))] = CookieService.safeDecodeURIComponent(cookieValue);
101 });
102 }
103 return cookies;
104 }
105 set(name, value, expiresOrOptions, path, domain, secure, sameSite) {
106 if (!this.documentIsAccessible) {
107 return;
108 }
109 if (typeof expiresOrOptions === 'number' || expiresOrOptions instanceof Date || path || domain || secure || sameSite) {
110 const optionsBody = {
111 expires: expiresOrOptions,
112 path,
113 domain,
114 secure,
115 sameSite: sameSite ? sameSite : 'Lax',
116 };
117 this.set(name, value, optionsBody);
118 return;
119 }
120 let cookieString = encodeURIComponent(name) + '=' + encodeURIComponent(value) + ';';
121 const options = expiresOrOptions ? expiresOrOptions : {};
122 if (options.expires) {
123 if (typeof options.expires === 'number') {
124 const dateExpires = new Date(new Date().getTime() + options.expires * 1000 * 60 * 60 * 24);
125 cookieString += 'expires=' + dateExpires.toUTCString() + ';';
126 }
127 else {
128 cookieString += 'expires=' + options.expires.toUTCString() + ';';
129 }
130 }
131 if (options.path) {
132 cookieString += 'path=' + options.path + ';';
133 }
134 if (options.domain) {
135 cookieString += 'domain=' + options.domain + ';';
136 }
137 if (options.secure === false && options.sameSite === 'None') {
138 options.secure = true;
139 console.warn(`[ngx-cookie-service] Cookie ${name} was forced with secure flag because sameSite=None.` +
140 `More details : https://github.com/stevermeister/ngx-cookie-service/issues/86#issuecomment-597720130`);
141 }
142 if (options.secure) {
143 cookieString += 'secure;';
144 }
145 if (!options.sameSite) {
146 options.sameSite = 'Lax';
147 }
148 cookieString += 'sameSite=' + options.sameSite + ';';
149 this.document.cookie = cookieString;
150 }
151 /**
152 * Delete cookie by name
153 *
154 * @param name Cookie name
155 * @param path Cookie path
156 * @param domain Cookie domain
157 * @param secure Cookie secure flag
158 * @param sameSite Cookie sameSite flag - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite
159 *
160 * @author: Stepan Suvorov
161 * @since: 1.0.0
162 */
163 delete(name, path, domain, secure, sameSite = 'Lax') {
164 if (!this.documentIsAccessible) {
165 return;
166 }
167 const expiresDate = new Date('Thu, 01 Jan 1970 00:00:01 GMT');
168 this.set(name, '', { expires: expiresDate, path, domain, secure, sameSite });
169 }
170 /**
171 * Delete all cookies
172 *
173 * @param path Cookie path
174 * @param domain Cookie domain
175 * @param secure Is the Cookie secure
176 * @param sameSite Is the cookie same site
177 *
178 * @author: Stepan Suvorov
179 * @since: 1.0.0
180 */
181 deleteAll(path, domain, secure, sameSite = 'Lax') {
182 if (!this.documentIsAccessible) {
183 return;
184 }
185 const cookies = this.getAll();
186 for (const cookieName in cookies) {
187 if (cookies.hasOwnProperty(cookieName)) {
188 this.delete(cookieName, path, domain, secure, sameSite);
189 }
190 }
191 }
192}
193CookieService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: CookieService, deps: [{ token: DOCUMENT }, { token: PLATFORM_ID }], target: i0.ɵɵFactoryTarget.Injectable });
194CookieService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: CookieService, providedIn: 'root' });
195i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.0.2", ngImport: i0, type: CookieService, decorators: [{
196 type: Injectable,
197 args: [{
198 providedIn: 'root',
199 }]
200 }], ctorParameters: function () { return [{ type: Document, decorators: [{
201 type: Inject,
202 args: [DOCUMENT]
203 }] }, { type: undefined, decorators: [{
204 type: Inject,
205 args: [PLATFORM_ID]
206 }] }]; } });
207
208/*
209 * Public API Surface of ngx-cookie-service
210 */
211
212/**
213 * Generated bundle index. Do not edit.
214 */
215
216export { CookieService };
217//# sourceMappingURL=ngx-cookie-service.mjs.map