|
|
import { loadScript } from '@automattic/load-script'; |
|
|
import debugFactory from 'debug'; |
|
|
|
|
|
const debug = debugFactory( 'calypso:analytics:recaptcha' ); |
|
|
|
|
|
const GOOGLE_RECAPTCHA_SCRIPT_URL = 'https://www.google.com/recaptcha/api.js?render=explicit'; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async function loadGoogleRecaptchaScript() { |
|
|
if ( window.grecaptcha ) { |
|
|
|
|
|
return true; |
|
|
} |
|
|
|
|
|
try { |
|
|
const src = GOOGLE_RECAPTCHA_SCRIPT_URL; |
|
|
await loadScript( src ); |
|
|
debug( 'loadGoogleRecaptchaScript: [Loaded]', src ); |
|
|
return true; |
|
|
} catch ( error ) { |
|
|
debug( 'loadGoogleRecaptchaScript: [Load Error] the script failed to load: ', error ); |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async function renderRecaptchaClient( elementId, siteKey ) { |
|
|
try { |
|
|
const clientId = await window.grecaptcha.render( elementId, { |
|
|
sitekey: siteKey, |
|
|
size: 'invisible', |
|
|
} ); |
|
|
debug( 'renderRecaptchaClient: [Success]', elementId ); |
|
|
return clientId; |
|
|
} catch ( error ) { |
|
|
debug( 'renderRecaptchaClient: [Error]', error ); |
|
|
return null; |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export async function recordGoogleRecaptchaAction( clientId, action ) { |
|
|
if ( ! window.grecaptcha ) { |
|
|
debug( |
|
|
'recordGoogleRecaptchaAction: [Error] window.grecaptcha not defined. Did you forget to init?' |
|
|
); |
|
|
return null; |
|
|
} |
|
|
|
|
|
try { |
|
|
const token = await window.grecaptcha.execute( clientId, { action } ); |
|
|
debug( 'recordGoogleRecaptchaAction: [Success]', action, token, clientId ); |
|
|
return token; |
|
|
} catch ( error ) { |
|
|
debug( 'recordGoogleRecaptchaAction: [Error]', action, error ); |
|
|
return null; |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export async function initGoogleRecaptcha( elementId, siteKey ) { |
|
|
if ( ! siteKey ) { |
|
|
return null; |
|
|
} |
|
|
|
|
|
if ( ! ( await loadGoogleRecaptchaScript() ) ) { |
|
|
return null; |
|
|
} |
|
|
|
|
|
await new Promise( ( resolve ) => window.grecaptcha.ready( resolve ) ); |
|
|
|
|
|
try { |
|
|
const clientId = await renderRecaptchaClient( elementId, siteKey ); |
|
|
if ( clientId == null ) { |
|
|
return null; |
|
|
} |
|
|
|
|
|
debug( 'initGoogleRecaptcha: [Success]', clientId ); |
|
|
return clientId; |
|
|
} catch ( error ) { |
|
|
|
|
|
|
|
|
debug( 'initGoogleRecaptcha: [Error]', error ); |
|
|
return null; |
|
|
} |
|
|
} |
|
|
|