import json
def write_json(data, file='users.json'):
with open(file, 'w') as f:
json.dump(data, f, indent=4)
while True:
user = {'name':[], 'password':[]}
choice = int(input('1) Register, 2) Login\n>> '))
if choice == 1:
username = input('Enter username: ')
password = input('Enter password: ')
user['name'] = username
user['password'] = password
print('Registered successfully')
with open('users.json') as json_file:
data = json.load(json_file)
users = data['users']
for user in users:
if user['name'] == username:
print(f'User "{username}" already exists')
break
new_user = user
users.append(new_user)
write_json(data)
if choice == 2:
username = input('Enter username: ')
password = input('Enter password: ')
with open('users.json', 'r') as f:
data = json.load(f)
for user in data['users']:
if user['name'] == username and user['password'] == password:
print('Logged in succesfully')
I am trying to make a simple login/register system, but when the user registers for the 2nd time, its gets overridden by the 1st key/value every time, I tried user.clear() but it doesnt seem to have an effect
The issue is that you are using a single dict item for all your users. The way you've set it up only allows for one user to exist.
You need to restructure your dict. You could do a list of dict items, but I would suggest using the username as the key in your dict. Since usernames are supposed to be unique, this makes sense IMHO.
In case you want to use the simpler list of dict items metioned above, you would structure it as follows:
[
{'Edo': 'mypassword'},
{'Iso': 'yourpassword'}
]
I've added some comments on the adjusted code below...
import json
def write_json(data, file="users.json"):
with open(file, "w") as outfile:
json.dump(data, outfile, indent=4)
def load_json(file="users.json"):
# try block in case file doesn't exist
try:
with open(file) as infile:
result = json.load(infile)
return result
except Exception as e:
# just printing out the error
print(e)
# should only be file not found error
# returning an empty dict
return {}
while True:
# you need to load before actually doing anything.
# if you don't you might overwrite the file
userlist = load_json()
# newlines for each option
choice = int(input("1) Register\n2) Login\n>> "))
if choice == 1:
username = input("Enter username: ")
# check if user already exists before requesting password
# since usernames are supposed to be unique, you can just
# create a dict with the key being username.
# you could use the value directly for password, but
# if you need to store more values for a user, I advice
# you use another dict as the value.
if username in userlist:
print(f"User {username} already exists")
# do some other magic here to handle this scenario
# continue makes the while loop go to the next iteration
continue
password = input("Enter password: ")
userlist[username] = {"password": password, "someotheruserdate": "dunno?"}
write_json(userlist)
# only print the success **after** you've actually
# completed all relevant logic.
print("Registered successfully")
# change this to elif instead of a second if statement
elif choice == 2:
username = input("Enter username: ")
password = input("Enter password: ")
if username in userlist and userlist[username]["password"] == password:
print("Logged in succesfully")
else:
# handle wrong username/password
# here you need to check after getting both username&password
print("Incorrect username/password combination")
Related
I am making a user system. I need to store the usernames and passwords in a file.
Case 1: If existing user=
I need to read the username and password to check existing user.
I need to check if the passwords match from the keyed in value and from the dictionary value.
Case 2 : If new user=
I need to check if the username already exist in the database.
If not then, i need to append the username and password in existing file without overwriting.
The problem here, i have utilised json here but it seems to overwrite the existing dict.
I have tried writing to a simple text file and i encounter problem in case when reading the file and also when i check if username exists in case 2.
# Login System Management
import json
class LoginSystem:
def __init__(self): # Opening and reading the registered users json.file
self.users = json.load(open("Users.json"))
self.login_screen()
def login_screen(self): # Log on screen to verify new or old user.
while True:
main_log = input("Are you new user?\n[Y]es or [N]o: ")
if main_log == "Y":
self.new_user()
break
elif main_log == "N":
self.old_user()
break
else:
print("Invalid answer.\n")
def old_user(self): # Log in screen if old user.
while True:
user_id = input("Please enter your user id: ")
user_password = input("Please enter your password: ")
if len(user_id) <= 64 and len(user_password) <= 64 and self.check_system(user_id, user_password):
print("Logging In")
break
else:
print("Wrong password or username!\n")
def check_system(self, name, password): # Checking system to verify old user id and password.
data = self.users
try:
expected_password = data[name]
except KeyError:
return False
if password != expected_password:
return False
return True
def new_user(self): # Log in screen if new user.
while True:
print("\nMax Length is 64 chars.")
reg_id = input("Register your username: ")
reg_password = input("Key in password: ")
if len(reg_id) <= 64 and len(reg_password) <= 64:
if reg_id not in self.users:
print("Loading.....")
self.update_database(reg_id, reg_password)
print("Registered Successfully.")
break
else:
print("User already registered!\n")
self.old_user()
break
else:
print("Error. Max Length is 64 chars.\n")
def update_database(self, new_user_name, new_user_password): # Writing new username and password to json.file
new_username = new_user_name
new_password = new_user_password
field = [new_username, new_password]
with open("Users.json", "w") as f:
json.dump(field, f)
check = LoginSystem()
The problem is that you are opening the csv file in "write" mode. This mode replaces what you have written in the database so far with the new line. Use "append" instead.
with open("Users.json", "a") as f:
I had figure out the answer. If anyone wants to refer you can follow.
First, I have created a csv file with row of line username,password and save it in the same directory.
The rest as follows the code.
# Login System Management import csv import time
class LoginSystem:
def __init__(self): # Opening
self.login_screen()
def login_screen(self): # Log on screen to verify new or old user.
while True:
main_log = input("Are you new user?\n[Y]es or [N]o: ")
if main_log == "Y":
self.new_user()
break
elif main_log == "N":
self.old_user()
break
else:
print("Invalid answer.\n")
def old_user(self): # Log in screen if old user.
while True:
user_id = input("\nPlease enter your user id: ")
user_password = input("Please enter your password: ")
if len(user_id) <= 64 and len(user_password) <= 64 and self.read_database(user_id, user_password):
print("Successful")
break
else:
print("Wrong password or username!\n")
def new_user(self): # Log in screen if new user.
print("\nMax Length is 64 chars.")
reg_id = input("Register your username: ")
if self.check_database(reg_id) is True:
while True:
reg_password = input("Key in password: ")
if len(reg_id) <= 64 and len(reg_password) <= 64:
print("Loading.....")
time.sleep(2)
self.update_database(reg_id, reg_password)
print("Registered Successfully.")
break
else:
print("Error. Max Length is 64 chars.\n")
else:
print("User Already Exists.\n")
self.old_user()
def read_database(self, name, password): # Checking if password match to username
with open("Users.csv", "r") as f:
reader = csv.reader(f)
user_list = {}
for row in reader:
user_list[row[0]] = row[1]
try:
expected_password = user_list[name]
if password == expected_password:
print("Logging In")
time.sleep(2)
return True
except KeyError:
return False
if password != expected_password:
return False
def check_database(self, new_name): # Checking if new id exists in user database
with open("Users.csv", "r") as f:
reader = csv.reader(f)
user_list = {}
for row in reader:
user_list[row[0]] = row[1]
if new_name in user_list.keys():
return False
elif new_name not in user_list.keys():
return True
def update_database(self, new_user_name, new_user_password): # Writing new username and password to file
with open("Users.csv", "a", newline="\n") as f: # appends the new username and password to new row of line
writer = csv.writer(f)
writer.writerow([new_user_name, new_user_password])
check = LoginSystem()
**This is a practice application
I have a text file containing a id & a password. Each pair is on separate lines like so:
P1 dogs
P2 tree
I then have 2 functions to allow the user the add another id/password or update the password by selecting an ID then the new password. (I have removed the save functionality so I don't create loads of pairs when testing)
The question is how would I write a check function so that when the user is creating a new pair.. it checks if the id/password already exists. Then on the update password function, it only checks if the password exists?
My code so far:
#Keyword check
def used_before_check(keyword, fname):
for line in open(fname, 'r'):
login_info = line.split()
username_found = False
for line in login_info:
if keyword in line:
username_found == True
if username_found == True:
return True
else:
return False
# New password function
def new_password():
print("\nCreate a new password")
new_id_input = input("Please give your new password an ID: ")
new_password_input = input("Please enter your new password: ")
print("ID in use?", used_before_check(new_id_input, txt_file))
print("Password in use?", used_before_check(new_password_input, txt_file))
#Change password function
def change_password():
print("\nChange password")
id_input = input("Enter the ID of the password you'd like to change: ")
password_input = input("Now enter the new password: ")
print("password_input",used_before_check(password_input, txt_file))
The easiest way would be to use JSON:
import json
import os
def new_password(user, password, password_dict={}):
if user in password_dict:
password_dict[user] = password # change password
else:
password_dict[user] = password # new password
return password_dict
def read_passwords(filename):
if not os._exists(filename):
return {}
with open(filename, 'r') as f:
s = f.read()
return json.loads(s)
password_filename = 'my_passwords.json'
password_dict = read_passwords(password_filename)
user = ''
while not user == 'q':
user = input('user:')
password = input('new password:')
if user != 'q':
password_dict = new_password(user, password, password_dict)
s = json.dumps(password_dict)
with open(password_filename, 'w') as f:
f.write(s)
Not that I have included a seemingly unnecessary if clause in new_password. This is just for you that you can easily enter your own code what you want to do (maybe different) in each case.
Create a function to store your usernames/passwords in a dictionary, then you can easily check it for existing usernames/passwords
To store in dictionary:
def process_file(fname):
username_pw_dict = {}
for line in open(fname, 'r'):
login_info = line.rstrip().split()
username = login_info[0]
pw = login_info[1]
username_pw_dict[username] = pw
return username_pw_dict
username_pw_dict = process_file(fname)
Then you can check for existing usernames or passwords like this:
if new_username in username_pw_dict:
print("username already exists")
if new_pw in username_pw_dict.values():
print("password already exists")
When you are reading the file, make a dictionary with all the IDs as its keys.
In next step, reverse the dictionary key-value pair so all its values (i.e all passwords) become its keys.
Finally, when you enter a new ID and password, just check those dictionaries to know if they already exist. You may refer to this below code:
dict_ids = {1 : "one", 2:"two", 3:"three"};
dict_pwds = {}
for key, value in dict_ids.items():
for string in value:
dict_pwds[value] = key;
print "dict_ids ", dict_ids;
print "dict_pwds ", dict_pwds;
if 'myid' in dict_ids.keys():
print "ID exist! "
else:
print "New ID"
if 'mypwd' in dict_pwds.keys():
print "Password exist! "
else:
print "New Password"
I am trying to make a login system that is looped basically and whenever I try to enter the correct details that are even stored in the .csv file, it outputs as incorrect username/password no matter what I put. This code works for python 3.6 but I need it to work for python 3.2.3.
loop1 = False #for this bit of code (logging in)
loop2 = False #for next bit of code
while loop1 == False:
choice = input("Login/SignUp [TYPE 'L' OR 'S']: ").lower()
if choice == "l":
username = input("Username: ")
password = input("Password: ")
f = open("usernamepassword.csv","r")
for line in f:
details = line.split(",")
if username == details[0] and password == details[1]:
print("Welcome")
break
#this whole bit of code is meant to read from the csv and check if the login details are correct
else:
print("Username/Password [INCORRECT]")
Allow me to refactor your code:
def login(username, password):
with open("usernamepassword.csv", "r") as csv:
all_details =
[[attr.strip() for attr in line.split(",")]
for line in csv]
return any(
username == details[0]
and password == details[1]
for details in all_details)
def login_action():
username = input("Username: ")
password = input("Password: ")
if not login(username, password):
raise ValueError("Username/Password [INCORRECT]")
return True
_USER_ACTIONS = {
'l': login_action
}
def main():
while True:
choice = input("Login/SignUp [TYPE 'L' or 'S']: ").lower()
action = _USER_ACTIONS[choice]
try:
if action():
break
except Exception as err:
print(err.message)
I think your unexpected behavior comes from not stripping the values you get after splitting by ,
Solved by replacing:
if username == details[0] and password == details[1]:
With:
if username == details[0] and (password+"\n") == details[1]:
You may have a bug in line.split(','), try line.strip().split(',')
TL; DR: posted a proper solution there : https://github.com/cgte/stackoverflow-issues/tree/master/47207293-csv-dict
I'll stuff up my answer later if needed.
Furthermore you have a poor code design here, and find yourself debugging in the middle of a loop.
So first of all : load the data file, store content to a dict.
f = open("usernamepassword.csv","r")
for line in f:
details = line.split(",")
if username == details[0] and password == details[1]:
print("Welcome")
break
Should become
user_pass = {}
f = open("usernamepassword.csv","r")
for line in f:
user, password = line.strip().split(",")
user_pass[user] = password
f.close()
or better
with open("usernamepassword.csv","r") as f:
for line in f.readlines():
user, password = line.split().split(",")
user_pass[user] = password
eventually run python -i yourfile.py and type "user_pass" to see what is actually stored when correct go on further code.
Think of using the csv module : https://docs.python.org/3/library/csv.html
Then get username and password from input and check:
if login in user_pass and user_pass[login] = password:
# or better `if user_pass.get(login, None) == password:`
do_stuff()
I'm writing a program that will verify a username:
def user_login():
""" Login and create a username, maybe """
with open('username.txt', 'r') as f:
if f.readline() is "":
username = raw_input("First login, enter a username to use: ")
with open('username.txt', 'a+') as user:
user.write(username)
else:
login_id = raw_input("Enter username: ")
if login_id == str(f.readline()):
return True
else:
print "Invalid username."
return False
if __name__ == '__main__':
if user_login() is not True:
print "Failed to verify"
Everytime I run this it outputs the following:
Enter username: tperkins91
Invalid username.
Failed to verify
How do I compare user input to reading from a file?
Opening the same file again in another nested context is not a good idea. Instead, open the file once in append mode, and use f.seek(0) to return to the start whenever you need to:
def user_login():
""" Login and create a username, maybe """
with open('username.txt', 'a+') as f:
if f.readline() is "":
username = raw_input("First login, enter a username to use: ")
f.seek(0)
f.write(username)
# return True/False --> make the function return a bool in this branch
else:
login_id = raw_input("Enter username: ")
f.seek(0)
if login_id == f.readline():
return True
else:
print "Invalid username."
return False
if __name__ == '__main__':
if user_login() is not True:
print "Failed to verify"
Returning a bool value in the if branch is something you may want to consider so the return type of your function is consistent as bool, and not None as in the current case.
When you use readline() the first time the current file position is moved past the first record. A better way to find if the file is empty is to test it's size:
import os.path
import sys
def user_login():
fname = 'username.txt'
""" Login and create a username, maybe """
if os.path.getsize(fname) == 0:
with open(fname, 'w') as f:
username = raw_input("First login, enter a username to use: ")
f.write(username)
return True #/False --> make the function return a bool in this branch
else:
with open(fname, 'r') as f:
login_id = raw_input("Enter username: ")
if login_id == f.readline().rstrip():
return True
else:
print >>sys.stderr, "Invalid username."
return False
if __name__ == '__main__':
if user_login() is not True:
print "Failed to verify"
f.readline() will include a trailing newline, if there is one in the file, whereas raw_input() will not. While we don't explicitly write one, someone might edit the file and add a newline unintentionally, hence the addition of the rstrip() as a defensive precaution.
I'm currently using JSON to make a username/password program but I have a problem with duplicate accounts. I tried to code a way to prevent users from creating usernames that the JSON database already contains, but it doesn't quite work.
Problems:
Asks for the username, doesn't ask for the password even when the file tried is empty
Sometimes says the username already exists, but creates the account duplicate anyway.
What I want the program to do:
Ask for the new username/password
If the username is unique, place the new account in the file
If the username is already owned, don't add the new account and go to the start of the function.
How would I do this efficiently?
This is the code I've tried, but the problems I mentioned make it invalid
def createUser():
global accounts
nUsername = input("Create Username » ")
for item in accounts:
if item[0] == nUsername:
return "Already Exsists!"
else:
nPassword = input("Create Password » ")
entry = [nUsername, nPassword]
accounts.append(entry)
accounts = accounts[:500000]
autoSave()
For anyone wondering, this is what the autosave() function is:
def autoSave():
with open("Accounts.json", "w") as outfile:
json.dump(accounts, outfile)
And this is what the inside of the JSON file looks like:
[["ExampleUsername", "BadPasswrdo14130"]]
There is many mistakes so I will use comment to explain changes:
# you file containt utf8 chars, you need to specify encoding
# coding=utf-8
import os
import json
# I use a dict structure instead of a list for easier retrieval
# you can easily see if an account exist and get its password
# also global keyword is to avoid, so prefer declaring in the global context instead of pushing to the global context
accounts = {}
# if we have a file, deserialize content
if os.path.exists("/tmp/Accounts.json"):
try:
with open("/tmp/Accounts.json") as f:
accounts = dict(json.loads(f.read()))
except:
pass
def createUser():
# input is equivalent to eval(raw_input(... which is not the goal here
nUsername = raw_input("Create Username » ")
# with a dict, no need to iterate through, simply use `in`
if nUsername in accounts.keys():
return createUser()
nPassword = raw_input("Create Password » ")
# this is how you assign the new account
accounts[nUsername] = nPassword
autoSave()
def autoSave():
with open("/tmp/Accounts.json", "w") as outfile:
# we convert here the dict to your list structure
json.dump(list(accounts.iteritems()), outfile)
def existingUser():
eUsername = raw_input("Your Username » ")
ePassword = raw_input("Your Password » ")
for item in accounts:
if eUsername in accounts and accounts[eUsername] == ePassword:
return 'Processing Sucessfully logged into your account!'
else:
return "Login failed"
createUser()
I would do it this way:
# This function will help us to check if the user already exists
def alreadyExist(nUsername):
global accounts
for account in accounts:
if account[0] == nUsername
return True
return False
def createUser():
global accounts
# We declarate nUsername first as None
nUsername = None
# While the username exists, we have to ask the user for the username
while not nUsername or alreadyExist(nUsername):
nUsername = input("Create Username » ")
# We are out of the bucle. The username doesn't exist, we can ask for the password
nPassword = input("Create Password » ")
entry = [nUsername, nPassword]
accounts.append(entry)
accounts = accounts[:500000]
autoSave()
Fixed one issue of my code, but made another. This section was working fine before the chances from #CyrBill
def existingUser():
eUsername = input("Your Username » ")
ePassword = input("Your Password » ")
for item in accounts: #no need for braces
if item[0] == eUsername and item[1] == ePassword:
return 'Processing Sucessfully logged into your account!'
else:
return "Login failed"