Answer the question
In order to leave comments, you need to log in
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)
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
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)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question