From cfc413f7825326f97e4b82bd91dda1c570136976 Mon Sep 17 00:00:00 2001 From: James Wang Date: Wed, 23 Dec 2015 23:31:50 -0500 Subject: [PATCH] Validate recaptcha for registration --- scripts/requirements.txt | 3 ++- server/api/user.py | 14 ++++++++++++++ web/js/register.js | 9 ++++++--- 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/scripts/requirements.txt b/scripts/requirements.txt index 08461f8..e0f3b60 100644 --- a/scripts/requirements.txt +++ b/scripts/requirements.txt @@ -2,4 +2,5 @@ Flask mysql-python Flask-SQLAlchemy SQLAlchemy -gunicorn \ No newline at end of file +gunicorn +requests \ No newline at end of file diff --git a/server/api/user.py b/server/api/user.py index 53bfe13..be8bf1f 100644 --- a/server/api/user.py +++ b/server/api/user.py @@ -4,6 +4,7 @@ from flask import current_app as app from models import db, Users from utils import api_wrapper +import requests import utils blueprint = Blueprint("user", __name__) @@ -11,6 +12,9 @@ blueprint = Blueprint("user", __name__) @blueprint.route("/register", methods=["POST"]) @api_wrapper def user_register(): + if not validate_captcha(request.form): + return { "success": 0, "message": "Please do the captcha." } + name = request.form["name"] username = request.form["username"] password = request.form["password"] @@ -59,3 +63,13 @@ def add_user(name, username, email, password): user = Users(name, username, email, password) db.session.add(user) db.session.commit() + +def validate_captcha(form): + if "captcha_response" not in form: + return False + captcha_response = form["captcha_response"] + data = {"secret": "6Lc4xhMTAAAAACFaG2NyuKoMdZQtSa_1LI76BCEu", "response": captcha_response} + response = requests.post("https://www.google.com/recaptcha/api/siteverify", data=data) + if response.json()["success"]: + return True + return False diff --git a/web/js/register.js b/web/js/register.js index 7a59132..be3fb03 100644 --- a/web/js/register.js +++ b/web/js/register.js @@ -1,19 +1,22 @@ $("#registration-form").on("submit", function(e) { e.preventDefault(); - register($("#name").val(), $("#username").val(), $("#password").val(), $("#password_confirm").val(), $("#email").val()); + register($("#name").val(), $("#username").val(), $("#password").val(), $("#password_confirm").val(), $("#email").val(), $("#g-recaptcha-response").val()); }); -function register(name, username, password, password_confirm, email) { +function register(name, username, password, password_confirm, email, captcha_response) { $.post("/api/user/register", { name: name, username: username, password: password, password_confirm: password_confirm, - email: email + email: email, + captcha_response: captcha_response }, function(data) { $("#status").text(data.message); if (data.success == 1) { // wait then redirect or whatever + } else { + grecaptcha.reset(); } }); }