Okay, so I am creating a password storage system. I have everything but a few last functions.
I need to be able to search for different sites and view all sites in a choicebox. for editting. I've tried a few different things but I just can't get it. the first set of code is the actual coding, and the second set is the simpleDB.py program that I'm using with it.
Thanks for any help.
Samantha
# Password Storage System
###########################################################
from easygui import *
from simpleDB import *
############ LIBRARY SECTION - DO NOT EDIT ########################
## create a new user account
def createLogin():
#prompt for new account information
while 1:
inputs = multpasswordbox("Please Choose", "ID Manager", ["Login ID", "Login Password"])
if len(inputs[0]) < 8 or len(inputs[1]) < 8: #too short id or password
msgbox("UserID and password must be at least 8 characters long." +
"Password must contain at least" +
"1 digit, 1 upper-case letter and 1 lower-case letter")
continue #repeat the prompt
if inputs[0] == inputs[1] : #id and password can't be the same
msgbox("UserID and password should not be the same")
continue #repeat the prompt
digit = 0
cap = 0
lower = 0
password = inputs[1]
#validating password format
i = 0
while i < len(password) :
if password[i] >= 'A' and password[i] <= 'Z':
cap = cap + 1
if password[i] >= 'a' and password[i] <= 'z':
lower = lower + 1
if password[i] >= '0' and password[i] <= '9':
digit = digit + 1
i = i+ 1 #check the next character
#let's see if we have the password int he right format
if cap > 0 and lower > 0 and digit > 0:
break # right format => stop checking
else:
msgbox("Password must contain at least 1 digit, 1 upper-case letter and 1 lower-case letter")
#everything is good, let's reprompt for the login information
i = 3
while i > 0 :
inputs2 = multpasswordbox("Please provide login information again for verification purpose",
"ID Manager", ["User ID", "Password"])
if inputs2[0] == inputs[0] and inputs2[1] == inputs[1] :
break
msgbox("Unmatched login information")
i = i - 1
else: #terminate the loop without executing the break
msgbox("You have repeatedly entered invalid information. Good bye!")
exit(0)
#now check with the database to make sure the id is not taken
for user in getUsers():
if user[0] == inputs2[0]:
msgbox(user[0] + ' has been taken. Please choose a different login ID')
return createLogin()
# everything is good, return the obtained loginID and login password
return inputs2
############################## END OF LIBRARY SECTION #############################
# print out user object
def printObj(obj):
msgbox( "Login ID:" + obj.get('login ID') +
'\nLogin Password: ' +obj.get('login password') +
'\nName: ' +obj.get('name') +
'\nEmail Address: '+ obj.get('email') +
'\Home Phone: '+ obj.get('home phone') +
'\nWork Phone: '+ obj.get('work phone') +
'\nHome Address: '+ obj.get('home address') +
'\nWork Address: '+ obj.get('work address'), '\nYour Information for Verification')
#################################################
#====== Main Program ======#
#=== Start putting your codes from here ======#
#################################################
#get all pairs of loginID and loginPass into a list
users = getUsers()
choice = None #starting with no choice
if len(users) > 0: #there are some user in the database
choice = buttonbox("Please choose", "ID Manager", ["New Account", "Login"])
if len(users)<= 0 or choice == "New Account":
while 1:
loginInfo = createLogin() # create an login account
userid = loginInfo[0] # get the entered login ID
password = loginInfo[1] #get the entered login password
#create a new user here
newUser = createUser(userid, password)
if newUser:
#prompt for personal information and update the new user with these information
userInfo = multenterbox("Please provide the following information", "ID Manager",
["Name", "Email", "Work phone", "Home phone",
"Work address", "Home address"] )
newUser.update('name', userInfo[0])
newUser.update('email', userInfo[1])
newUser.update('work phone', userInfo[2])
newUser.update('home phone', userInfo[3])
newUser.update('work address', userInfo[4])
newUser.update('home address', userInfo[5])
#display the input for verification
printObj(newUser)
# Repeated prompting for EXIT or NEW SITE:
sites =[]
while 1:
choice = buttonbox('Please Choose', 'Adding new Site', ['New Site', 'Exit'])
if choice == 'Exit' :
exitWithSave() #if EXIT: save the data and exit
#if NEW SITE: prompts for information and add them (update) into this user
siteInfo = multenterbox('Please enter site information', 'Adding Site',
['Site Desc','site login','site password'])
elif choice == "Login":
i = 3
while i > 0: # allow 3 tries
loginInfo = multpasswordbox('Log in', "ID Manager", ["Login ID", "Login Password"])
user = getUserInfo(loginInfo[0])
if user:
if loginInfo[1] == user.get('login password'):
break
i = i -1
else: #too many invalid attempts
msgbox("\nYou have too many attempts. Goodbye!")
exit(0)
# if we get here, the user must have provided us with a valid login information
# ACTION BLOCK
while 1:
storedInfo = buttonbox("Update Information", "ID Manager", ["EDIT", "SEARCH", "VIEW", "EXIT"])# ask if the user want to EDIT, SEARCH, VIEW, or EXIT the stored information
if storedInfo== "EDIT":# if EDIT is chosen:
userInfo = multenterbox("Please Make Any Changes Necessary Below", "ID Manager",["Name", "Password", "Email", "Work phone", "Home phone","Work address", "Home address"],
[user.get('name'), user.get('password'), user.get('email'), user.get('work phone'), user.get('home phone'), user.get('work address'), user.get('home address')])
user.update('name', userInfo[0])
user.update('password', userInfo[1])
user.update('email', userInfo[2])
user.update('work phone', userInfo[3])
user.update('home phone', userInfo[4])
user.update('work address', userInfo[5])
user.update('home address', userInfo[6])
elif storedInfo=="SEARCH": #if search is chosen:
keyword= enterbox('Enter Keyword', 'Search')
sites=user.get('sites')
if keyword in 'sites':
msgbox('please say hello')
elif storedInfo=="VIEW": #if VIEW is chosen:
if len(sites)>0:
#**********# site id : site password : site description
##*******#if the user clicks on any of this choice, show the selected site information for editing
print hello
elif storedInfo=="EXIT":
exitWithSave()
else: #unhandled cases
exit(0)
AND
import os.path
import pickle
from xml.dom import minidom, Node
DATABASE_NAME='db'
DATABASE = None #database root
######################################################
#simple xor encryption to the fisrt character
def __encryptXOR__(text):
#return text
data = []
if len(text) <= 0:
return ''
data.append(text[0])
i = 1
while i < len(text):
e = ord(text[i]) ^ ord(text[0])
data.append(chr(e))
i += 1
return ''.join(data)
#####################################################
#open a file, read its contain and return the content
def __loadFile__(fileName):
lines =[] # a list of all lines
openFile = open(fileName, 'rb')
#read the content into a list
if openFile:
lines = ''.join(openFile.readlines(os.path.getsize(fileName)))
openFile.close() #close the file
return __encryptXOR__(''.join(lines))
######################################################
#save the given string into a file
def __saveFile__(data):
data = __encryptXOR__(data)
if len(data) > 0:
newFile = file(DATABASE_NAME, "w")
newFile.write(data)
newFile.close()
#######################################################
# save the data and exit
def exitWithSave():
__saveFile__(DATABASE.toxml())
exit(0)
####################################################
#indicate if the data file exists
def __databaseExists__(fileName):
return os.path.exists(fileName)
###########################################
#read an xml database and return the root node
def __readDB__(fileName, createNew=0):
global DATABASE
if createNew: #create new database
DATABASE = minidom.parseString("<db></db>")
else:
s = __loadFile__(fileName) #load the data file as a string
DATABASE = minidom.parseString(s)
return DATABASE
############################
#class representing a user
class User:
#constructor
def __init__(self, node):
self.__user__ = node
#get the data of a given field with tag name
def get(self, tagName):
if tagName == 'sites':
accounts=[]
#retrieve account information
for acct in self.__user__.getElementsByTagName("site"):
desc = __getNodeData__(acct, "desc")
id = __getNodeData__(acct, "id")
passwd = __getNodeData__(acct, "pass")
accounts.append([desc, id, passwd])
return accounts
else: #return the data of the given field
return __getNodeData__(self.__user__, tagName);
# store this user back to the xml dom tree
def update(self, tagName, value):
tagName = __formatTagName__(tagName)
if tagName != 'SITES' and tagName != 'LOGINID': #can't change loginID
#update top level field
__setNodeData__(self.__user__, tagName, value)
else: #update the sites
#drop the sites element
element = self.__user__.getElementsByTagName('SITES')
if element:
self.__user__.removeChild(element[0])
#create a new sites node
sites = __newNode__('sites', '')
for item in value: #scan each site
site = __newNode__('site', '')
site.appendChild(__newNode__("desc", item[0]))
site.appendChild(__newNode__("id", item[1]))
site.appendChild(__newNode__("pass", item[2]))
sites.appendChild(site) #add the site to the list of sites
#add the sites back to the user
self.__user__.appendChild(sites)
# print '\nAfter update' + self.__user__.toprettyxml()
#######################################################
# format tagname
def __formatTagName__(tagName):
tagName = tagName.upper() #convert to upper case
tagName =tagName.replace(' ','') #remove blank
tagName = tagName.replace('-','')
tagName = tagName.replace('_','')
return tagName
#######################################################
def __newNode__(tagName, value):
tagName = __formatTagName__(tagName)
node = DATABASE.createElement(tagName)
node.appendChild(DATABASE.createTextNode(value.strip()))
return node
#######################################################
# return whether the given id is in the database
def __uniqueIDExist__(tagName, newID):
tagName = __formatTagName__(tagName)
root= DATABASE
for eID in root.childNodes:
existingID = __getNodeData__(eID, tagName)
# print 'comparing ' + existingID + 'with '+ newID
# raw_input()
if existingID == newID:
return True
return False
##############################################################
#given a node, return its text data
def __getNodeData__(node, tagName):
tagName = __formatTagName__(tagName) #convert to upper case
data = ""
element = node.getElementsByTagName(tagName)
if element: #if exists then extract data
for childNode in element[0].childNodes:
if childNode.nodeType == Node.TEXT_NODE:
data += childNode.data
return data
##############
#change the value of a node
def __setNodeData__(node, tagName, value):
tagName = __formatTagName__(tagName)
value = value.strip()
element = node.getElementsByTagName(tagName)
if element: #if exist, update it
for childNode in element[0].childNodes:
if childNode.nodeType == Node.TEXT_NODE:
childNode.data = value
break
else: #create a new node
node.appendChild(__newNode__(tagName, value))
###############################################################
## ===========Starting Database API ============
###############################################################
#return a list of loginID and loginPass
def getUsers():
info = []
#no database, create a new one and return empty list
if not __databaseExists__(DATABASE_NAME):
__readDB__(DATABASE_NAME, 1)
return info
#open database and extract information
__readDB__(DATABASE_NAME)
root= DATABASE
userTag = __formatTagName__('user')
for user in root.getElementsByTagName(userTag):
userID = __getNodeData__(user, "loginID")
password = __getNodeData__(user, "loginPassword")
#add these to the list
info.append([userID,password])
return info
#############################################
#get all information about a given user
def getUserInfo(userID):
root = DATABASE
#print '\nin get user info ', root.toprettyxml()
tagName = __formatTagName__('user')
for user in root.getElementsByTagName(tagName):
ID = __getNodeData__(user, "loginID")
#found the user, build a user object and return
if userID == ID:
return User(user)
#####################
#creating a new user with the given id and password
def createUser(loginID, password):
#make sure there is no duplicate id in the database
if __uniqueIDExist__('loginID', loginID):
#print 'ID: '+ loginID + ' exists'
return None
user = __newNode__("user", '')
user.appendChild(__newNode__('loginID', loginID))
user.appendChild(__newNode__('loginPassword', password))
root = DATABASE.getElementsByTagName("db")[0]
root.appendChild(user) #add the user to the database
return User(user)