musescore-downloader/src/recaptcha.ts

49 lines
1.2 KiB
TypeScript
Raw Normal View History

2020-03-08 21:36:37 +00:00
/**
* the site key for Google reCAPTCHA v3
*/
2020-05-17 22:57:28 +00:00
const SITE_KEY = '6Ldxtt8UAAAAALvcRqWTlVOVIB7MmEWwN-zw_9fM'
2020-03-08 21:36:37 +00:00
type token = string;
interface GRecaptcha {
2020-05-17 22:57:28 +00:00
ready (cb: Function): void;
execute (siteKey: string, opts: { action: string }): Promise<token>;
2020-03-08 21:36:37 +00:00
}
let gr: GRecaptcha | Promise<GRecaptcha>
/**
* load reCAPTCHA
*/
const load = (): Promise<GRecaptcha> => {
2020-05-17 22:57:28 +00:00
// load script
const script = document.createElement('script')
script.src = `https://www.recaptcha.net/recaptcha/api.js?render=${SITE_KEY}`
script.async = true
document.body.appendChild(script)
// add css
const style = document.createElement('style')
style.innerHTML = '.grecaptcha-badge { display: none !important; }'
document.head.appendChild(style)
return new Promise((resolve) => {
script.onload = (): void => {
const grecaptcha: GRecaptcha = window['grecaptcha']
grecaptcha.ready(() => resolve(grecaptcha))
}
})
2020-03-08 21:36:37 +00:00
}
2020-05-17 22:57:28 +00:00
export const init = (): GRecaptcha | Promise<GRecaptcha> => {
if (!gr) {
gr = load()
}
return gr
2020-03-08 21:36:37 +00:00
}
export const execute = async (): Promise<token> => {
2020-05-17 22:57:28 +00:00
const captcha = await init()
return captcha.execute(SITE_KEY, { action: 'downloadmscz' })
2020-03-08 21:36:37 +00:00
}