Silasi
Silasi

Reputation: 129

request.user.is_authenticated always return anonymous in python/django

its been 5 days strugling with this.It was working well at first but suddenly it started giving me some erros that i couldn't understand so i started modifying my code from MyCustomUser model and custom authentication backend but still i cant figure this problem.

I can sign in user and it does log in the user after sign up, but when i open django shell and test if user.is_authenticated it return True and user.is_anonymous return False.

Can please anyone help me identify what is the problem here. Please fellow django developers.

bellow is my sign_up view:

def sign_up(request):

     if request.method == 'POST':
         form = SignUpForm(request.POST)

         if form.is_valid():

            new_user = form.save(commit=False)

            #create string of first_name an last_name
            full_name = '{0} {1}' .format(new_user.first_name, new_user.last_name)

            #Slugify full name
            new_user.slug = slugify(full_name)

            new_user.save()

            email = request.POST.get('email')
            raw_password = request.POST.get('password1')

            #Authenticate the user
            user = authenticate(email=email, password=raw_password)

            if user is not None :

                login(request, user)
                if request.user.is_authenticated:

                     #Redirect to success url after user has successfully is logged in.
                      return HttpResponseRedirect(reverse_lazy('jogos:question-list'))


  else:
        form = SignUpForm()
    return render(request, 'jogos/sign_up.html', {'form':form})




from jogos.models import MyCustomUser
from django.contrib.auth import get_user_model

And my CustomBackend which i have also plugged in my settings.

class MyCustomBackend(object):

    def authenticate(self, request, email=None, password=None, **kwargs):

        if email is None:
            email = kwargs.get('email')


        try:
            user = MyCustomUser.objects.get(email=email)


            if user.check_password(password):
                return user
            else:
                return None

        except MyCustomUser.DoesNotExist:
                return None




        def get_user(self, user_id):
            try:
                user = MyCustomUser.objects.get(pk=user_id)
                if user.is_active:
                    return user

        except MyCustomUser.DoesNotExist:
            return None

My CustomUser model:

class MyCustomUser(AbstractBaseUser):
    email = models.EmailField(max_length=50, verbose_name='email', unique=True)
    first_name    = models.CharField( max_length=15,blank=False)
    last_name     = models.CharField( max_length=15,blank=True)
    slug          = models.SlugField(null=True, unique=True)
    is_staff      = models.BooleanField(default=False)
    is_active     = models.BooleanField(default=True)
    is_admin      = models.BooleanField(default=False)
    is_superuser  = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []


    def get_full_name(self):
        full_name = '{0} {1}'.format(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 has_module_perms(self, app_label):
        return True


    @property
    def is_superuser(self):
        return self.is_superuser

    @property
    def is_staff(self):
        return self.is_staff


    def __str__(self):
        return self.first_name

And alse My UserManager:

from django.contrib.auth.base_user import BaseUserManager


class UserManager(BaseUserManager):
    use_in_migrations = True

    def create_user(self, email, password=None):

        if not email:
            raise ValueError("Users must have an email address")

        email = UserManager.normalize_email(email)
        user = self.model(email=email)

        user.set_password(password)

        user.is_active = True
        user.save(using=self._db)
        return user



    def create_superuser(self, email, password):

        user = self.create_user(email, password=password)

        user.is_active = True
        user.is_superuser = True    
        user.is_admin = True
        user.save(using=self._db)

        return user

I can't figure out what is wrong here, and all this code was working smoothly and it all only started giving me problems as i continued growing my code base

Upvotes: 1

Views: 4436

Answers (2)

Juba Fourali
Juba Fourali

Reputation: 890

After sending Token using Authorization header, the token will be gotten in dispatch function as bellow:

def dispatch(self, request, *args, **kwargs):

   self.args = args
   self.kwargs = kwargs
   request = self.initialize_request(request, *args, **kwargs)
   self.request = request
   self.headers = self.default_response_headers  # deprecate?

   try:
      self.initial(request, *args, **kwargs)

      # Get the appropriate handler method
      if request.method.lower() in self.http_method_names:
          handler = getattr(self, request.method.lower(),
                          self.http_method_not_allowed)
      else:
          handler = self.http_method_not_allowed

      response = handler(request, *args, **kwargs)

    except Exception as exc:
       response = self.handle_exception(exc)

    self.response = self.finalize_response(request, response, *args, **kwargs)
    return self.response

So you are using django_role_permission's HasRoleMixin, the dispatch method of this mixin will hide dispatch of the view. I think that the solution is to redefine the mixin of roles-permissions

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599450

You have the logic the wrong way round. Until you log a user in, request.user is by definition an unauthenticated user. So request.user.is_authenticated will always be False.

You don't need or want to check that property there. You don't really need to check the user is not None either, since you have just created it so you know it exists. Just log the user in directly.

(Note, I don't understand why you have created a custom auth backend. It doesn't do anything different from the standard one. You don't need it.)

Upvotes: 4

Related Questions