I am building registration,login,logout apis with django rest.Registration works properly.I created a login view to authenticate users based on given username and password but authenticate return none instead of the user object.I am using a non hashed password for simplicity and It doesn't work.I can create users via the register api and they are shown in the database and is_active becomes True after email activation and although I give the same credentials to the login api it fails.I printed the username and password inside the function before authenticate to test if they hold their correct values and they do but yet fails to authenticate.
views.py
@api_view(['POST']) def register(request): userser = SignUpUserSerialzer(data=request.data) if userser.is_valid(): user = userser.save(is_active = False) activateEmail(request, user, userser.validated_data['email']) return Response(userser.data) else: return Response(status=status.HTTP_404_NOT_FOUND) @api_view(['POST']) def custom_login(request): # if request.user.is_authenticated: # return redirect(reverse('home')) username=request.data['username'] password=request.data['password'] print(username) print(password) print('login1') user = authenticate(username=username, password=password) print('login2') print(user) if user is not None: login(request, user) return Response({"user": user.id}) else: return Response("error") def activateEmail(request, user, to_email): mail_subject = 'Activate your user account.' message = render_to_string('template_activate_account.html', { 'user': user.username, 'domain': get_current_site(request).domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), 'protocol': 'https' if request.is_secure() else 'http' }) email = EmailMessage(mail_subject, message, to=[to_email]) if email.send(): messages.success(request, f'Dear <b>{user}</b>, please go to you email <b>{to_email}</b> inbox and click on \ received activation link to confirm and complete the registration. <b>Note:</b> Check your spam folder.') else: messages.error(request, f'Problem sending confirmation email to {to_email}, check if you typed it correctly.') @api_view(['GET']) def activate(request, uidb64, token): User = get_user_model() try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() return Response('account activated') else: return Response('activation failed') serializers.py
from rest_framework import serializers from .models import CustomUser class SignUpUserSerialzer(serializers.ModelSerializer): class Meta: model = CustomUser fields = '__all__' models.py
from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): email = models.EmailField(unique=True) def __str__(self): return self.username settings.py
AUTH_USER_MODEL = 'users.CustomUser' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'PAGE_SIZE': 10 } cmd
System check identified 1 issue (0 silenced). March 14, 2023 - 00:47:25 Django version 4.1.6, using settings 'crowdFunding.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. phan 1234567 login1 login2 None [14/Mar/2023 00:47:34] "POST /users/login/ HTTP/1.1" 200 7