Getting Token from Django Model to views - django

I created a user model in Django i want to know what JWT token is generated for my particular user in the views.py section could you please help
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=255, unique=True, db_index=True)
email = models.EmailField(max_length=255, unique=True, db_index=True)
is_verified = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
status=models.IntegerField(default=1)
phone=models.IntegerField(blank=True,null=True)
otp=models.IntegerField(blank=True,null=True)
auth_provider = models.CharField(
max_length=255, blank=False,
null=False, default=AUTH_PROVIDERS.get('email'))
#locations=models.ManyToManyField(Location)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = UserManager()
def __str__(self):
return self.email
def tokensd(self):
refresh = RefreshToken.for_user(self)
return {
'refresh': str(refresh),
'access': str(refresh.access_token)
}

If django version is or greater than 2.2 then you can use request.headers
it will give dictionary and check the token key and get the key
request.headers['HTTP_AUTHORIZATION']
else you can use request.META['HTTP_AUTHORIZATION']

Related

Django type object 'Account' has no attribute 'USERNAME_FIELD' django

i tried to adding username=None didnt work
Account model is for auth
other models that are diffrent languge are just profile pic or date joined nothing important to the error i imagine
models.py
class Account(AbstractBaseUser):
email= models.EmailField(verbose_name='ایمیل', max_length=60, unique=True)
username = models.CharField(max_length=255, unique=True)
مسکن = models.CharField(max_length=255)
تاریخ_ثبت_نام = models.DateTimeField(verbose_name='تاریخ_ثبت_نام', auto_now_add=True)
اخرین_ورود = models.DateTimeField(verbose_name='اخرین_ورود', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
عکس_پروفایل = models.ImageField(max_length=255 ,upload_to=get_profile_image_filepath,null=True ,blank=True, default=get_default_profile_image)
objects = MyAccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __str__(self):
return self.username
def get_profile_image_filenames(self):
return str(self.عکس_پروفایل)[str(self.عکس_پروفایل).index(f'uploads/{self.pk})/'):]
def has_perm(self,perm, obj=None):
return self.is_admin
def has_module_perm(self , applabel):
return True

modelManager get_by_natural key method change the USERNAME_FIELD affecting my authentication?

I have a custom User model that inherits from AbstractBaseUser which defines the username_field = email so that users will login using emails.
class User(AbstractBaseUser):
email = models.EmailField(verbose_name="Email", unique=True)
username = models.CharField(max_length=100, unique=True)
last_name = models.CharField(max_length=100, blank=True, null=True)
first_name = models.CharField(max_length=100, blank=True, null=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_site_administrator = models.BooleanField(default=False)
is_developer = models.BooleanField(default=False)
is_project_manager = models.BooleanField(default=False)
last_login = models.DateTimeField(verbose_name="Last Login", auto_now=True)
create_on = models.DateTimeField(verbose_name="Date Created", default=timezone.now)
# So that we will be working primarily with email and not username
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["username"]
objects = UserManager()
As the objects = UserManager() and this one contains a get_by_natural_key method as follows:
def get_by_natural_key(self, username):
return self.get(username=username)
Now rather using the email to login it uses the username to login. Note that the userManager inherits from BaseUserManager like this class UserManager(BaseUserManager):
Can somebody explain to me what is going on here.
Is the problem coming from the inheritance or the get_by_natural_key() itself ?

Cannot resolve keyword 'created' into field django rest framework

i have follwing structure:
class FullTreeAdminUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
class AdminFullTreeListView(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = FullTreeAdminUserSerializer
When i query users/all i have following error:
Cannot resolve keyword 'created' into field
The user model looks like
class User(AbstractBaseUser, PermissionsMixin):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
username = models.CharField(max_length=255, unique=True, db_index=True)
first_name = models.CharField(max_length=255, blank=True)
last_name = models.CharField(max_length=255, blank=True)
email = models.EmailField(max_length=255, unique=True, db_index=True)
is_verified = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
date_joined = models.DateTimeField(auto_now=True)
balance = models.FloatField(default=0.0)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = UserManager()
I cannot figure out where the problem is. I simply wanna get list of all user and i didn't expect such problems. I don't have created filed in my user model

Two different types of user with different username field types

Default User Model:
class User(AbstractBaseUser, PermissionsMixin):
avatar = models.ImageField(upload_to='user/avatar', null=True, blank=True)
date_joined = models.DateField(auto_now_add=True)
username = models.EmailField(unique=True, null=False, blank=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_employer = models.BooleanField(default=False)
is_employee = models.BooleanField(default=False)
object = managers.UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
class Meta:
verbose_name = 'User'
verbose_name_plural = 'Users'
Employer model:
class Employer(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True)
name = models.CharField(max_length=256, blank=False, null=False)
address = models.CharField(max_length=256, blank=False, null=False)
fax = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
email = models.EmailField(unique=True, blank=False, null=False)
economic_code = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True)
national_id = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True)
Employee model:
class Employee(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True)
employer = models.ForeignKey(Employer, null=False, blank=False, on_delete=models.CASCADE)
first_name = models.CharField(max_length=50, null=False, blank=False)
last_name = models.CharField(max_length=100, null=False, blank=False)
national_id = models.PositiveIntegerField(null=False, blank=False)
date_of_birth = models.DateField(blank=False, null=False)
post = models.CharField(max_length=100, null=True, blank=True)
mobile = models.DecimalField(max_digits=11, decimal_places=2, null=False, blank=False)
personnel_code = models.PositiveIntegerField(null=True, blank=True)
eligible_leave = models.FloatField(default=0, blank=False, null=False)
sick_leave_per_month = models.FloatField(default=0, null=False, blank=False)
rfid_card_code = models.CharField(max_length=256, blank=False, null=False)
I want the employer to be authenticated by email and the employee by national code (username filed). How?
you need a custom authentication backend. let's name it backends.py
from django.contrib.auth.backends import ModelBackend
class EmployeeAuthentication(ModelBackend):
"""
Employee Backend
Allows a user to sign in using national_id and password.
"""
def authenticate(self, request, **kwargs):
national_id = kwargs.get('username')
password = kwargs.get('password')
try:
employee = Employee.objects.get(national_id=national_id)
if employee.user.check_password(password) is True:
return employee.user
except Employee.DoesNotExist:
pass
class EmployerAuthentication(ModelBackend):
"""
Employer Backend
Allows a user to sign in using email and password.
"""
def authenticate(self, request, **kwargs):
email = kwargs.get('username')
password = kwargs.get('password')
try:
employer = Employer.objects.get(email=email)
if employer.user.check_password(password) is True:
return employer.user
except Employer.DoesNotExist:
pass
and in settings.py
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'app.backends.EmployerAuthentication',
'app.backends.EmployeeAuthentication',
]

Multiple user Login where multiple user can login and get redirected to respective pages

I have four types of user like buyer seller organizer and staff. So i would like to know how to implement multiple type login in django
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
class Seller(AbstractBaseUser):
"""
Custom user class.
"""
email = models.EmailField('email address', unique=True, db_index=True)
joined = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_seller = models.BooleanField(default=False)
class Buyer(AbstractBaseUser):
"""
Custom user class.
"""
email = models.EmailField('email address', unique=True, db_index=True)
joined = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_buyer = models.BooleanField(default=False)
class Staff(AbstractBaseUser):
"""
Custom user class.
"""
email = models.EmailField('email address', unique=True, db_index=True)
joined = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
class Organizer(AbstractBaseUser):
"""
Custom user class.
"""
email = models.EmailField('email address', unique=True, db_index=True)
joined = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_organizer = models.BooleanField(default=False)