Reputation: 21
I see the error {"detail": "Authentication credentials were not provided." }
.
This is the code I am using for Login
My Model:
class User(AbstractBaseUser):
STUDENT = 'STU'
SCHOOL = 'SCH'
INSTITUTE = 'INST'
TUTOR = 'TUT'
ACCOUNT_TYPE_CHOICES = [
(STUDENT, 'Student'),
(SCHOOL, 'School'),
(INSTITUTE, 'Institute'),
(TUTOR, 'Tutor'),
]
account_type = models.CharField(
max_length=4,
choices=ACCOUNT_TYPE_CHOICES,
default=SCHOOL,
)
name = models.CharField(max_length=255)
email = models.EmailField(unique=True,max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name','account_type']
objects=UserManager()
def __str__(self):
return self.email
def has_perm(self,perm,obj=None):
return True
def has_module_perms(self,app_label):
return True
@property
def is_staff(self):
return self.is_admin
My serializers:
from rest_framework import serializers
from .models import User
from django.contrib.auth import authenticate
# User Serializer
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'account_type', 'name', 'email')
# Login Serializer
# I guess the validate function is not working .
class LoginSerializer(serializers.Serializer):
email = serializers.EmailField()
password = serializers.CharField()
def validate(self, data):
user = authenticate(request=None,**data)
if user and user.is_active:
return user
raise serializers.ValidationError("Incorrect Credentials")
My Views:
from rest_framework import generics, permissions,authentication
from rest_framework.response import Response
from knox.models import AuthToken
from knox.views import LoginView as KnoxLoginView
from .serializers import UserSerializer, RegisterSerializer, LoginSerializer
from django.contrib.auth import authenticate,login
# Login API
class LoginAPI(generics.GenericAPIView):
serializer_class = LoginSerializer
# authentication_class=[authentication.BasicAuthentication]
def post(self, request, *args, **kwargs):
serializer = LoginSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data
return Response({
"user": UserSerializer(user, context=self.get_serializer_context()).data,
"token": AuthToken.objects.create(user)[1]
})
My Urls:
from django.urls import path, include
from .api import RegisterAPI, LoginAPI
from knox import views as knox_views
urlpatterns = [
path('api/auth/', include('knox.urls')),
path('api/auth/register/', RegisterAPI.as_view()),
path('api/auth/login/', LoginAPI.as_view()),
path('api/auth/logout/', knox_views.LogoutView.as_view(), name='knox_logout')
]
Also when I provide the token generated while registration, it gives user is inactive or dead.But when i check my database and the token expiry time its still active. I have tried different third party libraries like rest-auth it also gives the same error.I have checked many other answers regarding the same topic too but applying them also isn't helping.
Upvotes: 2
Views: 763
Reputation: 1
I already had a similar problem and the solution was to set the Authorization token in the Postman headers
Upvotes: 0
Reputation: 11
You should confirm from your settings.py file in the REST_FRAMEWORK settings that you have the 'DEFAULT_PERMISSION_CLASSES' set to 'rest_framework.permissions.AllowAny'.
it should be like:
# Rest framework
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
],
}
Upvotes: 1