basic user log in/pw code - python

Just started learning python a couple days ago and have been trying to use what code I know to practice a basic code of asking for a user name and password from a list. I know there are far better/cleaner/matching user to password inputs but I'm just playing with what I know at this point.
users = ['Jon','Joe', 'Jole']
user_input = input('Username: ')
while user_input != users:
user_redo = input("I'm sorry but we dont recognize you. Please try another username: ")
this is where my problem is. Is there a simple way of breaking the loop if the user enters a matching username from the list?
passwords = ['donkey808','Hanna5006']
password = input('Password: ')
I guess the same question would apply to the password entry as well
while password != passwords:
pw_redo = input(f'Please enter correct password for user {user_input}: ')
else:
print(f'Access Granted {user_input}')

Write it like this.
users = ["Jon","Joe", "Jole"]
while 0 < 1 :
user_input = input('Username: ')
if user_input not in users:
print("I'm sorry but we dont recognize you. Please try another username: ")
elif user_input in users:
break

Just do while user_input not in users:
not in checks if user_input is literally not in users
It might also be better to do if user_input not in users:, I don't see the point of a while.

Related

Username and password verification in a game

I'm a beginner in coding and I need to do an assignment- I've tried to do the above task as planned but all I ended up doing was verifying a username. The task is for Player 2 and Player 2 to enter a username and password. If password is correct then the game starts- but I don't know how to start the game. Keeping in mind I'm just a ks3/GCSE student so my code will not be very high-level. Please may I have some help? Thank you!
you can create a function around the game code. Than you add in over the function
username = input("Enter Username: ")
password = input("Enter password")
if username == Username and password == Password:
game()

My login system will not work - regardless of any user passwords entered

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()

Integrating login function inside a Class

sorry for my nooby question; I had a python application with only functions but now I have to revise it with classes that I am not expert on.
Here is my basic user Class;
class User:
def __init__(self,username,password,basket):
self.username=username
self.password=password
self.basket=basket
and the input function that I want to put inside the class;
def Login(self):
while True:
username = raw_input('\nPlease log in by providing your user credentials \nUser Name :')
if (username == users[0]['username'] or username == users[1]['username']):
password = raw_input('Password : ')
if (password == users[0]['password'] or password == users[1]['password']):
print('Successfully logged in!')
print (
'Welcome,' + username + '! Please choose of the following options by entering the corresponding menu number.')
global LoggedUserName
LoggedUserName = username;
return True;
break;
else:
print('Your password is not correct. Please try again!')
else:
print ('Your username is not correct. Please try again!')
Thank you for your precious helps!
You need to make instance of your class like that
Aname=User()
Aname.login()
But im not sure im too newbie object orriented programming

Using while loop to get the right username from user [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I want to create a code which will ask the user its username and password.
The username and password will already be a variable.
This code will keep asking the user the username and password over and over again
until the right username and password are typed in.
However I am not able to create this code, please help.
Can anyone give me an example, please?
I tried to create this code however, it doesn't work.First, if the username and the password are wrong the "Incorrect" just keeps repeating that's what I don't to happen and second I want that if the username or password is wrong the enter your username and enter your password keeps repeating until the user puts the credentials right.
answer_1 = ("america")
asnwer_2 = ("italy")
getin=input("Enter your Username: ")
getin_2=input("Enter your password :")
if getin!=answer_1 or getin_2!=answer_2:
print("Incorrect")
continue
print("Please proceed")
break
I fixed your code:
answer_1 = "america"
answer_2 = "italy"
getin_1 = input("Enter your Username: ")
getin_2 = input("Enter your password: ")
while getin_1 != answer_1 or getin_2 != answer_2:
print("Incorrect")
print("Please proceed")
getin_1 = input("Enter your Username: ")
getin_2 = input("Enter your password: ")
print("Your username and password are OK.")
To ask user again and again, you have to put question in a loop - if command is not sufficient.
There is no need to use break or continue commands as all required conditions are already in the while loop.
username = Bob
password = 123
user = ''
passw = ''
while username != user and password != passw:
passw = input('Input password:')
user = input('Input username:')

Python - Help needed with file reading

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.

Categories

Resources