captcha.js 1.3 KB

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