How should I go about coding this password Manager? - python

I am new to programming and have recently been trying to learn/understand OOP. I decided to do a password manager as a project to help me learn as I have already done it using FP. However, I have gotten a tad lost in what I am doing and would greatly appreciate some help. I am lost in the creation of a user account and making an object out of it. And then use this in a login function to access the users password collection and make new passwords or edit existing ones if the credentials of the account match those in a dictionary of users. But i don't know how to do this honestly.
Any comments regarding my code style, like its readability and if it follows convention would also be of help.
`import random
import string
import secrets
class User():
def __init__(self, username, credentials, password_dict) -> None:
self.credentials = {}
self.password_dict = {}
def passGen(self, passDicts):
n = int(input('Define password length. Longer passwords are safer.'))
source = string.ascii_letters + string.digits
password = ''.join((random.choice(source) for i in range(n)))
print('Password has been generated!')
print('Would you like to save this password? Type y or n: ')
yon = input()
if yon == 'y':
site = input('Please enter the site password is to be used:')
self.password_dict[site] = password
if yon == 'n':
print('Okay')
main()
return self.password_dict
#^Generates a new password for a given site and saves it to the users password (dictionary) collection
def Credentials(self, credentials):
username = str(input('Enter username: '))
password = str(input('Enter password for your account'))
if username in credentials:
print('')
self.credentials[username] = password
def main():
choice = input()
if choice == '1':
login()
if choice == '2':
`
#^^^
main() above is to display the menu and take the user to their saved passwords. Choice 1 is
login and choice 2 is exit. This will take the user to a menu where the can check passwords, download password dictionary as a text file, or edit existing passwords for a specified site.

I'd format it as following:
import random
import string
import secrets
class User():
def __init__(self, username, credentials, password_dict) -> None:
self.credentials = {}
self.password_dict = {}
def Credentials(self, credentials): # save username and password
username = str(input('Enter username: '))
password = str(input('Enter password for your account'))
if username in credentials:
print('')
self.credentials[username] = password
def passGen(self, passDicts): # random password generator
n = int(input('Define password length. Longer passwords are safer.'))
source = string.ascii_letters + string.digits
password = ''.join((random.choice(source) for i in range(n)))
print('Password has been generated!')
print('Would you like to save this password? Type y or n: ')
yon = input()
if yon == 'y':
site = input('Please enter the site password is to be used:')
self.password_dict[site] = password
if yon == 'n':
print('Okay')
main()
return self.password_dict
def main():
choice = input()
if choice == '1':
login()
if choice == '2':

Related

Writing to text file formatting

I have an assignment to make a simple task manager/todo list. This code block is just the part of the program that handles login, new username and password registration. When the user registers that input is written to a text file called user.txt.
Whenever it writes to the text file, it writes like this:(['admin', 'adm1n'])
instead, it should write it like this:admin, adm1n
user_file = open("user.txt","r+")
login = False
while login == False:
new = input("Are you a new user? Y/N:\n").lower()
if new == "y":
print("Please register a new username and password:\n")
new_user1 = input("Please enter a new username:\n").split()
new_pass1 = input("Please enter a new password:\n").split()
new_user2 = input("Please confirm your username:\n").split()
new_pass2 = input("Please confirm your password:\n").split()
user_pass1 = new_user1 , new_pass1
user_pass2 = new_user2 , new_pass2
if user_pass1 == user_pass2:
user_file.write(f"{user_pass2},")
user_file.seek(0)
break
elif new == "n":
username = input("Enter your username:\n")
password = input("Enter your password:\n")
valid_user = username
valid_password = password
for line in user_file:
valid_user, valid_password = line.split(", ")
if username == valid_user and password == valid_password:
login = True
if login == False:
print("Incorrect details! Please enter a valid username and password")
What am I doing wrong? I'm sure it's something small.
Thanks in advance!
Because you are making a tuple there. Instead, you should create a string. Here is the corrected version of your code
user_pass1 = new_user1 + ',' + new_pass1
user_pass2 = new_user2 + ',' + new_pass2
if user_pass1 == user_pass2:
user_file.write(f"{user_pass2},")
user_file.seek(0)
break
Thanks for your feedback everyone.
I managed to get it figured out. I added an index to it to print the string and it worked just fine.
user_pass2 = new_user2 , new_pass2
if user_pass1 == user_pass2:
#Writes username and password to text file in format requested.
user_file.write(f'\n{user_pass2[0]}, {user_pass2[1]}')

Creating a Login System

I am trying to create a login system. I could make the system without implementing class and just functions. I would like to make each steps into specific methods without writing all into one function.
My question is how to revert back into login asking username and password if the character length is > 5 or wrong password.
If the username and password not in the list how do i revert it back or do i need to code again?
class LoginSystem:
def __init__(self):
self.user_id = input("Please enter your user id: ")
self.user_password = input("Please enter your password: ")
def login(self):
username = self.user_id
password = self.user_password
if len(username) <= 5 and len(password) <= 5:
print("Logging In")
else:
print("Error! Max Length is 5 chars.") #return back to
login system
def check_system(self):
registered_user = {
"test#gmail.com": "test"
}
if self.user_id in registered_user:
print("Successful")
else:
new_user = input("Id not found! Are you are new user?\n [Y]es or [N]o\n")
new_user = new_user.lower()
if new_user == "Y":
return back to login system
elif new_user == "N": #how to return back to main login system
new_username = input("Please enter your user id: ")
new_userpassword = input("Please enter your password: ")
else:
return #back to login system
Your LoginSystem treats the wrong data as its instance attributes. The set of registered users is constant across method calls; the login method itself should be prompting for the user id and password.
class LoginSystem:
def __init__(self):
self.users = {"test#gmail.com": "test"}
def login(self):
while True:
username = input("Please enter your user id: ")
password = input("Please enter your password: ")
if len(username) <= 5 and len(password) <= 5 and self.check_system(username, password):
print("Logging In")
break
else:
# TODO Disallow infinite retries to get it right
print("Error! Max Length is 5 chars.")
def check_system(self, name, password):
try:
expected_password = self.registered_user[name]
except KeyError:
# Or try to add a new user to the system here
return False
if password != expected_password:
return False
return True
A separate method can be added to add a new user to the system where necessary.

