কনফিগার করি
প্রথমে লাইব্রেরি ইনস্টল করি
pip install djangorestframework-authtoken
প্রজেক্টের সাথে যুক্ত করি
#settings.py
INSTALLED_APPS = [
# ...
'rest_framework.authtoken',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
ডেটাবেজ মাইগ্রেট করি ফলে ডেটাবেজে টোকেন সেভ হবে
python manage.py migrate
ইউজার রেজিস্ট্রেশন লগইন লগআউট এর জন্য সিরিয়ালিজার ,ভিউ ও রাউট বানাই
# serializers.py
views.py
urls.py
Create Registration And Login System
# serializers.py
from rest_framework import serializers
from django.contrib.auth.models import User
class UserRegistrationSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=True)
password = serializers.CharField(write_only=True)
class Meta:
model = User
fields = ('username', 'password', 'email')
def create(self, validated_data):
user = User(
username=validated_data['username'],
email=validated_data['email']
)
user.set_password(validated_data['password'])
user.save()
return user
# Registration
from rest_framework.generics import CreateAPIView
from django.contrib.auth.models import User
from .serializers import UserRegistrationSerializer
class UserRegistrationView(CreateAPIView):
queryset = User.objects.all()
serializer_class = UserRegistrationSerializer
# Login
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
class CustomObtainAuthToken(ObtainAuthToken):
def post(self, request, *args, **kwargs):
email = request.data.get('email')
password = request.data.get('password')
if email is None or password is None:
return Response({'error': 'Please provide both email and password.'}, status=HTTP_400_BAD_REQUEST)
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
return Response({'error': 'User not found.'}, status=HTTP_404_NOT_FOUND)
if not user.check_password(password):
return Response({'error': 'Invalid password.'}, status=HTTP_401_UNAUTHORIZED)
token, created = Token.objects.get_or_create(user=user)
return Response({'token': token.key, 'user_id': user.id})
# views.py
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
class UserLogoutView(APIView):
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
def post(self, request):
request.auth.delete()
return Response({'message': 'Successfully logged out.'}, status=status.HTTP_200_OK)
# urls.py
from django.urls import path
from .views import UserRegistrationView, CustomObtainAuthToken
urlpatterns = [
path('api/register/', UserRegistrationView.as_view(), name='user-registration'),
path('api/login/', CustomObtainAuthToken.as_view(), name='user-login'),
]
যেভাবে ভিউকে প্রটেক্ট করবো
function view
class view
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import authentication_classes, permission_classes
@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])
class YourApiView(APIView):
# Your API view code here
from rest_framework.authtoken.views import ObtainAuthToken
class CustomObtainAuthToken(ObtainAuthToken):
# Customize if needed