I am currently attempting to make a login/signup program on my computer that will allow for multiple sets of usernames and passwords. Right now anytime I sign up, it overwrites the previous login. I am using Python 3.4.
Is there a way I can prevent this?
My code is available below:
import os
import pickle
import sys
import time
user_name = 'default'
pass_word = '12345'
login = {'username' : user_name,
'password' : pass_word}
def cls():
os.system('cls')
def space():
print(' ')
def load():
with open('logins', 'rb') as f:
login = pickle.load(f)
def save():
with open('logins', 'wb') as f:
pickle.dump(login, f)
def MainMenu():
print('Select an Option.')
while True:
print('1) Login')
print('2) Signup')
user_input = input('Option #: ')
if user_input == '1':
cls()
login_user()
elif user_input == '2':
cls()
signup_user()
else:
cls()
continue
def signup_user():
user_chosen_name = input('Username: ')
login['username'] = user_chosen_name
user_chosen_password = input('Password: ')
login['password'] = user_chosen_password
space()
cls()
print('Setup complete. Please login.')
os.system('pause')
save()
cls()
login_user()
def login_user():
load()
while True:
print('Please Login.')
space()
user_input_name = input('Username: ')
user_input_password = input('Password: ')
if user_input_name == login['username'] and user_input_password == login['password']:
space()
print('Login Successful.')
else:
space()
print('Login Failed. Please Try Again.')
while True:
print('1) Try Again.')
print('2) Main Menu.')
user_cont = input('Continue?: ')
if user_cont == '1':
cls()
break
elif user_cont == '2':
cls()
MainMenu()
break
if __name__ == '__main__':
if os.path.isfile('logins') == False:
save()
else:
pass
MainMenu()
Here are two proposals for the login/password data model.
Use a dictionary, this is probably the simplest way ; I suggest using this.
# init with default
passwords = {user_name: pass_word}
# password look-up
if login in passwords:
print passwords[login]
else:
print 'User', login, 'is not registered'
# password set or update
password[login] = new_password
List of couples or list of dictionaries.
This may be closer to your current solution, but I would not recommend it.
I only show what the initialization would be.
# list of couples
logins = [(user_name, pass_word)]
# list of dictionaries
logins = [{'username' : user_name,
'password' : pass_word}]
Related
I am fairly new to Python and am trying this project. I need to store usernames and passwords in a text file ( to create a database). I have used the pickle module. The code I've tried erases previously-stored data every time I run the code.
I have understood that I have to append data to the file instead of writing to it but I don't know how. How can I correct the code?
import pickle
# pickle mod converts obj into byte stream to store in database
import time
def load_Dictionary():
try :
with open("UserDict.txt" , "rb") as ufile :
return pickle.load(ufile)
except IOError :
with open("UserDict.txt" , "ab") as ufile :
pickle.dump(dict() , ufile)
return dict()
def save_Dictionary(UserDict):
with open("UserText.txt" , "wb") as ufile :
pickle.dump(UserDict , ufile)
def new_User_Login():
userDict = load_Dictionary() # dictionary is loaded
checkUserAcc = input("Are you a new user ( Yes or No ) ? ")
# insert buttons for yes no
# tk.Button(window, text="", command=password_generator).pack(pady=10)
if (checkUserAcc == "Yes" or checkUserAcc == "yes" or checkUserAcc == "YES"):
username = input("Please enter your username : ")
Root_password = input ("Please enter your password :")
if ( username in userDict):
print("Username you entered is not available")
new_User_Login()
else :
userDict[username] = Root_password
print("Login Successful!")
save_Dictionary(userDict) # saves new login info
time.sleep(2.0)
elif (checkUserAcc == "No" or checkUserAcc == "no" or checkUserAcc == "NO") :
user_login()
else :
print("Invalid input! Try Again.")
new_User_Login()
def user_login():
global username
global Root_password
global tries
login_Username = input("Enter your Username : ")
login_Password = input("Enter your Password : ")
UserDict = load_Dictionary()
if ( tries < 5):
for key in UserDict:
if (login_Username == key and login_Password == UserDict[key]):
print("You have successfully logged in !")
else :
print("Login Failed! Please try again")
tries = tries + 1
user_login()
if( tries >= 5 ):
print("You have attempted login too man times. Try again later. ")
time.sleep(30.0)
tries = 1 # reset tries counter
user_login()
global tries
tries=1
new_User_Login()
It appears you were using "wb" instead of "ab" in this function, which caused the file to reset everytime you wished to save to it. Also, The filename should be "UserDict", instead of "UserText".
def save_Dictionary(UserDict):
with open("UserDict.txt" , "ab") as ufile:
pickle.dump(UserDict , ufile)
I am trying to make a python program that will allow a user to sign up or sign in, and I am currently doing so by creating a file that stores every username and its password. Right now, it is not writing to the file, and I was wondering if anyone could tell me what I'm doing wrong. Please forgive me if it is a stupid error, I am not very experienced with python, but I can still make a basic program. This is my code:
# -*- coding: utf-8 -*-
from time import sleep
def signin():
usrlist = open("users.txt", 'w+')
complete = False
while (complete == False):
usr = raw_input("Username: ")
pwd = raw_input("Password: ")
usrinfo = (usr + ":" + pwd)
if (usrinfo in usrlist.read()):
print("Welcome back " + usr + ".")
complete = True
else:
print("Username or Password incorrect. Please try again.")
def signup():
usrlist = open("users.txt", 'w+')
usravailable = False
while (usravailable == False):
newusr = raw_input("Please choose a Username: ")
if (newusr in usrlist.read()):
print("Username taken. Please choose again.")
else:
usravailable = True
newpwd = raw_input("Please choose a password: ")
oldusrlist = usrlist.read()
usrlist.write(oldusrlist + newusr + ":" + newpwd + ".")
print("Thank You. Please Sign in.")
signin()
print("Please Choose An Option:")
print("1. Sign In")
print("2. Sign Up")
inorup = input()
if (inorup == 1):
signin()
elif (inorup == 2):
signup()
Also, if you have any suggestions about how I could do this differently, or better(even if it's using a different language) Thank you and I appreciate your help.
EDIT:
If anyone can give me information on doing a program like this either using JSON, javascript, or multiple files that can store larger amounts of data about each account, please tell me how in the comments or an answer. I appreciate the help.
To fix your not saving issue, you need to do two changes:
1) in your signin() routine, change the line 'usrlist = open("users.txt", 'w+')' into 'usrlist = open("users.txt", 'r')
2) in your singup() routine, after the line 'usrlist.write(oldusrlist + newusr + ":" + newpwd + ".")', add: 'usrlist.close()'
Then you should be able to see the stuff got saved.
here is a way to use json
import json
import os
FILENAME = "./f.json"
# init the data file
def init_data():
with open(FILENAME, "wb") as f:
json.dump({}, f)
def load_content():
with open(FILENAME) as f:
infos = json.load(f)
return infos
def save_content(content):
with open(FILENAME, "w+") as f:
json.dump(content, f)
return True
def save_info(username, password):
infos = load_content()
if username in infos:
return False
infos[username] = password
save_content(infos)
return True
def sign_in(username, password,):
status = save_info(username, password)
if not status:
print "username exists"
def login(username, password):
infos = load_content()
if username in infos:
if password == infos[username]:
print "login success"
return True
else:
print "password wrong"
return False
else:
print "no user named %s" %username
if __name__ == "__main__":
# here is some simple test
os.system("rm -f %s" %FILENAME)
if not os.path.exists(FILENAME):
init_data()
# login fail
login("hello","world")
# sign_in
sign_in("hello", "world")
# login success
login("hello","world")
# sign_in fail
sign_in("hello", "world")
# login fail
login("hello", "hello")
import random
import pickle, shelve
import os
#import RPi.GPIO as GPIO | Raspberry pi only
import tkinter
import sys
import time
class Operator(object):
global list_name
def __init__(self):
print("Welcome to Python OS 1.0")
print("type 'help' to access help...") # ADD CODE OS.REMOVE("FILE")
def CheckDetails(self):
if not os.path.isfile( 'details.dat' ) :
data=[0]
data[0] = input('Enter Your Name: ' )
file= open( 'details.dat' , 'wb' )
pickle.dump( data , file )
file.close()
else :
File = open( 'details.dat' , 'rb' )
data = pickle.load( File )
file.close()
user = ""
while user != data[0]:
input("please enter your username...")
print( 'Welcome Back To Python OS, '+ data[0])
def Help(self):
print("""
write(sentence) - Prints the typed sentence on the screen
open(file, mode) - Opens the file and mode such as 'r'
create(listName) - creates the list, listName
add(data, listName) - adds the data to listName
remove(data, listName) - removes the selected data from listName
""")
def write(self, sentence):
print(sentence)
#classmethod
def create(self):
list_name = input("Please enter the list name...")
vars()[list_name] = []
time.sleep(1)
print("List (" + list_name + ") created")
def add(self):
data = input("Please specify the data to be added...")
list_name += data
def remove(self, data, list_name):
remove_data = input("Plese specify the data to be removed...")
list_name -= data
def main():
os = Operator()
os.CheckDetails()
ans = ""
ans = ans.lower()
while ans != "quit":
ans = input()
if ans == "write":
os.write()
elif ans == "help":
os.Help()
elif ans == "create":
os.create()
elif ans == "add":
os.add()
elif ans == "remove":
os.remove()
elif ans == "quit":
break
else:
print("Sorry, that command does not exist or it will be added into a future update...")
print("goodbye...")
main()
I am trying to make some sort of simplified python, but hitting errors only on the CheckDetails() function. I'm pickling data (which is fine) but getting errors when making the user check his or her username is correct, I've tested it and even though I have typed in the correct username, it carry's on asking for my username. Can anyone please help?
You have a while loop that will execute forever because you are not assigning your user variable to anything.
while user != data[0]:
user = input("please enter your username...")
print( 'Welcome Back To Python OS, '+ data[0])
So I'm trying to write a program that can create an account, by creating a .txt file that's the usernames, and then hashes the password with md5 and puts it in the file. However, whenever I run
hashlib.md5(pasw.encode)
it produces bizarrely inconsistent results, that vary whether it encodes it in a function or not, and last time I tested it seemed to produce a random hash the first time ran. Now, when testing in a new project it sometimes produces the same hash for different strings. I've tried everything I could think of and I've got nothing. You can see some of the things I've tried to do.
Thanks in advance for the help, sorry if my code looks horrible I'm doing this project to learn. Here's the full code, sorry if some is irrelevant:
import hashlib
# Creates an account
def create():
print('Create an account')
user = input('Please enter a username: ')
pasw = input('Please enter a password: ')
usef = user+'.txt'
f = open(usef,'w')
# hash'd it
hash_object = str(hashlib.md5(pasw.encode()))
# Printing hash for debug
print(hash_object)
# This doesn't help but I tried
hash_object = str(hashlib.md5(pasw.encode()))
# Printing hash for debug
print(hash_object)
f.write(hash_object)
f.close()
# Logs into a pre-existing account
def login():
print('Welcome! To log in:')
user = input('Please enter a username: ')
pasw = input('Please enter a password: ')
usef = user+'.txt'
# Comparative hash
hash_object = str(hashlib.md5(pasw.encode()))
# Printing hash for debug
print(hash_object)
# This doesn't help but I tried
hash_object = str(hashlib.md5(pasw.encode()))
# Printing hash for debug
print(hash_object)
f = open(usef,'r')
# Checks to see if it's right
if hash_object == f:
print('Welcome, '+user+'!')
return(user)
else:
print('User/password not found')
return(0)
# Changes a password for a user
def change(user):
while True:
pasw = input('Please enter your current password: ')
usef = user+'.txt'
hash_object = str(hashlib.md5(pasw.encode()))
# Printing hash for debug
print(hash_object)
# This doesn't help but I tried
hash_object = str(hashlib.md5(pasw.encode()))
f = open(usef,'r')
if hash_object == f:
pasw = input('Please enter your new password: ')
past = input('Please repeat your new password: ')
while True:
if pasw == past:
usef = p+'.txt'
f = open(usef,'w')
hash_object = str(hashlib.md5(pasw.encode()))
# Printing hash for debug
print(hash_object)
# This doesn't help but I tried
hash_object = str(hashlib.md5(pasw.encode()))
f.write(hash_object)
f.close()
print('Done!')
return()
else:
print('They aren\'t the same')
pass
else:
print('That doesn\'t match the password on the system')
# Help with commands
def halp():
print('You can type "Create" to create an account')
print('You can type "Login" to log into a pre-existing account')
print('More functionality will be added')
print('Maybe')
# =============== Main Body of Code ==================
while True:
print('What do you want to do?')
print('Type "Help" for commands')
x = input()
x = x.upper()
if x == 'CREATE':
create()
elif x == 'LOGIN':
p = login()
if p != 0:
while True:
print('What would you like to do now?')
print('"Logout" to log out')
print('or "Change password"')
print('I think you can guess that')
x = input()
x = x.upper()
if x == 'CHANGE PASSWORD':
change(p)
elif x == 'HELP':
halp()
elif x == 'DEV':
y = input()
print(str(hashlib.md5(y.encode())))
# This doesn't help but I tried
print(str(hashlib.md5(y.encode())))
else:
print("Command not found")
print("There are four commands")
print("It's not that hard")
edit: Oh, I understand now. Thanks for the help!
What's the best way to implement this - reuse user input on menu?
Here's my sample code below:
def input():
user = raw_input('user: ')
passwd = getpass.getpass('passwd: ')
return (user,passwd)
def function1():
user, passwd, vcenter = input()
do something
def function2():
user, passwd, vcenter = input()
do something
def function3():
user, passwd, vcenter = input()
do something
def main():
while True:
if choice == 1:
function1()
elif choice == 2:
function2()
elif choice == 3:
function3()
else:
print 'Choose from the options only!'
break
I think i get what you mean, you want to use the input() once in the while loop, and not repeat calling it in every function. if so I suggest this solution:
def input():
user = raw_input('user: ')
passwd = getpass.getpass('passwd: ')
return (user,passwd)
def function1(param):
user, passwd = param
do something
def function2(param):
user, passwd = param
do something
def function3(param):
user, passwd = param
do something
def main():
while True:
if choice in [1,2,3]:
param = input()
if choice == 1:
function1(param)
elif choice == 2:
function2(param)
elif choice == 3:
function3(param)
else:
print 'Choose from the options only (1, 2, 3): '
break
hope this helps.