Captcha.vue 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <template>
  2. <div class="d-flex flex-column">
  3. <vue-hcaptcha
  4. :sitekey="siteKey"
  5. challenge-container="captchaBox"
  6. @verify="onVerify"
  7. @expired="onExpire"
  8. @challenge-expired="onChallengeExpire"
  9. @error="onError"
  10. />
  11. <v-checkbox
  12. v-model="honeyPotChecked"
  13. :rules="[validateCaptchaState]"
  14. class="hidden-ctrl"
  15. />
  16. <div id="captchaBox"></div>
  17. </div>
  18. </template>
  19. <script setup lang="ts">
  20. import VueHcaptcha from '@hcaptcha/vue3-hcaptcha'
  21. import type { Ref } from 'vue'
  22. const runtimeConfig = useRuntimeConfig()
  23. const siteKey = runtimeConfig.public.hCaptchaSiteKey
  24. const verified: Ref<boolean> = ref(false)
  25. const expired: Ref<boolean> = ref(false)
  26. const token: Ref<string> = ref('')
  27. const eKey: Ref<string> = ref('')
  28. const error: Ref<string> = ref('')
  29. // La case étant masquée, si elle est cochée, alors on peut en déduire
  30. // qu'on a affaire un robot (voir mécanisme du honey pot)
  31. const honeyPotChecked: Ref<boolean> = ref(false)
  32. const emit = defineEmits(['update'])
  33. const validateCaptchaState = () =>
  34. (verified.value && !honeyPotChecked.value) ||
  35. 'Veuillez procéder à la vérification'
  36. function onVerify(tokenStr: string, ekey: string) {
  37. verified.value = true
  38. token.value = tokenStr
  39. eKey.value = ekey
  40. emit('update', true)
  41. }
  42. function onExpire() {
  43. verified.value = false
  44. token.value = ''
  45. eKey.value = ''
  46. expired.value = true
  47. }
  48. function onChallengeExpire() {
  49. verified.value = false
  50. token.value = ''
  51. eKey.value = ''
  52. expired.value = true
  53. }
  54. function onError(err: string) {
  55. token.value = ''
  56. eKey.value = ''
  57. error.value = err
  58. console.log(`Error: ${err}`)
  59. if (process.dev) {
  60. console.log('Dev mode: force captcha validation')
  61. verified.value = true
  62. }
  63. }
  64. </script>
  65. <style scoped lang="scss">
  66. .hidden-ctrl {
  67. :deep(.v-input__control) {
  68. display: none;
  69. }
  70. }
  71. </style>