Adding new users/passwords to dictionary in python email application - python

I'm having a bit of trouble with this program I've been working on for part of the final for my ITP 100 class. It's supposed to be an email application where you can log in if you are an existing user, or create a new username and password. I'm able to log into existing users with their passwords, and I can create a new username, but when I try to create the new password for it, I keep getting errors. I'm sure it's because I'm not updating the dictionary properly. I'm still pretty new to Python, so hopefully this all makes sense. Any advice?
Also, my program seems to be stuck in an "if loop..?". Whenever I successfully log into an existing user, it show that I've been logged in, but will also go back to the original question "Are you a registered user? y/n? Press q to quit"
Any help is greatly appreciated. Thank you.
import re
users = {}
users={"nkk202": "konrad", "jfk101": "frederick"}
choice = None
login = None
createPassword = None
createUser = None
createLogin = None
print("Welcome to Kmail. The most trusted name in electronic mail.")
print("\nLet's get started")
while choice != "q":
choice = input("Are you a registered user? y/n? Press q to quit: ")
if choice == "q":
print("Thank you for using Kmail. Goodbye.")
if choice == "n":
print("Okay then, let's set up an account for you then.")
createUser = input("Create login name: ")
if createUser in users:
print("I'm sorry, that username is already in use. Please try another!\n")
else:
createPassword = input("Enter a password: ")
if len(createPassword) <5:
print("I'm sorry, this password is too short. Please try another.")
passValue = {1:'Weak', 2:'Good', 3:'Excellent'}
passStrength = dict.fromkeys(['has_upper', 'has_lower', 'has_num'], False)
if re.search(r'[A-Z]', createPassword):
passStrength['has_upper'] = True
if re.search(r'[a-z]', createPassword):
passStrength['has_lower'] = True
if re.search(r'[0-9]', createPassword):
passStrength['has_num'] = True
value = len([b for b in passStrength.values() if b])
print ('Password is %s' % passValue[value])
users.update((createUser, createPassword))
elif choice == "y":
login = input("Enter your username: ")
if login in users:
password = input("Enter your password: ")
if users[login] == password:
print("Welcome", login, "!")
else:
print
print("I'm sorry, either the password/username was unaccaptable, or does not exist. Please try again. \n")

Seems like you just want
users[createUser] = createPassword

Related

Weird Functions Calling and Inconsistent Result

