76 lines
2.4 KiB
Python
76 lines
2.4 KiB
Python
import secrets
|
|
|
|
from django.conf import settings
|
|
from django.contrib.auth.models import AbstractUser
|
|
from django.db import models
|
|
from django.utils import timezone
|
|
|
|
|
|
class User(AbstractUser):
|
|
"""Plain Django user. Accounts are created with `manage.py createsuperuser`."""
|
|
|
|
def __str__(self):
|
|
return self.username
|
|
|
|
|
|
class ApiToken(models.Model):
|
|
"""Bearer token for the Flutter app (the web admin uses session auth)."""
|
|
|
|
key = models.CharField(max_length=64, unique=True, editable=False)
|
|
user = models.ForeignKey(
|
|
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="api_tokens"
|
|
)
|
|
name = models.CharField(
|
|
max_length=100, blank=True, help_text="Which device this token is for."
|
|
)
|
|
created_at = models.DateTimeField(auto_now_add=True)
|
|
last_used_at = models.DateTimeField(null=True, blank=True)
|
|
|
|
class Meta:
|
|
ordering = ["-created_at"]
|
|
|
|
def __str__(self):
|
|
return f"{self.user} — {self.name or 'unnamed device'}"
|
|
|
|
def save(self, *args, **kwargs):
|
|
if not self.key:
|
|
self.key = secrets.token_urlsafe(32)
|
|
return super().save(*args, **kwargs)
|
|
|
|
def touch(self):
|
|
self.last_used_at = timezone.now()
|
|
self.save(update_fields=["last_used_at"])
|
|
|
|
|
|
class PushSubscription(models.Model):
|
|
"""One installed PWA that has agreed to receive reminders.
|
|
|
|
The endpoint is issued by the browser's push service; the two keys are what
|
|
let us encrypt a payload only that device can read.
|
|
"""
|
|
|
|
user = models.ForeignKey(
|
|
settings.AUTH_USER_MODEL,
|
|
on_delete=models.CASCADE,
|
|
related_name="push_subscriptions",
|
|
)
|
|
endpoint = models.URLField(max_length=500, unique=True)
|
|
p256dh = models.CharField(max_length=200)
|
|
auth = models.CharField(max_length=100)
|
|
user_agent = models.CharField(max_length=300, blank=True)
|
|
created_at = models.DateTimeField(auto_now_add=True)
|
|
last_success_at = models.DateTimeField(null=True, blank=True)
|
|
|
|
class Meta:
|
|
ordering = ["-created_at"]
|
|
|
|
def __str__(self):
|
|
return f"{self.user} — {self.user_agent[:40] or self.endpoint[:40]}"
|
|
|
|
def as_subscription_info(self) -> dict:
|
|
"""The shape pywebpush expects, i.e. what the browser handed us."""
|
|
return {
|
|
"endpoint": self.endpoint,
|
|
"keys": {"p256dh": self.p256dh, "auth": self.auth},
|
|
}
|