Django authenticate() resets password - python

I have a weird problem here. When I login, it works well as expected but when I try to logout and try to login again, it says that my password is invalid.
I checked my User table and it's really changing my password everytime I use authenticate() function.
I got this error a month ago (still django 1.8 at that time) but gone after many testing and tracing and praying and didn't have a single idea what happened. It only occurs in my local machine though.
authentication.py
after authenticate() function, my password is already changed (tried to put a breakpoint after the function so I know for sure that this is the culprit).
from django.contrib.auth import authenticate, logout, login
def signin(request):
if request.method == "POST":
result = {}
data = req_data(request)
try:
user = authenticate(username = data['email'], password = data['password'])
if user:
if user.is_active:
login(request, user)
#return success for redirection
else:
raise ValueError("This user is inactive. Please contact your admin.")
else:
raise ValueError("Invalid username/password.")
except Exception as e:
return HttpResponse(e, status = 400)
else:
return redirect("login")
def signout(request):
logout(request)
return redirect("login")
#gets the params from ajax post
def req_data(request):
return json.loads(request.body.decode("utf-8")) if request.body.decode("utf-8") else {}
I checked the DB and got this result.
Old Password
pbkdf2_sha256$20000$N4esMaOT5BYi$nIehHw63b+iZSz2Vmu1hEO10BqPfzAGu1cZA1ci/nXI=
New Password (After login)
pbkdf2_sha256$24000$KVZeuG4pgSkv$VIenbuq0Wk8sYZros4kE4Q7W0Jt+bOC23ha4/VSOXV8=
EDIT:
for the meantime, I am not using authenticate() and just use a generic password.
username = data.get('email',"")
password = data.get('password',"")
if password == "genericpassword123":
try:
user = User.objects.get(email = username)
user.backend = 'django.contrib.auth.backends.ModelBackend'
except User.DoesNotExist:
raise ValueError("Invalid username/password.")
else:
user = authenticate(username = username, password = password)
if user:
if user.is_active:
login(request, user)
#return success for redirection
else:
raise ValueError("This user is inactive. Please contact your admin.")
else:
raise ValueError("Invalid username/password.")
Python 2.7
Django 1.9
Postgre 9.4
Thanks!

It's working now. I never thought that it works in different account with different password.

Related

Django Login Access with token

