Home > OS >  Custom User Model, Custom Authentication not working
Custom User Model, Custom Authentication not working

Time:10-26

I am a beginner in Django and I am working on a project which requires Custom user model as I Don't require is_staff, is_superuser, is_admin.

So, but searching and other ways I made my own Custom user model. But it is not working and I am stuck on it for days.

It will be a huge help if someone can help me with the code.

settings.py


AUTH_USER_MODEL = 'accounts.Usermanagement'

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'accounts.backends.EmailAuthBackend',
]

models.py (models manager)

#models.py
class UsermanagementCustomUserManager(BaseUserManager):
    # create_user(username_field, password=None, **other_fields)
    def create_user(self,emailid,roleid,organizationid,firstname, password=None,
                    passwordexpirydate="2022-12-12 12:00:00",createdby=0,modifiedby=0):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not emailid:
            raise ValueError('Users must have an email address')

        user = self.model(
            emailid=self.normalize_email(emailid),
            roleid = roleid,
            organizationid=organizationid,
            firstname = firstname,
            password=password,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self,emailid,roleid,organizationid,firstname,passwordexpirydate,password=None,createdby=0,modifiedby=0):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(
            emailid=emailid,
            roleid = roleid,
            organizationid=organizationid,
            firstname = firstname,
            password=password,
            passwordexpirydate=passwordexpirydate,
        )
        user.save(using=self._db)
        return user





class Organization(models.Model):
    organizationid = models.AutoField(db_column='OrganizationID', primary_key=True,blank=True)  
    organizationname = models.CharField(db_column='OrganizationName', max_length=45,blank=True)

    def __str__(self):
        return self.organizationname

    class Meta:
        managed = False
        db_table = 'Organization'


class Role(models.Model):
    roleid = models.AutoField(db_column='RoleID', primary_key=True,blank=True)  
    organizationid = models.ForeignKey(Organization, on_delete=models.CASCADE, db_column='OrganizationID',blank=True)  
    rolename = models.CharField(db_column='RoleName', max_length=45,blank=True)  
    read = models.BooleanField(db_column='Read', default=1,blank=True) 
    write = models.BooleanField(db_column='Write', default=1,blank=True) 
    delete = models.BooleanField(db_column='Delete', default=1,blank=True) 
    isactive = models.BooleanField(db_column='IsActive', default=1,blank=True)

    def __str__(self):
        return self.rolename

    class Meta:
        managed = False
        db_table = 'Role'


class Usermanagement(AbstractBaseUser):
    userid = models.BigAutoField(db_column='UserID', primary_key=True)  
    emailid = models.CharField(db_column='EmailID', unique=True, max_length=45,default=1)  
    roleid = models.ForeignKey(Role, on_delete=models.CASCADE, db_column='RoleID',blank=True)  
    organizationid = models.ForeignKey(Organization, on_delete=models.CASCADE, db_column='OrganizationID',blank=True)  
    firstname = models.CharField(db_column='FirstName', max_length=45,blank=True)  
    middlename = models.CharField(db_column='MiddleName', max_length=45, blank=True, null=True)  
    lastname = models.CharField(db_column='LastName', max_length=45, blank=True, null=True)  
    numberofretry = models.IntegerField(db_column='NumberOfRetry',default=0,blank=True)  
    timeoffset = models.CharField(db_column='TimeOffSet', max_length=6,default=" 5:30",blank=True)  
    password = models.CharField(db_column='Password', max_length=45)  
    passwordexpirydate = models.DateTimeField(db_column='PasswordExpiryDate',default='2022-12-30 12:30:59',blank=True)  
    dateofcreation = models.DateTimeField(db_column='DateOfCreation',auto_now_add = True,blank=True)  
    dateofmodification = models.DateTimeField(db_column='DateOfModification',auto_now = True,blank=True)  
    createdby = models.BigIntegerField(db_column='CreatedBy',blank=True)  
    modifiedby = models.BigIntegerField(db_column='ModifiedBy',blank=True)  
    isactive = models.BooleanField(db_column='IsActive',default=1,blank=True)

    last_login = False

    objects = UsermanagementCustomUserManager()

    USERNAME_FIELD = "emailid"
    EMAIL_FIELD = "emailid"
    REQUIRED_FIELDS = ["roleid","organizationid","firstname","passwordexpirydate","createdby","modifiedby"]


    def __str__(self):
        return self.emailid
    
    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    # @property
    # def emailid(self):
    #     return self.email

    # @property
    # def email(self):
    #     return self.emailid

    # @property #original
    # def isactive(self):
    #     return self.is_active

    @property
    def is_active(self):
        return self.isactive

    # @property
    # def userid(self):
    #     return self.user_id

    @property
    def user_id(self):
        return self.userid

    class Meta:
        managed = False
        db_table = 'UserManagement'

backends.py

#backends.py

# from django.contrib.auth.models import User
from django.contrib.auth.hashers import check_password
from django.contrib.auth import get_user_model

Usermanagement = get_user_model()

class EmailAuthBackend:
    def authenticate(self,request,username=None,password=None):
        print(request)
        try:
            user = Usermanagement.objects.get(emailid=username)
            print(password)
            print(user.password)
            # print(check_password(password))
            # print(user.check_password(password))
            if user.check_password(password):
                return user
            return None
            
        except user.DoesNotExist:
            return None
    
    def get_user(self,user_id): 
        try:
            return user.objects.get(pk=user_id)
        except user.DoesNotExist:
            return None

views.py

# views.py

def loginPage(request):
    # POST
    if request.method == 'POST':
        form = AuthenticationForm(request,data=request.POST)

# loginPage.html the html tag has attribute name = username for email , 
# name = password for password

        if form.is_valid(): # Form Valid
            email = request.POST['username']
            password = request.POST['password']
            #Check
            print("EMAIL: ",email)
            print("PASSWORD: ",password)
            # Authentication USER
            user = authenticate(request,username=email,password=password)
            print("Authenticated ",user) # Check
            # check
            print(user)

            if user is not None: # If User found
                login(request,user,backend='accounts.backends.EmailAuthBackend')
                messages.info(request, f"You are now logged in as {email}.")
                return redirect("home")

            else: # If User Not found
                messages.error(request,"User not found")
                return HttpResponse("User not found, not able to login")

        else: # Form InValid
            messages.error(request,"Invalid username or password.")
            return HttpResponse("Form Invalid")
    # GET
    else:
        form = AuthenticationForm()
        context = {"form":form}
        return render(request,"loginPage.html",context=context)

urls.py and other configurations are correct.

Problems:

  1. check_password : always False
  2. In DB I have unencrypted password ( ex:- password=admin )
  3. DB is a legacy(existing) DB , so I first made the DB and then I did "python manage.py inspectdb" , which created models for me and then I changed few things, but did not changed the field names or the db_table name.
  4. I am very much ok to create user through SHELL.
  5. In loginPage.html the html tag has attribute name = username for email , name = password for password

if any other requirements I will edit the Questions

CodePudding user response:

i think you cannot use the check_password function in your case, because it has been created for encrypted password case. Just make a user.password == password in your EmailAuthBackend

For second problem with get_user(), I think your userId is not the primary key for Django maybe, problem probably can be solved by filter directly by userId:

    def get_user(self, user_id): 
        try:
            return user.objects.get(userId=user_id)
        except User.DoesNotExist:
            return None

CodePudding user response:

Concerning the problem No.2

Remove the password=password in your user=self.model()

It's making it difficult to make reference to the password in your user.set_password()

  • Related