I've stumped myself on my login project and suggestions with the order of my code! it is a login project - function

So I have the code written I think and it works but I am not sure how to order it properly so for example in my menu function when they enter 2 to end the program it will end completely as after I call this function I need to call the others but at the moment it while just run the next part of the code
print("----------------------Welcome User----------------------\n\n")
# this function is used for apperance in the program
def linebreak():
print("---------------------------------------------------------")
# Menu for user to choose what they would like to do
# this functuon gives the user a choice from the menu above if they want to log in it will break out of
# the loop and go onto the next block of code below
def menu():
while True:
print("-----------------------Main Menu------------------------\n")
print("To login enter 1:")
print("To end the program enter 2:")
print("")
try:
sUserSelection = int(input("What would you like to do? \n"))
# make a conditional statement to see if the user wants to start the login program or exit
if sUserSelection == 1:
break
elif sUserSelection == 2:
print("Ending program, Goodbye!")
break
except:
print("ERROR! Invalid choice please choose from the menu to continue or exit the program.\n")
menu()
menu()
# This is a function that will return two print statements one to tell the user that their login was successful
# And it will then print greet with that users inputted name
def welcome_user():
print("Login successful. ")
print("Welcome ")
# Create a function for the admin login
sAdmin = "admin"
sAdminPassWord = "aDmin002"
def admin_login():
print("Please login to the administrator account to create your new personal account: \n")
while True:
sUserInput = input("Please enter admin username: \n")
sUserInput = sUserInput.lower()
if sUserInput == sAdmin:
break
else:
print("Wrong username please try again! \n")
while True:
sPassInput = input("Please enter admin password: \n")
if sPassInput == sAdminPassWord:
print("Login Successful")
break
else:
print("Wrong password please try again! \n")
# this function allows the user to create a new account starting with the username and then
# it asks for the creation of a password
def new_account():
print("\nPlease create a new account.\n")
while True:
global sNewUser1
sNewUser1 = input("\nPlease enter a new username.\n"
"It should be at least 5 characters long\n"
"and not contain spaces or special characters: \n\n")
if len(sNewUser1) < 5:
print("Your username is too short. Please try again: ")
elif sNewUser1.count(" ") > 0:
print("Your username contains spaces. Please try again: ")
elif sNewUser1.isalnum() is False:
print("Your username contains a special character. "
"Please try again: ")
else:
# call another function
break
while True:
global sNewPass1
sNewPass1 = input("\n\nPlease enter a new password.\n"
"It should be at least 6 characters long\n"
"with at least one uppercase letter,\n"
"one lowercase letter, one special character"
"and one number: \n\n")
if len(sNewPass1) < 6:
print("\nYour password is too short. Please try again: ")
elif any(lower.islower() for lower in sNewPass1) is False:
print("\nYour password does not contain lowercase letters. "
"Please try again: ")
elif any(upper.isupper() for upper in sNewPass1) is False:
print("\nYour password does not contain uppercase letters. "
"Please try again: ")
elif any(digit.isdigit() for digit in sNewPass1) is False:
print("\nYour password does not contain a number. "
"Please try again: ")
elif any(not char.isalnum() for char in sNewPass1) is False:
print("\nYour password does not contain a special character. "
"Please try again: ")
elif sNewPass1.replace(" ", "") != sNewPass1:
print("\nYour password contains whitespaces. "
"Please try again: ")
else:
# call another function
break
def name_selection():
print("Account created sucessfully!")
global sName1
sName1 = input("Please enter your name:\n")
def user_login():
while True:
sUserLogin = input("Please enter your username:\n")
if sUserLogin == sNewUser1:
break
else:
print("Wrong username please try again:\n")
while True:
sUserPass = input("Please enter your password:\n")
if sUserPass == sNewPass1:
print("\nWelcome: ", sName1)
break
# # calls the menu function
menu()
# # calls the admin login function
admin_login()
# calls the function to create a new account
new_account()
# calls the name creation function after an account has been made
name_selection()
# calls the function to allow the user to login using there credentials
user_login()

Related