I am developing a Django project, I have created an API in the same project since other tools should be able to use functions from this project. This method is not working and I need someone who has done a similar thing to assist with a more refined and secured method or point out where am doing wrong.
When a user is registered, I create an access token ( md5 has ) for this user and store it in a model, each token has a user foreign key.
class AuthToken(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
token = models.TextField()
created_date = models.DateField(auto_now_add=True)
created_time = models.TimeField(auto_now=True)
status = models.IntegerField(default=0)
in the API, I have added a function to authenticate the user with the token.
When the view to authenticate the user is invoked, what I do is.
Check if the token exists.
Get the user ( AuthToken.user.username )
Get user password ( AuthToken.user.password)
Authenticate these details with Django authenticate
I understand this will definitely fail since the password fetched from AuthToken.user.password with be an encrypted one, and passing the encrypted password to Django for authentication will encrypt that and compare again.
Below is my API authentication view
if module == 'auth': # authentication model queried
api_token = crud # api access token
token_filter = AuthToken.objects.filter(token=api_token) # filter for token existence
if token_filter.count() == 1: # if there is token
token_d = AuthToken.objects.get(token=api_token)
username = token_d.user.username
password = token_d.user.password
# login
user = authenticate(request, username=username, password=password)
try:
# check if user is valid
if hasattr(user, 'is_active'):
auth_login(request, user)
# Redirect to a success page.
return redirect('home')
else:
messages.error(request,
f"There is an error logging in, please check your credentials again or contact "
f"Administrator")
return redirect('login')
except Exception as e:
messages.error(request, f"There was an error {e}")
return redirect('login')
else:
return HttpResponse('INVALID TOKEN')
elif module == 'auth': # authentication model queried
api_token = crud # api access token
token_filter = AuthToken.objects.filter(token=api_token) # filter for token existence
if token_filter.count() == 1: # if there is token
token_d = AuthToken.objects.get(token=api_token)
username = token_d.user.username
password = token_d.user.password
# login
user = authenticate(request, username=username, password=password)
try:
# check if user is valid
if hasattr(user, 'is_active'):
auth_login(request, user)
# Redirect to a success page.
return redirect('home')
else:
messages.error(request,
f"There is an error logging in, please check your credentials again or contact "
f"Administrator")
return redirect('login')
except Exception as e:
messages.error(request, f"There was an error {e}")
return redirect('login')
else:
return HttpResponse('INVALID TOKEN')

Custom User Model, Custom Authentication not working

I am a beginner in Django and I am working on a project which requires Custom user model as I Don't require is_staff, is_superuser, is_admin.
So, but searching and other ways I made my own Custom user model. But it is not working and I am stuck on it for days.
It will be a huge help if someone can help me with the code.
settings.py
AUTH_USER_MODEL = 'accounts.Usermanagement'
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'accounts.backends.EmailAuthBackend',
]
backends.py
#backends.py
# from django.contrib.auth.models import User
from django.contrib.auth.hashers import check_password
from django.contrib.auth import get_user_model
Usermanagement = get_user_model()
class EmailAuthBackend:
def authenticate(self,request,username=None,password=None):
print(request)
try:
user = Usermanagement.objects.get(emailid=username)
print(password)
print(user.password)
# print(check_password(password))
# print(user.check_password(password))
if user.check_password(password):
return user
return None
except user.DoesNotExist:
return None
def get_user(self,user_id):
try:
return user.objects.get(pk=user_id)
except user.DoesNotExist:
return None
views.py
# views.py
def loginPage(request):
# POST
if request.method == 'POST':
form = AuthenticationForm(request,data=request.POST)
# loginPage.html the html tag has attribute name = username for email ,
# name = password for password
if form.is_valid(): # Form Valid
email = request.POST['username']
password = request.POST['password']
#Check
print("EMAIL: ",email)
print("PASSWORD: ",password)
# Authentication USER
user = authenticate(request,username=email,password=password)
print("Authenticated ",user) # Check
# check
print(user)
if user is not None: # If User found
login(request,user,backend='accounts.backends.EmailAuthBackend')
messages.info(request, f"You are now logged in as {email}.")
return redirect("home")
else: # If User Not found
messages.error(request,"User not found")
return HttpResponse("User not found, not able to login")
else: # Form InValid
messages.error(request,"Invalid username or password.")
return HttpResponse("Form Invalid")
# GET
else:
form = AuthenticationForm()
context = {"form":form}
return render(request,"loginPage.html",context=context)
urls.py and other configurations are correct.
Problems:
check_password : always False
In DB I have unencrypted password ( ex:- password=admin )
DB is a legacy(existing) DB , so I first made the DB and then I did "python manage.py inspectdb" , which created models for me and then I changed few things, but did not changed the field names or the db_table name.
I am very much ok to create user through SHELL.
In loginPage.html the html tag has attribute name = username for email , name = password for password
if any other requirements I will edit the Questions
i think you cannot use the check_password function in your case, because it has been created for encrypted password case. Just make a user.password == password in your EmailAuthBackend
For second problem with get_user(), I think your userId is not the primary key for Django maybe, problem probably can be solved by filter directly by userId:
def get_user(self, user_id):
try:
return user.objects.get(userId=user_id)
except User.DoesNotExist:
return None
Concerning the problem No.2
Remove the password=password in your user=self.model()
It's making it difficult to make reference to the password in your user.set_password()

Trying to connect Django to Payfort with an API .(Payment gateway integration). when i run the pay.html it gives me a value error in my views file

