Discussion:
auth-jwt api end point not generating token with custom user model.
(too old to reply)
m***@gmail.com
2018-12-08 06:34:13 UTC
Permalink
Settings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication')
}
AUTH_USER_MODEL = '**app_name**.Users'
models.py
from django.db import models
import jwt

from datetime import datetime, timedelta

from django.conf import settings
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager, PermissionsMixin
)

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

class Users(AbstractBaseUser, PermissionsMixin) :
UserID= models.IntegerField(primary_key=True)
BranchID = models.ForeignKey(Branch,on_delete=models.DO_NOTHING,null=False)
username = models.CharField(db_index=True, max_length=255, unique=True)
email = models.CharField(db_index=True, unique=True,max_length=255)
password = models.CharField(max_length=100)
CustomerID= models.ForeignKey(Customers,on_delete=models.DO_NOTHING,null=
False)
ProductID= models.ForeignKey(Products,on_delete=models.DO_NOTHING,null=False
)
FirstLoggedDate = models.DateTimeField()
ExpiryDate = models.DateTimeField()
CreatedDate = models.DateTimeField()
IsActive = models.BooleanField(default=True)
IsAdmin = models.BooleanField(default=True)
last_login = models.DateTimeField()
date_joined = models.DateTimeField()
is_superuser = models.BooleanField(default=False)

USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['password']
# is_anonymous = False
# is_authenticated = False
# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager()

def __str__(self):
"""
Returns a string representation of this `User`.

This string is used when a `User` is printed in the console.
"""
return self.email

@property
def token(self):
"""
Allows us to get a user's token by calling `user.token` instead of
`user.generate_jwt_token().

The `@property` decorator above makes this possible. `token` is called
a "dynamic property".
"""
return self._generate_jwt_token()

def get_full_name(self):
"""
This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. Since we do
not store the user's real name, we return their username instead.
"""
return self.username

def get_short_name(self):
"""
This method is required by Django for things like handling emails.
Typically, this would be the user's first name. Since we do not store
the user's real name, we return their username instead.
"""
return self.username

def _generate_jwt_token(self):
"""
Generates a JSON Web Token that stores this user's ID and has an expiry
date set to 60 days into the future.
"""
dt = datetime.now() + timedelta(days=60)

token = jwt.encode({
'id': self.pk,
'exp': int(dt.strftime('%s'))
}, settings.SECRET_KEY, algorithm='HS256')

return token.decode('utf-8')
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+***@googlegroups.com.
To post to this group, send email to django-***@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/8cda755a-f205-4dbd-a4c7-cddb10608520%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Continue reading on narkive:
Loading...