M
M
Maxim Dunayevsky2015-10-06 15:24:40
Django
Maxim Dunayevsky, 2015-10-06 15:24:40

Django authenticate() always returns None and SO doesn't answer the question. What to do?

Hello!
Today I discovered an unpleasant thing - the self-written authorization module is broken. If this code worked before, now it doesn't:

class LoginView(AuthView, GenericAPIView):

    """
    Вид предназначен для простой аутентификации
    """

    def post(self, request, *args, **kwargs):
        data = request.data

        username = data.get('username', None)
        email = data.get('email', None)
        password = data.get('password', None)

        if username is None:
            username = email

        account = authenticate(username=username, password=password)

        if account is None:
            raise Exception("Не удалось авторизоваться")

        if account is not None:
            if account.is_active:
                login(request, account)
                return Response(status=status.HTTP_200_OK)
            else:
                return Response({
                    'status': 'Unauthorized',
                    'message': 'This account has been disabled.'
                }, status=status.HTTP_401_UNAUTHORIZED)
        else:
            return Response({
                'status': 'Unauthorized',
                'message': 'Имя пользователя или пароль указаны неверно.'
            }, status=status.HTTP_401_UNAUTHORIZED)

The authenticate() function always returns None, even when authenticating with the Django shell. Where to dig? What is the reason? I transfer CSRF tokens, logins and passwords are correct, I set it via set_password() and all that. I can not log in, although everything worked yesterday.
In settings.py :
AUTH_USER_MODEL = 'extuser.User'

AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.locale.LocaleMiddleware',
)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rostislav Grigoriev, 2015-10-06
@dunmaksim

For debugging, instead of the standard authenticate function, write a copy above the view, for example:

def authenticate(username=None, password=None, **kwargs):
        from django.contrib.auth import get_user_model
        UserModel = get_user_model()
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
            if user.check_password(password):
                return user
        except UserModel.DoesNotExist:
            # Run the default password hasher once to reduce the timing
            # difference between an existing and a non-existing user (#20760).
            UserModel().set_password(password)

After that, you can track where the plug occurs. UserModel.DoesNotExist or user.check_password(password) fails . This can also be done through the IDE in debug mode, without copying the code.
It can be assumed that the user model changed, but the migrations were not carried out.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question