Python User Registration - python

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.

Related

register system in python 3 cant identify already taken usernames

I started learning python(and coding in general) a couple of weeks ago and I am having struggle in a project I trying to make. In part of the project I am trying to make a register and login system, everything went fine expect the 'username already taken' part in the register section.
No matter what I do, the code just keep allowing registering even if the username already taken(You can register with "x" username, and right after registering again with "x" username).
I will appreciate any kind of help!(and sorry for the english :) )
import re
Users = open('Users.txt', mode = 'a')
Hquestion = input("\t\t If you already registered please press Y, if you need to register
please press N")
def register():
if Hquestion == "N" or Hquestion == "n":
with open('Logindata.txt', mode = 'a') as logindata:
firstname = input('please write your first name(only a-zA-Z allowed): ')
username = input('Enter Username : ')
with open('Users.txt', mode = 'r') as userdata:
if username in userdata:
print("username already taken!")
return register()
password = input ('Enter Password (using only a-zA-Z0-9!##$%^&*. min 8 characters) : ' )
passpattern = re.compile('[a-zA-Z0-9##$%^&*()-+=?/".,{}\;:~]{8,}')
namepattern = re.findall('[0-9!##$%^&*()-+=?/".,{}\;:~]',firstname)
while not passpattern.match(password):
print("Your password is invalid. Please make sure you password is atleast 8 characters long!\n")
return register()
if namepattern:
print("Please use only a-z A-Z characters for first and last name!\n")
return register()
Users.write(f'{username}\n')
Users.close()
logindata.write(f'{username} ')
logindata.write(f'{password} ')
logindata.write(f'{firstname}\n')
def login():
if Hquestion == "Y" or Hqeustion == "y":
loginuser = input('Write your username: ')
loginpass = input('Write your password: ')
for user_pass in open('Logindata.txt', mode = 'r').readlines():
loginsplit = user_pass.split()
if loginuser == loginsplit[0] and loginpass == loginsplit[1]:
print("You have succsesfuly loged in! Enjoy shoping in Tomer's Shop!")
return
else:
print("Your username or password wrong, please try again")
return login()
register()
login()
From Membership test operations, python will iterate containers that do not implement __contains__. The file object is one of those containers.
That means that your membership test if username in userdata: will iterate the file line by line until username is found. The thing is, that's the full line, including newline. A quick test shows that username without newline is False and reads through the entire file
>>> # create test file
>>> open("users.txt", "w").write("Alice\nBob\nChuck\n")
16
>>> username = "Bob"
>>> f = open("users.txt")
>>> username in f
False
>>> f.read()
''
But adding the newline fixes the problem
>>> f = open("users.txt")
>>> username + "\n" in f
True
>>> f.read()
'Chuck\n'

Can not get "while" statement to progress [duplicate]

This question already has answers here:
Simple boolean inequality operators mistake
(6 answers)
Closed 4 years ago.
I had previously made a simple logging in code and it was working but when i went to separate data from the code to another .py file and import it, it will not progress passed the "username: " input part (it keeps loading the input for username). Does that mean that the file is not being imported correctly or is it in the main code?
Login.py
print ("Loading please wait...")
import logindata
import inputdata
import time
time.sleep(1.5)
username = ""
while username != logindata.user1 or username != logindata.user2:
print ("Username: ")
username = input()
password = ""
while password != logindata.passw1 or password != logindata.passw2:
print ("password")
password = input()
if username == logindata.user1 and password == logindata.passw1:
print ("Logging in...")
time.sleep(3)
print ("Welcome, user1!")
if username == logindata.user2 and password == logindata.passw2:
print ("Logging in...")
time.sleep(3)
print ("Welcome, user2!")
logindata.py
#Login Data#
user1 = "user1"
passw1 = "pass1"
user2 = "user2"
passw2 = "pass2"
############
It was previously working before i added a second "user" to it.
The issue is in this line:
while username != logindata.user1 or username != logindata.user2:
If user1 and user2 are different, than the condition will always evaluate to false. You'll want to use and rather than or.
Also, you'll probably want to connect the username & password, and not allow user1 to login with the password for user2 and vice versa ...
Change the or to an and.
username = ""
while username != logindata.user1 and username != logindata.user2:
print ("Username: ")
username = input()
password = ""
while password != logindata.passw1 and password != logindata.passw2:
print ("password")
password = input()
When you type in something that matches logindata.user1, user != logindata.user2 evaluates to True and the loop continues. Therefore, you need the username to not match both logindata.user1 and logindata.user2. Same goes for the password.

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

Python: login using 1 username but different passwords

I am trying to write a function that will understand how to login using one username but several passwords .
import sys
def login():
username = raw_input('username')
password = raw_input('password')
if username == 'pi':
return password
# if the correct user name is returned 'pi' I want to be
# prompted to enter a password .
else:
# if 'pi' is not entered i want to print out 'restricted'
print 'restricted'
if password == '123':
# if password is '123' want it to grant access
# aka ' print out 'welcome'
return 'welcome'
if password == 'guest':
# this is where the second password is , if 'guest'
# is entered want it to grant access to different
# program aka print 'welcome guest'
return 'welcome guest'
This is what I get when i run the function.
>>> login()
usernamepi
password123
'123'
Should be returning 'welcome'
>>> login()
usernamepi
passwordguest
'guest'
if the correct user name is returned 'pi' I want to be prompted to enter a password.
Your code prompts for both username and password. Only after that it checks what was entered.
Assuming you want your login function to return the values and not to print them out, I believe what you want is something like this:
def login():
username = raw_input('username: ')
if username != 'pi':
# if 'pi' is not entered i want to print out 'restricted'
return 'restricted'
# if the correct user name is returned 'pi' I want to be
# prompted to enter a password .
password = raw_input('password: ')
if password == '123':
# if password is '123' want it to grant access
# aka ' print out 'welcome'
return 'welcome'
if password == 'guest':
# this is where the second password is , if 'guest'
# is entered want it to grant access to different
# program aka print 'welcome guest'
return 'welcome guest'
# wrong password. I believe you might want to return some other value
if username == 'pi':
return password
That's doing exactly what you tell it: returning the password you entered when you enter pi as a username.
You probably wanted to do this instead:
if username != 'pi':
return 'restricted'
What is happening is here is very simple.
raw_input('username') gets the username and puts it in the variable username and same way for password.
After that, there is simply an if condition saying if username is 'pi' then return password. Since you are entering the username 'pi' that's what its doing.
I think you are looking for something like this:
>>> def login():
username = raw_input('username ')
password = raw_input('password ')
if username == 'pi':
if password == '123':
return 'welcome'
elif password == 'guest':
return 'welcome guest'
else:
return 'Please enter the correct password'
else:
print 'restricted'
>>> login()
username pi
password 123
'welcome'
>>> login()
username pi
password guest
'welcome guest'
>>> login()
username pi
password wrongpass
'Please enter the correct password'

Categories

Resources