Reputation: 372
I want a custom authentication which will authenticate the token in my model.I have a model called User_Auth where there is a field called 'secret_token'. I want the Django Rest Framework to Authenticate token through that model. I had followed the docs on django rest framework website but didnt work for me. Please help me to solve this issue.
models.py
class User_Auth(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(User_Master, on_delete=models.CASCADE)
secret_token = models.CharField(max_length=2000, null=True, blank=True)
authentication.py
class UserAuthentication(authentication.TokenAuthentication):
def authenticate(self, request):
secret_token = request.META.get('Authorization')
if not secret_token:
return None
try:
ua = User_Auth.objects.get(secret_token=secret_token)
except User_Auth.DoesNotExist:
raise exceptions.AuthenticationFailed('Unauthorized')
return (ua, None)
views.py
class User(viewsets.ModelViewSet):
authentication_classes = (UserAuthentication,)
permission_classes = (IsAuthenticated,)
I am passing the token through the Header.
Authorization: 'a7c14fc808b58533e4d1651cd2375c3b41a38ef5d120254a1cb4bbd90b3be1534215516b023818e4'
Its Returning this error
'User_Auth' object has no attribute 'is_authenticated'
Please help me.
Upvotes: 0
Views: 6041
Reputation: 815
You are missing is_authenticated
property in User_Auth
model. This is a read only attribute and always return True
for a valid user. Django's User
class has this attribute and internally it has been used for authentication.
So to resolve the error add this attribute in User_Auth
class like following.
class User_Auth(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(User_Master, on_delete=models.CASCADE)
secret_token = models.CharField(max_length=2000, null=True, blank=True)
@property
def is_authenticated(self):
"""
Always return True. This is a way to tell if the user has been
authenticated in templates.
"""
return True
Upvotes: 2