First, I just want to say I'm a newbie, and I apologize for the bad explanation and the long post...
So, as a practice, I wrote a simple python login system with a JSON file where the profiles are stored.
Everything was going well, but all of a sudden my code started behaving weirdly.
this is my main.py file:
import json
with open("profiles.json") as f:
profiles = json.load(f)
def main():
print("-----------------Main--------------------")
option = input("[L]ogin | [S]ign up: ").upper()
if option == "L":
login()
elif option == "S":
sign_up()
else:
print("Please select a valid option.")
main()
def login():
print("-----------------Login--------------------")
username = input("Username: ")
password = input("Password: ")
check_credentials(username, password)
def sign_up():
print("-----------------Sign up--------------------")
new_username = None
new_password = None
# check if this username already exists, return to sign up if true
def username_match():
nonlocal new_username
new_username = input("Username: ")
for profile in profiles["profiles"]:
if new_username == profile["username"]:
print("This username is taken.")
username_match()
# loop back if the passwords do not match
def password_match():
nonlocal new_password
new_password = input("Password: ")
confirm_password = input("Confirm Password: ")
if new_password != confirm_password:
print("Passwords do not match.")
password_match()
username_match()
password_match()
security_question = input("Security Question: ")
security_answer = input("Security Question Answer: ")
profiles["profiles"].append({"username": new_username,
"password": new_password,
"security_question": security_question,
"security_answer": security_answer})
with open("profiles.json", "w") as w:
json.dump(profiles, w, indent=2)
check_credentials(new_username, new_password)
def profile_settings():
input("-----------------Options--------------------"
"\n"
"[P] change password | [U] change username"
"\n"
"[S] change security question | [E] add email"
"\n"
"What would you like to do: ").upper()
print("\nThis section is under construction. Please visit later.")
def check_credentials(username, password):
print("\nchecking credentials...\n")
for profile in profiles["profiles"]:
if profile["username"] != username and profile["password"] != password:
print("Wrong username and password, please try again.")
login()
if profile["username"] == username:
print(f"found username: {username}")
if profile["password"] == password:
print(f"found password: {password}")
else:
print("Wrong password, please try again.")
login()
else:
print("Wrong username, please try again.")
login()
profile_settings()
main()
and this is my profiles.json file:
{
"profiles": [
{
"username": "Hakobu",
"password": "123",
"security_question": "favorite food",
"security_answer": "lemon"
},
{
"username": "Mohammed",
"password": "345",
"security_question": "1",
"security_answer": "1"
}
]
}
Here is what I found weird:
When I try to login to a second profile, it tells me, wrong credentials and put me back to the login() function, but it lets me in for the first profile.
when trying to make a new profile through the sign_up() function, it is supposed to automatically log in but beyond the first profile, the second profile created just does the same thing, it tells me, wrong credentials and put me back to the login() function.
when successfully logging in with the first profile, the profile_settings() function gets called. it's supposed to close after inputing anything, but instead it goes back to the check_credentials() function, says I input the wrong username and password, then going to the login() function straight after the profile_settings() function even though I have not called them anywhere in the profile_settings() function
I have no idea why in god's name this happens. It was working fine just a little bit ago. Tried commenting out the code I wrote after it was working but nothing worked. I have a huge headache now and my back hurts.
After learning about stack calls and stack frames, I now know that the issue was simply the for loop getting resumed after exiting the check_credentials() resulting in what seemed to be an infinite loop of that function.
Here is the improved code:
def check_credentials(username, password):
print("\nchecking credentials...\n")
username_found = False
password_found = False
for profile in profiles["profiles"]:
if profile["username"] == username:
print(f"found username: {username}")
username_found = True
if profile["password"] == password:
print(f"found password: {password}")
password_found = True
break
if not username_found and not password_found:
print("Wrong username and password, please try again.")
login()
elif not username_found:
print("Wrong username, please try again.")
login()
elif not password_found:
print("Wrong password, please try again.")
login()
profile_settings()

Writing to text file formatting

I have an assignment to make a simple task manager/todo list. This code block is just the part of the program that handles login, new username and password registration. When the user registers that input is written to a text file called user.txt.
Whenever it writes to the text file, it writes like this:(['admin', 'adm1n'])
instead, it should write it like this:admin, adm1n
user_file = open("user.txt","r+")
login = False
while login == False:
new = input("Are you a new user? Y/N:\n").lower()
if new == "y":
print("Please register a new username and password:\n")
new_user1 = input("Please enter a new username:\n").split()
new_pass1 = input("Please enter a new password:\n").split()
new_user2 = input("Please confirm your username:\n").split()
new_pass2 = input("Please confirm your password:\n").split()
user_pass1 = new_user1 , new_pass1
user_pass2 = new_user2 , new_pass2
if user_pass1 == user_pass2:
user_file.write(f"{user_pass2},")
user_file.seek(0)
break
elif new == "n":
username = input("Enter your username:\n")
password = input("Enter your password:\n")
valid_user = username
valid_password = password
for line in user_file:
valid_user, valid_password = line.split(", ")
if username == valid_user and password == valid_password:
login = True
if login == False:
print("Incorrect details! Please enter a valid username and password")
What am I doing wrong? I'm sure it's something small.
Thanks in advance!
Because you are making a tuple there. Instead, you should create a string. Here is the corrected version of your code
user_pass1 = new_user1 + ',' + new_pass1
user_pass2 = new_user2 + ',' + new_pass2
if user_pass1 == user_pass2:
user_file.write(f"{user_pass2},")
user_file.seek(0)
break
Thanks for your feedback everyone.
I managed to get it figured out. I added an index to it to print the string and it worked just fine.
user_pass2 = new_user2 , new_pass2
if user_pass1 == user_pass2:
#Writes username and password to text file in format requested.
user_file.write(f'\n{user_pass2[0]}, {user_pass2[1]}')

Trouble navigating through my loops in Python

