Python Forum
[URGENT] Trying to create a simple password manager in python - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: [URGENT] Trying to create a simple password manager in python (/thread-4168.html)



[URGENT] Trying to create a simple password manager in python - equanox314 - Jul-27-2017

Hi, all apologies if this is in the wrong spot or my program has some basic errors as I am relatively new to both python  and this forum. I continuesly run into problems with this code, I am trying to have a master key registration and a login menu which checks the contents of a text file containing the master key before been able to add records such as usernames and other data. Any help would be mostly appreciated. thanks

code:

#importing all necessary modules

import pickle
import random
import os
import tkinter

MasterKeyList = []
UserRecordsList = []

#Specifying paths for source files

fileIn1 = "MasterRecords.txt"
fileOut1 = "MasterRecords.txt"

fileIn2 = "UserRecords.txt"
fileOut2 = "UserRecords.txt"

######################################################################################################################################

# defining all necessary variables

def AddAccount(UserRecords):
    with open(fileOut2, "wb") as file:
        pickle.dump((UserRecords), (file))

def EditAccount(UserRecords):
    for i in range(len(UserRecords)):
        if records[i][0] == AccountName:
            records[i] = newRecord
        break
    return records

def FindAccount(UserRecords):
    AccountName = input("Enter the name of the account you wish to search for e.g reddit")

    for i in range(len(records)):
        if UserRecords[i][1].lower() == AccountName:
            return UserRecords[i]

def DeleteAccount(UserRecords):
        for i in range(len(UserRecords)):
            if UserRecords[i][0] == AccountName:
                del UserRecords[i]
                break
            
        return UserRecords 

def CreateMasterKey(NewKey):
        with open(fileOut1, "wb") as file:
            pickle.dump((NewKey), (file))

def GetMasterKey(MasterRecords):
    MasterKey
######################################################################################################################################

# First menu 

# Login stage
def login():
    attempts = 3

    choosing = True
    while choosing:
        choice = int(input("1)Login\n2)Register\n3)Quit\n> "))

        # login
        if choice ==1:
            for cd in reversed(range(attempts)):
                MasterKey = input("Enter your master key to continue:")
                if input("Enter your master key to continue:") == MasterKey():
                    return True
                else:
                    print ("Incorrect, {} attempts remaining..".format(cd))
            return False

        # Registration stage
        elif choice ==2:
            if choice ==2:
                print ("Welcome to SmartPass please create your master key,")
                print ("this key will be required the next time you login")
                print ("please take not of this key as you will be unable to recover it if lost.")
                print ("")
                print ("")
            MasterKey = input("Enter your master Key:")
            print("Your master key has been successfully created!")
            CreateMasterKey(NewKey)
            LoggedIn = True
            choosing = False

        # Quit option
        elif choice ==3:
            print("Thank you for using SmartPass, bye now")
            os.exit(3)

        else:
            print("Invalid input, please try again")

def main():

    if login():
        print("You are currently logged in to SmartPass")
        loggedIn = True

        while LoggedIn:
            choice = int(input("1)Add account\n2)Edit\n3)Display all accounts\n4)Find account\n5)Delete account\n6)Generate random password\n7)Logout\n> "))
                        
        # Add Account option
        if choice ==1:
            account = "stuff"
            AddAccount(UserRecords)

        # Edit Account option
        elif choice ==2:
            input("Enter the name of the account you wish to edit:")
            EditAccount(UserRecords)

        # View all accounts/records
        elif choice ==3:
            DisplayAccounts(UserRecords)

        # Find Account
        elif choice ==4:
            print("Enter the name of the account you would like to find e.g facebook")
            FindAccount(UserRecords)

        # Delete Account
        elif choice ==5:
            DeleteAccount(UserRecords)

        # Generate random password option
        elif choice ==6:
            alphabet = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ#!$&(@3187%=+}{<->?"
        pw_length = 15
        mypw = ""

        for i in range(pw_length):
            next_index = random.randrange(len(alphabet))
        mypw = mypw + alphabet[next_index]

        print(mypw)

        # Logout and quit program
        if choice ==7:
            LoggedIn = False
            print("Logging out of your session....")

        else:
            print("You are now logged out, bye!")

if __name__ == "__main__":
    main()



RE: [URGENT] Trying to create a simple password manager in python - ichabod801 - Jul-27-2017

Please use Python tags around your code. I added them for you this time. For details on how to do so, see the BBCode link in my signature.

What is the problem you are having with this code? Please be as specific as possible. Give the full traceback if you're getting any errors. If you're getting the wrong output, how exactly is it wrong?


RE: [URGENT] Trying to create a simple password manager in python - equanox314 - Jul-27-2017

sure sorry about that will keep that in mind, after choosing registration and placing a key I get:

CreateMasterKey(NewKey)
NameError: name 'NewKey' is not defined

Also once I choose the login option I get:

TypeError: 'str' object is not callable which is on line 78 I think I haven't set up the login variable correctly.

I have tried looking at it again and fixed some errors regarding the exit option although I am still getting the 2 errors above after entering some input in the login and register options


RE: [URGENT] Trying to create a simple password manager in python - ichabod801 - Jul-28-2017

The first problem is because you never define NewKey in the login function. The input you get from the user right before that you assign to MasterKey instead. You need to change NewKey to MasterKey in login, or vice versa.

Are you sure about the line number on the second one? Line 78 in the code you posted is elif choice == 2: with has neither a string nor a call. When posting errors, post the full text of the error.


RE: [URGENT] Trying to create a simple password manager in python - equanox314 - Jul-28-2017

Ok thanks, I ended up getting it working. thanks for your help though


RE: [URGENT] Trying to create a simple password manager in python - DeaD_EyE - Jul-28-2017

First of all, don't use buzzwords like URGENT in your topic. This will lead not to answer a question.

Some hints.
  1. Don't use pickle to save consistent data outside of Python. Sometimes the format changes after an update and then your data is lost. Use something different. First you can try plain text files, later you should look for an database.
  2. Don't invent your own password manager, if you don't know about hashing, symmetric and asymmetric encryption and entropy. You can still do your program, to understand the concepts behind a little bit better.
  3. Functions in Python are doing something. Use verbs for functions, lower case and underscore.
  4. Look into the string module of the Python stdlib. There are already prepared strings for ascii_lowercase, ascii_uppercase, digits
  5. Python don't have a switch statement. Instead of asking for every selected option, you can make a dict for this task:
    def create_user():
    username = input('Enter your username: ')
    # code
    
    def delete_user():
    username = input('Enter your username: ')
    # code
    
    selection_dict = {0: create_user, 1: delete_user}
    userinput = int(1) # user choose option 1
    try:
    function_to_call = selection_dict[userinput]
    except KeyError:
    print('You have selected a non existing option...')
    else:
    function_to_call()
  6. Later you can try to do the same task object oriented. But first do the basics.