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

Allow nonce in reCaptcha #312

Open
wants to merge 1 commit 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
5 changes: 4 additions & 1 deletion flask_wtf/recaptcha/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ class RecaptchaField(Field):

# error message if recaptcha validation fails
recaptcha_error = None
# nonce
nonce = None

def __init__(self, label='', validators=None, **kwargs):
def __init__(self, label='', validators=None, nonce=None, **kwargs):
validators = validators or [Recaptcha()]
self.nonce = nonce
super(RecaptchaField, self).__init__(label, validators, **kwargs)
13 changes: 9 additions & 4 deletions flask_wtf/recaptcha/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
JSONEncoder = json.JSONEncoder

RECAPTCHA_SCRIPT = u'https://www.google.com/recaptcha/api.js'
RECAPTCHA_NONCE = u' nonce="%s"'
RECAPTCHA_TEMPLATE = u'''
<script src='%s' async defer></script>
<script src='%s' async defer%s></script>
<div class="g-recaptcha" %s></div>
'''

Expand All @@ -16,7 +17,7 @@

class RecaptchaWidget(object):

def recaptcha_html(self, public_key):
def recaptcha_html(self, public_key, nonce=None):
html = current_app.config.get('RECAPTCHA_HTML')
if html:
return Markup(html)
Expand All @@ -25,10 +26,14 @@ def recaptcha_html(self, public_key):
if params:
script += u'?' + url_encode(params)

nonce_attr = ''
if nonce is not None:
nonce_attr = RECAPTCHA_NONCE % nonce

attrs = current_app.config.get('RECAPTCHA_DATA_ATTRS', {})
attrs['sitekey'] = public_key
snippet = u' '.join([u'data-%s="%s"' % (k, attrs[k]) for k in attrs])
return Markup(RECAPTCHA_TEMPLATE % (script, snippet))
return Markup(RECAPTCHA_TEMPLATE % (script, nonce_attr, snippet))

def __call__(self, field, error=None, **kwargs):
"""Returns the recaptcha input HTML."""
Expand All @@ -38,4 +43,4 @@ def __call__(self, field, error=None, **kwargs):
except KeyError:
raise RuntimeError('RECAPTCHA_PUBLIC_KEY config not set')

return self.recaptcha_html(public_key)
return self.recaptcha_html(public_key, nonce=field.nonce)
13 changes: 13 additions & 0 deletions tests/test_recaptcha.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ class Meta:
recaptcha = RecaptchaField()


class RecaptchaNonceForm(FlaskForm):
class Meta:
csrf = False

recaptcha = RecaptchaField(nonce='foobar')


@pytest.fixture
def app(app):
app.testing = False
Expand Down Expand Up @@ -53,6 +60,12 @@ def test_render_has_js():
assert 'https://www.google.com/recaptcha/api.js' in render


def test_render_has_nonce():
f = RecaptchaNonceForm()
render = f.recaptcha()
assert 'nonce="foobar"' in render


def test_render_custom_html(app):
app.config['RECAPTCHA_HTML'] = 'custom'
f = RecaptchaForm()
Expand Down