Using a while loop to reject duplicate new username - python

I'm trying to create a simple new user registration function. There should be a process for assessing new usernames entered by the user which checks for duplicates in an external file and rejects them. The file user.txt is simply a line-by-line list of usernames and passwords separated by a comma.
Problem: the code keeps ignoring my effort to match each new user input variable user with the usernames stored in the text file (line[0])
The contents of "user.txt" is as follows:
admin, admin
admin1, admin1
admin2, admin2
etc.
Any help appreciated thanks
def reg_user():
if username == "admin" and login == True:
registry = open("user.txt", "r+")
# Requests username and prevents duplicates
for line in registry:
line = line.split(", ")
while registry:
user = input("Please enter a username to register:\n")
if user == line[0]:
print("Sorry, that username is taken. Try a different one.")
password = input("Please enter a password to register:\n")
passcheck = input("Please re-enter your password:\n")
if password != passcheck:
print("Your password doesn't match. Please re-enter your password.")
else:
print("Thanks. You're registered")
user = registry.write("\n" + user + ", " + password)
registry.close()

Something like this should work:
username = 'admin'
login = True
if username == "admin" and login == True:
file = open("user.txt", "r+")
registry = file.read().split('\n')
# Requests username and prevents duplicates
ok = False
while not ok:
user = input("Please enter a username to register:\n")
ok = True
for line in registry:
if user == line.split(', ')[0]:
print("Sorry, that username is taken. Try a different one.")
ok = False
password = input("Please enter a password to register:\n")
passcheck = input("Please re-enter your password:\n")
if password != passcheck:
print("Your password doesn't match. Please re-enter your password.")
else:
print("Thanks. You're registered")
user = file.write("\n" + user + ", " + password)
file.close()
user.txt file:
a, foo
e, pass
Example interaction:
Please enter a username to register:
a
Sorry, that username is taken. Try a different one.
Please enter a username to register:
e
Sorry, that username is taken. Try a different one.
Please enter a username to register:
f
Please enter a password to register:
pass1
Please re-enter your password:
pass1
Thanks. You're registered

Related

How to create a login system that can validate user to enter valid username and password?

