-
Notifications
You must be signed in to change notification settings - Fork 25
/
ReCaptchaVuePlugin.ts
77 lines (64 loc) · 2.41 KB
/
ReCaptchaVuePlugin.ts
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
66
67
68
69
70
71
72
73
74
75
76
77
import { load as loadReCaptcha, ReCaptchaInstance } from 'recaptcha-v3'
import { App, Ref, ref, inject, InjectionKey } from 'vue'
import { IReCaptchaOptions } from './IReCaptchaOptions'
const VueReCaptchaInjectKey: InjectionKey<IReCaptchaComposition> = Symbol('VueReCaptchaInjectKey')
interface IGlobalConfig {
loadedWaiters: Array<({resolve: (resolve: boolean) => void, reject: (reject: Error) => void})>
error: Error | null
}
const globalConfig: IGlobalConfig = {
loadedWaiters: [],
error: null
}
export const VueReCaptcha = {
install (app: App, options: IReCaptchaOptions) {
const isLoaded = ref(false)
const instance: Ref<ReCaptchaInstance | undefined> = ref(undefined)
app.config.globalProperties.$recaptchaLoaded = recaptchaLoaded(isLoaded)
initializeReCaptcha(options).then((wrapper) => {
isLoaded.value = true
instance.value = wrapper
app.config.globalProperties.$recaptcha = recaptcha(instance)
app.config.globalProperties.$recaptchaInstance = instance
globalConfig.loadedWaiters.forEach((v) => v.resolve(true))
}).catch((error) => {
globalConfig.error = error
globalConfig.loadedWaiters.forEach((v) => v.reject(error))
})
app.provide(VueReCaptchaInjectKey, {
instance,
isLoaded,
executeRecaptcha: recaptcha(instance),
recaptchaLoaded: recaptchaLoaded(isLoaded)
})
}
}
export function useReCaptcha (): IReCaptchaComposition | undefined {
return inject(VueReCaptchaInjectKey)
}
async function initializeReCaptcha (options: IReCaptchaOptions): Promise<ReCaptchaInstance> {
return await loadReCaptcha(options.siteKey, options.loaderOptions)
}
function recaptchaLoaded (isLoaded: Ref<boolean>) {
// eslint-disable-next-line @typescript-eslint/promise-function-async
return () => new Promise<boolean>((resolve, reject) => {
if (globalConfig.error !== null) {
return reject(globalConfig.error)
}
if (isLoaded.value) {
return resolve(true)
}
globalConfig.loadedWaiters.push({ resolve, reject })
})
}
function recaptcha (instance: Ref<ReCaptchaInstance | undefined>) {
return async (action: string): Promise<string | undefined> => {
return await instance.value?.execute(action)
}
}
export interface IReCaptchaComposition {
isLoaded: Ref<boolean>
instance: Ref<ReCaptchaInstance | undefined>
executeRecaptcha: (action: string) => Promise<string>
recaptchaLoaded: () => Promise<boolean>
}