I have already asked people around me and tried countlessly to get this fix program. The program should be able to add the users websites and passwords as many times as they want to, and show the websites and password they selected.
For now when you answer would you like to add another website? with yes it dosn't re ask for a new website name and password but just repeats the question would you like to add another website?, also when you have entered in a website name and password and answer would you like to add another website? with no then selected option 1 to see existing accounts, it repeats would you like to add another website?, when this should even come up at option one
Inputs and how it should output:
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
You have no stored websites and passwords
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
What is the name of the website/app your are adding? instagram
What is the password of your {instagram} account? bob91
Would you like to add another website? yes
What is the name of the website/app your are adding? facebook
What is the password of your {facebook} account? bob92
Would you like to add another website? no
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
enter the app you want to find the password for instagram
websitename = instagram
password = bob91
Full code:
vault_apps = []
app_name = ""
def locker_menu_func():
print('''You have opened the locker,
Please select what you would like to do,''')
locker_menu_var = input('''Press: \n1) find your existing passwords \n2) save a new password for your apps\n3) see a summary of your password locke \n4) exit password locker successfully\n---------------------------------------------------------------------------------
''')
print('''----------------------------------------------------------------''')
while True:
if locker_menu_var == "1":
while len(vault_apps) < 1:
print('''you have nothing stored''')
if len(vault_apps) > 1:
print(vault_apps)
break
break
if 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:
ask_again = input('''Would you like to add another app and password?
''')
if ask_again.lower() == "yes":
locker_menu_var = "2"
elif ask_again.lower() == "no":
locker_menu_func()
else:
print("please enter a valid response") #should repeat if user want to add another website
Your code does not work because you do not break from a while True:-loop:
while True:
ask_again = input('''Would you like to add another app and password?''')
if ask_again.lower() == "yes":
locker_menu_var = "2" <--- does not leave while loop
elif ask_again.lower() == "no":
locker_menu_func()
else:
# etc.
Keep your methods small and handling one concern to simplify your control flow, example:
vault_apps = {}
# ,2,Hallo,Yuhu,y,Hallo2,Yuh,n,3,4
def menu():
print('\n'+'-'*40)
print('1) find your existing passwords')
print('2) save a new password for your apps')
print('3) see a summary of your password locker')
print('4) exit password locker successfully')
print('-'*40)
k = None
while k not in {"1","2","3","4"}:
k = input("Choose: ")
return int(k) # return the number chosen
def input_new_app():
global vault_apps
app = None
while not app:
app = input("What is your apps name? ")
pw = None
while not pw:
pw = input("What is your apps passphrase? ")
vault_apps[app]=pw
def print_vault():
print("Vault content:")
for key,value in vault_apps.items():
print(f" {key:<10}\t==>\t{value}")
def find_password():
if vault_apps:
pass
else:
print("nothing in your password store")
def main():
k = None
print('You have opened the locker,\nPlease select what you would like to do.')
while True:
choice = menu()
if choice == 1:
find_password()
elif choice == 2:
input_new_app()
k = input("Would you like to add another app and password?").lower()
while k in {"yes","y"}:
input_new_app()
elif choice == 3:
print_vault()
elif choice == 4:
print("Good bye")
break
main()
Output:
You have opened the locker,
Please select what you would like to do.
----------------------------------------
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
----------------------------------------
Choose: 1
nothing in your password store
----------------------------------------
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
----------------------------------------
Choose: 2
What is your apps name? A
What is your apps passphrase? 66
Would you like to add another app and password? n
----------------------------------------
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
----------------------------------------
Choose: 3
Vault content:
A ==> 66
----------------------------------------
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
----------------------------------------
Choose: 4
Good bye
This logic is flawed.
Once you enter the infinite while loop, you have no way to exit it, other than to enter "no". When you enter "yes", the value of locker_menu_var changes, but you donot exit the loop, so it keeps repeating the same menu.
while True:
ask_again = input('''Would you like to add another app and password?
''')
if ask_again.lower() == "yes":
locker_menu_var = "2"
elif ask_again.lower() == "no":
locker_menu_func()
You are mixing the looping and recursion, which is making things confusing. One simple way to do this is:
vault_apps = []
def locker_menu():
# the entry message
msg = '''You have opened the locker, Please select what you would like to do,'''
print(msg, end="\n\n")
# nume options
menu = ["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"]
menu_string = f"Press:\n{menu[0]}\n{menu[1]}\n{menu[2]}\n{menu[3]}\n"
# now enter the loop
while True:
# input variable
# NOTE: This variable is inside the loop,
# so that the user can enter the value everytime
# the loop repeates.
locker_menu_var = input(menu_string)
if locker_menu_var == "1":
# retrieve password for an existing record.
# although it's not a good idea to just print
# all the records, I am not changing your application logic
# because I don't see any use in it.
# you missed one case in your logic,
# which I have fixed here.
if len(vault_apps) == 0:
print("you have nothing stored")
else:
print(vault_apps)
elif locker_menu_var == "2":
# for a new entry
# enter your logic here
an = input("app name: ")
passw = input("password: ")
vault_apps.append([an, passw])
done = False # flag for exiting
while not done:
inp = input("enter another?")
if inp == "yes":
# enter logic here
an = input("app name: ")
passw = input("password: ")
vault_apps.append([an, passw])
else:
done = True
elif locker_menu_var == "3":
# do something
pass
elif locker_menu_var == "4":
return
if __name__ == "__main__":
locker_menu()