I was trying to create a login system that can check if the username and password is include in the userlist (which I use it to store different user password and their name).
userlist = []
def userpage():
print("user page accessed")
opt = int(input("Enter '0' to log out"))
if opt == 0:
mainpage()
def signin():
username = input("Please enter username: ")
for user in userlist:
if username in user:
password = input("Please enter password: ")
if password in user:
userpage()
else:
print("Incorrect password")
mainpage()
else:
print("Unregister username")
mainpage()
def signup():
username = input("Please enter username: ")
password = input("Please enter password: ")
userlist.append([username,password])
print(userlist)
userpage()
def mainpage():
opt = int(input("Enter '0' to sign up, '1' to sign in: "))
if opt == 0:
signup()
elif opt == 1:
signin()
mainpage()
Notice that I use print(userlist) to check whether the username and password is being store in the list or not. The signup function works(As from what I saw from the print(userlist), but there's issue with signin function(which I want to use it to check valid username and password). As the user will straight away access the userpage after they signup, the signin function works when the first user signup and sign in again after they logout. But the follow up user signup and wanted to sign in again after log out, it will keep saying it is an unregister username, but I can clearly see that the userlist have their username.
Your problem is that you raise an error immediately if the first array of credentials does not match. It checks the first user-password pair, then if it doesn't match,you raise an error. So your code should be:
def signin():
username = input("Please enter username: ")
for c,user in enumerate(userlist):
if username in user:
password = input("Please enter password: ")
if password in user:
userpage()
else:
print("Incorrect password")
mainpage()
else:
if c != len(userlist):
pass
else:
print("Unregistered username")
mainpage()

infinite while loop in last lines of code

Could anyone please assist me with the following:
I have a code that reads a username and password then allows users to access a program. I have the first option to register a new user correct. I'm having a problem with an infinite loop problem with my last two lines of code. Id like to run a string stating that if an unregistered username is entered it returns with a string saying that there is no such registered user. The string just keeps running in the loop and is there anything I could do to change this.
username: admin
password: adm1n
my code is as follows:
users = {}
with open ('user.txt', 'rt')as username:
for line in username:
username, password = line.split(",")
users[username.strip()] = password.strip() # strip removes leading/trailing whitespaces
uinput = input("Please enter your username:\n")
while uinput not in users:
print("Username incorrect.")
uinput = input("Please enter a valid username:/n")
if uinput in users:
print ("Username correct")
with open('user.txt', 'rt') as password:
for line in password:
username, password = line.split(",")
users[password.strip()] = username.strip() # strip removes leading/trailing whitespaces
uinput2 = input("Please enter your password:\n")
while uinput2 not in users:
print("Your username is correct but your password is incorrect.")
uinput2 = input("Please enter a valid password:\n")
if uinput2 in users:
password2 = ("Password correct")
print (password2)
if password2 == ("Password correct"):
menu = (input("\nPlease select one of the following options:\nr - register user\na - add task\nva - view all tasks\nvm - view my tasks\ne - exit\n"))
if menu == "r" or menu == "R":
new_user = (input("Please enter a new user name:\n"))
new_password = (input("Please enter a new password:\n"))
with open ('user.txt', 'a')as username:
username.write("\n" + new_user + ", " + new_password)
elif menu == "a" or menu == "A":
task = input("Please enter the username of the person the task is asigned to.\n")
while task not in username:
print("User not registered. Please enter a valid username:\n")
You have a loop at the end that says
while task not in username:
print("User not registered. Please enter a valid username:\n")
This is unfinished and will loop endlessly since if task is not in username, printing something will not change that fact so it will just loop and print again. You probably wanted to add something like
task = input("Please enter a valid username of a person the task is assigned to.\n")

Using lists to check usernames and passwords

I'm not sure why this code isn't working. I have the error TypeError: 'int' object is not iterable I need the code to check the usernames and passwords from two different lists, and if the username and password match spots in the list and are correct, the user is "granted access."
#Part 1: Opening the files and grabbing data
filename1 = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\usernames.txt"
file = open(filename1, "r")
#Usernames
users = file.read()
usernameslist = [line.strip() for line in open("c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\usernames.txt")]
print(users) #Check file
print(usernameslist) #Check usernames list
filename2 = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\passwords.txt"
file = open(filename2, "r")
#Passwords
passwords = file.read()
passwordslist = [line.strip() for line in open("c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\passwords.txt")]
print(passwords) #Check file
print(passwordslist) #Check passwords list
#Compile the usernames and passwords lists for easy checking
compiled_list = list(zip(usernameslist,passwordslist))
print(compiled_list)
#Scores
filename3 = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\scores.txt"
file = open(filename3, "r")
scores = file.read()
scoreslist = [line.strip() for line in open("c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\scores.txt")]
print(scores) #Check file
print(scoreslist) #Check scores
def login():
username = input("Please enter your username: ")
password = input("Please enter your password: ")
for i in range(len(usernameslist)):
if username == i and password == [i]:
print("Access granted!")
else:
print("Incorrect Login credentials, please try again.")
login()
The problem is in login(), you are using i as an iterator within itself.
def login():
username = input("Please enter your username: ")
password = input("Please enter your password: ")
for i in [usernameslist]:
if username == [i]:
for j in [passwordslist]:
if password == [j]:
return "Access granted!"
else:
return "Incorrect Login credentials, please try again."
else:
return "Incorrect Login credentials, please try again."
This above should find the password and work with your logic.
However, shouldn't you be using the specific username for the password? This is checking if the username and the password are available, not whether the password matches the username. As you are looping through password and username separately, you would simply check if someone has the password and someone has the username, whether it is the same person or not. If so, replace with this:
def login():
username = input("Please enter your username: ")
password = input("Please enter your password: ")
for i in range(len(usernameslist)):
if username == i and password == j:
return "Access granted!"
else:
return "Incorrect Login credentials, please try again."
Make sure with this that the usernames and passwords are ordered the same within both lists. Or, I'd recommend storing a 2D list looking something like this:
list = [["Annie","password1"],["bob","wordpass39"]] where the first entry is the username and second is the password.
Edit: with the fixed login() function you should now do this:
def login():
username = input("Please enter your username: ")
password = input("Please enter your password: ")
for i in range(len(usernameslist)):
if username == i and password == i:
print("Access granted!")
else:
print("Incorrect Login credentials, please try again.")

how do i create a username and password system that remembers different usernames everytime i use the code?

i need to create a music quiz game but only authorised players are allowed to play the game so i figured id create a username and password system but how do i do this please?
so far i have this:
name = input("Please enter your name. ")
age = input("Now please enter you age. ")
username = name[0:3] + age
print ("Your username has been created and
is", username, ".")
password = input("Now please create a
password. ")
file = open("Login.txt","a")
file.write (username)
file.write (",")
file.write (password)
file.write("\n")
file.close()
print ("Your login details have been saved")
it saves the username and passwords created but how do I create a system so that the user can just enter their username and password after this from the stored usernames and passwords?
You can use dictionnary for doing it.
import json
create_user():
global users
name = input("Please enter your name. ")
age = input("Now please enter you age. ")
username = name[0:3] + age
print ("Your username has been created and is", username, ".")
password = input("Now please create a password.")
users[username] = password
with open ("Login.txt", 'w') as fd:
json.dump(users, fd)
print("Your login details have been saved")
load_users():
try:
with open("Login.txt", 'r') as fd:
users = json.load(fd)
except:
print("can't load Login.txt, default dict used")
users = {}
login():
username = input("username >")
password = input("password >")
if username in users.keys() and password == users[username]:
print("logged as", username)
return username
else
print("login failed")
return None
users = load_users()
Some suggestions flat out:
Ask for the password twice at the time of creation; saves the pain of dealing with typos
Use getpass.getpass() for inputting passwords
Don't store passwords in a file. If databases are too much of a hassle, use one-way hash functions.
Now, assuming you'd still like to continue without a database, an easier way to do this might be to store username-password pairs in a dictionary format in [say] a pickle object. Every time you ask somebody to log in, ask for a username, check for the presence of the username in the dictionary keys. If you find the key, ask for the password, and match it with the value corresponding to the key.
from getpass import getpass
import os, pickle, hashlib
userdata = dict()
if os.path.exists('userinfo.pickle'):
userdata = pickle.load(open('userinfo.pickle','rb'))
username = raw_input("Enter username:")
pwd = getpass("Enter password:")
pwd2 = getpass("Enter password again:")
if pwd != pwd2:
exit(0)
h = hashlib.md5()
h.update(pwd)
pwd = h.hexdigest()
if username not in userdata:
userdata[username] = pwd
with open('userinfo.pickle','wb') as handle:
pickle.dump(userdata,handle)
# Logging in
userdata = pickle.load(open('userinfo.pickle','rb'))
username = raw_input("Enter username:")
pwd = getpass("Enter password:")
h = hashlib.md5()
h.update(pwd)
pwd = h.hexdigest()
if username in userdata:
if userdata[username] == pwd:
print("Success.")
else:
print("Incorrect password.")
else:
print("User not found.")
This should do it.
I think you would be better off using a CSV to separate your names and usernames, this would make it much easier to search for a username and password pair. If you would want to use this, the following should work:
Creating username/password:
import pandas as pd
userpass = pd.read_csv('Login.csv')
name = input("Please enter your name. ")
age = input("Now please enter you age. ")
username = name[0:3] + age
print ("Your username has been created and
is", username, ".")
password = input("Now please create a
password. ")
newuserpass = [(username, password)]
newuserpass = pd.DataFrame(newuserpass) #Creates a dataframe of username & pass
userpass = userpass.append(newuserpass) #Adds username and pass dataframe to end of username/password save file
userpass.to_csv('Login.csv')
'''This has now saved the login details. Now to read the login details, where pandas makes this quite easy'''
Loading username/password:
loggedin = 0
while loggedin = 0:
userpass = pd.read_csv('Login.csv')
inputusername = input('What is your username?')
inputpassword = input('What is your password?')
if userpass.Password.values[userpass.Username==inputusername] == inputpassword:
userpass = 1
print('Logged in successfully!')
You will need to create a blank file named 'Login.csv' with Username, Password as its contents before this code would function.

python read/write to file login script

I was wondering if anyone would help. I am new to python. I am trying to create a basic login script for a game, that will write a username and password to a text file. When logging in, it will read from that text file and compare the entry made by the user. The code is below:
def Register():
print("Hello! You need to register an account before you can begin")
username = input("Please enter a username: ")
password = input("Now please enter a password: ")
file = open("Login.txt","a")
file.write (username)
file.write (",")
file.write (password)
file.write("\n")
file.close()
print ("Your login details have been saved. ")
print("You will now need to login")
Login()
def Login():
print("Please enter your details to log in")
username1 = input("Please enter your username: ")
password1 = input("Please enter your password: ")
file = open("Login.txt","r")
for row in file:
field = row.split(",")
username = field[0]
password = field[1]
lastchar = len(password)-1
password = password[0:lastchar]
print(username,password)
if username1 == username and password1 == password:
print("Hello",username)
else:
print("incorrect")
#file.close()
user=input("Are you already a user? ")
if user == "Yes":
Login()
elif user =="No":
Register()
print("Welcome to our game")
I have entered the second user who is stored in the text file, It seems to be working but it checks my first entry and says its incorrect and then loops to the second entry. This is the output I keep getting:
Are you already a user? Yes
Please enter your details to log in
Please enter your username: jen
Please enter your password: ben
tess bess
incorrect
jen ben
Hello jen
Welcome to the dice game
>>>
Does anyone have an idea on how to only display the entry you have entered?
Thanks
Like Sharku said, put the print(username,password) in your if below. Also writting clearly the name and password of the user after he typed it isn"t really a smart moove, delete it and just let your message when a user is logging in !
for row in file:
field = row.split(",")
username = field[0]
password = field[1]
lastchar = len(password)-1
password = password[0:lastchar]
if username1 == username and password1 == password:
print("Hello",username)
else:
print("incorrect")
As said by sytech, you could use the break and else clauses of the for loop:
for row in file:
field = row.split(",")
username = field[0]
password = field[1]
lastchar = len(password)-1
password = password[0:lastchar]
if username1 == username and password1 == password:
print("Hello",username)
break
else:
print("incorrect")
Your 'for loop' will loop through each entry in your file, that means for each entry in the file your for loop prints the entry due to this line:
print(username,password)
If you don't want it to print all values in the file remove this line of code.
Adding a 'break' to your if statement, as suggested by others, will mean that as soon as your loop has found the entry that matches the one entered by the user it will leave the loop and not continue going through all values unnecessarily.
You could do something like this:
if username1 == username and password1 == password:
print("Hello",username)
break
else:
continue
This means that when a user input doesn't match an entry in the file the loop will just continue till it finds a match.
However, your code doesn't take into consideration if a user doesn't exist.
import os.path
if not os.path.exists('register.txt'):
file = open('register.txt', 'w')
file.close()
def register():
username = input('Enter username: ')
if username in open('register.txt', 'r').read():
print('Username already exists')
exit()
password = input('Enter password: ')
c_password = input('Enter confirm password: ')
if password != c_password:
print('Sorry password not match')
exit()
handle = open('register.txt', 'a')
handle.write(username)
handle.write(' ')
handle.write(password)
handle.write('\n')
handle.close()
print('User was successfully registered')
exit()
def login():
username = input('Enter username: ')
password = input('Enter password: ')
get_data = open('register.txt', 'r').readlines()
users_data = []
for user in get_data:
users_data.append(user.split())
total_user = len(users_data)
increment = 0
login_success = 0
while increment < total_user:
usernames = users_data[increment][0]
passwords = users_data[increment][1]
if username == usernames and password == passwords:
login_success = 1
increment += 1
if login_success == 1:
print('Welcome ' + username)
else:
print('invalid username & password')
question = input('Do you have an account?/yes/no')
if question == 'yes':
login()
else:
register()

Categories

Resources