Reputation: 5
I'm trying to create an authenticator with python to add into another project.
Here is my code:
# User authentication
global authenticated
def checkAuth():
global authenticated
authenticated = False
# User enters their username and password
username = input("Enter your username: ")
password = input("Enter your password: ")
username = username.strip()
password = password.strip()
for line in open("users.txt","r").readlines():
line = line.strip()
loginInfo = line.split(",")
print(loginInfo)
if username == loginInfo[0] and password == loginInfo[1]:
print("Authorised")
authenticated = True
isAuth = checkAuth()
if (isAuth):
input("Authorised \t Press any key to continue: ")
else:
input("no auth")
When I run my code and enter a correct username and password the if statement inside the checkAuth function evaluated to true, but the if statement at the bottom doesn't get the True value.
These are the two username and password combos in the users.txt file.
Upvotes: 0
Views: 7101
Reputation: 1778
You either need to do if(authenticated)
or instead of setting authenticated to true, just return true
. Your checkAuth()
function is void, so it has no return value. Using globals for this isn't a good idea.
If you're absolutely sure you want to use a text file for this, try this:
def isAuthorized():
username = input("Enter your username: ").strip()
password = input("Enter your password: ").strip()
with open("users.txt", "r") as f:
for line in f:
loginInfo = line.strip().split(",")
if username == loginInfo[0] and password == loginInfo[1]:
return True
return False
if isAuthorized():
input("Authorized \t Press any key to continue: ")
else:
input("no auth")
Using a text file for this provides no security whatsoever so keep that in mind. The problem with a global boolean is that you have to reset it after each login or it will remain true even if the wrong information is given.
Upvotes: 5
Reputation: 153
you need to return a value from the checkAuth()
function
checkAuth()
...
...
return authenticated
Upvotes: 3