Python User Registration

I am trying to make a working user registration program. When asked for the username, the system will look to see if the text entered has already been stored. If the username has already been stored, it will ask for the password for that user. However, if the username has not been stored, it will ask for a password. When these are entered, the script will then appendix onto a .txt of a .py file to make an new account. After the account has been made, the script can then read the .txt or .py file for the login information. My current login code:
loop = "true"
while(loop == "true"):
username = input("Enter Username: ")
password = input("Enter Password: ")
h = input ("Do You Need Help [Y/N]: ")
if(h == "Y" or h == "y" or h == "yes" or h == "Yes"):
print ("Enter username and password to login. If you do not have an account yet, enter 'Guest' as the username and press enter when it asks for the password.")
elif(h == "N" or h == "n" or h == "no" or h == "No"):
print (" >> ")
if(username == "Hello World" and password == "Hello World" or username == "Test User" and password == "Test User" or username == "Guest"):
print ("Logged in Successfully as " + username)
if(username == "Guest"):
print ("Account Status: Online | Guest User")
if not (username == "Guest"):
print ("Account Status: Online | Standard User")
How do you make a database that python can read from for the username and password? Also, how do you make it so that python can appendix to the database to add more usernames and passwords?
This is Python v3.3.0 Mac OSX 10.8
Thank you in advance!
Try using the pickle module:
>>> import pickle
>>> myusername = "Hello"
>>> mypassword = "World"
>>> login = [myusername, mypassword]
>>> pickle.dump(login, open("%s.p" % login[0], "wb")) #Saves credentials in Hello.p, because Hello is the username
>>> #Exit
Now to get it back
>>> import pickle
>>> try:
... password = pickle.load(open("Hello.p", "rb"))[1]
... username = pickle.load(open("Hello.p", "rb"))[0]
... except IndexError: #Sees if the password is not there
... print("There is no information for those credentials")
...
>>> password
'mypassword'
>>> username
'myusername'
If there is no password or username, it prints There is no information for those credentials... Hope this helps!
AND JUST A TIP: don't bother going through if(h == 'n'..., just do a h.lower().startswith("n") == True. .lower() makes everything lowercase, and str.startswith("n") checks if str starts with the letter n.

Simple username and password application in Python