How do I loop my password/username login page and read the password/username from an external file?

I'm aware of the multiple posts and sources regarding how to loop and read from a text file. I'm sorry to be that guy but I'm a recent noob at Python and I'm writing this at 1:00 in the morning.
As the title suggests, how do I loop my login page so that if the user enters details incorrectly then they get another chance to try, until they have entered details correctly. The password/username also needs to be read from an external file.
My code:
print ("\nEnter details to access wallet...\n")
username = 'Janupedia'
password = '12345'
userInput = input("What is your username?\n")
if userInput == username:
userInput = input("Password?\n")
if userInput == password:
print("Welcome!")
print('\n--------------------------------------------------------\n')
print ("BTN = 0.10")
print ("= £315.37")
else:
print("That is the wrong password.")
else:
print("That is the wrong username.")
print('\n--------------------------------------------------------\n')
Let's say your text file (credentials.txt) reads:
Janupedia
12345
Maybe something like this will work for you. I've commented the code that I added. You probably want to name the credentials file something else.
print ("\nEnter details to access wallet...\n")
"""
Open File
"""
with open("Credentials.txt", "r") as f:
array = []
for line in f:
array.append(line) #stores username and password
username = array[0]
password = array[1]
login = 0 #initial login status
while login == 0: #as long as login status = 0 loop repeats
userInput = input("Username?")
if username.strip(' \n') == userInput.strip(' \n'):
userInput = input("Password?")
if password.strip(' \n') == userInput.strip(' \n'):
login = 1 #login successful set login status to 1 thus breaking loop
else:
print("Incorrect")
else:
print("Incorrect")
print('\n--------------------------------------------------------\n')
# Login successful loop finished
print("Welcome!")
print('\n--------------------------------------------------------\n')
print ("BTN = 0.10")
print ("= 315.37")
So you want to loop it. Where would a good place for that be? How about when we ask for a question.
Now, look at the condition where we get the right username and password. We don't want to handle it inside the loop. The loop is only there to get the correct username and password.
print("\nEnter details to access wallet...\n")
username = "Janupedia"
password = "12345"
userInput = ""
while userInput != password:
userInput = input("What is your username?\n")
if userInput == username:
userInput = input("Password?\n")
if userInput == password:
break
else:
print("That is the wrong password.")
else:
print("That is the wrong username.")
print("Welcome!")
print("\n--------------------------------------------------------\n")
print("BTN = 0.10")
print("= £315.37")
todo_list = open("Credentials", "a")
todo_list.write("Username = Janupedia + Password = 12345")
todo_list.close()
print("\n--------------------------------------------------------\n")
Now to read your username/password from a file. Let's make it simple. The first line is the username and the second line is the password. There are no other items.
Now create a proper function.
def read_credentials_from_file(filename):
"""Read the file and return (username, password).
File contents are first line username and second line password.
"""
# Using the `with` statement is current best practice.
with open(filepath, "rt") as user:
username = user.readline().strip()
password = user.readline().strip()
return username, password
Now fix your code to use the function.
username, password = read_credentials_from_file(...)
Note in the function we strip line endings. If you are using Python 3.7, use the breakpoint function to step through the code and watch what it is doing.
do something like this:
password = "password"
username = "username"
theirUsername = input("What is your username")
theirPassword = input("What is your password")
while theirUsername != username or theirPassword != password:
print("incorrect")
theirUsername = input("What is your username")
theirPassword = input("What is your password")
print("correct")
You can read from an external file with file = open("externalfile.txt","r") then do text = file.read() and if the file is formatted as
username
password
do text = text.split("\n") and then username = text[0] and password = text[1]
this is what it should look like with an explanation:
file = open("password.txt","r") #this opens the file and saves it to the variable file
text = file.read() #this reads what is in the file and saves it to the variable text
text = text.split("\n") #this makes the text into a list by splitting it at every enter
username = text[0] #this sets the username variable to the first item in the list (the first line in the file). Note that python starts counting at 0
password = text[1] #this sets the password variable to the second item in the list (the second line in the file)
theirUsername = input("What is your username") #gets username input
theirPassword = input("What is your password") #get password input
while theirUsername != username or theirPassword != password: #repeats the code inside while theirUsername is not equeal to username or theirPassword is not equal to password
print("incorrect") #notifies them of being wrong
theirUsername = input("What is your username") #gets new username input
theirPassword = input("What is your password") #gets new password input
print("correct") #tells them they are corrected after the looping is done and the password and username are correct

Python User Registration

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.

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

Categories

Resources