So basically what this code is supposed to do is to be a login page. It asks wether if the user has an account or not ( in my case the user doesn't have an account ). The user creates an account ( this part works ) but the user info is not saved in the txt file. I looked at other sites and youtube videos that explain this topic, but none of them work. Visual Studio doesn't give me an error but when I open the txt file, the info is not shown. Also, I work on a mac ( don't know if it will matter ).
def main_menu():
OPTION = input("Do you have an account? (yes/no)\n")
if OPTION == "yes":
login()
if OPTION == "no":
register()
def register():
USERNAME = input("Create your username: \n")
PASSWORD = input("Create your password: \n")
database = open("databse.txt", "w")
database.write(USERNAME)
database.write(PASSWORD)
database.close()
PASSWORD_CHECK = input("Confirm your password: \n")
if PASSWORD_CHECK != PASSWORD:
print("Your passwords do not match. Try again. \n")
register()
if PASSWORD_CHECK == PASSWORD:
print("You have successfully created an account! Welcome!")
# another menu here
def login():
pass
main_menu()
Related
My sign up and login authentication system is not working as it is supposed to. My signup issue was fixed, but my login has a problem. Either the code will let me go through and access the account, or it will not, depending on the code. But anytime I try to fix it, the output is one of the two options. ALWAYS, regardless of the password I enter.
The usernames and passwords are stored in a txt file, like this:
John Appleseed:hisSuperSecretPassword
JohnDoe:1234
The login code:
found = False
username = input("Enter your username:\n")
file = open("account.txt", "r+")
for line in file:
if line.split(':')[0] == username:
found = True
if found == True:
password = input("Enter your password:\n")
for counter, line in enumerate(file):
if line.strip() == username + ":" + password:
print("You have signed in.")
else:
print("Password incorrect. Program closing.")
sys.exit()
else:
print("Username not valid.")
sys.exit()
Can anyone help? Running Python 3.9.2.
Here is something I've adjusted to work....
import sys
found = False
username = input("Enter your username:\n")
file = open("account.txt", "r+")
for line in file:
if line.split(':')[0] == username:
account_details = line.split(':')
found = True
if found == True:
password = input("Enter your password:\n")
if account_details[1].strip() == password:
print("You have signed in.")
else:
print("Password incorrect. Program closing.")
sys.exit()
else:
print("Username not valid.")
sys.exit()
You are exiting the program as soon as you find a non-matching password, instead of comparing the password to the correct user. You also don't need to re-read the entire password file: you already found the expected password when you verified that the user name existed.
As an aside, there's no sense confirming for an attacker that they have correctly guessed a user name. Just get the user name and password first, then look for them in the password file.
username = input("Enter your username:\n")
password = input("Enter your password:\n")
with open("account.txt") as fh:
if any(f'{username}:{password}' == line.strip() for line in fh):
print("You have signed in.")
else:
print("Invalid username or password, exiting")
sys.exit()
I've seemed to create a bank account log in system that works correctly. The only problem is that once a login is successful, the program would get stuck in a loop. For example: Say, I create my account and set my username as "Hello" and my password as "123".
The program will except these log in details but when I later try to log in with them, the infinite loop would happen.
I've tried amending this problem by plugging in return/global values for status and even put them in as many places in my program as possible but the infinite loop problem still persists. Could you please help me find why the loop keeps executing?
users = {}
status = ""
#--------------- Login menu -----------------#
def displayMenu():
global status
status = input("Are you a registered user? \n1 - Yes \n2 - No \nQ - Quit \n")
if status == '1':
oldUser()
elif status == '2':
newUser()
return status
def mainMenu():
print("Hello account holder", login,"what service would you like to use today?")
#---------- Screen for new users -------------#
def newUser():
createLogin = input("Create login name: ")
if createLogin in users: # check if login name exists
print ("\nLogin name already exists!\n")
else:
createPassw = input("Create password: ")
users[createLogin] = createPassw # add login and password
print("\nAccount created!\n")
#---------- Screen for old users -------------#
def oldUser():
global login
login = input("Enter login name: ")
passw = input("Enter password: ")
# check if user exists and login matches password
if login in users and users[login] == passw:
print("\nLogin successful!\n")
mainMenu()
else:
print("\nUser doesn't exist or wrong password!\n")
# Main -------------------------------------------------------------------------------------------------------------
while status != "q":
status = displayMenu()
Your code is working exactly as it is designed.
The main loop starts:
while status != "q":
status = displayMenu()
Note that your program will only ever "quit" if the user gives an input of "q" in the displayMenu(), rather than "Q". This can be fixed by checking status.lower() instead.
Then you specify that no, you are not a registered user by providing 2 as an input to the displayMenu().
This brings you to newUser(), where you create your new account.
You'll then get returned to displayMenu(), where you can this time select 1 to login as a registered user, bringing you to oldUser().
Once you enter your login credentials in oldUser(), you'll get brought to mainMenu(), where it will print the welcome message in mainMenu(), then return to oldUser(), then to displayMenu(), then back to the main loop.
Unless you're expecting something else to happen in mainMenu(), the only error here is that you're not normalizing the case of status before checking if it is "q".
My assessment is to construct a password vault, with basic python lists, functions while loops, etc, but am having issues on the part where the user actually inputs passwords for their apps. The first problem is when they ask to see their passwords and don't have any it should say "you have nothing stored", it says this but don't stop repeating it, and also wondered if I could get some help on completing the rest of it. here is what I would like this part of the code to look like in terms of using it.
Press: 1) find your existing passwords 2) save a new password for your apps
3) see a summary of your password locker 4) exit password locker successfully
2
Name of website: Facebook
Username of site: bob91
password of site: bob95
would you like to add another app: yes
Name of website: Instagram
Username of site: albert91
password of site: albert95
would you like to add another app: no
Press: 1) find your existing passwords 2) save a new password for your apps
3) see a summary of your password locker 4) exit password locker successfully
1
Which app password would you like to access: Facebook
Facebook
username: bob91
password: bob95
-------------------------------------------------- My actual code right now -->
vault_apps = []
app_name = ""
def locker_menu_func():
print('''You have opened the locker,
Please select what you would like to do,''')
while True:
locker_menu_var = input('''Press: \n1) find your existing passwords \n2) save a new password for your apps
3) see a summary of your password locke \n4) exit password locker successfully
---------------------------------------------------------------------------------
''')
print('''----------------------------------------------------------------''')
if locker_menu_var == "1":
while len(vault_apps) < 1:
print('''you have nothing stored''')
break
break
elif locker_menu_var == "2":
app_name = input('''
What is the name of the website/app your are adding?
''')
app_password = input('''What is the password of your {} account?
'''.format(app_name))
vault_apps.append([app_name, app_password])
while True: another_app = input('''Would you like to add another app to your password locker?''')
if another_app in {"Y", "YES"}:
print("okay")
break
break
locker_menu_func()
I used dictionary to store the password. Try it this way. If it solved your problem, Kindly upvote and make it as a answer.
app_passwords = {}
def locker_menu_func():
print('''You have opened the locker,
Please select what you would like to do,''')
while True:
locker_menu_var = input('''Press: \n1) find your existing passwords \n2) save a new password for your apps
3) see a summary of your password locke \n4) exit password locker successfully''')
if locker_menu_var == "1":
while len(app_passwords) < 1:
print('''you hve nothing stored''')
break
else:
for kv in app_passwords.items():
a= kv[0],kv[1]
print(str(a).replace("(","").replace(")","").replace("[","").replace("]",""))
#print (app_passwords)
elif locker_menu_var == "2":
web = input("Enter Website")
username = input("Enter username")
password = input("Enter password")
app_passwords[web]=["username:"+username+","+"password:"+password]
elif locker_menu_var == "3":
print ("Count of Websites stored",len(app_passwords))
elif locker_menu_var == "4":
break
locker_menu_func()
I'm new at python, and I'm trying to do a simple Register & Login System with Text file. What I would like to do is:
1.When app is launched ask for user Login or Register. (Done)
2.If user wants to login, we launch the file reader and get the data of the list, from TXT file. (NOT DONE.)
3. If user wants to register we launch the file writer, and write to the list in TXT file to add a user to the registered users list.
In my Opinion the list in the TXT File should look something like this.
Accounts = ["Username" : username, "Password" : password]
while True:
Login_Register = input("Welcome,\nType L for Login, R to Register\n")
if "L" in Login_Register or "l" in Login_Register:
Vardas = input("~ Please enter your Username!\n")
with open(ban_list, mode='r', encoding='utf-8') as f:
if Vardas in f.read():
Password = input("Please enter your password for user {}".format(Vardas))
else:
print("Account With'in this name does not exist!")
continue
if "R" in Login_Register or "r" in Login_Register:
break
EDIT *
I thinked abit, and changed a mind about the List in The TXT File should look something like this :
Accounts = ["Username" : Vardas, "Password" : password]
We use Vardas as a variable in the code, so I think this is how its done.
This code does everthing that you have said in your qestion if anything is wrong tell me in the comments
check = True
Login_Register = input("Welcome,\nType L for Login, R to Register\n")
if Login_Register == "l" or Login_Register =="L":
while check:
with open('accountfile.txt', 'r') as f:
username1 = input("Enter your username: ")
password1 = input("Enter your password: ")
for line in f:
if("Username:"+username1+" Password:"+password1) == line.strip():
print("you are logged in")
check = False
break;
else:
print("Username or password does not exist")
elif Login_Register == "r" or Login_Register == "R":
f = open("accountfile.txt","a+")
username2 = input("~ Please enter your Username!\n")
password2 = input("~ Please enter your password!\n")
f.write(f"\nUsername:{username2} Password:{password2}\n")
f.close()
print("username and password has been made")
The list you have provided
["Username" : Vardas, "Password" : password]
is not a valid python list, you will need to use a dictionary which is like this:
{"Username" : Vardas, "Password" : password}
As for storing passwords in a .txt file is not a great idea, you should look into getting a database for example Google's Firebase and read up on the python package firebase which you can get from pip install firebase
Hope this helps.
I am trying to create a simple login system. What I'm doing is storing the login data in a text file called 'accounts.txt'
Now, when user tires to login, it first checks if the username given by the user is in the 'accounts.txt'. If it exists, then it asks for the password and then checks if password matches with the password in 'accounts.txt'
fr = open('accounts.txt', 'r')
while True:
username = input('Enter your username: ') # Ask for their username
if username in fr.read(): # Check if username exists
password = input('Enter password: ') # Ask for password if username exists
if username+password in fr.read():
print('Welcome ' + username)
break
else:
print('Wrong password')
Note, the password save in accounts.txt is in the format of usernamepassword so if username is jack and password is gate, the actual password in the txt file will be jackgate, hence im using username+password to check if password is correct.
The problem occuring is if the user enters correct username, then program moves ahead properly but even if the password entered is right, it still displays 'Wrong password' .When the second time user enters username, it even shows error for wrong username. I tried to play with the code for a long time but couldn't come up with a solution. I guess it has something to do with fr.read(). Can I use that 'fr' object only once?
Let me suggest some improvements with my answer to your question. I would read the accounts file in its entirety so you have an in-memory structure. If you do this as a dictionary in the form accounts[USER] -> PASS you can easily check for any account as per the code below.
Regarding my suggestions (they do not exactly only answer your questions, but IMHO the topic of writing login code should be treated with care):
I strongly recommend not to store passwords in plain text, regardless of application importance, always use hashes.
Do not store just the password hash, always use salting.
Do not tell the person trying to log in, if the username or the password was wrong, always just say "that's not the right combination", thus making it harder to break in.
Please find information about hashing functions in Python here: https://docs.python.org/3/library/hashlib.html#randomized-hashing
This site has a good introduction on salting ans securing passwords: https://crackstation.net/hashing-security.htm
Do you users a favor and treat the username as no case-sensitive. That is a totally valid approach, but it annoys me every time I have to use such a site (just like email addr are not case-sensitive)
As I am a total layman regarding password security, maybe one of the other Stackoverflow users can jump in with a comment and expand on this topic.
Anyway, here is my answer for your question on how to check for a login. I created a function check_account() that returns True or False, depending on wether the supplied credentials were correct or not.
import hashlib
import os
import binascii
def check_account(usr, pwd):
# read the accounts file, a simple CSV where
# username, salt value and password hash are
# stored in three columns separated by a pipe char
accounts = {}
fr = open('/users/armin/temp/test.csv', 'r')
for line in [x.strip().split("|") for x in fr.readlines()]:
accounts[line[0].lower()] = (line[1], line[2])
fr.close()
# now go looking if we do have the user account
# in the dictionary
if usr in accounts:
credentials = accounts[usr]
# credentials is a list with salt at index 0
# and pwd hash at index 1
# generate the hash form the functions parameters
# and compare with our account
h = hashlib.blake2b(salt=binascii.unhexlify(credentials[0]))
h.update(pwd.encode('utf-8'))
if credentials[1] == h.hexdigest():
return True
else:
return False
else:
return False
def main():
while True:
username = input('Enter your username: ') # Ask for their username
password = input('Enter password: ') # Ask for password if username exists
if check_account(username.lower(), password):
print("Welcome, {0}".format(username))
else:
print('Username or password unknown')
if __name__ == '__main__':
main()
To create the data for a user account, use may this code.
def create():
username = input('Enter your username: ').lower() # Ask for their username
password = input('Enter password: ') # Ask for password if username exists
salt = binascii.hexlify(os.urandom(hashlib.blake2b.SALT_SIZE))
print("SALT value:", salt)
h = hashlib.blake2b(salt=binascii.unhexlify(salt))
h.update(password.encode('utf-8'))
print("Pwd hash:", h.hexdigest())
You can use startswith and endswith:
fr = [i.strip('\n') for i in open('accounts.txt')]
while True:
username = input()
if any(i.startswith(username) for i in fr):
password = input('Enter password: ')
if any(username+password == i for i in fr):
print("welcome")
break
else:
print("wrong password")
I would do
if password in fr.read():
instead of
if username+password in fr.read():
This is because for it to get to the if password in fr.read loop it first has to pass the if username in fr.read loop. However, the only problem I find with this is that if they enter a correct username but enter the wrong password for that username but correct password for another username it will still pass.
That is why I think you should use a dictionary not a text file.
For example, if the usernames allowed is username and username1 and the password is username and username1, then in a different .py file, you can say.
username_password={'username':'username','username1':'username1'}
that makes a dictionary that has the username and passwords.
let's say you name that file stuff.py. Then in the second file that has to be in the same directory, you can do
from stuff import * #imports all values from stuff.py
while True:
username = input('Enter your username: ') #gets username
if username_password.has_key(username):
password = input('Enter password: ')
if password== username_password[username]:
print('Welcome '+username)
break
else:
print('Wrong password')
break
else:
print('Wrong username')
I still don't get why you have a while loop, but if you want it, it is fine. Also, I added an else loop just in case the username is wrong.