captcha.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import 'abort-controller/polyfill'
  2. import { postJSON } from '../../infrastructure/fetch-json'
  3. const grecaptcha = window.grecaptcha
  4. let recaptchaId
  5. const recaptchaCallbacks = []
  6. export async function canSkipCaptcha(email) {
  7. let timer
  8. let canSkip
  9. try {
  10. const controller = new AbortController()
  11. const signal = controller.signal
  12. timer = setTimeout(() => {
  13. controller.abort()
  14. }, 1000)
  15. canSkip = await postJSON('/login/can-skip-captcha', {
  16. signal,
  17. body: { email },
  18. swallowAbortError: false,
  19. })
  20. } catch (e) {
  21. canSkip = false
  22. } finally {
  23. clearTimeout(timer)
  24. }
  25. return canSkip
  26. }
  27. export async function validateCaptchaV2() {
  28. if (
  29. // Detect blocked recaptcha
  30. typeof grecaptcha === 'undefined' ||
  31. // Detect stubbed recaptcha
  32. typeof grecaptcha.render !== 'function' ||
  33. typeof grecaptcha.execute !== 'function' ||
  34. typeof grecaptcha.reset !== 'function'
  35. ) {
  36. return
  37. }
  38. if (recaptchaId === undefined) {
  39. const el = document.getElementById('recaptcha')
  40. recaptchaId = grecaptcha.render(el, {
  41. callback: token => {
  42. recaptchaCallbacks.splice(0).forEach(cb => cb(token))
  43. grecaptcha.reset(recaptchaId)
  44. },
  45. })
  46. }
  47. return await new Promise(resolve => {
  48. recaptchaCallbacks.push(resolve)
  49. grecaptcha.execute(recaptchaId)
  50. })
  51. }