This is my python password system using pickle. It's bad, I know, but it's my first time with pickle.
import pickle
import os
userlist = {'user1':'userpass1', 'user2':'userpass2'}
users = open ("users.pkl", 'wb')
pickle.dump (userlist, users)
username = input ("Enter your username: ")
password = input ("Enter your password: ")
if (username in userlist) and (password == userlist[username]):
print ("Access Granted")
else:
newaccount = input ("User not found. Shall I create a new account? ")
if newaccount == "yes":
username = input ("Please enter your username: ")
password = input ("Please enter yout password: ")
userlist.update({username:password})
pickle.dump (userlist, users)
users.close()
My problem is that, whenever I go to add a new account, using this part:
newaccount = input ("User not found. Shall I create a new account? ")
if newaccount == "yes":
username = input ("Please enter your username: ")
password = input ("Please enter yout password: ")
userlist.update({username:password})
pickle.dump (userlist, users)
users.close()
It seems to add it (and it looks like it's there in the pickle file using notepad) but, I restart the python file, and it does not see it.
I believe it is something to do with this part:
userlist = {'user1':'userpass1', 'user2':'userpass2'}
users = open ("users.pkl", 'wb')
pickle.dump (userlist, users)
Any help is appreciated! :D
You overwrite each time you run the program with w:
users = open ("users.pkl", 'wb')
If you wanted to get the previously pickled items you would need to see if the file already exists and pickle.load to get the previously pickled items and then dump at the end of your code.
Something like the following:
from tempfile import NamedTemporaryFile
try:
# see if we have run this before
with open ("users.pkl", 'rb') as users:
users_dict = pickle.load(users)
except IOError:
# if not set to defualt
users_dict = {'user1':'userpass1', 'user2':'userpass2'}
username = input ("Enter your username: ")
password = input ("Enter your password: ")
if users_dict.get(username) == password: # unless a password can be None we can use get
print ("Access Granted")
else:
newaccount = input("User not found. Shall I create a new account? ")
if newaccount == "yes":
username = input("Please enter your username: ")
password = input ("Please enter yout password: ")
users_dict[username] = password # just use key = value
with NamedTemporaryFile("wb",dir=os.path.dirname("users.pkl"),delete=False) as f: # in case we get exception use temp file
pickle.dump (users_dict, f)
os.replace(f.name,"users.pkl") # update original
Related
I am currently developing a desktop login-register app for my practice, and was having some trouble with login and register. If I type REGISTER and add my info in f.write() command it stores my info but after that everything just goes, like the whole file gets formatted (this was register issue).
The login issue is if I want to check whether a name or password in file exists or not (this command could be wrong). I tried to use if login_email and login password in f: but it says that login_email and password do not exist.
Code:
f = open('pass.txt', 'w')
fr = open('pass.txt', 'r')
from time import sleep
login_list = "LOGIN"
register_list = "REGISTER"
if 1 > -3232:
print("Type register for new account\ntype login for login into existing account")
bi = input("==> ")
if bi.upper() in login_list:
print("you are registered?? nice now loginnn!!")
login_1 = input("your username: ")
login_2 = input("your password: ")
if login_1 and login_2 in fr:
print("Nice my program worked??")
exit()
else:
exit()
elif bi.upper() in register_list:
print("you are in register section: ")
sleep(.9)
print("NOTE: Your password should only contain alphabets!")
sleep(4)
reg_1 = input("your username: ")
sleep(.9)
reg_2 = input("your password: ")
sleep(.9)
reg_2v1 = input("confirm password")
if reg_2 == reg_2v1:
f.write(reg_1 + " : " + reg_2 + "\n")
print("now login again,\")
else:
print("invalid password, try again")
else:
print("you gave me the wrong command")
else:
exit()
You shouldn't open the file in both read and write mode at the beginning of the script. Opening it in write mode empties the file, so you won't be able to read it. You'll also wipe out all the other usernames and passwords. You should open the file in read mode when logging in, and append mode when registering, to add a new line without removing the old ones. And you should use with to just open the file around the code that needs to use it.
if login_1 and login_2 in fr: is not the correct way to test if both the username and password are in the file. Due to operator precedence, that's parsed as if login_1 and (login_2 in fr):. This just checks that login_1 is not empty, and then just checks if login_2 is in the file. The second test will never work, because the lines of the file all end with newline, but login_2 doesn't, so they'll never match.
You need to check for the fully formatted line, including the newline.
if f'{login_1} : {login_2}\n' in fr:
if bi.upper() in login_list: seems suspicious. login_list is not a list, it's a string. So this will check whether bi.upper() is any substring -- it will succeed if the user enters log or in or gi, not just login. Is that intentional?
Full code:
from time import sleep
login_list = "LOGIN"
register_list = "REGISTER"
if 1 > -3232:
print("Type register for new account\ntype login for login into existing account")
bi = input("==> ")
if bi.upper() in login_list:
print("you are registered?? nice now loginnn!!")
login_1 = input("your username: ")
login_2 = input("your password: ")
with open('pass.txt', 'r') as fr:
if f'{login_1} : {login_2}\n' in fr:
print("Nice my program worked??")
exit()
else:
exit()
elif bi.upper() in register_list:
print("you are in register section: ")
sleep(.9)
print("NOTE: Your password should only contain alphabets!")
sleep(4)
reg_1 = input("your username: ")
sleep(.9)
reg_2 = input("your password: ")
sleep(.9)
reg_2v1 = input("confirm password")
if reg_2 == reg_2v1:
with open('pass.txt', 'a') as f:
f.write(reg_1 + " : " + reg_2 + "\n")
print("now login again,")
else:
print("invalid password, try again")
else:
print("you gave me the wrong command")
else:
exit()
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")
The issue I keep having is that after I register a username/password, then try to login if I get any letters or numbers of the login/password correct it accepts it, for example if my username is Fof and my Password is tog and I enter the username as just f or o it will accept it.
Here's the code written in Python idle 3.7:
if Game == "1":
username = input("Please enter your username: ")
if username in open("Names.txt").read(): #fix
print ("Welcome " + username)
password = input("Please enter your password: ")
if password in open("Passwords.txt").read():
print ("success!")
else:
print("Username incorrect!")
An explanation of what you need:
You need to look for the exact match of the word in the file, not just in because that would always return True and hence it would bypass:
An example:
NamesList:
Fof
Abc
Def
and then:
import re
text = input("enter Name to be searched:")
NamesFile = open("NamesList.txt", "r")
for line in NamesFile:
if re.search(r"\b" + text + r"\b", line):
print(line)
else:
print("Name not found")
break
OUTPUT:
enter Name to be searched:Fof
Fof
In another case:
enter Name to be searched:f
Name not found
If you store logins and passwords the way you do, then one user can use password of another user and vice versa. It's better to store login-password pair together:
File credentials.json:
{"Fof": "tog"}
Code:
import json
with open('credentials.json') as f:
credentials = json.load(f)
username = input('Please enter your username: ')
if credentials.get(username):
print('Welcome {}'.format(username))
password = input('Please enter your password: ')
if credentials[username] == password:
print('success!')
else:
print('Username incorrect!')
Let's try to hack:
Please enter your username: f
Username incorrect!
Successful login:
Please enter your username: Fof
Welcome Fof
Please enter your password: tog
success!
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.
I need to check that the usernames and passwords match up with the details in a text file. I'm not sure how to do this. Here is what i have so far (saving the username to the file).
print("Are you a returning player?")
user = input()
if user.lower() == "no":
username = input("Please enter a username for your account.\n")
password = input("Please enter a password for your account.\n")
file = open("account.txt","a")
file.write(username)
file.write("\n")
file.write(password)
file.close()
else:
user_name = input("Please enter your username.\n")
pass_word = input("Please enter your password.\n")
There is another method using with open that close your file after the procedures are done inside the loop, so you can create a read loop and an append loop. For this I like the idea of storing the name and password on the same line, that way we can check to make sure the name and corresponding password are linked to each other rather than being able to use any password for any name. Also when using append we are going to have to add a '\n' or everything we write will be written to the same line
To verify the user we open the file as r and then we can use for line in f to get all the lines in the .txt from there we can loop through each line and if both username and password exist in the same line, we can welcome the user, if not send them back to the beginning.
Hope this helps!
while True:
user = input('\nAre you a returning player: ')
if user.lower() == 'no':
with open('accounts.txt', 'a') as f:
username = input('\nEnter username: ')
password = input('Enter password: ')
combo = username + ' ' + password
f.write(combo + '\n')
else:
with open('accounts.txt', 'r') as f:
username = input('\nEnter username: ')
password = input('Enter password: ')
for line in f:
if username + ' ' + password + '\n' == line:
print('Welcome')
break
else:
print('Username and/or Password Incorrect')
Are you a returning player: no
Enter username: vash
Enter password: stampede
Are you a returning player: yes
Enter username: vash
Enter password: stacko
Username and/or Password Incorrect
Are you a returning player: yes
Enter username: vash
Enter password: stampede
Welcome