mirror of
https://github.com/netbox-community/netbox.git
synced 2025-12-21 04:42:22 -06:00
Add a REST API endpoint to provision new tokens using username & password
This commit is contained in:
@@ -1,8 +1,12 @@
|
||||
from django.contrib.auth import authenticate
|
||||
from django.contrib.auth.models import Group, User
|
||||
from django.db.models import Count
|
||||
from rest_framework.exceptions import AuthenticationFailed
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.routers import APIRootView
|
||||
from rest_framework.status import HTTP_201_CREATED
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.viewsets import ViewSet
|
||||
|
||||
from netbox.api.views import ModelViewSet
|
||||
@@ -56,6 +60,34 @@ class TokenViewSet(ModelViewSet):
|
||||
return queryset.filter(user=self.request.user)
|
||||
|
||||
|
||||
class TokenProvisionView(APIView):
|
||||
"""
|
||||
Non-authenticated REST API endpoint via which a user may create a Token.
|
||||
"""
|
||||
permission_classes = []
|
||||
swagger_schema = None # TODO: Generate a schema
|
||||
|
||||
def post(self, request):
|
||||
serializer = serializers.TokenProvisionSerializer(data=request.data)
|
||||
serializer.is_valid()
|
||||
|
||||
# Authenticate the user account based on the provided credentials
|
||||
user = authenticate(
|
||||
request=request,
|
||||
username=serializer.data['username'],
|
||||
password=serializer.data['password']
|
||||
)
|
||||
if user is None:
|
||||
raise AuthenticationFailed("Invalid username/password")
|
||||
|
||||
# Create a new Token for the User
|
||||
token = Token(user=user)
|
||||
token.save()
|
||||
data = serializers.TokenSerializer(token, context={'request': request}).data
|
||||
|
||||
return Response(data, status=HTTP_201_CREATED)
|
||||
|
||||
|
||||
#
|
||||
# ObjectPermissions
|
||||
#
|
||||
|
||||
Reference in New Issue
Block a user