Weird Functions Calling and Inconsistent Result - python

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

Related

Password keeper program does not merge dictionaries as intended

I need help with some code id been writing randomly about a passwor keeper
I'd appreciate it so much if the help is beginner friendly.
I tried searching for some ways to merge dicts and the entire app isn't working.
User_password_dict = {" " : " "}
def merge_lists(username, password):
dict_append = {}
dict_append[username] = password
User_password_dict.update
def user_info_collection():
while True:
username = input (f"What is would you like your'e username to be ?\n\t:")
if username in User_password_dict:
print ("you need to change your'e username")
break
else:
password = input(f"Type a password\n\t:")
password_check = input(f"Type your password again \n\t: ")
if password_check != password:
print("you have not input the correct password")
break
else:
User_info = merge_lists(username, password)
return User_info
user_info_collection()
print(User_password_dict)
Okay, so you made a good effort but overcomplicated the dict part.
The merge_lists function is not needed as appending a dict is much simpler than that !!
The key line of code that i added was this:
user_password_dict[username] = password
and i removed a couple of unnecessary parts.
So, this will work:
user_password_dict = {}
def user_info_collection():
while True:
username = input (f"What is would you like your'e username to be ?\n\t:")
if username in user_password_dict:
print ("you need to change your'e username")
break
else:
password = input(f"Type a password\n\t:")
password_check = input(f"Type your password again \n\t: ")
if password_check != password:
print("you have not input the correct password")
break
else:
user_password_dict[username] = password
return
user_info_collection()
print(user_password_dict)
here is the result:
What is would you like your'e username to be ?
:test
Type a password
:blah
Type your password again
: blah
{'test': 'blah'}

Python login limit

i'm trying to implement login attempt system to my current code, but i don't know where i should tick it. Can someone suggest anything? I would like to give three attempts to login, if user fails to login, system will lock user out. I just dont know where to position the code properly.
granted = False
def grant():
global granted
granted = True
def login(name,password):
success = False
file = open("user_details.txt","r")
for i in file:
a,b = i.split(",")
b = b.strip()
if(a==name and b==password):
success=True
break
file.close()
if(success):
print("Login Succesful")
grant()
else:
print("wrong username or password")
The better way to do this problem is by having a JSON file instead of a txt file. You can have the file in this format:
{
"username": {
"password": "",
"attempts": 0,
}
}
In the login() function increment and write the count of attempts if the password is wrong.
And before the function begins read the JSON and check if the attempts value is greater than 3. If it is greater send an appropriate message else to continue the login action and ask for the password.
Your code had some minor errors which I have handled here:
import re
granted = False
def grant():
global granted
granted = True
def login(name,password):
success = False
file = open("user_details.txt","r")
for i in file:
if i.count(',') > 0: # check whether i has at least one ','
a,b = i.split(",")
b = b.strip()
if(a==name and b==password):
success=True
break
file.close()
if(success):
print("Login Succesful")
grant()
else:
print("wrong username or password")
def register(name,password):
file = open("user_details.txt","a")
file.write( "\n"+name[0]+","+password) # name is an array so only the first element is stored.
file.close()
grant()
def access(option):
global name
if(option=="login"):
name = input("Enter your name: ")
password = input("enter your password: ")
login(name,password)
else:
print("Enter yor name and password to register")
name = input("Please enter your name: ").lower().split()
if len(name) > 1:
first_letter = name[0][0]
three_letters_surname = name[-1][:3].rjust(3, 'x')
name = '{}{}'.format(first_letter, three_letters_surname)
print(name)
while True:
password = input("Enter a password: ")
if len(password) < 8:
print("Make sure your password is at lest 8 letters")
elif re.search('[0-9]',password) is None:
print("Make sure your password has a number in it")
elif re.search('[A-Z]',password) is None:
print("Make sure your password has a capital letter in it")
else:
print("Your password seems fine")
break
register (name,password)
def begin():
global option
print("Welcome to Main Menu")
option = input("Login or Register (login,reg): ")
if(option!="login" and option!="reg"):
begin()
begin()
access(option)
if(granted):
print("Welcome to main hub")
print("#### Details ###")
print("Username:",name)

I cant get the expected output in my code (signup login system)

Hi i'm new in python and in programming in general ! i tried to make a login system with python but it doesnt seem to be working as i expect
the problem is even if i enter false login informations at the end the program will print login successful instead of printing incorrect username or password
NOTE : i'm not trying to make real login system it's just some practice form what i learned
signup_username = ""
signup_password = ""
login_username = ""
login_password = ""
false_login_info = False
def signup() :
signup_username = input("Choose your username :")
signup_password = input("Choose your password :")
def login() :
login_username = input("Enter username :")
login_password = input("Enter password :")
signup()
print("Signup successful")
login()
if login_username != signup_username or login_password != signup_password :
print("Incorrect username or password")
else :
print("login successful")
EXPECTED Result :
1) if login informations are same as signup infos i should get :
- Login successful
2) if login informations are NOT same as signup infos i shoul get :
- Incorrect username or password
ACTUAL Result :
in both cases the program will print login successful
You need to return the values from your functions. The names defined inside the function are not the same as those that exist outside of the function. In this case, I have appended x to the names in the global scope to differentiate them from the ones inside the function to hopefully make it clearer. I could have used the same names both inside the function and outside; it wouldn't have made a difference. You can see more here.
There is no need to "initialise" the variables as empty strings before the function call. Instead, we'll just create them in the function, return them, and then unpack them into the variables ending in x.
false_login_info = False # You never use this
def signup() :
signup_username = input("Choose your username :")
signup_password = input("Choose your password :")
return signup_username, signup_password
def login() :
login_username = input("Enter username :")
login_password = input("Enter password :")
return login_username, login_password
signup_usernamex, signup_passwordx = signup()
print("Signup successful")
login_usernamex, login_passwordx = login()
if login_usernamex != signup_usernamex or login_passwordx != signup_passwordx:
print("Incorrect username or password")
else :
print("login successful")

Adding new users/passwords to dictionary in python email application

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

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