As a continuation of my previous question Creating a login program using a text file, my program is trying to validate the username and password that a user enters and if the username and password exists in the user.txt, the user should be able to access the menu. The problem is that it only reads the last line of the user.txt file so only the last registered user is allowed to login. I want all users in the user.txt file to be able to login.
This is what I've tried so far
usernames = []
passwords = []
user_name = input("Please enter your username: ")
pass_word = input("Please enter your password: ")
with open("user.txt", "r+") as f1, open("tasks.txt", "r+") as f2:
for lines in f1:
logins = lines.strip()
logins = lines.split(", ")
username = logins[0]
password = logins[1]
usernames.append(logins[0])
passwords.append(logins[1])
while user_name == username and pass_word == password:
menu = input('''Please select one of the following options:\n
r - register a user
a - add task
va - view all tasks
vm - view my tasks
e - exit ''').lower()
Contents of user.txt file
admin, adm1n
Maverick, FlyGuy
You're not using the
usernamesandpasswordslists, so the check is done against only the last iteration/line. It's also easier to verify credentials if the (username, password) are stored as pairs, like so:You can also store the credentials in a dictionary that has username as keys and passwords as values. That would make it easier to check if the username is correct, but the password isn't.
I'm assuming this is a homework question, since anyone running the program can also read the
user.txtfile and get all the passwords. A more secure solution would hash the passwords and compare them using a constant-time algorithm.