utils.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. 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. */
  9. const TOKEN_COOKIE_NAME = 'ckCsrfToken';
  10. const TOKEN_LENGTH = 40;
  11. const 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. *
  17. * @returns {String}
  18. */
  19. export function getCsrfToken() {
  20. let token = getCookie( TOKEN_COOKIE_NAME );
  21. if ( !token || token.length != TOKEN_LENGTH ) {
  22. token = generateToken( TOKEN_LENGTH );
  23. setCookie( TOKEN_COOKIE_NAME, token );
  24. }
  25. return token;
  26. }
  27. /**
  28. * Returns the value of the cookie with a given name or `null` if the cookie is not found.
  29. *
  30. * @param {String} name
  31. * @returns {String|null}
  32. */
  33. export function getCookie( name ) {
  34. name = name.toLowerCase();
  35. const parts = document.cookie.split( ';' );
  36. for ( const part of parts ) {
  37. const pair = part.split( '=' );
  38. const key = decodeURIComponent( pair[ 0 ].trim().toLowerCase() );
  39. if ( key === name ) {
  40. return decodeURIComponent( pair[ 1 ] );
  41. }
  42. }
  43. return null;
  44. }
  45. /**
  46. * Sets the value of the cookie with a given name.
  47. *
  48. * @param {String} name
  49. * @param {String} value
  50. */
  51. export function setCookie( name, value ) {
  52. document.cookie = encodeURIComponent( name ) + '=' + encodeURIComponent( value ) + ';path=/';
  53. }
  54. // Generates the CSRF token with the given length.
  55. //
  56. // @private
  57. // @param {Number} length
  58. // @returns {string}
  59. function generateToken( length ) {
  60. let result = '';
  61. const randValues = new Uint8Array( length );
  62. window.crypto.getRandomValues( randValues );
  63. for ( let j = 0; j < randValues.length; j++ ) {
  64. const character = tokenCharset.charAt( randValues[ j ] % tokenCharset.length );
  65. result += Math.random() > 0.5 ? character.toUpperCase() : character;
  66. }
  67. return result;
  68. }