Reputation: 1586
I've attempted to follow this very straight forward guide on how to prevent non-twilio requests from hitting the webhook url that I've setup for incoming twilio messages. It basically involves copying a function they've developed as a decorator and applying it to the view that handles incoming messages.
from django.http import HttpResponse, HttpResponseForbidden
from functools import wraps
from twilio import twiml
from twilio.request_validator import RequestValidator
import os
def validate_twilio_request(f):
"""Validates that incoming requests genuinely originated from Twilio"""
@wraps(f)
def decorated_function(request, *args, **kwargs):
# Create an instance of the RequestValidator class
validator = RequestValidator(os.environ.get('TWILIO_AUTH_TOKEN'))
# Validate the request using its URL, POST data,
# and X-TWILIO-SIGNATURE header
request_valid = validator.validate(
request.build_absolute_uri(),
request.POST,
request.META.get('HTTP_X_TWILIO_SIGNATURE', ''))
# Continue processing the request if it's valid, return a 403 error if
# it's not
if request_valid:
return f(request, *args, **kwargs)
else:
return HttpResponseForbidden()
return decorated_function
Unfortunately, immedialy after I apply the decorator to my view that handles incoming messages, I get this error.
Traceback (most recent call last):
File "/home/jason/lib/python3.6/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/jason/lib/python3.6/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/jason/lib/python3.6/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/jason/webapps/project/jason/jasonsproject/decorators.py", line 14, in decorated_function
validator = RequestValidator(os.environ.get('TWILIO_AUTH_TOKEN'))
File "/home/jason/lib/python3.6/twilio/request_validator.py", line 66, in __init__
self.token = token.encode("utf-8")
Exception Type: AttributeError at /incomingsmsmessages/
Exception Value: 'NoneType' object has no attribute 'encode'
Request information:
USER: AnonymousUser
GET: No GET data
Thanks for your help!
Upvotes: 0
Views: 245
Reputation: 64298
Seems like RequestValidator
doesn't accept None. This should fix it:
validator = RequestValidator(os.environ.get('TWILIO_AUTH_TOKEN', ''))
Upvotes: 2