Search code examples
djangodjango-modelsdjango-templatesdjango-authenticationdjango-custom-user

Using custom user model in Django always return anonymous user in template


I have created a custom user model since I need three information( email, institute id, password) to login to the system. I have also created an authentication backend for this purpose. when I try to login, it redirects to the correct view. But the template shows anonymous user instead of logged in user. It's not going into this condition {% if user.is_authenticated %}. However, user.is_authenticated is true in view. Can anyone please help me to figure out the problem? Any suggestion will be appreciated. I have attached my code below. Thanks in advance.

model.py

class UserManager(BaseUserManager):
use_in_migrations = True

def _create_user(self, email, center_id, password, **extra_fields):
    values = [email, center_id]
    field_value_map = dict(zip(self.model.REQUIRED_FIELDS, values))
    for field_name, value in field_value_map.items():
        if not value:
            raise ValueError('The {} value must be set'.format(field_name))

    email = self.normalize_email(email)
    user = self.model(
        email=email,
        center_id=center_id,
        **extra_fields
    )
    user.set_password(password)
    user.save(using=self._db)
    return user

def create_user(self, email, center_id, password=None, **extra_fields):
    extra_fields.setdefault('is_staff', False)
    extra_fields.setdefault('is_superuser', False)
    return self._create_user(email, center_id, password, **extra_fields)

def create_superuser(self, email, center_id, password=None, **extra_fields):
    extra_fields.setdefault('is_staff', True)
    extra_fields.setdefault('is_superuser', True)

    if extra_fields.get('is_staff') is not True:
        raise ValueError('Superuser must have is_staff=True.')

    if extra_fields.get('is_superuser') is not True:
        raise ValueError('Superuser must have is_superuser=True.')

    return self._create_user(email, center_id, password, **extra_fields)


class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(
        verbose_name='email address',max_length=255,unique=True,)
    first_name = models.CharField(max_length=150)
    last_name = models.CharField(max_length=150)
    center_id = models.CharField(max_length=50)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now)
    last_login = models.DateTimeField(null=True)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['center_id']

    def get_full_name(self):
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        return self.first_name

    def has_perm(self, perm, obj=None):
        return True

    def email_user(self, subject, message, from_email=None, **kwargs):
        send_mail(subject, message, from_email, [self.email], **kwargs)

    def has_module_perms(self, app_label):
        return True

backend.py

from django.contrib.auth import get_user_model
from authentication.models import User
from django.db.models import Q

class AuthBackend(object):
    supports_object_permissions = True
    supports_anonymous_user = False
    supports_inactive_user = False

    def get_user(self, user_id):
       try:
          return User.objects.get(pk=user_id)
       except User.DoesNotExist:
          return None
    def authenticate(self, email=None, password=None, center_id=None):
        usermodel = get_user_model()
        try:
            user = usermodel.objects.get(Q(email__iexact=email) & Q(center_id__iexact=center_id))
            if user.check_password(password):
                return user
        except ObjectDoesNotExist:
            return None

settings.py

AUTHENTICATION_BACKENDS = (
    'accounts.backends.AuthBackend',
    'django.contrib.auth.backends.ModelBackend',
)
AUTH_USER_MODEL = 'authentication.User'

view.py:

def userLoginView(request):
if request.method == 'POST':
    center_id = request.POST.get('center_id')
    email = request.POST.get('email')
    password = request.POST.get('password')
    request.session['center_id'] = center_id
    request.session['email'] = email
    user = AuthBackend.authenticate(request, email=email, password=password, center_id=center_id)
    if user:
        if user.is_active:
            auth_login(request, user, backend='fileupload_project.accounts.backends.AuthBackend')
            if user.is_authenticated:
                print('authenticated')
            return redirect('accounts:search')
        else:
            return HttpResponse("Your account is disabled.")
    else:
        return HttpResponseRedirect(reverse('accounts:login'))
else:
    return render(request, 'accounts/registration/login.html', {}) 

def searchPatientView(request):
        return render(request,'accounts/patient_registration/search.html',{})

template/search.html:

 <div class="col-sm-8 text-left">
    {{ user }}
        {% if user.is_authenticated %}
            {{ user.email }}
        {% endif %}
</div>

Solution

  • I have solved my problem. It's a silly mistake though. I did not call my custom authentication backend correctly. So, the system never uses it for authentication. I made changes in view.py and settings.py. I have posted the updated version below. view.py:

    if user.is_active:
            auth_login(request, user, backend='accounts.backends.AuthBackend')
            if user.is_authenticated:
                print('authenticated')
            return redirect('accounts:search')
    

    settings.py:

        AUTHENTICATION_BACKENDS = (
        'accounts.backends.AuthBackend',
        #'django.contrib.auth.backends.ModelBackend',
    )
        AUTH_USER_MODEL = 'authentication.User'