All files / src/components TurnstileWidget.vue

100% Statements 28/28
91.66% Branches 11/12
100% Functions 6/6
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65  7x                         7x 7x   7x 7x 7x 7x   7x 7x 7x   1x 1x 1x   6x 5x         1x 1x   1x 1x         7x 2x 2x       1x 1x     7x                  
<template>
  <div ref="container" class="turnstile-widget" data-testid="turnstile-widget" />
</template>
 
<script setup lang="ts">
// @implements UC-AUTH-009.1
/**
 * The Cloudflare Turnstile CAPTCHA (utils/turnstile.ts). Emits the token once
 * the visitor passes, null when it expires or fails. A token is single-use:
 * call reset() after a refused sign-up for a new one.
 */
import { onBeforeUnmount, onMounted, ref } from 'vue'
import { loadTurnstile, type TurnstileApi } from '@/utils/turnstile'
 
const props = defineProps<{ siteKey: string; action: string; language: string }>()
const emit = defineEmits<{ token: [token: string | null]; error: [] }>()
 
const container = ref<HTMLElement | null>(null)
let api: TurnstileApi | null = null
let widgetId: string | null = null
let unmounted = false
 
onMounted(async () => {
  try {
    api = await loadTurnstile()
  } catch (error) {
    console.error('[TurnstileWidget] failed to load:', error)
    emit('error')
    return
  }
  if (unmounted || !container.value) return
  widgetId = api.render(container.value, {
    sitekey: props.siteKey,
    action: props.action,
    language: props.language,
    theme: 'auto',
    callback: (token) => emit('token', token),
    'expired-callback': () => emit('token', null),
    'error-callback': () => {
      emit('token', null)
      emit('error')
    }
  })
})
 
onBeforeUnmount(() => {
  unmounted = true
  if (api && widgetId) api.remove(widgetId)
})
 
function reset() {
  emit('token', null)
  Eif (api && widgetId) api.reset(widgetId)
}
 
defineExpose({ reset })
</script>
 
<style scoped>
.turnstile-widget {
  min-height: 65px;
  margin-top: 1rem;
}
</style>