mpeltriaux
3938db1893
* adds token checking to AbstractModelAPIView * adds user accessibility filtering for intervention API v1 * extends fetch_and_serialize() method to take a dict for db filtering instead of a single field and value * organizes urlnames into supporting formats like "api:v1:intervention"
49 lines
1.3 KiB
Python
49 lines
1.3 KiB
Python
from django.core.exceptions import ObjectDoesNotExist
|
|
from django.db import models
|
|
from django.utils import timezone
|
|
|
|
from konova.utils.generators import generate_token
|
|
|
|
|
|
class APIUserToken(models.Model):
|
|
token = models.CharField(
|
|
primary_key=True,
|
|
max_length=1000,
|
|
default=generate_token,
|
|
)
|
|
valid_until = models.DateField(
|
|
blank=True,
|
|
null=True,
|
|
help_text="Token is only valid until this date",
|
|
)
|
|
is_active = models.BooleanField(
|
|
default=False,
|
|
help_text="Must be activated by an admin"
|
|
)
|
|
|
|
def __str__(self):
|
|
return self.token
|
|
|
|
@staticmethod
|
|
def get_user_from_token(token: str):
|
|
""" Getter for the related user object
|
|
|
|
Args:
|
|
token (str): The used token
|
|
|
|
Returns:
|
|
user (User): Otherwise None
|
|
"""
|
|
_today = timezone.now().date()
|
|
try:
|
|
token_obj = APIUserToken.objects.get(
|
|
token=token,
|
|
)
|
|
if not token_obj.is_active:
|
|
raise PermissionError("Token unverified")
|
|
if token_obj.valid_until is not None and token_obj.valid_until < _today:
|
|
raise PermissionError("Token validity expired")
|
|
except ObjectDoesNotExist:
|
|
raise PermissionError("Token invalid")
|
|
return token_obj.user
|