# Path: app/api/models.py
# class ApiKey(TimestampMixin):
#     """Model representing clients' api keys."""
# 
#     token = HashidField(
#         min_length=32,
#         alphabet='0123456789abcdef',
#         default=timestamp_seconds,
#         unique=True,
#         editable=False
#     )
#     revoked = models.BooleanField(default=False)
#     owner = models.ForeignKey(User, on_delete=models.CASCADE)
# 
#     def clean(self):
#         if not self.owner.is_superuser:
#             raise ValidationError(_('Ensure the owner is a superuser.'))
# 
#         super().clean()
# 
#     def save(self, *args, **kwargs):
#         self.full_clean()
#         return super().save(*args, **kwargs)
# 
#     def __str__(self):
#         return self.token.hashid


from base64 import b64decode
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.http import JsonResponse
from django.views import View
from .models import ApiKey
    @classmethod
    def authenticate_user(cls, request):
        if 'HTTP_AUTHORIZATION' not in request.META:
            data = {'message': 'Use Basic Auth and supply your username and password.'}
            return JsonResponse(data, status=401)

        auth = request.META['HTTP_AUTHORIZATION'].split()
        if len(auth) != 2 and auth[0].lower() != 'basic':
            data = {'message': 'Use Basic Auth and supply your username and password.'}
            return JsonResponse(data, status=401)

        uname, passwd = b64decode(auth[1]).decode('utf-8').split(':')
        user = authenticate(username=uname, password=passwd)
        if user is None:
            data = {'message': 'Invalid Credentials.'}
            return JsonResponse(data, status=401)

        return user

    def post(self, request, **kwargs):
        if kwargs:
            data = {'message': 'Bad Request.'}
            return JsonResponse(data, status=400)

        response = self.authenticate_user(request)

        if not isinstance(response, User):
            return response

        try:

# Path: app/api/models.py
# class ApiKey(TimestampMixin):
#     """Model representing clients' api keys."""
# 
#     token = HashidField(
#         min_length=32,
#         alphabet='0123456789abcdef',
#         default=timestamp_seconds,
#         unique=True,
#         editable=False
#     )
#     revoked = models.BooleanField(default=False)
#     owner = models.ForeignKey(User, on_delete=models.CASCADE)
# 
#     def clean(self):
#         if not self.owner.is_superuser:
#             raise ValidationError(_('Ensure the owner is a superuser.'))
# 
#         super().clean()
# 
#     def save(self, *args, **kwargs):
#         self.full_clean()
#         return super().save(*args, **kwargs)
# 
#     def __str__(self):
#         return self.token.hashid


# Path: app/api/views.py
from base64 import b64decode
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.http import JsonResponse
from django.views import View
from .models import ApiKey

    @classmethod
    def authenticate_user(cls, request):
        if 'HTTP_AUTHORIZATION' not in request.META:
            data = {'message': 'Use Basic Auth and supply your username and password.'}
            return JsonResponse(data, status=401)

        auth = request.META['HTTP_AUTHORIZATION'].split()
        if len(auth) != 2 and auth[0].lower() != 'basic':
            data = {'message': 'Use Basic Auth and supply your username and password.'}
            return JsonResponse(data, status=401)

        uname, passwd = b64decode(auth[1]).decode('utf-8').split(':')
        user = authenticate(username=uname, password=passwd)
        if user is None:
            data = {'message': 'Invalid Credentials.'}
            return JsonResponse(data, status=401)

        return user

    def post(self, request, **kwargs):
        if kwargs:
            data = {'message': 'Bad Request.'}
            return JsonResponse(data, status=400)

        response = self.authenticate_user(request)

        if not isinstance(response, User):
            return response

        try:

            api_key, created = ApiKey.objects.get_or_create(owner=response, revoked=False)