57 lines
1.4 KiB
Python
57 lines
1.4 KiB
Python
import json
|
|
from hashlib import sha256
|
|
from hmac import compare_digest
|
|
|
|
import sentry_sdk
|
|
from django.conf import settings
|
|
from django.http import (
|
|
HttpResponse,
|
|
HttpResponseBadRequest,
|
|
HttpResponseNotFound,
|
|
HttpResponseServerError,
|
|
)
|
|
|
|
from .inbound import receiver
|
|
from .signals import incoming_message
|
|
|
|
|
|
def handle_inbound(request):
|
|
if receiver.handle is None:
|
|
return HttpResponseNotFound()
|
|
|
|
kwargs = request.GET.dict()
|
|
|
|
try:
|
|
secret = kwargs.pop("secret")
|
|
|
|
if not compare_digest(
|
|
sha256(settings.SMS_WEBHOOK_SECRET.encode("utf-8")).digest(),
|
|
sha256(secret.encode("utf-8")).digest(),
|
|
):
|
|
return HttpResponseNotFound()
|
|
except KeyError:
|
|
return HttpResponseNotFound()
|
|
|
|
kwargs |= request.POST.dict()
|
|
|
|
if request.content_type == "application/json":
|
|
try:
|
|
body = json.loads(request.read())
|
|
except json.JSONDecodeError:
|
|
return HttpResponseBadRequest()
|
|
|
|
if not isinstance(body, dict):
|
|
return HttpResponseBadRequest()
|
|
|
|
kwargs |= body
|
|
|
|
try:
|
|
incoming_message.send(receiver, messages=receiver.handle(**kwargs))
|
|
except (IndexError, KeyError, ValueError):
|
|
return HttpResponseBadRequest()
|
|
except Exception as e:
|
|
sentry_sdk.capture_exception(e)
|
|
return HttpResponseServerError()
|
|
|
|
return HttpResponse()
|