Files @ 3b1b440b5082
Branch filter:

Location: kallithea/kallithea/lib/recaptcha.py

Mads Kiilerich
celery: use the proper configured global app for scheduling and retrieving tasks

193138922d56 broke celery, due to magic dependencies on initialization and
setting global configuration at import time.

Instead, always use the correctly configured global Celery app, both when
creating tasks and checking result status.

This has been tested to work on Python 3.6 - for example for sending mails and
forking repos.

Celery has however been found to not work on Python 3.7, due to Celery 3.x
using the new reserved keyword 'async'.
# -*- coding: utf-8 -*-
import json
import urllib.parse
import urllib.request


class RecaptchaResponse(object):
    def __init__(self, is_valid, error_code=None):
        self.is_valid = is_valid
        self.error_code = error_code

    def __repr__(self):
        return '<RecaptchaResponse:%s>' % (self.is_valid)


def submit(g_recaptcha_response, private_key, remoteip):
    """
    Submits a reCAPTCHA request for verification. Returns RecaptchaResponse for the request

    g_recaptcha_response -- The value of g_recaptcha_response from the form
    private_key -- your reCAPTCHA private key
    remoteip -- the user's IP address
    """

    if not (g_recaptcha_response and len(g_recaptcha_response)):
        return RecaptchaResponse(is_valid=False, error_code='incorrect-captcha-sol')

    def encode_if_necessary(s):
        if isinstance(s, str):
            return s.encode('utf-8')
        return s

    params = urllib.parse.urlencode({
        'secret': encode_if_necessary(private_key),
        'remoteip': encode_if_necessary(remoteip),
        'response': encode_if_necessary(g_recaptcha_response),
    }).encode('ascii')

    req = urllib.request.Request(
        url="https://www.google.com/recaptcha/api/siteverify",
        data=params,
        headers={
            "Content-type": "application/x-www-form-urlencoded",
            "User-agent": "reCAPTCHA Python"
        }
    )

    httpresp = urllib.request.urlopen(req)
    return_values = json.loads(httpresp.read())
    httpresp.close()

    if not (isinstance(return_values, dict)):
        return RecaptchaResponse(is_valid=False, error_code='incorrect-captcha-sol')
    elif (("success" in return_values) and ((return_values["success"] is True) or (return_values["success"] == "true"))):
        return RecaptchaResponse(is_valid=True)
    elif (("error-codes" in return_values) and isinstance(return_values["error-codes"], list) and (len(return_values["error-codes"]) > 0)):
        return RecaptchaResponse(is_valid=False, error_code=return_values["error-codes"][0])
    else:
        return RecaptchaResponse(is_valid=False, error_code='incorrect-captcha-sol')