I'm trying to build a simple login and password application using a dictionary. It works fine except the part where it checks if the login matches the password (in the bottom where it says "Login successful!").
If I were to create login 'a' and password 'b', and then create login 'b' and password 'a', it would log me in if I tried to log in with login 'a' and password 'a'. It just checks if those characters exist somewhere in the dictionary, but not if they are a pair.
Any suggestions how to fix this?
users = {}
status = ""
while status != "q":
status = raw_input("Are you a registered user? y/n? Press q to quit: ")
if status == "n": #create new login
createLogin = raw_input("Create login name: ")
if createLogin in users: # check if login name exist in the dictionary
print "Login name already exist!\n"
else:
createPassw = raw_input("Create password: ")
users[createLogin] = createPassw # add login and password
print("\nUser created!\n")
elif status == "y": #login the user
login = raw_input("Enter login name: ")
if login in users:
passw = raw_input("Enter password: ")
print
if login in users and passw in users: # login matches password
print "Login successful!\n"
else:
print
print("User doesn't exist!\n")
Edit
Now that this is working, I'm trying to divide the application to three functions, for readability purposes. It works, except that I get infinite loop.
Any suggestions why?
users = {}
status = ""
def displayMenu():
status = raw_input("Are you a registered user? y/n? Press q to quit: ")
if status == "y":
oldUser()
elif status == "n":
newUser()
def newUser():
createLogin = raw_input("Create login name: ")
if createLogin in users: # check if login name exists
print "\nLogin name already exist!\n"
else:
createPassw = raw_input("Create password: ")
users[createLogin] = createPassw # add login and password
print("\nUser created!\n")
def oldUser():
login = raw_input("Enter login name: ")
passw = raw_input("Enter password: ")
# check if user exists and login matches password
if login in users and users[login] == passw:
print "\nLogin successful!\n"
else:
print "\nUser doesn't exist or wrong password!\n"
while status != "q":
displayMenu()
Right now you are checking if the given password, passw, matches any keys in users (not right). You need to see if the password entered matches that particular user's password. Since you have already checked if the username exists in the dictionary's keys you don't have to check again, so try something like:
if passw == users[login]:
print "Login successful!\n"
EDIT:
For your updated code, I'm going to assume by "infinite loop" you mean that you cannot use q to exit the program. It's because when you're inside displayMenu, you save user input in a local variable named status. This local variable does not refer to the same status where you are checking,
while status != "q":
In other words, you are using the variable status in two different scopes (changing the inner scope does not change the outer).
There are many ways to fix this, one of which would be changing,
while status != "q":
status = displayMenu()
And adding a return statement at the end of displayMenu like so,
return status
By doing this, you are saving the new value of status from local scope of displayMenu to global scope of your script so that the while loop can work properly.
Another way would be to add this line to the beginning of displayMenu,
global status
This tells Python that status within displayMenu refers to the global scoped status variable and not a new local scoped one.
change
if login in users and passw in users: # login matches password
to
if users[login] == passw: # login matches password
Besides, you should not tell the hackers that "User doesn't exist!". A better solution is to tell a generall reason like: "User doesn't exist or password error!"
Please encrypt you passwords in database if you go put this online.
Good work.
import md5
import sys
# i already made an md5 hash of the password: PASSWORD
password = "319f4d26e3c536b5dd871bb2c52e3178"
def checkPassword():
for key in range(3):
#get the key
p = raw_input("Enter the password >>")
#make an md5 object
mdpass = md5.new(p)
#hexdigest returns a string of the encrypted password
if mdpass.hexdigest() == password:
#password correct
return True
else:
print 'wrong password, try again'
print 'you have failed'
return False
def main():
if checkPassword():
print "Your in"
#continue to do stuff
else:
sys.exit()
if __name__ == '__main__':
main()
usrname = raw_input('username : ')
if usrname == 'username' :
print 'Now type password '
else :
print 'please try another user name .this user name is incorrect'
pasword = raw_input ('password : ')
if pasword == 'password' :
print ' accesses granted '
print ' accesses granted '
print ' accesses granted '
print ' accesses granted '
print 'this service is temporarily unavailable'
else :
print 'INTRUDER ALERT !!!!' , 'SYSTEM LOCKED'
print 'INTRUDER ALERT !!!!' , 'SYSTEM LOCKED'
print 'INTRUDER ALERT !!!!' , 'SYSTEM LOCKED'
exit()
This is a very simple one based on the one earlier for a single user with improved grammar and bug fixes:
print("Steam Security Software ©")
print("-------------------------")
print("<<<<<<<<<Welcome>>>>>>>>>")
username = input("Username:")
if username == "username" :
print ("Now type password")
else :
print ("please try another user name. This user name is incorrect")
password = input ("Password:")
if password == "password" :
print ("ACCESS GRANTED")
print ("<<Welcome Admin>>")
#continue for thins like opening webpages or hidden files for access
else :
print ("INTRUDER ALERT !!!!" , "SYSTEM LOCKED")
exit()

Categories

Resources