Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: combining v2 and v3 #91

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions example/combined/api/recaptcha.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { useBody } from 'h3'
import { $fetch } from 'ohmyfetch/node'

/**
* It is highly recommended to use enviroment variables instead of hardcoded secrets.
*/
const SECRET_KEYS = {
'2': '6LecsLIaAAAAABd-yNkMXt_rf7GjWaxVJDlWryYy', // v2 secret key
'3': '6LfembIaAAAAACcZlTsRvwf62fuCGXfR7e2HIj8S' // v3 secret key
}

/**
* This is an example that demonstrates how verifying reCAPTCHA on the server side works.
* Do not use this middleware in your production.
*/
export default async (req, res) => {
res.setHeader('Content-Type', 'application/json')
try {
const { token, v } = await useBody(req)

if (!SECRET_KEYS[v]) {
res.end(JSON.stringify({
success: false,
message: 'Invalid version'
}))
return
}

if (!token) {
res.end(JSON.stringify({
success: false,
message: 'Invalid token'
}))
return
}
const response = await $fetch(
`https://www.google.com/recaptcha/api/siteverify?secret=${SECRET_KEYS[v]}&response=${token}`
)

if (response.success) {
res.end(JSON.stringify({
success: true,
message: 'Token verifyed',
response: response
}))
} else {
res.end(JSON.stringify({
success: false,
message: 'Invalid token',
response: response
}))
}
} catch (e) {
console.log('ReCaptcha error:', e)
res.end(JSON.stringify({
success: false,
message: 'Internal error'
}))
}
}
24 changes: 24 additions & 0 deletions example/combined/nuxt.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const { resolve } = require('path')

module.exports = {
buildDir: resolve(__dirname, '.nuxt'),

modules: [
['../../lib/module', {
hideBadge: true,
siteKey: [
'6LecsLIaAAAAAEeBOiX7b4rSwMDNL9zhIXlPNEB1', // v2 site key
'6LfembIaAAAAACPEdfjUpSmmYqMyJZn-ZU0aFUvb' // v3 site key
]
}]
],

serverMiddleware: [
{ path: '/api/check-token', handler: '~/api/recaptcha' }
],

srcDir: __dirname,

render: { resourceHints: false },
rootDir: resolve(__dirname, '..')
}
8 changes: 8 additions & 0 deletions example/combined/pages/about.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<template>
<section class="about-page">
<h2>About page</h2>
<p>Text</p>

<nuxt-link :to="{ name: 'index' }">Go to Index</nuxt-link>
</section>
</template>
119 changes: 119 additions & 0 deletions example/combined/pages/index.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
<template>
<section class="index-page">
<h2>With v2</h2>

<form @submit.prevent="onSubmitV2">
<input
v-model="email"
autocomplete="true"
placeholder="Email"
type="email"
>
<input
v-model="password"
autocomplete="current-password"
placeholder="Password"
type="password"
>
<recaptcha
@error="onError"
@success="onSuccess"
@expired="onExpired"
/>

<button type="submit">
Sign In
</button>
</form>

<hr>
<h2>With v3</h2>

<form @submit.prevent="onSubmitV3">
<input
v-model="email"
autocomplete="true"
placeholder="Email"
type="email"
>
<input
v-model="password"
autocomplete="current-password"
placeholder="Password"
type="password"
>
<button type="submit">
Sign In
</button>
</form>
<hr>
<nuxt-link :to="{ name: 'about' }">About</nuxt-link>
</section>
</template>

<script>
export default {
data: () => ({
email: '[email protected]',
password: '123'
}),

async mounted() {
try {
await this.$recaptcha.init()
} catch (e) {
console.log(e)
}
},

methods: {
async onSubmitV2() {
try {
const token = await this.$recaptcha.getResponse()
console.log('v2 ReCaptcha token:', token)
const response = await fetch('/api/check-token', {
method: 'POST',
body: JSON.stringify({
v: 2,
token,
email: this.email,
password: this.password
})
}).then(res => res.json())
console.log('v2 Server Response: ', response)
await this.$recaptcha.reset()
} catch (error) {
console.log('v2 Login error:', error)
}
},
async onSubmitV3() {
try {
const token = await this.$recaptcha.execute('login')
console.log('v3 ReCaptcha token:', token)
const response = await fetch('/api/check-token', {
method: 'POST',
body: JSON.stringify({
v: 3,
token,
email: this.email,
password: this.password
})
}).then(res => res.json())
console.log('v3 Server Response: ', response)
} catch (error) {
console.log('v3 Login error:', error)
}
},
onSuccess(token) {
console.log('v2 Succeeded:', token)
},

onExpired() {
console.log('v2 Expired')
},
onError(error) {
console.log('v2 Error happened:', error)
}
}
}
</script>
50 changes: 37 additions & 13 deletions lib/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ class ReCaptcha {
throw new Error('ReCaptcha error: No key provided')
}

