overleaf/services/web/frontend/js/features/form-helpers/captcha.js
Jakob Ackermann 8e77ada424 Merge pull request #6417 from overleaf/jpa-device-history
[web] add cookie/JWE based device history for skipping captcha challenge

GitOrigin-RevId: b091564bfd93f7e587d396c860fd864f220f4b63
2022-01-27 09:03:34 +00:00

53 lines
1.3 KiB
JavaScript

import { postJSON } from '../../infrastructure/fetch-json'
const grecaptcha = window.grecaptcha
let recaptchaId
const recaptchaCallbacks = []
export async function canSkipCaptcha(email) {
const controller = new AbortController()
const signal = controller.signal
const timer = setTimeout(() => {
controller.abort()
}, 1000)
let canSkip
try {
canSkip = await postJSON('/login/can-skip-captcha', {
signal,
body: { email },
swallowAbortError: false,
})
} catch (e) {
canSkip = false
} finally {
clearTimeout(timer)
}
return canSkip
}
export async function validateCaptchaV2() {
if (
// Detect blocked recaptcha
typeof grecaptcha === 'undefined' ||
// Detect stubbed recaptcha
typeof grecaptcha.render !== 'function' ||
typeof grecaptcha.execute !== 'function' ||
typeof grecaptcha.reset !== 'function'
) {
return
}
if (recaptchaId === undefined) {
const el = document.getElementById('recaptcha')
recaptchaId = grecaptcha.render(el, {
callback: token => {
recaptchaCallbacks.splice(0).forEach(cb => cb(token))
grecaptcha.reset(recaptchaId)
},
})
}
return await new Promise(resolve => {
recaptchaCallbacks.push(resolve)
grecaptcha.execute(recaptchaId)
})
}