Login simulation. Dictionary with {["username"]: ["password"]} key:value pairs. How do I authenticate a user trying to log in?

Inside of a json file, each line stores the information of every different user that is created through separate classes. In the user_login file, retrieves this info and isolates username and passwords for each user to attempt to create a login page.
File: user_login
import json
filename = "users.json"
with open(filename, "r+", encoding='utf8') as file:
'''opens json file and separates it by line by storing each line into an
array'''
lines = file.readlines()
login_info = {}
'''array that will store usernames and passwords for each user(each line in
the file is a user)'''
for line in lines:
'''simply prints each element of the lines array displaying the
information of each user'''
info = json.loads(line)
print("USER: " + str(info))
print("username: " + info["username"])
print("password: " + info["password"] + "\n")
login_info[info["username"]] = info["password"]
'''creates a new pair of username and password for each user(each line is
a user)'''
print(login_info)
print(lines)
print(login_info)
'''prompts user for their username and password'''
prompt_username = input("Please enter username: ")
prompt_password = input("Please input password: ")
The problem is in the following method(it does not work):
def login(username, password):
'''if username exists and the inputed strings match one of the key-value
pairs, login is successful'''
if username in login_info:
if password == info["password"]:
print("LOGIN SUCCESSFUL")
else:
print("Sorry, password does not exist.")
else:
print("Sorry this username or password does not exist.")
login(prompt_username, prompt_password)
How do I effectively check if the user inputs for username and password match any of the dictionary pairs to simulate a login?
The following is the users.json file.
File: users.json
{"first": "Gilberto", "last": "Robles", "username": "girobles1", "password": "1234", "location": "San Diego", "interests": [["eat", "sleep", "code", "repeat"]]}
{"first": "Gilberto", "last": "Robles", "username": "girobles2", "password": "12345", "location": "San Diego", "interests": [["eat", "sleep", "code"]]}
It looks like you're just calling the wrong object to check if the password is correct
if password == info["password"]:
should be
if password == login_info[username]:
Follow-up question about number of attempts:
I rewrote your function to return the status of the username and password accuracy:
def login(username, password):
'''if username exists and the inputed strings match one of the key-value
pairs, login is successful returns (Username Correct, Password Correct)'''
if username in login_info:
if password == login_info[username]:
print("LOGIN SUCCESSFUL")
return (True, True)
else:
print("Sorry, password does not exist.")
return (True, False)
else:
print("Sorry this username does not exist.")
return (False, False)
login(prompt_username, prompt_password)
Then added a loop to check the results and logic to handle them (This is untested, since I don't have your dictionary):
'''prompts user for their username and password'''
username_attempts = 3
password_attempts = 3
prompt_username = input("Please enter username: ")
prompt_password = input("Please input password: ")
username_guess = 1
password_guess = 1
while True: #Loops until broken
if username_guess > username_attempts:
print("Too many invalid usernames, goodbye")
#What do you want it to do if they fail?
break
if password_guess > password_attempts:
print("Too many invalid passwords, goodbye")
#What do you want it to do if they fail?
break
username_status, password_status = login(prompt_username, prompt_password)
if all([username_status, password_status]):
break
elif not username_status:
print("Invalid username, please try again")
prompt_username = input("Please enter username: ")
username_guess += 1
elif not password_status:
print("Invalid password, please try again")
prompt_password = input("Please input password: ")
password_guess += 1

Exit from a loop python 3

im new ish to python and ive got this code and i want it to allow for the word "exit" to be entered at any time when inputting. And once that is done, it closes the script.
Any help would be really appreciated.
import sys
while True:
def inputs():
first=input("Enter your first name: ")
last=input("Enter your last name: ")
gender=input("Enter your gender: ")
form=input("Enter your form: ")
file = open("signup.txt", "a")
#Records the user's details in the file
file.write("\nFirst name: "+first+", Last name: "+last+", Gender: "+gender+", Form: "+form)
#Closes the file
file.close()
if input(inputs) == "exit":
sys.exit()
inputs()
You can just encapsulate input function to exit on the "exit" word :
import sys
def exitInput(prompt):
pInput = input(prompt)
return pInput if pInput != "exit" else sys.exit()
def inputs():
first = exitInput("Enter your first name: ")
last = exitInput("Enter your last name: ")
gender = exitInput("Enter your gender: ")
form = exitInput("Enter your form: ")
file = open("signup.txt", "a")
file.write("\nFirst name: "+first+", Last name: "+last+", Gender: "+gender+", Form: "+form)
file.close()
inputs()
you can check every time after input that it is exit or not. if it is exit then terminate the program. as your code you can put the code given bellow after every time of taking input
if input(inputs) == "exit":
sys.exit()

Python username and password login while and for loop

I have a school assignment to make a program with a login for a hospital (we have to make a eHealth system). But the problem with my code is that it checks every .csv line only once. Whenever my first login is wrong it stops looping and I can't login anymore. Also it checks every single line and prints the one's that are wrong. How can I fix my code so that I can still login after filling in a wrong login?
import csv
def login():
print('Welcome to the eHealth program, please sign in')
with open('users.csv') as csvfile:
database = csv.DictReader(csvfile)
loggedin = False
while loggedin is not True:
Username = input('Fill in your username: ')
Password = input('Fill in your password: ')
for row in database:
Username_File = row['username']
Password_File = row['password']
Function_File = row['function']
if (Username_File == Username and
Password_File == Password and
Function_File == 'patient'):
loggedin = True
print('Succesfully logged in as a patient.')
# patientmenu() # we will add this later on
elif (Username_File == Username and
Password_File == Password and
Function_File == 'arts'):
loggedin = True
print('Succesfully logged in as a doctor.')
# artsmenu() # we will add this later on
elif Username_File != Username and Password_File == Password:
# loggedin = False
print('Failed to sign in, wrong username.')
elif Username_File == Username and Password_File != Password:
# loggedin = False
print('Failed to sign in, wrong password.')
elif Username_File != Username and Password_File != Password:
# loggedin = False
print('Failed to sign in, wrong username and password.')
else:
print('Error 404, Login Not Found')
# ---- Main ---- #
login()
example of thats in the csv file: (doesn't really matter for this case)
username,password,function
patient1,patient1,patient
patient2,patient2,patient
arts1,arts1,arts
arts2,arts2,arts
I've tried fixing it by putting the with open into the while loop, but another problem occurs then. Now it prints 4 lines every single time, if you are correctly logged in it prints 1 line with successfully logged in and 3 lines with wrong username and password.
import csv
def login():
print('Welcome to the eHealth program, please sign in')
loggedin = False
while loggedin != True:
Username = input('Fill in your username: ')
Password = input('Fill in your password: ')
with open ('users.csv') as csvfile:
database = csv.DictReader(csvfile)
for row in database:
Username_File = row['username']
print(Username_File)
Password_File = row['password']
print(Password_File)
Function_File = row['function']
print(Function_File)
if Username_File == Username and Password_File == Password and Function_File == 'patient':
loggedin = True
print('Succesfully logged in as a patient.')
elif Username_File == Username and Password_File == Password and Function_File == 'arts':
loggedin = True
print('Succesfully logged in as a doctor.')
elif Username_File != Username and Password_File == Password:
loggedin = False
print('Failed to sign in, wrong username.')
elif Username_File == Username and Password_File != Password:
loggedin = False
print('Failed to sign in, wrong password.')
elif Username_File != Username and Password_File != Password:
loggedin = False
print('Failed to sign in, wrong username and password.')
else:
print('Error 404, Login Not Found')
login()
I suggest you to build a database feeding a dictionary on program start with cvs content.
After that you can create your loop to check this dictionary and apply your logic on it.
This link maybe can help you to understand python dictionary: http://www.tutorialspoint.com/python/python_dictionary.htm
So here's what's happening:
Your while loop stays active, but after you have looped over all rows in your csv file, you don't enter the for loop any more because there's no rows left to loop over. If you want to fix it, you need to find a way to reset the for loop once you have processed the last row.
As suggested by Roberto Alcantara in his answer, a more elegant solution would be to construct 3 datasets with all the usernames, passwords and functions before you even enter your while loop, then you can just check along the lines of:
if username in usernames:
do some stuff
else:
do some other stuff
and that would allow you to do that in the while loop without having to iterate over the csv reader instance all the time.
I've also taken the liberty of fixing some formatting stuff that was not really pythonic in your code (though not really wrong).
Edit:
Here's something i quickly cobbled together, it's not as nice a i intended it to be because it does once again loop over the content of the created database, but at least it works:
import csv
def login():
print('Welcome to the eHealth program, please sign in')
with open('users.csv') as csvfile:
reader = csv.DictReader(csvfile)
database = []
for row in reader:
database.append(dict(username=row['username'],
password=row['password'],
function=row['function']))
loggedin = False
while not loggedin:
Username = input('Fill in your username: ')
Password = input('Fill in your password: ')
for row in database:
Username_File = row['username']
Password_File = row['password']
Function_File = row['function']
if (Username_File == Username and
Password_File == Password and
Function_File == 'patient'):
loggedin = True
print('Succesfully logged in as a patient.')
elif (Username_File == Username and
Password_File == Password and
Function_File == 'arts'):
loggedin = True
print('Succesfully logged in as a doctor.')
if loggedin is not True:
print ('Failed to sign in, wrong username or password.')
# ---- Main ---- #
login()
I'm sure some python wizard around here could come up with a solution to cleverly use datatypes so you can still link usernames, passwords and roles without having to loop, but it gets the job done.
Another thing i'd like to suggest:
As you've probably seen, i have removed the prints that indicated whether a password was found, but the username was wrong and vice versa. It greatly compromises security to hint at whether a username or password scored a hit in your database even though the login as such was unsuccessful, so unless your assignment specifically asks for it, i would leave that be. On the otherhand, talking security is kind of moot when you store passwords in plaintext. ;-)

Creating a Caesar Cipher Program in Python 3.4, but function doesn't work

Currently, I am creating a Caesar Cipher but it is not working correctly, can anyone help at all? The code will be below. At the moment, if the program is run first time (as in, no functions have to be re run) it works perfectly, but when the getKey() function is re run, it returns an error. After the code, the error is shown:
def runProgram():
def choice():
userChoice = input("Do you wish to Encrypt of Decrypt? Enter E or D: ").lower()
if userChoice == "e":
return userChoice
elif userChoice == "d":
return userChoice
else:
print("Invalid Response. Please try again.")
choice()
def getMessage():
userMessage = input("Enter your message: ")
return userMessage
def getKey():
try:
userKey = int(input("Enter a key number (1-26): "))
except:
print("Invalid Option. Please try again.")
getKey()
else:
if userKey < 1 or userKey > 26:
print("Invalid Option. Please try again.")
getKey()
else:
return userKey
def getTranslated(userChoice, message, key):
translated = ""
if userChoice == "e":
for character in message:
num = ord(character)
num += key
translated += chr(num)
savedFile = open('Encrypted.txt', 'w')
savedFile.write(translated)
savedFile.close()
return translated
else:
for character in message:
num = ord(character)
num -= key
translated += chr(num)
return translated
userChoice = choice() #Runs function for encrypt/decrypt selection. Saves choice made.
message = getMessage() #Run function for user to enter message. Saves message.
key = getKey() #Runs function for user to select key. Saves key choice.
translatedMessage = getTranslated(userChoice, message, key) #Runs function to translate message, using the choice, message and key variables)
print("\nTranslation complete: " + translatedMessage)
runProgram()
I have tried to create it error proof during the getKey() function with the try, except and else commands. It will 'Try' to see that the input is an int or not, if it is, it goes to else, but if it isn't an int, then it will rerun the function. If the function is rerun, and an int is entered, this error is given:
This is an example of it working:
Do you wish to Encrypt of Decrypt? Enter E or D: E
Enter your message: Hello
Enter a key number (1-26): 5
Translation complete: Mjqqt
This is an example when the getKey() function must be re run due to an int not being entered:
Do you wish to Encrypt of Decrypt? Enter E or D: E
Enter your message: Hello
Enter a key number (1-26): H
Invalid Option. Please try again.
Enter a key number (1-26): 5
Traceback (most recent call last):
File "C:\Python34\Encryptor2.py", line 54, in
runProgram()
File "C:\Python34\Encryptor2.py", line 52, in runProgram
translatedMessage = getTranslated(userChoice, message, key) #Runs function to translate message, using the choice, message and key variables)
File "C:\Python34\Encryptor2.py", line 35, in getTranslated
num += key
TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'
As you can see, it re runs the function as I want it too, but the error occurs when adding the key to the ord of character.
The first call to getKey(), with your comment:
key = getKey() #Runs function for user to select key. Saves key choice.
Another place you call it:
if userKey < 1 or userKey > 26:
print("Invalid Option. Please try again.")
getKey()
If you were to write that with the same kind of comment, it would be:
getKey() #Runs function for user to select key. Doesn't save key choice.
What the user types in, comes out of getKey() ... and you aren't keeping track of it, so it vanishes. You then do.
return userKey
userKey is still the H you tried to convert to int, the one that failed. You didn't get rid of it, so it's still there.
The better solution is to rework the shape of your code, so getKey() never calls getKey() inside itself. Do the error checking outside, perhaps, like this kind of shape:
def getKey():
prompt user for key
try to convert to int and return the int
if it fails, return None as an indication that getting the key went wrong.
key = None #set some wrong placeholder
while (key is None) or (key < 1) or (key > 26):
key = getKey()
change your input to raw_input
just use the maketrans and translate functions that basically encrypt or decrypt the message for you.they make for a very short and efficient solution to the problem
message = input('enter message').lower()
offset = int(input('enter offset (enter a negative number to decrypt)'))
alphabet = 'abcdefghijklmnopqrstuvwxyz'
enc_alphabet = (alphabet[alphabet.index(alphabet[offset]):len(alphabet)])+ alphabet[0:offset]
data = str.maketrans(alphabet,enc_alphabet)
final_message = str.translate(message, data)
print(final_message)
This code really doesn't need to be this complicated at all, if you just use regex the code will be much shorter but (in my opinion) way better.
Here's a code I created for Caesar cipher encrypting, decrypting and using a shift of the user's choice using regex.
import re
def caesar(plain_text, shift):
cipherText = ''
for ch in plain_text:
stayInAlphabet = ord(ch) + shift
if ch.islower():
if stayInAlphabet > ord('z'):
stayInAlphabet -= 26
elif stayInAlphabet < ord('a'):
stayInAlphabet += 26
elif ch.isupper():
if stayInAlphabet > ord('Z'):
stayInAlphabet -= 26
elif stayInAlphabet < ord('A'):
stayInAlphabet += 26
finalLetter = chr(stayInAlphabet)
cipherText += finalLetter
print(cipherText)
return cipherText
selection = input ("encrypt/decrypt ")
if selection == 'encrypt':
plainText = input("What is your plaintext? ")
shift = (int(input("What is your shift? ")))%26
caesar(plainText, shift)
else:
plainText = input("What is your plaintext? ")
shift = ((int(input("What is your shift? ")))%26)*-1
caesar(plainText, shift)

MySql Database connection with python

I've got an issue trying to connect to a database with python. It compiles without error but it doesn't seem to do anything. I'm not sure if I'm instantiating the class incorrectly or what the issue may be. Could someone point me in the right direction?
import _mysql
import MySQLdb
class Operations:
def open():
db=_mysql.connect("127.0.0.1","root","admin","test")
c=db.cursor()
#deletes the cursor
def close(self):
c.close()
#verifies the credentials and advances
def login(self):
print "Welcome to the online bookstore login!"
x = raw_input('Please enter your user id. ')
y = raw_input('Please enter your password. ')
c.execute("""SELECT userid,password FROM members WHERE userid = %s""", (x,))
z = c.password
if y == z:
member_menu()
else:
close()
def new_user(self):
print "Welcome to the Online book store new user registration page!"
print "To begin, please enter your first name: "
fName = raw_input('Please enter your first name: ')
lName = raw_input('Please enter your last name: ')
address = raw_input('Please enter your street address: ')
city = raw_input('Please enter your city: ')
state = raw_input('Please enter your state: ')
zip_code = raw_input('Please enter your zip code: ')
phone = raw_input('Please enter your phone number: ')
email = raw_input('Please enter your email: ')
user_ID = raw_input('Please enter your user id: ')
password = raw_input('Please enter your password: ')
c.executemany("""INSERT INTO members(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,) VALUES (fName, lName, address, city, state, zip_code, phone, email, user_id, password,)""")
print "Your account has been created. returning to the welcome menu. "
welcome()
def welcome(self):
choice = NONE;
print "**********************************************************************\n"
print "***\t\t\t\t\t\t\t\t ***\n"
print "***\t\tWelcome to the Online Book Store\t\t ***\n"
print "***\t\t\t\t\t\t\t\t ***\n"
print "**********************************************************************\n"
print "1. Member Login\n"
print "2. New Member Registration\n"
print "3. Quit\n"
choice = raw_input('Type in your option: ')
if choice == 1:
login()
elif x == 2:
new_user()
else:
close()
def member_menu(self):
x = NONE
print "**********************************************************************\n"
print "***\t\t\t\t\t\t\t\t ***\n"
print "***\t\t Welcome to the Online Book Store \t\t ***\n"
print "***\t\t\t Member Menu \t\t\t ***\n"
print "***\t\t\t\t\t\t\t\t ***\n"
print "**********************************************************************\n"
print "1. Search by Author/Title/Subject\n"
print "2. View/Edit Shopping Cart\n"
print "3. Check Order Status\n"
print "4. One Click Check Out\n"
print "5. Logout\n"
print "Type in your option: "
x = raw_input('Please enter your choice. ')
if x == 1:
close_conn(),
elif x == 2:
close_conn(),
elif x == 3:
close_conn(),
elif x == 4:
close_conn(),
else:
close_conn()
def main():
start = Operations()
print "Opening conenction to database"
start.welcome
if __name__ == '__main__':
main()
Well, there are so many problems with your code, that I'll probably miss some of them anyway.
Nothing happens, because your main() function and condition are both parts of the class definition, so all the interpreter sees are actually two imports and a class definition.
Let's say we unindented the main() definition and the condition. All that would happen then is creating an instance of Operations (with no special effects, as you have no custom constructor defined) and printing "Opening connection to database" to the screen, because all the last line in main() does is getting a reference to the welcome() method and ignoring it. You need to call it: start.welcome()
When you do call it, much more problems will appear. NameErrors will probably come first, as you are using identifiers that do not exist in given scopes. It seems you're new to Python's object model and probably coming from a language with a different approach, like C++. In Python all non-static and non-class instance methods take a reference to the object they're operating on as the first parameter, traditionally called 'self'. If you want to access any of the fields of the object, you need to do this through 'self', they are not visible to the interpreter otherwise. E.g.: you open a connection and keep the cursor as c, which you later reuse in other methods:
def open():
# ...
c=db.cursor()
# ...
def login(self):
# ...
c.execute("...")
That's incorrect for two reasons:
your open() method does not take self as a parameter
you're creating c as a local variable in scope of the open() method and then trying to access it in login(), which essentialy results in a "reference before assignment" error.
In order to be correct, it should be written like this:
def open(self):
# ...
self.c = db.cursor()
# ...
def login(self):
# ...
self.c.execute("...")
You're making the same mistake in many places. You need to call self.login(), self.new_user(), self.close(), etc.
You're using Python 2, at least according to the question's tags and there is one thing you need to remember when declaring classes in Python 2. There exist so called old- and new-style classes and what you want to do is use the new-style ones. Therefore your class must inherit from object:
class Operations(object):
# ...
They've finally decided to drop the old-style classes support in Python 3 and there's no need to explicitly inherit from object anymore, but while in Python 2, you need to cope with it.
While there are still some errors or potential errors (what is close_connection()?), I think it's enough for a good start ;). Good luck.