UNPKG

2.09 kBJavaScriptView Raw
1/**
2 * @license Copyright (c) 2003-2022, 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
6/* globals window, document */
7
8/**
9 * @module adapter-ckfinder/utils
10 */
11
12const TOKEN_COOKIE_NAME = 'ckCsrfToken';
13const TOKEN_LENGTH = 40;
14const tokenCharset = 'abcdefghijklmnopqrstuvwxyz0123456789';
15
16/**
17 * Returns the CSRF token value. The value is a hash stored in `document.cookie`
18 * under the `ckCsrfToken` key. The CSRF token can be used to secure the communication
19 * between the web browser and the CKFinder server.
20 *
21 * @returns {String}
22 */
23export function getCsrfToken() {
24 let token = getCookie( TOKEN_COOKIE_NAME );
25
26 if ( !token || token.length != TOKEN_LENGTH ) {
27 token = generateToken( TOKEN_LENGTH );
28 setCookie( TOKEN_COOKIE_NAME, token );
29 }
30
31 return token;
32}
33
34/**
35 * Returns the value of the cookie with a given name or `null` if the cookie is not found.
36 *
37 * @param {String} name
38 * @returns {String|null}
39 */
40export function getCookie( name ) {
41 name = name.toLowerCase();
42 const parts = document.cookie.split( ';' );
43
44 for ( const part of parts ) {
45 const pair = part.split( '=' );
46 const key = decodeURIComponent( pair[ 0 ].trim().toLowerCase() );
47
48 if ( key === name ) {
49 return decodeURIComponent( pair[ 1 ] );
50 }
51 }
52
53 return null;
54}
55
56/**
57 * Sets the value of the cookie with a given name.
58 *
59 * @param {String} name
60 * @param {String} value
61 */
62export function setCookie( name, value ) {
63 document.cookie = encodeURIComponent( name ) + '=' + encodeURIComponent( value ) + ';path=/';
64}
65
66// Generates the CSRF token with the given length.
67//
68// @private
69// @param {Number} length
70// @returns {string}
71function generateToken( length ) {
72 let result = '';
73 const randValues = new Uint8Array( length );
74
75 window.crypto.getRandomValues( randValues );
76
77 for ( let j = 0; j < randValues.length; j++ ) {
78 const character = tokenCharset.charAt( randValues[ j ] % tokenCharset.length );
79 result += Math.random() > 0.5 ? character.toUpperCase() : character;
80 }
81
82 return result;
83}