I'm making a account login system in python by having the username and password stored in a separate file and the program access it, then read the password and compare it with what the user has entered. It can read the password in the file but for some reason when it compares it to what the user has entered, it always says it's wrong.
I've tried comparing the actual password to the user's input and I know it's reading the file right as I made it print out what it read and it printed the correct password. I've also made it print the user's input to make sure that's right and that was working too.
Just so you know, the file already exists which contains the password on the second line and it finds the right file as the file is named after the account that it's for.
Account = str(input("Enter the username. "))
Account_Password = str(input("Enter the password. "))
AccountFileName = (Account + ".txt")
with open(AccountFileName,"r") as AF:
for x, line in enumerate(AF):
if x == 1:
Account_Password_Check = (line)
if Account_Password == Account_Password_Check:
print("Welcome, " + Account + "!")
else:
print("Either the username or password were incorrect.")
If the user input is the same as the password, it should print, "Welcome (username here)!" and if they're different then it should print, "Either the username or password were incorrect."
If you know what's wrong, please let me know.
Thanks.
In comments to your question, you will find the first reason why it doesn't work, but:
for x, line in enumerate(AF):
if x == 1:
Account_Password_Check = (line)
Is also not fully correct, enumerate start count from zero, but condition checks 1 line, it means that you will compare your current user password from previous. The correct version will be
for x, line in enumerate(AF):
if x == 0:
Account_Password_Check = line.strip()
break
Related
My question is that I am creating a login system in python. This system is very simple. The user type login , his email and password. The program checks from a file whether the email or password is correct or not. But I am running into some issues with that. So I first opened the file then asked the user if he wants to log in or signup. If he types login the program asks for email and password and check in the file whether this matches or not. The program takes input correctly but at the time of checking it fails. It does not give an error but it does not print the desired statement. This my code
with open('Data_Login_System.txt' , 'r') as data:
user_input = input("""Type Either Login or SignUp> """)
if user_input.lower() == "login":
Email = input("""Type your Email> """)
Password = input("""Type Your Password> """)
for line in data:
if line.lower() == f"email : {Email.lower()}" or line.lower() == f"password : {Password.lower()}":
print("Logged in")
These are the contents of the file.
Email : shabeebasghar123#gmail.com
Password : shabeebasghar123
Whenever I enter the correct email and password it should print logged in but it does not the program just run finely and nothing at the end
This is the execution of the program
Type Either Login or SignUp
> login
Type your Email
> shabeebasghar123#gmail.com
Type Your Password
> shabeebasghar123
It worked by just doing line.lower().strip() intead of just line.lower()
First of all you got to use a readlines() function to read lines from the .txt file with a loop. You could actually read a lines without a loop on that one. See code below.
lines = data.readlines()
print(data)
The out put for that would be:
['Email : mail#gmail.com\n', 'Password : passwd123'].
So I would try a bit different approach. Make sure that you don't have any unwanted extra lines in txt file.
user_input = input("Type Either Login or SignUp")
if user_input.lower() == "login":
email = input("""Type your Email""")
password = input("""Type Your Password""")
with open("data.txt", 'r') as f:
t_mail = f.readline()
t_passwd = f.readline()
if f"Email : {email}\n" == t_mail and f"Password : {password}" == t_passwd:
print('You are now logged in')
This works fine for me.
I am creating a quiz algorithm which utilities a log in system. For the sign up process, the usernames and passwords are stored in a text file and are read in order to see if they already exist.If this is the case, the user is told that the username or password already exists and this is repeated until something that doesn't already exist is input. When this happens,the text file is appended to add the username. For some reason however, the program doesn't check if the user attempt is already in the text file,but just adds it to the text file, even if it already exists.
The log in procedure, which does the first part of checking if a string is the same in both the variable and text file works just fine. The program checks if the username and password are in the files and if they are it logs in. The hashed code is used for testing and will be removed when the program works.
##Sign up
if Option == ("2"):
exit = False
while exit == False:
Userattempt = input("Please enter a username:\n>>> ")
file = open("Usernames.txt","r")
searchline = file.readline()
Flag = False
Username = ""
for line in file:
print(Userattempt, line)# used to see how the program goes through each line
Username = str(line)
if Userattempt == Username:
Flag = True
print("Yes", Userattempt, line)# Used to test after each line
else:
print("False")# Used to test after each line
if Flag == True:
print("That Username already exists, Please try another")
else:
#file.close()
file = open("Usernames.txt","a")
file.write(Userattempt)
file.write("\n")
print("Okay",Userattempt, "is your username")
exit = True
file.close()
This program runs fine, but for some reason it doesn't check if the user input is equal to each line and if it does,the flag used to catch that the username or password already exists isn't changed.
The main reason it's not working is that you didn't remove the newline from the line being read from the file, so it never matches the user input.
You have other problems with the program logic. You shouldn't write the new username inside the for loop, because you don't know if the username is available until you get to the end of the file.
Instead of the Flag variable, you can use the else: block of the for loop. This will run if the loop completes normally instead of from a break statement. Then you break out of the loop when finding a matching line in the file.\
It's generally best to use a with statement to open a file and automatically close it when done.
##Sign up
if Option == ("2"):
while True:
Userattempt = input("Please enter a username:\n>>> ")
with open("Usernames.txt","r") as file:
for line in file:
Username = line.strip()
print(Userattempt, Username)# used to see how the program goes through each line
if Userattempt == Username:
print("That Username already exists, Please try another")
break # break out of for-loop
else: # name not found, so add it
with open("Usernames.txt","a") as outfile:
outfile.write(Userattempt)
outfile.write("\n")
print("Okay",Userattempt, "is your username")
break # break out of while-loop
I'm creating a Login & Password program in Python for my school, I've created already the sign up part with many validations and it fully works & the login part partly works.
The login part has a issue. It locates the username and also the password however it also locates the password beginning with that initial and it lets you log in the account (bug). For example, my password is "mat" if I type ma or m it will let me log into the account. But the good thing is it doesn't let me log in with other letters just those.
PATH=("pass"+" "+username+".txt")
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
print ("Username does exist please enter password: ")
w = input("Password: ")
with open("pass"+" "+username+".txt") as f:
found = False
for line in f:
if w in line:
loginuser()
found = True
if not found:
print("Wrong password. Please re-enter")
login()
else:
print("Username not found.")
Replace this line, which check for substring match
if w in line:
With complete string match
if w == line.strip():
Your string ends with '\n' that's why you need to trim it. This would also delete spaces at string beginning and end, like " mat \n" would become "mat", so be careful.
It is because you are using this line
if w in line:
You are checking if a part of that line contains the input so the below are correct:
"w" in "password" -> True
"pass" in "password" -> True
"word" in "password" -> True
and this is of course not correct, you need to check for equality thus:
if w == line.strip():
should do the job
the line
if w in line:
tests if any letter of the input 'w' is in the line of the password text file. You need to do an equivalence test like so:
if line == w:
so that an exact match logs the user in, and not just if one or more letters match.
If you are storing the passwords each on a separate line why don't you just directly compare them. So instead of doing if w in line do this instead:
if w==line
This is my code:
users = []
users.append([username, password])
usersFile = open("users.txt","w+")
for users in users:
usersFile.write("%s" % users)
usersFile.close()
def loginFunction():
userEntry = ""
foundName = 0
while userEntry == "":
userEntry = raw_input("Enter your username: ")
usersFile = open("users.txt", "r")
lines = usersFile.readlines()
usersLen = len(users)
for index in range (0, usersLen-1):
if userEntry == users[index, 0]:
foundName = 1
passwordEntry = raw_input("Enter your password: ")
if passwordEntry == users[index, 1]:
print "Username and passwords are correct"
else:
print "incorrect"
userEntry = ""
if foundName == 0:
print "Username not recognised"
userEntry = ""
I have produced a program that registers the username and password of a user. I have checked the files and it saves the username and password successfully but when I try to login using the correct username that I know is in the file as a list, it still always comes up "Username not recognised". Any ideas as to why this might be?
It looks like you're writing out the user/passwords, as lists, as single lines in the file. Then when you read it back, each pair is read back as one string. readlines() doesn't automatically convert text back to a list object. If you want to do that, you might use Pickle instead. Pickle should let you save the entire users list of lists object all at once.
Also to be pythonic your for loop should iterate over the list directly. If you need the current index, use for i, user in enumerate(users). Using range(len(users)) is suboptimal in python. You can then use user[0] to get the username and user[1] for the password.
I've made a few changes to your program. Firstly, I've changed it to use the modern print function instead of the print statement. The print function is available in Python 2.6 and later. It's more powerful than the old print statement, and IMHO it's a good idea to start using it in preparation for Python 3 (which doesn't have the print statement).
To simplify reading & writing the username & password data we can use the standard csv module. It's not strictly necessary for this simple task, but it means we don't have to worry about the messy details of parsing the name and password strings. Eg, if the strings contain spaces or quotes, the csv will handle them correctly. Note that in Python 2 CSV files must be opened in binary mode, but in Python 3 they must be opened in text mode. This is rather annoying when you're trying to write code that runs correctly on both versions.
The easy way to look up a password given the username is to use a dictionary with the username as the key and the password as the value. This is much more efficient than scanning through a list row by row looking for a match.
Of course, in a real program we would never store passwords as plain text. That's extremely insecure! The usual procedure is to store a hashed version of the password, using a strong cryptographic hash function applied a very large number of times to make it a time-consuming operation. For further info please see PBKDF2, scrypt, and bcrypt.
Also, it's bad practice to let a potential attacker know that a username is valid but that the password they submitted is invalid. That allows them to easily build a list of valid usernames. Instead, you should always ask for the password, even if the username is invalid.
from __future__ import print_function
import csv
users = [
['Alice', 'aardvark'],
['Bob', 'bobcat'],
['Steve', 'swordfish'],
]
# Save the users list to a CSV file
users_filename = "users.txt"
with open(users_filename, "wb") as f:
writer = csv.writer(f)
writer.writerows(users)
def login_function():
# Load the usernames & passwords into a dictionary
with open(users_filename, "rb") as f:
users = dict(csv.reader(f))
# Give the user 3 chances to login
for i in range(2, -1, -1):
user_entry = raw_input("Enter your username: ")
password_entry = raw_input("Enter your password: ")
if user_entry in users and password_entry == users[user_entry]:
print("Username and password are correct")
return True
else:
print("Username and password are invalid")
print(i, "login attempts remaining")
print("Login failed")
return False
print(login_function())
demo
Enter your username: Alan
Enter your password: runner
Username and password are invalid
2 login attempts remaining
Enter your username: Alice
Enter your password: aardvark
Username and password are correct
True
I am new to programming and am wondering if this is possible. I am trying to create a password protected script, where the password is entered once and then required to progress the script the next time the script is opened. I am storing and encrypting the password in a file, and then checking to see if the file exists the next time the script is opened. The problem I am running into is checking to see if the passwords match, since the original password is in a function as a local variable.
def createFile():
pw = input('Enter Password: ')
pw2 = input('ReType Password: ')
if pw == pw2:
newPw = encrypt(pw, 10) #encodes the string with a key in a seperate encrypt function
pwFile = open('PW.txt', 'a')
pwFile.write(newPw)
pwFile.close()
else:
print('The passwords do not match')
createFile()
if os.path.isfile('PW.txt'):
print('File exists')
pwCheck = input('What is the password? ')
#I can not check pwCheck == pw since pw is a local var.
#progression of script here
else:
createFile()
I know that it is considered bad for to make a local variable global. Is there a way to restructure what I have so far to make this work? As I wrote this, I think I may have came up with a possible solution but I do not have time to test it now. Do I run the same encrypt function with the same key for pwCheck and then check if it is == to the first line of PW.txt? Is that correct and/or are there other solutions?
Thank you.
Using Windows, Python 3.4
Instead of "encrypt", perhaps use a 1-way hash.. Then, you can hash the subsequently entered password and check it versus the hash stored in the file... Something like:
def createFile():
pw = input('Enter Password: ')
pw2 = input('ReType Password: ')
if pw == pw2:
newPw = sha.new(pw).digest
pwFile = open('PW.txt', 'a')
pwFile.write(newPw)
pwFile.close()
else:
print('The passwords do not match')
createFile()
if os.path.isfile('PW.txt'):
print('File exists')
pwCheck = input('What is the password? ')
previous = open('PW.txt', 'r')
prevPass = previous.read()
hashed = sha.new(pwCheck).digest()
if (hashed==prevPass):
#progression of script here
else:
createFile()
I really hope that this is just an exercise, because if you care about security, you should be using some other authentication mechanism to gate access. Most obviously, unix permissions, and sudo to gate access.
Assuming it is an exercise only, simply have a function which checks the input against the file. Something like:
def doAuth():
isAuthed = getPassInput() == getPassFromFile()
if isAuthed:
return True
else:
raise HellNoException("Passwords differ")