All files / app/assets/javascripts/captcha wait_for_captcha_to_be_solved.js

100% Statements 14/14
100% Branches 2/2
100% Functions 5/5
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54                            2x 2x   2x   2x     2x               2x 2x 2x   2x 2x     2x 1x       1x 1x                  
import Vue from 'vue';
import CaptchaModal from '~/captcha/captcha_modal.vue';
import UnsolvedCaptchaError from '~/captcha/unsolved_captcha_error';
 
/**
 * Opens a Captcha Modal with provided captchaSiteKey.
 *
 * Returns a Promise which resolves if the captcha is solved correctly, and rejects
 * if the captcha process is aborted.
 *
 * @param captchaSiteKey
 * @returns {Promise}
 */
export function waitForCaptchaToBeSolved(captchaSiteKey) {
  return new Promise((resolve, reject) => {
    let captchaModalElement = document.createElement('div');
 
    document.body.append(captchaModalElement);
 
    let captchaModalVueInstance = new Vue({
      el: captchaModalElement,
      render: (createElement) => {
        return createElement(CaptchaModal, {
          props: {
            captchaSiteKey,
            needsCaptchaResponse: true,
          },
          on: {
            hidden: () => {
              // Cleaning up the modal from the DOM
              captchaModalVueInstance.$destroy();
              captchaModalVueInstance.$el.remove();
              captchaModalElement.remove();
 
              captchaModalElement = null;
              captchaModalVueInstance = null;
            },
            receivedCaptchaResponse: (captchaResponse) => {
              if (captchaResponse) {
                resolve(captchaResponse);
              } else {
                // reject the promise with a custom exception, allowing consuming apps to
                // adjust their error handling, if appropriate.
                const error = new UnsolvedCaptchaError();
                reject(error);
              }
            },
          },
        });
      },
    });
  });
}