Checking Tuples in a list - python

So i am working on a program that is and I am stuck.
I have a login and signup system that saves new signups in a mysql database.
At the start of the program I take the passwords and names and put them together in a tuple.
Then i put that tuple in a list.
If i wanna login it cant check a tuple in that list.
Here is my code:
Login:
def login():
userKnown = input("Hallo, heeft u al een account? y/n ")
if userKnown == "y":
user = input("username: ")
passw = input("password: ")
userjoin = (user,passw)
if userjoin in bigdata:
print("login succesful")
else:
print("try again")
UploadData:
def uploadData():
print("Bezig met uploaden.")
mycursor.execute("SELECT name, password FROM userData")
data = mycursor.fetchall()
bigdata.append(data)
print("Upload worked. \n")
I hope someone can help me.
A fix to the login system.

I solved it thanks to Georg Richter.
I used the Where function in select and that worked
Here is the code:
def login():
userKnown = input("Hallo, heeft u al een account? y/n ")
if userKnown == "y":
user = input("username: ")
passw = input("password: ")
userB = (user, passw)
query = 'SELECT name, password FROM userData WHERE name =%s'
name = (user,)
mycursor.execute(query, name)
userA = mycursor.fetchone()
print(userA)
if userA == userB:
print("succes")
else:
print("failed")

I think the error is that bigdata does not exist into your login function.
Try this: def login(bigdata) and call the function in this way: login(bigdata)

Try using try block to find the user its easier this way.
try:
pass
#code to search database
except Exception as e:
print(e)
SELECT has a WHERE clause where you can specify user and password to optimize your application.

Related

TypeError in simple registration/login program

For practice purposes I tried coding a little registration/login system which stores the registered users' data in a list.
I tried to solve this by getting user input (name, nickname and password), then create a list with the chosen "Name" which then stores "Nickname" and "PW" . This then should be then stored in the created list "users" which is being created in the beginning.
So I would have a list with different names/persons which includes their data.
The problem is that in the else statement it won't let me create the name-variable list with (username, password) in it. "TypeError: string indices must be integers"
users = []
def register():
print("Please insert your Name")
name = input()
print("Please insert your Username")
username = input()
print("Please type your Password")
userpw = input()
if name in users:
print("Account already exist, try again")
register()
else:
users.append(name[username, userpw])
This code creates a dictionary for a user and then check if its already registrated. I recommend using some sort of database to avoid dataloss from program restarts.
users = []
def register():
print("Please insert your Name")
name = input()
print("Please insert your Username")
username = input()
print("Please type your Password")
userpw = input()
for x in users:
if x['name'] == name:
print("Account already exist, try again")
register()
return
user = {'name': name,
'username': username,
'password': userpw}
users.append(user)

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

Python : Referencing Data from JSON file in python

I'm currently making a username + password login system and have a file containing the usernames and passwords of previously signed up users. The side of the programme that signs up users works perfectly, but I have tried to implement a system to check the data from the file and sign the user in if they input the right data.
Edit: One combination from the database, it's all structured like this; [["ExampleUsername", "BadPasswrdo14130"]]
This is the code:
# Login Interface using files as a 'login database' of sorts?
import json
def autoSave():
with open("Accounts.json", "w") as outfile:
json.dump(accounts, outfile)
def loadUsers():
with open("Accounts.json") as infile:
return json.load(infile)
def existingUser():
eUsername = input("Your Username » ")
ePassword = input("Your Password » ")
for index, item in (accounts):
if item[1] == eUsername and item[2] == ePassword:
print("Logged in")
else:
print("Login failed")
def createUser():
global accounts
nUsername = input("Create Username » ")
nPassword = input("Create Password » ")
entry = [nUsername, nPassword]
accounts.append(entry)
accounts = accounts[:500000]
autoSave()
accounts = loadUsers()
How would I retrieve data from the database file and check that data with the data that the user inputted?
I've tried already but it does not work, always says login failed, which is this bit of the code:
def existingUser():
eUsername = input("Your Username » ")
ePassword = input("Your Password » ")
for index, item in (accounts):
if item[1] == eUsername and item[2] == ePassword:
print("Logged in")
else:
print("Login failed")
In your code accounts is a list. When you're iterating over it, you get sublists. You should iterate over the sublists to get the username and password.
So you can do:
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 "Logged in"
else:
return "Login failed"
print existingUser()
In your current code you seem to have forgotten that in Python list indexes start with 0.
#ForceBru
This is the code I tried to prevent dup accounts, it doesent allow you to dupe accounts but when making a new account, it says its already created when its not, but creates it anyway.
def createUser():
global accounts
nUsername = input("Create Username » ")
nPassword = input("Create Password » ")
for item in accounts:
if item[0] == nUsername:
return "Account Username already exists, try again"
else:
entry = [nUsername, nPassword]
accounts.append(entry)
accounts = accounts[:500000]
autoSave()

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