本文整理汇总了Python中twilio.util.RequestValidator.validate方法的典型用法代码示例。如果您正苦于以下问题:Python RequestValidator.validate方法的具体用法?Python RequestValidator.validate怎么用?Python RequestValidator.validate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twilio.util.RequestValidator
的用法示例。
在下文中一共展示了RequestValidator.validate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: decorator
# 需要导入模块: from twilio.util import RequestValidator [as 别名]
# 或者: from twilio.util.RequestValidator import validate [as 别名]
def decorator(request_or_self, *args, **kwargs):
class_based_view = not isinstance(request_or_self, HttpRequest)
if not class_based_view:
request = request_or_self
else:
assert len(args) >= 1
request = args[0]
# Turn off Twilio authentication when explicitly requested, or
# in debug mode. Otherwise things do not work properly. For
# more information, see the docs.
use_forgery_protection = getattr(
settings,
'DJANGO_TWILIO_FORGERY_PROTECTION',
not settings.DEBUG,
)
if use_forgery_protection:
if request.method not in ['GET', 'POST']:
return HttpResponseNotAllowed(request.method)
# Forgery check
try:
validator = RequestValidator(TWILIO_AUTH_TOKEN)
url = request.build_absolute_uri()
signature = request.META['HTTP_X_TWILIO_SIGNATURE']
except (AttributeError, KeyError):
return HttpResponseForbidden()
if request.method == 'POST':
if not validator.validate(url, request.POST, signature):
return HttpResponseForbidden()
if request.method == 'GET':
if not validator.validate(url, request.GET, signature):
return HttpResponseForbidden()
# Blacklist check, by default is true
check_blacklist = getattr(
settings,
'DJANGO_TWILIO_BLACKLIST_CHECK',
True
)
if check_blacklist:
blacklisted_resp = get_blacklisted_response(request)
if blacklisted_resp:
return blacklisted_resp
response = f(request_or_self, *args, **kwargs)
if isinstance(response, (text_type, bytes)):
return HttpResponse(response, content_type='application/xml')
elif isinstance(response, Verb):
return HttpResponse(str(response), content_type='application/xml')
else:
return response
示例2: decorator
# 需要导入模块: from twilio.util import RequestValidator [as 别名]
# 或者: from twilio.util.RequestValidator import validate [as 别名]
def decorator(request, *args, **kwargs):
# Here we'll use the twilio library's request validation code to ensure
# that the current request actually came from twilio, and isn't a
# forgery if settings.DEBUG is True. If it is a forgery, then we'll
#return a HTTP 403 error (forbidden).
if not settings.DEBUG:
try:
url = request.build_absolute_uri()
signature = request.META['HTTP_X_TWILIO_SIGNATURE']
except (AttributeError, KeyError):
return HttpResponseForbidden()
validator = RequestValidator(settings.TWILIO_AUTH_TOKEN)
if not validator.validate(url, request.POST, signature):
return HttpResponseForbidden()
# Run the wrapped view, and capture the data returned.
response = require_POST(f(request, *args, **kwargs))
else:
response = f(request, *args, **kwargs)
# If the view returns a string, we'll assume it is XML TwilML data and
# pass it back with the appropriate mimetype. We won't check the XML
# data because that would be too time consuming for every request.
# Instead, we'll let the errors pass through to be dealt with by the
# developer.
if isinstance(response, Verb):
return HttpResponse(response, mimetype='text/xml')
else:
return response
示例3: decorated
# 需要导入模块: from twilio.util import RequestValidator [as 别名]
# 或者: from twilio.util.RequestValidator import validate [as 别名]
def decorated(*args, **kwargs):
print request.values
if 'CallSid' not in request.values:
return abort(401, 'Request must be a signed Twilio request.')
if validate and False:
validator = RequestValidator(settings.TWILIO_AUTH_TOKEN)
sig_header = request.headers.get('X-Twilio-Signature', '')
if request.method == 'POST':
vparams = request.form
vurl = request.url
else:
vparams = {}
vurl = request.url
# validator params are called URL, POST vars, and signature
if not validator.validate(vurl, vparams, sig_header):
return abort(401, 'Request signature could not be validated')
# load the call from Mongo or create if one does not exist
g.call = load_call(request.values['CallSid'], request.values)
g.zipcode = read_context('zipcode', None)
g.legislator = read_context('legislator', None)
twilio_response = func(*args, **kwargs)
return Response(str(twilio_response), mimetype='application/xml')
示例4: test_international_sms
# 需要导入模块: from twilio.util import RequestValidator [as 别名]
# 或者: from twilio.util.RequestValidator import validate [as 别名]
def test_international_sms(self):
token = os.environ["TWILIO_AUTH_TOKEN"]
validator = RequestValidator(token)
uri = "http://www.postbin.org/1c2pdoc"
params = {
"AccountSid": "AC4bf2dafb92341f7caf8650403e422d23",
"ApiVersion": "2010-04-01",
"Body": "Chloéñ",
"From": "+15305451766",
"FromCity": "SOUTH LAKE TAHOE",
"FromCountry": "US",
"FromState": "CA",
"FromZip": "89449",
"SmsMessageSid": "SM51d6d055f53f1072543872c601aae89b",
"SmsStatus": "SM51d6d055f53f1072543872c601aae89b",
"SmsStatus": "received",
"To": "+15304194304",
"ToCity": "WOODLAND",
"ToCountry": "US",
"ToState": "CA",
"ToZip": "95695",
}
expected = "UHkWu+6WLOzPunzb8PuCGPeW1Uw="
self.assertEquals(validator.compute_signature(uri, params), expected)
self.assertTrue(validator.validate(uri, params, expected))
示例5: validate
# 需要导入模块: from twilio.util import RequestValidator [as 别名]
# 或者: from twilio.util.RequestValidator import validate [as 别名]
def validate(self, request):
validator = RequestValidator(self.auth[1])
signature = request.META.get('HTTP_X_TWILIO_SIGNATURE', '')
base_url = settings.TEMBA_HOST
url = "https://%s%s" % (base_url, request.get_full_path())
return validator.validate(url, request.POST, signature)
示例6: get
# 需要导入模块: from twilio.util import RequestValidator [as 别名]
# 或者: from twilio.util.RequestValidator import validate [as 别名]
def get(self):
client = TwilioRestClient(account_sid, auth_token)
validator = RequestValidator(auth_token)
url = self.request.url
params = {}
try:
twilio_signature = self.request.headers["X-Twilio-Signature"]
logging.debug(twilio_signature)
except:
twilio_signature = ""
if validator.validate(url, params, twilio_signature):
logging.debug("Validated")
call_id = self.request.get('to_call')
print call_id
infos = Call.query(Call.key==ndb.Key(Call, int(call_id))).fetch()
print infos
for info in infos:
print info
for i in json.loads(info.calls):
print i
call_out = client.calls.create(to=i, from_="2065576875",
url="https://teen-link.appspot.com/make-calls?RecordingUrl=" + self.request.get("RecordingUrl"),
method="GET",
if_machine="Continue")
print call_out
else:
self.response.headers['Content-Type'] = 'text/html'
self.response.write("Please don't try to hack me.")
示例7: SMSReceiver
# 需要导入模块: from twilio.util import RequestValidator [as 别名]
# 或者: from twilio.util.RequestValidator import validate [as 别名]
class SMSReceiver(ApplicationSession):
webapp = Klein()
logger = Logger()
def __init__(self, config):
ApplicationSession.__init__(self)
self.t_token = config.extra["twilio-token"]
self.t_receiver = config.extra["twilio-receiver"]
self.t_validator = RequestValidator(self.t_token)
self.logger.info("receiving SMS at %s" % '/'+ SMS_EVENT.replace('.','/'))
def onConnect(self):
self.join("realm1")
reactor.listenTCP(9090, Site(self.webapp.resource()))
def validSignature(self, request):
signature = request.getHeader("X-Twilio-Signature")
if not signature:
return False
return self.t_validator.validate(self.t_receiver, request.args, signature)
@webapp.route('/'+ SMS_EVENT.replace('.','/'), methods=['POST'])
@inlineCallbacks
def receive(self, request):
"publish incoming new SMS as (sender, recipient, message)"
if self.validSignature(request):
form = request.args
msg = (form["sender"], form["recipient"], form["message"])
yield self.session.publish(SMS_EVENT, msg)
returnValue(succeed(None))
else:
request.setResponseCode(401)
signature = request.getHeader("X-Twilio-Signature") or "(no signature)"
returnValue("Missing or invalid signature: %s" % signature)
示例8: hello
# 需要导入模块: from twilio.util import RequestValidator [as 别名]
# 或者: from twilio.util.RequestValidator import validate [as 别名]
def hello():
"""Respond to incoming requests."""
resp = twiml.Response()
first_request = True
twilio_account_sid = os.environ.get("TWILIO_ACCOUNT_SID")
twilio_auth_token = os.environ.get("TWILIO_AUTH_TOKEN")
twilio_number = os.environ.get("TWILIO_NUMBER")
validator = RequestValidator(twilio_auth_token)
if 'X-Twilio-Signature' not in request.headers:
if first_request:
first_request = False
else:
abort(401)
else:
my_url = request.url
if my_url.startswith('http://'):
my_url = my_url.replace("http", "https")
params = request.form
twilio_signature = request.headers['X-Twilio-Signature']
if validator.validate(my_url, params, twilio_signature):
resp.say("Hello! Welcome to the telephone fizz buzz game!")
with resp.gather(timeout=10, finishOnKey="*", action="/handle-key", method="POST") as g:
g.say("Please enter your number and then press star.")
else:
abort(401)
return str(resp)
示例9: decorator
# 需要导入模块: from twilio.util import RequestValidator [as 别名]
# 或者: from twilio.util.RequestValidator import validate [as 别名]
def decorator(request_or_self, methods=['POST'],
blacklist=True, *args, **kwargs):
class_based_view = not(isinstance(request_or_self, HttpRequest))
if not class_based_view:
request = request_or_self
else:
assert len(args) >= 1
request = args[0]
# Turn off Twilio authentication when in debug mode otherwise
# things do not work properly. For more information see the docs
if not settings.DEBUG:
if request.method not in methods:
return HttpResponseNotAllowed(request.method)
# Forgery check
try:
validator = RequestValidator(
django_twilio_settings.TWILIO_AUTH_TOKEN)
url = request.build_absolute_uri()
signature = request.META['HTTP_X_TWILIO_SIGNATURE']
except (AttributeError, KeyError):
return HttpResponseForbidden()
if request.method == 'POST':
if not validator.validate(url, request.POST, signature):
return HttpResponseForbidden()
if request.method == 'GET':
if not validator.validate(url, request.GET, signature):
return HttpResponseForbidden()
# Blacklist check
if blacklist:
blacklisted_resp = get_blacklisted_response(request)
if blacklisted_resp:
return blacklisted_resp
response = f(request_or_self, *args, **kwargs)
if isinstance(response, str):
return HttpResponse(response, content_type='application/xml')
elif isinstance(response, Verb):
return HttpResponse(str(response), content_type='application/xml')
else:
return response
示例10: decorator
# 需要导入模块: from twilio.util import RequestValidator [as 别名]
# 或者: from twilio.util.RequestValidator import validate [as 别名]
def decorator(request, *args, **kwargs):
# Only handle Twilio forgery protection stuff if we're running in
# production. This way, developers can test their Twilio view code
# without getting errors.
if not settings.DEBUG:
# Attempt to gather all required information to allow us to check the
# incoming HTTP request for forgery. If any of this information is not
# available, then we'll throw a HTTP 403 error (forbidden).
#
# The required fields to check for forged requests are:
#
# 1. ``TWILIO_ACCOUNT_SID`` (set in the site's settings module).
# 2. ``TWILIO_AUTH_TOKEN`` (set in the site's settings module).
# 3. The full URI of the request, eg: 'http://mysite.com/test/view/'.
# This may not necessarily be available if this view is being
# called via a unit testing library, or in certain localized
# environments.
# 4. A special HTTP header, ``HTTP_X_TWILIO_SIGNATURE`` which
# contains a hash that we'll use to check for forged requests.
# Ensure the request method is POST
response = require_POST(f)(request, *args, **kwargs)
if isinstance(response, HttpResponse):
return response
# Validate the request
try:
validator = RequestValidator(django_twilio_settings.TWILIO_AUTH_TOKEN)
url = request.build_absolute_uri()
signature = request.META['HTTP_X_TWILIO_SIGNATURE']
except (AttributeError, KeyError):
return HttpResponseForbidden()
# Now that we have all the required information to perform forgery
# checks, we'll actually do the forgery check.
if not validator.validate(url, request.POST, signature):
return HttpResponseForbidden()
# If the user requesting service is blacklisted, reject their
# request.
blacklisted_resp = get_blacklisted_response(request)
if blacklisted_resp:
return blacklisted_resp
# Run the wrapped view, and capture the data returned.
response = f(request, *args, **kwargs)
# If the view returns a string (or a ``twilio.Verb`` object), we'll
# assume it is XML TwilML data and pass it back with the appropriate
# mimetype. We won't check the XML data because that would be too time
# consuming for every request. Instead, we'll let the errors pass
# through to be dealt with by the developer.
if isinstance(response, str):
return HttpResponse(response, mimetype='application/xml')
elif isinstance(response, Verb):
return HttpResponse(str(response), mimetype='application/xml')
else:
return response
示例11: _wrapped_view
# 需要导入模块: from twilio.util import RequestValidator [as 别名]
# 或者: from twilio.util.RequestValidator import validate [as 别名]
def _wrapped_view (request, *args, **kwargs):
validator = RequestValidator(settings.TWILIO_AUTH_TOKEN)
url = settings.TWILIO_CALLBACK_URL
post = request.POST
signature = request.META.get("HTTP_X_TWILIO_SIGNATURE")
if not validator.validate(url, post, signature):
return HttpResponse("Invalid call. Are you twilio?")
return view_func(request, *args, **kwargs)
示例12: dec
# 需要导入模块: from twilio.util import RequestValidator [as 别名]
# 或者: from twilio.util.RequestValidator import validate [as 别名]
def dec(request, *args, **kwargs):
signature = request.META.get('HTTP_X_TWILIO_SIGNATURE', '')
data = dict()
for k, v in request.REQUEST.items():
data[k] = v
validator = RequestValidator(settings.TWILIO_AUTH_TOKEN)
if validator.validate(settings.TWILIO_URL, data, signature):
return func(request, *args, **kwargs)
else:
return HttpResponse(status=401)
示例13: decorator
# 需要导入模块: from twilio.util import RequestValidator [as 别名]
# 或者: from twilio.util.RequestValidator import validate [as 别名]
def decorator(request, *args, **kwargs):
# Attempt to gather all required information to allow us to check the
# incoming HTTP request for forgery. If any of this information is not
# available, then we'll throw a HTTP 403 error (forbidden).
# Ensure the request method is POST
if request.method != "POST":
logger.error(
"Twilio: Expected POST request", extra={"request": request})
return HttpResponseNotAllowed(request.method)
if not getattr(settings, "TWILIO_SKIP_SIGNATURE_VALIDATION"):
# Validate the request
try:
validator = RequestValidator(settings.TWILIO_AUTH_TOKEN)
url = request.build_absolute_uri()
# Ensure the original requested url is tested for validation
# Prevents breakage when processed behind a proxy server
if "HTTP_X_FORWARDED_SERVER" in request.META:
protocol = "https" if request.META[
"HTTP_X_TWILIO_SSL"] == "Enabled" else "http"
url = "{0}://{1}{2}".format(
protocol, request.META[
"HTTP_X_FORWARDED_SERVER"], request.META["REQUEST_URI"]
)
signature = request.META["HTTP_X_TWILIO_SIGNATURE"]
except (AttributeError, KeyError) as e:
logger.exception(
"Twilio: Missing META param", extra={"request": request})
return HttpResponseForbidden("Missing META param: %s" % e)
# Now that we have all the required information to perform forgery
# checks, we'll actually do the forgery check.
if not validator.validate(url, request.POST, signature):
logger.error(
"Twilio: Invalid url signature %s - %s - %s",
url, request.POST, signature, extra={"request": request}
)
return HttpResponseForbidden("Invalid signature")
# Run the wrapped view, and capture the data returned.
response = f(request, *args, **kwargs)
# If the view returns a string (or a ``twilio.Verb`` object), we'll
# assume it is XML TwilML data and pass it back with the appropriate
# mimetype. We won't check the XML data because that would be too time
# consuming for every request. Instead, we'll let the errors pass
# through to be dealt with by the developer.
if isinstance(response, six.text_type):
return HttpResponse(response, mimetype="application/xml")
elif isinstance(response, Verb):
return HttpResponse(force_text(response), mimetype="application/xml")
else:
return response
示例14: twilio_validator_function
# 需要导入模块: from twilio.util import RequestValidator [as 别名]
# 或者: from twilio.util.RequestValidator import validate [as 别名]
def twilio_validator_function(request):
"""returns true for authentic Twilio request, false for unauthenticated request"""
validator = RequestValidator(app.config['TWILIO_AUTH_TOKEN'])
URL = request.url
params = {}
if request.method == 'POST':
params = request.values
else:
params = request.args
twilio_signature = request.headers.get('X-Twilio-Signature')
return validator.validate(URL, params, twilio_signature)
示例15: decorator
# 需要导入模块: from twilio.util import RequestValidator [as 别名]
# 或者: from twilio.util.RequestValidator import validate [as 别名]
def decorator(*args, **kwargs):
if not current_app.config['DEBUG']:
validator = RequestValidator(current_app.config['TWILIO_AUTH_TOKEN'])
if not validator.validate(request.url, request.form, request.headers['HTTP_X_TWILIO_SIGNATURE']):
abort(401)
response = f(*args, **kwargs)
if isinstance(response, Verb):
response = str(response)
response = make_response(response)
response.mimetype = 'application/xml'
return response