I need help with token-based authentication for a custom user model.
I have a User model that inherits from AbstractBaseUser
:
class User(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255, blank=True, null=True)
USERNAME_FIELD = 'email'
I have a DojoMaster
model that extends the User
model and am using a post_save
receiver:
models.py
class DojoMaster(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
phone = models.BigIntegerField()
country = models.ForeignKey(Country, on_delete=models.CASCADE)
@receiver(post_save, sender=User)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
I have added the following authentication classes:
settings.py
REST_FRAMEWORK = {
'Default_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.TokenAuthentication',
)
}
To access token authentication I have:
urls.py
urlpatterns = [
url(r'^get-token', obtain_auth_token)
]
I have the following DojoMaster
user:
{
"user": {
"name": "XYZ",
"email": "xyz@mail.com",
"password": "p@55w0rd"
},
"username": "iAmXYZ",
"phone": 2685211,
"country": 575
}
When I try to get the authentication token with {"email": "xyz@mail.com", "password": "p@55w0rd"}
I get a Status 400 error {"username": ["This field is required."]}
When I use {"username": "xyz@mail.com", "password": "p@55w0rd"}
I get a Status 400 error {"non_field_errors": ["Unable to log in with provided credentials."]}
I tried using advice from posts such as this and this.
How can I use email
+password
to perform token-based authentication for such a custom user?
Your help will be much appreciated.