Skip to content

Commit

Permalink
API Key Creation & Management
Browse files Browse the repository at this point in the history
Added functionality for superusers and users to create and manage API keys, with Knox integration for secure key hashing.
  • Loading branch information
NEZRI Ygal authored and NEZRI Ygal committed Jul 22, 2024
1 parent 695dad3 commit e63422d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 13 deletions.
24 changes: 18 additions & 6 deletions Watcher/Watcher/accounts/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
from knox.models import AuthToken
from .serializers import UserSerializer, LoginSerializer, UserPasswordChangeSerializer
from django.utils import timezone
from django.contrib.auth.models import User
from hashlib import sha256
from django.contrib.auth.hashers import make_password, check_password


# Login API
Expand All @@ -13,9 +16,10 @@ def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data
raw_key, _ = generate_api_key(user)
return Response({
"user": UserSerializer(user, context=self.get_serializer_context()).data,
"token": AuthToken.objects.create(user)[1]
"token": raw_key
})


Expand All @@ -38,9 +42,17 @@ class PasswordChangeViewSet(viewsets.ModelViewSet):
serializer_class = UserPasswordChangeSerializer


# Generate API Key
def generate_api_key(user, expiration):
expiry = timezone.timedelta(days=expiration)
token_instance, raw_key = AuthToken.objects.create(user=user, expiry=expiry)
# Generate Api Key
def generate_api_key(user, expiration_days=30):
expiry = timezone.timedelta(days=expiration_days)
token_instance, raw_key = AuthToken.objects.create(user, expiry=expiry)

return raw_key, token_instance
# Generate hash using pbkdf2_sha256
hashed_key = make_password(raw_key, salt=None, hasher='pbkdf2_sha256')

if raw_key:
print(f"API Key generated for user {user.username}: {raw_key}")
return raw_key, hashed_key
else:
print(f"Failed to generate API Key for user {user.username}")
return None, None
15 changes: 8 additions & 7 deletions Watcher/Watcher/accounts/models.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
from django.db import models
from django_auth_ldap.backend import populate_user
from django.contrib.auth.models import User
from knox.models import AuthToken


class APIKey(models.Model):
"""
Manages creation, modification, and deletion of user API keys.
"""
auth_token = models.OneToOneField(AuthToken, on_delete=models.CASCADE, null=True, blank=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
key = models.CharField(max_length=100, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
expiration = models.IntegerField(default=30)
expiry_at = models.DateTimeField(null=True, blank=True)
key_details = models.TextField(null=True, blank=True) # Ajout de ce champ

def __str__(self):
return f"API Key for {self.auth_token.user.username}"
return f"API Key for {self.user.username}"

class Meta:
verbose_name = "API Key"
Expand All @@ -23,4 +23,5 @@ def make_inactive(sender, user, **kwargs):
if not User.objects.filter(username=user.username):
user.is_active = False


populate_user.connect(make_inactive)

0 comments on commit e63422d

Please sign in to comment.