2023-05-04 04:42:37 +00:00
|
|
|
import urlman
|
2022-12-11 04:03:14 +00:00
|
|
|
from django.db import models
|
2023-07-15 18:37:34 +00:00
|
|
|
from pydantic import BaseModel
|
|
|
|
|
|
|
|
|
|
|
|
class PushSubscriptionSchema(BaseModel):
|
|
|
|
"""
|
|
|
|
Basic validating schema for push data
|
|
|
|
"""
|
|
|
|
|
|
|
|
class Keys(BaseModel):
|
|
|
|
p256dh: str
|
|
|
|
auth: str
|
|
|
|
|
|
|
|
endpoint: str
|
|
|
|
keys: Keys
|
|
|
|
alerts: dict[str, bool]
|
|
|
|
policy: str
|
2022-12-11 04:03:14 +00:00
|
|
|
|
|
|
|
|
|
|
|
class Token(models.Model):
|
|
|
|
"""
|
|
|
|
An (access) token to call the API with.
|
|
|
|
|
|
|
|
Can be either tied to a user, or app-level only.
|
|
|
|
"""
|
|
|
|
|
|
|
|
application = models.ForeignKey(
|
|
|
|
"api.Application",
|
|
|
|
on_delete=models.CASCADE,
|
|
|
|
related_name="tokens",
|
|
|
|
)
|
|
|
|
|
|
|
|
user = models.ForeignKey(
|
|
|
|
"users.User",
|
|
|
|
blank=True,
|
|
|
|
null=True,
|
|
|
|
on_delete=models.CASCADE,
|
|
|
|
related_name="tokens",
|
|
|
|
)
|
|
|
|
|
|
|
|
identity = models.ForeignKey(
|
|
|
|
"users.Identity",
|
|
|
|
blank=True,
|
|
|
|
null=True,
|
|
|
|
on_delete=models.CASCADE,
|
|
|
|
related_name="tokens",
|
|
|
|
)
|
|
|
|
|
2023-01-01 18:46:55 +00:00
|
|
|
token = models.CharField(max_length=500, unique=True)
|
2022-12-11 04:03:14 +00:00
|
|
|
scopes = models.JSONField()
|
|
|
|
|
|
|
|
created = models.DateTimeField(auto_now_add=True)
|
|
|
|
updated = models.DateTimeField(auto_now=True)
|
2023-01-01 18:46:55 +00:00
|
|
|
revoked = models.DateTimeField(blank=True, null=True)
|
2023-02-19 18:37:02 +00:00
|
|
|
|
2023-07-15 18:37:34 +00:00
|
|
|
push_subscription = models.JSONField(blank=True, null=True)
|
|
|
|
|
2023-05-04 04:42:37 +00:00
|
|
|
class urls(urlman.Urls):
|
|
|
|
edit = "/@{self.identity.handle}/settings/tokens/{self.id}/"
|
|
|
|
|
2023-02-19 18:37:02 +00:00
|
|
|
def has_scope(self, scope: str):
|
|
|
|
"""
|
|
|
|
Returns if this token has the given scope.
|
|
|
|
It's a function so we can do mapping/reduction if needed
|
|
|
|
"""
|
|
|
|
# TODO: Support granular scopes the other way?
|
|
|
|
scope_prefix = scope.split(":")[0]
|
|
|
|
return (scope in self.scopes) or (scope_prefix in self.scopes)
|
2023-07-15 18:37:34 +00:00
|
|
|
|
|
|
|
def set_push_subscription(self, data: dict):
|
|
|
|
# Validate schema and assign
|
|
|
|
self.push_subscription = PushSubscriptionSchema(**data).dict()
|
|
|
|
self.save()
|