Error is :ValueError: The view hadid.views.initiate_payment didn't return an HttpResponse object. It returned None instead.
Exception Location: C:\Users\Chaims music\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py in _get_response, line 124
I am adding my def initiate_payment below
def initiate_payment(request):
if request.method == "GET":
return render(request, 'templates/pay.html')
try:
username = request.POST['username']
password = request.POST['password']
amount = int(request.POST['amount'])
user = authenticate(request, username=username, password=password)
if user is None:
raise ValueError
auth_login(request=request, user=user)
except:
return render(request, 'templates/pay.html', context={'error': 'Wrong Account Details or amount'})
transaction = Transaction.objects.create(made_by=user, amount=amount)
transaction.save()
This is just the initiate_payment where the error is coming from. please help i already tried similiar error
if any other file is needed let me know .
any help is appreciated .
Your view has to return a response, you return render(...) in your except block but you don’t return anything in the try block

Syntax Error on Login in django

I am getting a syntax error on the last else statement, i don't no where i am not doing it right but am assuming its a result of an idention error. sublime text auto idention not helped me out:
#csrf_exempt
def pagelogin(request):
context =RequestContext(request)
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
# Is the account active? It could have been disabled.
if user.is_active:
# If the account is valid and active, we can log the user in.
# We'll send the user back to the homepage.
login(request, user)
#return HttpResponseRedirect('/home/')
return render(request,'index.html')
else:
# An inactive account was used - no logging in!
return HttpResponse("Your account is disabled.")
else:
# Bad login details were provided. So we can't log the user in.
print "Invalid login details: {0}, {1}".format(username, password)
return HttpResponse("Invalid login details supplied.")
# The request is not a HTTP POST, so display the login form.
# This scenario would most likely be a HTTP GET.
else:
# No context variables to pass to the template system, hence the
# blank dictionary object...
#messages.success(request, 'You have successfully logged in to your account')
return render(request,'pagelogin.html')
Indent like this:
#csrf_exempt
def pagelogin(request):
context =RequestContext(request)
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
# Is the account active? It could have been disabled.
if user.is_active:
# If the account is valid and active, we can log the user in.
# We'll send the user back to the homepage.
login(request, user)
#return HttpResponseRedirect('/home/')
return render(request,'index.html')
else:
# An inactive account was used - no logging in!
return HttpResponse("Your account is disabled.")
else:
# Bad login details were provided. So we can't log the user in.
print "Invalid login details: {0}, {1}".format(username, password)
return HttpResponse("Invalid login details supplied.")
# The request is not a HTTP POST, so display the login form.
# This scenario would most likely be a HTTP GET.
else:
# No context variables to pass to the template system, hence the
# blank dictionary object...
#messages.success(request, 'You have successfully logged in to your account')
return render(request,'pagelogin.html')

Django User Authentication - Can't pass #login_required decorator

So I'm currently trying to implement an already existing application for payment processing via Braintree (https://github.com/Tivix/django-braintree for reference). It seems like all the meat of this application is placed at the /payments-billing/ directory but I can't seem to get into it to check it out. It seems like what's stopping me is a #login_required decorator placed just before the view since whenever I access the directory it sends me back to the defined LOGIN_URL. However I have set up a login feature at the LOGIN_URL that authenticates the user and then sends them to /payments-billing/ but it just redirects back again. Here is my code:
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
# Password verified for user
if user.is_active:
return redirect(self.success_url)
else:
return redirect('/')
else:
return redirect('/')
Clearly the user is being authenticated and is active since it passes both tests when you try it, but it always just sends the user back to the LOGIN_URL rather than /payments-billing/. Anyone know what's the deal here?
The authenticate function doesn't log a user in, it just checks their username/password. You also have to call django.contrib.auth.login() to do the actual logging in. See the example in the documentation.
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
login(request, user)
### Now it should get redirected to /payments-billing/
if user is not None:
# Password verified for user
if user.is_active:
return redirect(self.success_url)
else:
return redirect('/')
else:
return redirect('/')

Categories