amazon-csrf.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License").
  5. * You may not use this file except in compliance with the License.
  6. * A copy of the License is located at
  7. *
  8. * http://aws.amazon.com/apache2.0
  9. *
  10. * or in the "license" file accompanying this file. This file is distributed
  11. * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  12. * express or implied. See the License for the specific language governing
  13. * permissions and limitations under the License.
  14. */
  15. define([
  16. 'sjcl',
  17. 'jquery',
  18. 'mage/cookies'
  19. ], function (sjcl, $) {
  20. 'use strict';
  21. return {
  22. options: {
  23. wordsLength: 8,
  24. cookieName: 'amazon-csrf-state'
  25. },
  26. /**
  27. * Create random string for Amazon CSRF cookie
  28. */
  29. generateNewValue: function () {
  30. var randomString = sjcl.codec.base64.fromBits(sjcl.random.randomWords(this.options.wordsLength));
  31. $.mage.cookies.set(this.options.cookieName, randomString);
  32. return randomString;
  33. },
  34. /**
  35. * Check if Amazon CSRF cookie is valid and clear cookie
  36. * @param {String} stateString
  37. * @returns {Boolean}
  38. */
  39. isValid: function (stateString) {
  40. var isValid = $.mage.cookies.get(this.options.cookieName) === stateString;
  41. this.clear(); // always clear nonce when validating
  42. return isValid;
  43. },
  44. /**
  45. * Clear Amazon CSRF cookie
  46. */
  47. clear: function () {
  48. $.mage.cookies.clear(this.options.cookieName);
  49. }
  50. };
  51. });