UNPKG

1.95 kBJavaScriptView Raw
1/**
2 * @license Copyright (c) 2003-2023, CKSource Holding sp. z o.o. All rights reserved.
3 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4 */
5/* globals window, document */
6/**
7 * @module adapter-ckfinder/utils
8 */
9const TOKEN_COOKIE_NAME = 'ckCsrfToken';
10const TOKEN_LENGTH = 40;
11const tokenCharset = 'abcdefghijklmnopqrstuvwxyz0123456789';
12/**
13 * Returns the CSRF token value. The value is a hash stored in `document.cookie`
14 * under the `ckCsrfToken` key. The CSRF token can be used to secure the communication
15 * between the web browser and the CKFinder server.
16 */
17export function getCsrfToken() {
18 let token = getCookie(TOKEN_COOKIE_NAME);
19 if (!token || token.length != TOKEN_LENGTH) {
20 token = generateToken(TOKEN_LENGTH);
21 setCookie(TOKEN_COOKIE_NAME, token);
22 }
23 return token;
24}
25/**
26 * Returns the value of the cookie with a given name or `null` if the cookie is not found.
27 */
28export function getCookie(name) {
29 name = name.toLowerCase();
30 const parts = document.cookie.split(';');
31 for (const part of parts) {
32 const pair = part.split('=');
33 const key = decodeURIComponent(pair[0].trim().toLowerCase());
34 if (key === name) {
35 return decodeURIComponent(pair[1]);
36 }
37 }
38 return null;
39}
40/**
41 * Sets the value of the cookie with a given name.
42 */
43export function setCookie(name, value) {
44 document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) + ';path=/';
45}
46/**
47 * Generates the CSRF token with the given length.
48 */
49function generateToken(length) {
50 let result = '';
51 const randValues = new Uint8Array(length);
52 window.crypto.getRandomValues(randValues);
53 for (let j = 0; j < randValues.length; j++) {
54 const character = tokenCharset.charAt(randValues[j] % tokenCharset.length);
55 result += Math.random() > 0.5 ? character.toUpperCase() : character;
56 }
57 return result;
58}