Email login: authentication function doesn't work
def EmailLoginVerify(request):
if request.method == 'POST':
if 'token' in request.POST:
try:
submitted_token = int(request.POST['token'])
except ValueError:
return HttpResponse('Invalid token format', status=400)
if submitted_token == request.session.get('login_token'):
email = request.session.get('email')
try:
target = MyUser.objects.get(email=email)
print('user is', target.username, 'and password is', target.password)
#export:
#>>>>>>>user is maziar and password is pbkdf2_sha256$720000$CY5sjiqAL1yScKzGhzYBp9$2tUx8ScBbbuZlj+u0YfMxwTIRfz5Vfmv+58piWCAjKM=
except MyUser.DoesNotExist:
return HttpResponse('User Not Found', status=404)
user = authenticate(request, username=target.username, password=target.password)
print(user)
#export:
#>>>>> None
if user is not None:
login(request, user)
return HttpResponse('good')
else:
return HttpResponse('Authentication failed', status=401)
else:
return HttpResponse('Invalid token', status=403)
else:
return HttpResponse('Token not provided', status=400)
else:
return render(request, 'login_verify.html')
in the end it return 'Authrntication Failed' this code get an email from the user if a user with that email exists it send a code to the email and if user enter the correct code it should authenticate the user and log it in but it return 'Authentication Failed'
When you try to authenticate the user with the username and password from the database, you're passing the hashed password directly to the authenticate
function. However, Django's authenticate
function expects the raw password(not the hashed one), and it will hash it internally to check against the stored hash in the database.
Since you're trying to authenticate the user with the hashed password, the authentication fails.
You can't directly authenticate using the standard authenticate
method since the user hasn't provided their password in this step. You might want to consider this process as a separate verification step where you log the user in after verifying the token without requiring the password.
def EmailLoginVerify(request):
if request.method == 'POST':
if 'token' in request.POST:
try:
submitted_token = int(request.POST['token'])
except ValueError:
return HttpResponse('Invalid token format', status=400)
if submitted_token == request.session.get('login_token'):
email = request.session.get('email')
try:
target = MyUser.objects.get(email=email)
print('user is', target.username, 'and password is', target.password)
except MyUser.DoesNotExist:
return HttpResponse('User Not Found', status=404)
# Bypass password authentication after successful token verification
login(request, target)
return HttpResponse('good')
else:
return HttpResponse('Invalid token', status=403)
else:
return HttpResponse('Token not provided', status=400)
else:
return render(request, 'login_verify.html')
I hope this will help you a little.