Debug School

rakesh kumar
rakesh kumar

Posted on

How to protect api using token based authentication restframewok in django

Protect Object level or class level api protection

Step 1: install Django Rest Framework, you can use the following command:

$ pip install djangorestframework
Enter fullscreen mode Exit fullscreen mode

Step 2: Update the settings.py file.

INSTALLED_APPS = [
    ...

    'rest_framework',
    'rest_framework.authtoken',
]


REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
}
Enter fullscreen mode Exit fullscreen mode

Step 3: put code in serializers.py.

from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Employee



class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email')
Enter fullscreen mode Exit fullscreen mode

Step 4: create route in settings.py.

from django.contrib import admin
from django.urls import path,include
from myaccount import views
from myaccount.views import ListUsers,CustomAuthToken
from myaccount.views import EmployeeAPIView


urlpatterns = [
    path('api/users', ListUsers.as_view()),   
    path('api/token/', CustomAuthToken.as_view()),   
]
Enter fullscreen mode Exit fullscreen mode

Step 4: create function in settings.py.

from django.shortcuts import render
from django.shortcuts import render,HttpResponse,redirect
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions
from django.contrib.auth.models import User
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
import requests
from .forms import EmployeeForm
from .models import Employee
from .serializers import EmployeeSerializer


class ListUsers(APIView):
    """
    View to list all users in the system.

    * Requires token authentication.
    * Only admin users are able to access this view.
    """
    authentication_classes = [authentication.TokenAuthentication]
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request, format=None):
        """
        Return a list of all users.
        """
        usernames = [user.username for user in User.objects.all()]
        return Response(usernames)


class CustomAuthToken(ObtainAuthToken):

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        return Response({
            'token': token.key,
            'user_id': user.pk,
            'email': user.email
        })
Enter fullscreen mode Exit fullscreen mode

Output:

http://localhost:8000/api/token/
Enter fullscreen mode Exit fullscreen mode

Image description

http://localhost:8000/api/users/
Enter fullscreen mode Exit fullscreen mode

Image description

Protect Function level or Function level api protection

import in view.py

from rest_framework.authtoken.models import Token
from rest_framework.decorators import api_view, permission_classes,authentication_classes
from rest_framework.authentication import  TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
Enter fullscreen mode Exit fullscreen mode

step2 set route in settings.py

path('api/myquestion_analysis/', views.api_question_analysis, name='api_question_analysis'),
Enter fullscreen mode Exit fullscreen mode

in view.py

@api_view(['POST'])
@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])   
@csrf_exempt    
def api_question_analysis(request):
    authentication_classes = [authentication.TokenAuthentication]
    permission_classes = [permissions.IsAuthenticated]
    openai.api_key = settings.OPENAI_API_KEY
    message = request.POST.get('message')
    response = openai.Completion.create(
                engine='text-davinci-003',
                prompt=message,
                max_tokens=100,
                temperature=0,                
                top_p=1,
                frequency_penalty=0,
                presence_penalty=0,
            )
    if response.choices:
                print('data 200 choices')
                generated_message = response.choices[0].text.strip()
                print(generated_message)
    else:
                print('data else choices')
                generated_message = 'Failed to generate response'

    category=1
    product = ChatMessage.objects.create(message=message, generated_message=generated_message,category_id=category)
    data = {'product': {
        'generated_message': product.generated_message       
    }}

    return JsonResponse(data)
Enter fullscreen mode Exit fullscreen mode

Output

http://localhost:8000/api/myquestion_analysis/
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)