Skip to content

Commit

Permalink
Merge 145a606 into c8a470e
Browse files Browse the repository at this point in the history
  • Loading branch information
sboily committed Oct 9, 2014
2 parents c8a470e + 145a606 commit 17c338c
Show file tree
Hide file tree
Showing 7 changed files with 144 additions and 3 deletions.
25 changes: 23 additions & 2 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,30 @@ Flask-WTF
.. image:: https://coveralls.io/repos/lepture/flask-wtf/badge.png?branch=master
:target: https://coveralls.io/r/lepture/flask-wtf

Simple integration of Flask and WTForms, including CSRF, file upload
and Recaptcha integration.
Simple integration of Flask and WTForms, including CSRF, file upload, Recaptcha and are you a human integration.

For more information please refer to the online docs:

https://flask-wtf.readthedocs.org


This version was patch to support Are you a human from http://areyouahuman.com.

On the dashboard configuration from are you a human, you need to select game style : embedded.

You need to add : AYAH_PUBLISHER_KEY and AYAH_PUBLISHER_KEY to your flask conf.py for exemple.

Example
=======

In form.py

from flask.ext.wtf import AreYouAHumanField

[...]

areyouahuman = AreYouAHumanField(_('Human ?'))

In your template with a macro jinja2 render_field

{{ render_field(form.areyouahuman) }}
1 change: 1 addition & 0 deletions flask_wtf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,6 @@
from .form import Form
from .csrf import CsrfProtect
from .recaptcha import *
from .areyouahuman import *

__version__ = '0.10.2'
4 changes: 4 additions & 0 deletions flask_wtf/areyouahuman/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# flake8: noqa
from .fields import *
from .validators import *
from .widgets import *
19 changes: 19 additions & 0 deletions flask_wtf/areyouahuman/fields.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# -*- coding: utf-8 -*-

from wtforms.fields import Field

from . import widgets
from .validators import AreYouAHuman

__all__ = ["AreYouAHumanField"]


class AreYouAHumanField(Field):
widget = widgets.AreYouAHumanWidget()

# error message if AreYouAHuman validation fails
areyouahuman_error = None

def __init__(self, label='', validators=None, **kwargs):
validators = validators or [AreYouAHuman()]
super(AreYouAHumanField, self).__init__(label, validators, **kwargs)
48 changes: 48 additions & 0 deletions flask_wtf/areyouahuman/validators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# -*- coding: utf-8 -*-

try:
import urllib2 as http
except ImportError:
# Python 3
from urllib import request as http

from flask import request, current_app, json
from wtforms import ValidationError
from werkzeug import url_encode

__all__ = ["AreYouAHuman"]


class AreYouAHuman(object):
"""Validates an are You a Human ?"""

def __init__(self, message=u'Invalid game score. Please try again.'):
self.message = message

def __call__(self, form, field):
config = current_app.config
if current_app.testing and 'WTF_AYAH_PUBLISHER_KEY' not in config:
return True

challenge = request.form.get('session_secret', '')
remote_ip = request.remote_addr

if not challenge:
raise ValidationError(field.gettext(self.message))

if not self._validate_areyouahuman(challenge, remote_ip):
raise ValidationError(field.gettext(self.message))

def _validate_areyouahuman(self, challenge, remote_addr):
config = current_app.config
server = config.get('WTF_AYAH_SERVER', 'ws.areyouahuman.com')
data = {'scoring_key': config['WTF_AYAH_SCORING_KEY'],
'session_secret': challenge}
scoring_url = "https://{}/ws/scoreGame".format(server)
values = url_encode(data)
response = http.urlopen(scoring_url, values)
result = False
if response.code == 200:
content = json.loads(response.readline())
result = content['status_code']
return result
47 changes: 47 additions & 0 deletions flask_wtf/areyouahuman/widgets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# -*- coding: utf-8 -*-

try:
from urlparse import urljoin
except ImportError:
# Python 3
from urllib.parse import urljoin

from flask import current_app, Markup
from werkzeug import url_encode, url_quote
from .._compat import text_type

__all__ = ["AreYouAHumanWidget"]


class AreYouAHumanWidget(object):

def areyouahuman_html(self, server, query, html):
return Markup(html % dict(
script_url='%schallenge?%s' % (server, query),
frame_url='%snoscript?%s' % (server, query)
))

def __call__(self, field, error=None, **kwargs):
"""Returns the areyouahuman input HTML."""

current_app.config.setdefault('WTF_AYAH_SERVER', 'ws.areyouahuman.com')
try:
public_key = current_app.config['WTF_AYAH_PUBLISHER_KEY']
except KeyError:
raise RuntimeError("WTF_AYAH_PUBLISHER_KEY/WTF_AYAH_SCORING_KEY \
config not set")
query_options = dict(k=public_key)

if field.areyouahuman_error is not None:
query_options['error'] = text_type(field.areyouahuman_error)

query = url_encode(query_options)

server = current_app.config['WTF_AYAH_SERVER']
publisher_url = urljoin("https://{}/ws/script/".format(server),
url_quote(public_key, safe=''))
publisher_html = "<div id=\"AYAH\"></div> \
<script type=\"text/javascript\" src=\"{}\"> \
</script>".format(publisher_url)

return self.areyouahuman_html(server, query, publisher_html)
3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
long_description=__doc__,
packages=[
'flask_wtf',
'flask_wtf.recaptcha'
'flask_wtf.recaptcha',
'flask_wtf.areyouahuman'
],
test_suite='nose.collector',
zip_safe=False,
Expand Down

0 comments on commit 17c338c

Please sign in to comment.