if (!version) {
if (!version && !Array.isArray(siteKey)) {
throw new Error('ReCaptcha error: siteKey must be array when version not provided')
} else if (!version && typeof(siteKey) == 'string') {
throw new Error('ReCaptcha error: No version provided')
}

Expand All @@ -26,6 +28,18 @@ class ReCaptcha {
this.size = size
}

get siteKeyV2() {
if (this.version === 2) return this.siteKey;
else if (Array.isArray(this.siteKey)) return this.siteKey[0];
else return null;
}

get siteKeyV3() {
if (this.version === 3) return this.siteKey;
else if (Array.isArray(this.siteKey)) return this.siteKey[1];
else return null;
}

destroy () {
if (this._ready) {
this._ready = false
Expand All @@ -43,11 +57,13 @@ class ReCaptcha {
if (head.contains(style)) {
head.removeChild(style)
}

const badge = document.querySelector('.grecaptcha-badge')
if (badge) {
badge.remove()
}

delete window.grecaptcha;
}
}

Expand All @@ -57,7 +73,7 @@ class ReCaptcha {

if ('grecaptcha' in window) {
return window.grecaptcha.execute(
this.siteKey,
this.siteKeyV3,
{ action }
)
}
Expand Down Expand Up @@ -117,7 +133,7 @@ class ReCaptcha {
script.setAttribute('defer', '')

const params = []
if (this.version === 3) { params.push('render=' + this.siteKey) }
if (this.siteKeyV3) { params.push('render=' + this.siteKeyV3) }
if (this.language) { params.push('hl=' + this.language) }
script.setAttribute('src', API_URL + '?' + params.join('&'))

Expand All @@ -127,12 +143,7 @@ class ReCaptcha {

this._ready = new Promise((resolve, reject) => {
script.addEventListener('load', () => {
if (this.version === 3 && this.hideBadge) {
style.innerHTML = '.grecaptcha-badge { display: none }'
document.head.appendChild(style)
} else if(this.version === 2 && this.hideBadge) {
// display: none DISABLES the spam checking!
// ref: https://stackoverflow.com/questions/44543157/how-to-hide-the-google-invisible-recaptcha-badge
if (this.hideBadge) {
style.innerHTML = '.grecaptcha-badge { visibility: hidden; }'
document.head.appendChild(style)
}
Expand All @@ -156,14 +167,27 @@ class ReCaptcha {
return this._eventBus.on(event, callback)
}

off (event, callback) {
return this._eventBus.off(event, callback)
}

reset (widgetId) {
if (this.version === 2 || typeof widgetId !== 'undefined') {
if (this.siteKeyV2 || typeof widgetId !== 'undefined') {
window.grecaptcha.reset(widgetId)
}
}

render (reference, { sitekey, theme }) {
return window.grecaptcha.render(reference.$el || reference, { sitekey, theme })
render (reference, options) {
return window.grecaptcha.render(reference.$el || reference, Object.assign({
"sitekey": this.siteKeyV2,
"size": this.size
},
options,
{
"callback": "recaptchaSuccessCallback",
"expired-callback": "recaptchaExpiredCallback",
"error-callback": "recaptchaErrorCallback",
}));
}
}

Expand Down
39 changes: 19 additions & 20 deletions lib/recaptcha.vue
Original file line number Diff line number Diff line change
@@ -1,16 +1,5 @@
<template>
<div
:data-sitekey="siteKey || $recaptcha.siteKey"
:data-size="computedDataSize"
:data-theme="dataTheme"
:data-badge="dataBadge"
:data-tabindex="dataTabindex"

data-callback="recaptchaSuccessCallback"
data-expired-callback="recaptchaExpiredCallback"
data-error-callback="recaptchaErrorCallback"
class="g-recaptcha"
/>
<div class="g-recaptcha" />
</template>

<script>
Expand Down Expand Up @@ -53,24 +42,34 @@ export default {
type: Number
}
},

computed: {
computedDataSize() {
return (this.dataSize || this.$recaptcha.size) || 'normal'
}
},
beforeDestroy() {
this.$recaptcha.destroy()
this.$recaptcha.off('recaptcha-error', this.onError)
this.$recaptcha.off('recaptcha-success', this.onSuccess)
this.$recaptcha.off('recaptcha-expired', this.onExpired)
},

mounted() {
this.$recaptcha.init()
this.$recaptcha.init().then(() => {
this.$recaptcha.render(this, {
siteKey: this.siteKey || this.$recaptcha.siteKeyV2,
size: this.computedDataSize,
theme: this.dataTheme,
badge: this.dataBadge,
tabindex: this.dataTabindex
})
})

this.$recaptcha.on('recaptcha-error', this.onError)
this.$recaptcha.on('recaptcha-success', this.onSuccess)
this.$recaptcha.on('recaptcha-expired', this.onExpired)
},

computed: {
computedDataSize() {
return (this.dataSize || this.$recaptcha.size) || 'normal'
}
},

methods: {
onError(message) {
return this.$emit('error', message)
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"dev": "nuxt example/both",
"dev:v3": "nuxt example/v3",
"dev:v2": "nuxt example/v2",
"dev:combined": "nuxt example/combined",
"lint": "eslint lib test",
"test": "yarn lint && jest",
"release": "standard-version && git push --follow-tags && npm publish"
Expand Down
Loading