Mercurial > kallithea
view kallithea/lib/recaptcha.py @ 8751:ad239692ea95
mail: fix duplicate "From" headers
Problem introduced in 9a0c41175e66: When iterating the headers dict and setting
"msg[key] = value", it wasn't replacing the header but performing add_header so
we sometimes ended up with two From headers.
It is also a general problem that while the headers dict only can contain each
key once, it can contain entries that only differ in casing and thus will fold
to the same message header, making it possible to end up adding duplicate
headers.
"msg.replace_header(key, value)" is not a simple solution to the problem: it
will raise KeyError if no such previous key exists.
Now, make the problem more clear by explicitly using add_header.
Avoid the duplication problem by deleting the key (no matter which casing)
before invoking add_header. Delete promises that "No exception is raised if the
named field isn’t present in the headers".
author | Mads Kiilerich <mads@kiilerich.com> |
---|---|
date | Wed, 04 Nov 2020 00:35:21 +0100 |
parents | 620c13a373c5 |
children |
line wrap: on
line source
# -*- 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')