Search code examples
djangocurljwtdjango-rest-authdjango-custom-user

unable to log in using curl and django JWT even though credentials correct


I have a custom user model in django here:

class UserManager(BaseUserManager):
    def create_User(self, email, name, companyname=None, userphoto=None,
                    userphotokey=None, signupvalidatestring=None, is_active=False, phone=None, jobtitle=None,
                    isclient=False, issuitsviewer=False, issuitsadministrator=False, issuitssuperuser=False,
                    password=None):
        if not email:
            raise ValueError('Users must have an email address')
        if not name:
            raise ValueError('Users must have a name')
        user = self.model(email = self.normalize_email(email),
                          name = name,
                          companyname= companyname,
                          userphoto= userphoto,
                          userphotokey=userphotokey,
                          signupvaildatestring=signupvalidatestring,
                          is_active=is_active,
                          phone=phone,
                          jobtitle=jobtitle,
                          isclient=isclient,
                          issuitsviewer = issuitsviewer,
                          issuitsadministrator=issuitsadministrator,
                          isuitssuperuser=issuitssuperuser)
        if not password:
            user.set_unusable_password()
        else:
            user.set_password(password)
            user.is_active = True
            user.save(using=self._db)
            return user

    def create_superuser(self):
        pass

# permissions table



class STUser(AbstractBaseUser):
    email = models.EmailField(unique=True)
    name = models.CharField(max_length=255)
    companyname = models.CharField(max_length=200, blank=True, null=True)
    userphoto = models.CharField(max_length=200, blank=True, null=True)
    userphotokey = models.CharField(max_length=200, blank=True, null=True)
    signupvaildatestring = models.CharField(max_length=200, blank=True, null=True)
    is_active = models.BooleanField(default=False)
    phone = models.CharField(max_length=10, null=True, blank=True)
    jobtitle = models.CharField(max_length=100, null=True, blank=True)
    isclient = models.BooleanField(default=False)
    issuitsviewer = models.BooleanField(default=False)
    issuitsadministrator = models.BooleanField(default=False)
    issuitssuperuser = models.BooleanField(default=False)
    # password field function is provided by AbstractBaseUser

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']
    EMAIL_FIELD = 'email'

class VenuePermissions(models.Model):
    user = models.ForeignKey(STUser, on_delete=models.CASCADE)
    venue = models.ForeignKey(Venue, on_delete=models.CASCADE, blank=True, null=True)
    isvenueviewer = models.BooleanField(default=False)
    isvenueeventplanner = models.BooleanField(default=False)
    isvenueadministrator = models.BooleanField(default=False)
    receiverfp = models.BooleanField(default=False)

I have the jwt auth class up:

#REST Framework
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',

I have the url endpoint:

from rest_framework_jwt.views import obtain_jwt_token
url(r'^api-token-auth/', obtain_jwt_token),

when I create a user in the shell like this:

>>> from STuser.models import STUser
>>> user = STUser(email='blah@gmail.com',name='Christopher Jakob',password='zaq11qaz')
>>> user.save()

then run a curl post:

curl -X POST -d "email=blah@gmail.com&password=zaq11qaz" http://127.0.0.1:8000/api-token-auth/

and also tried the JSON implementation

curl -X POST -H "Content-Type: application/json" -d '{"email":"blah@gmail.com","password":"zaq11qaz"}' http://127.0.0.1:8000/api-token-auth/

I also tried with wget:

wget --post-data="email=christopher.m.jakob@gmail.com&password=zaq11qaz" http://127.0.0.1:8000/api-token-auth/

I get the following error:

{"non_field_errors":["Unable to log in with provided credentials."]}
"POST /api-token-auth/ HTTP/1.1" 400 68

However the email and the password info I have submitted is what is in the database.

I am not sure what is going on here. I am wondering if it is in my manager? But I would imagine if such where the case the user objects wouldn't get added at all. As you can see I am using a custom user model.

here is the resource I am using:

https://getblimp.github.io/django-rest-framework-jwt/

question that might help me looking into it: Django (using TokenAuthentication): "non_field_errors": "Unable to log in with provided credentials?

this question may also provide help: looking into it. JSON Web Token for Django REST won't authenticate to user database

The relevant code in the package I am using starts on line 22 https://github.com/GetBlimp/django-rest-framework-jwt/blob/master/rest_framework_jwt/serializers.py


Solution

  • Stackoverflow help is hit or miss sometimes.

    I got it to work

    First. I had to update the code in my custom manager it wasn't correct:

    class UserManager(BaseUserManager):
    
        def create_user(self, email, name, password ,**extraarguments):
            if not email:
                raise ValueError('Users must have an email address')
            if not name:
                raise ValueError('Users must have a name')
            if not password:
                raise ValueError('User must have a password')
            user = self.model(email = self.normalize_email(email),
                              name = name, **extraarguments)
            user.set_password(password)
            user.is_active = True
            user.save()
            return user
    
        def create_superuser(self, email, name, password, **extraarguments):
            if not email:
                raise ValueError('Users must have an email address')
            if not name:
                raise ValueError('Users must have a name')
            if not password:
                raise ValueError('Users must have a password')
            user = self.model(email = self.normalize_email(email),
                              name = name, **extraarguments)
            user.set_password(password)
            user.is_active = True
            user.save()
            return user
    

    then I needed to not just not create an STUser object like I did but calling the create_user function in the manager.

    so in the shell

    >>>from STuser.models import STUser
    >>> user = STUser.objects.create_user('bobby@test.com','chris','zaq11qaz')
    >>> exit()
    

    then make a new curl request

    curl -X POST -d "email=bobby@test.c
    om&password=zaq11qaz" http://127.0.0.1:8000/api-token-auth/
    

    and look what happend...

    curl -X POST -d "email=bobby@test.c
    om&password=zaq11qaz" http://127.0.0.1:8000/api-token-auth/
    {"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImJvYmJ5QHRlc3QuY29tIiwidXN... you dont get the rest of my token homie"}
    

    soooo thats cool.

    Hugs and kisses