2021-01-28 09:09:07 +00:00
|
|
|
// NOTE: This module will be used in https://gitlab.com/gitlab-org/gitlab/-/merge_requests/52044
|
|
|
|
import { memoize } from 'lodash';
|
|
|
|
|
2021-08-24 18:10:53 +00:00
|
|
|
export const RECAPTCHA_API_URL_PREFIX = window.gon.recaptcha_api_server_url;
|
2021-01-28 09:09:07 +00:00
|
|
|
export const RECAPTCHA_ONLOAD_CALLBACK_NAME = 'recaptchaOnloadCallback';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Adds the Google reCAPTCHA script tag to the head of the document, and
|
|
|
|
* returns a promise of the grecaptcha object
|
|
|
|
* (https://developers.google.com/recaptcha/docs/display#js_api).
|
|
|
|
*
|
|
|
|
* It is memoized, so there will only be one instance of the script tag ever
|
|
|
|
* added to the document.
|
|
|
|
*
|
|
|
|
* See the reCAPTCHA documentation for more details:
|
|
|
|
*
|
|
|
|
* https://developers.google.com/recaptcha/docs/display#explicit_render
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
export const initRecaptchaScript = memoize(() => {
|
2021-02-02 03:09:10 +00:00
|
|
|
// Appends the the reCAPTCHA script tag to the head of document
|
2021-01-28 09:09:07 +00:00
|
|
|
const appendRecaptchaScript = () => {
|
|
|
|
const script = document.createElement('script');
|
|
|
|
script.src = `${RECAPTCHA_API_URL_PREFIX}?onload=${RECAPTCHA_ONLOAD_CALLBACK_NAME}&render=explicit`;
|
|
|
|
script.classList.add('js-recaptcha-script');
|
|
|
|
document.head.appendChild(script);
|
|
|
|
};
|
|
|
|
|
|
|
|
return new Promise((resolve) => {
|
2021-02-02 03:09:10 +00:00
|
|
|
// This global callback resolves the Promise and is passed by name to the reCAPTCHA script.
|
2021-02-06 09:09:11 +00:00
|
|
|
window[RECAPTCHA_ONLOAD_CALLBACK_NAME] = () => {
|
2021-02-02 03:09:10 +00:00
|
|
|
// Let's clean up after ourselves. This is also important for testing, because `window` is NOT cleared between tests.
|
|
|
|
// https://github.com/facebook/jest/issues/1224#issuecomment-444586798.
|
|
|
|
delete window[RECAPTCHA_ONLOAD_CALLBACK_NAME];
|
2021-02-06 09:09:11 +00:00
|
|
|
resolve(window.grecaptcha);
|
2021-02-02 03:09:10 +00:00
|
|
|
};
|
2021-01-28 09:09:07 +00:00
|
|
|
appendRecaptchaScript();
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Clears the cached memoization of the default manager.
|
|
|
|
*
|
|
|
|
* This is needed for determinism in tests.
|
|
|
|
*/
|
|
|
|
export const clearMemoizeCache = () => {
|
|
|
|
initRecaptchaScript.cache.clear();
|
|
|
|
};
|