79 lines
2.6 KiB
Python
79 lines
2.6 KiB
Python
import json
|
|
from base64 import urlsafe_b64encode
|
|
|
|
from django.contrib.auth import get_user_model
|
|
from django.test import Client, TestCase
|
|
from django.urls import reverse
|
|
from djangoldp_webpushnotification.models import VAPIDKeyset
|
|
from ecdsa import NIST256p, SigningKey
|
|
from webpush.models import PushInformation, SubscriptionInfo
|
|
|
|
|
|
class TestAcceptSubscription(TestCase):
|
|
def setUp(self):
|
|
self.client = Client()
|
|
self.user = get_user_model().objects.create(
|
|
username="john", email="jlennon@beatles.com", password="glass onion"
|
|
)
|
|
self.client.force_login(self.user)
|
|
|
|
def tearDown(self):
|
|
self.user.delete()
|
|
|
|
def gen_vapid_key(self):
|
|
generated = SigningKey.generate(curve=NIST256p)
|
|
encoded = urlsafe_b64encode(generated.to_string()).strip(b"=")
|
|
return VAPIDKeyset.objects.create(private_key=encoded)
|
|
|
|
def test_accept_sub(self):
|
|
vapid_key_set = self.gen_vapid_key()
|
|
|
|
payload = {
|
|
"status_type": "subscribe",
|
|
"subscription": {
|
|
"endpoint": "https://hubl.example.com",
|
|
"keys": {
|
|
"auth": "front-end-generated-secret",
|
|
"p256dh": vapid_key_set.public_key.decode("utf-8"),
|
|
},
|
|
},
|
|
"browser": "firefox",
|
|
}
|
|
|
|
url = reverse("save_webpush_info")
|
|
response = self.client.post(
|
|
url, data=json.dumps(payload), content_type="application/json"
|
|
)
|
|
|
|
self.assertEqual(response.status_code, 201)
|
|
|
|
sub_info = SubscriptionInfo.objects.get()
|
|
self.assertEqual(sub_info.browser, "firefox")
|
|
self.assertEqual(sub_info.endpoint, "https://hubl.example.com")
|
|
self.assertEqual(sub_info.auth, "front-end-generated-secret")
|
|
self.assertEqual(sub_info.p256dh, vapid_key_set.public_key.decode("utf-8"))
|
|
|
|
push_info = PushInformation.objects.get()
|
|
self.assertEqual(push_info.user, self.user)
|
|
self.assertEqual(push_info.subscription, sub_info)
|
|
|
|
def test_accept_sub_missing_vapid_key(self):
|
|
payload = {
|
|
"status_type": "subscribe",
|
|
"subscription": {
|
|
"endpoint": "https://hubl.example.com",
|
|
"keys": {
|
|
"auth": "front-end-generated-secret",
|
|
"p256dh": "INVALID-PUBLIC-KEY",
|
|
},
|
|
},
|
|
"browser": "firefox",
|
|
}
|
|
|
|
url = reverse("save_webpush_info")
|
|
response = self.client.post(
|
|
url, data=json.dumps(payload), content_type="application/json"
|
|
)
|
|
|
|
self.assertEqual(response.status_code, 403)
|