Skip to content

Commit c4203fb

Browse files
committed
Added py4web/utils/racaptcha.py, to use:
from py4web.utils.recaptcha import ReCaptcha auth.extra_form_fields = {"login": [recaptcha.field]} auth.enable(uses=(session, T, db, recaptcha.fixture), env=dict(T=T)) and add [[=recaptcha]] to yourapp/templates/auth.html
1 parent 89846ce commit c4203fb

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

py4web/utils/recaptcha.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import requests
2+
from yatl.helpers import XML
3+
4+
from py4web.core import Field, Fixture, request
5+
6+
7+
class recaptcha_fixture(Fixture):
8+
def __init__(self, api_key):
9+
self.api_key = api_key
10+
Fixture.__init__(self)
11+
12+
def on_request(self, context):
13+
value = request.POST.get("g-recaptcha-response")
14+
if value:
15+
request.POST["g_recaptcha_response"] = value
16+
del request.POST["g-recaptcha-response"]
17+
18+
def on_success(self, context):
19+
context["output"]["recaptcha"] = XML(
20+
"""<script>
21+
var field = document.querySelector("input[name=g_recaptcha_response]");
22+
if(field) {
23+
field.hidden = true;
24+
var form = document.querySelector(".auth-container form");
25+
var button = form.querySelector("input[type=submit]");
26+
window.recaptcha_submit = function(token){ form.submit(); };
27+
button.setAttribute("class", "g-recaptcha");
28+
button.setAttribute("data-action", "submit");
29+
button.setAttribute("data-callback", "recaptcha_submit");
30+
button.setAttribute("data-sitekey", "%s");
31+
}
32+
</script>
33+
<script src="https://www.google.com/recaptcha/api.js"></script>
34+
"""
35+
% self.api_key
36+
)
37+
38+
39+
class ReCaptcha:
40+
def __init__(self, api_key, api_secret):
41+
self.api_key = api_key
42+
self.api_secret = api_secret
43+
44+
@property
45+
def fixture(self):
46+
return recaptcha_fixture(self.api_key)
47+
48+
@property
49+
def field(self):
50+
return Field("g_recaptcha_response", requires=self.validator, label="")
51+
52+
@property
53+
def script(self):
54+
return recaptcha_script(self.api_key)
55+
56+
def validator(self, value, _):
57+
data = {"secret": self.api_secret, "response": value}
58+
res = requests.post(
59+
"https://www.google.com/recaptcha/api/siteverify", data=data
60+
)
61+
try:
62+
if res.json()["success"]:
63+
return (True, None)
64+
return (False, "Invalid ReCaptcha response")
65+
except exc:
66+
return (False, str(exc))

0 commit comments

Comments
 (0)