Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import secrets
- import string
- import json
- import time
- from datetime import datetime
- now = datetime.now()
- """Password generation"""
- class PasswordGenerator:
- def __init__(self):
- self.password_dict = {
- }
- self.filename = 'password_login.json'
- self.deleted_logins = []
- def create_password(self, login, length=8):
- """Creating a password and saving it to a dictionary"""
- if login in self.password_dict:
- print(f"Login: {login} is already in password list.\nTake another login.")
- alphabet = string.ascii_letters + string.digits + string.punctuation
- password = ''.join(secrets.choice(alphabet) for _ in range(length))
- while True:
- if self.validate_password(password) == True:
- self.password_dict[login] = password
- print(f"Login: {login} | Password: {password} saved!")
- break
- elif self.validate_password(password) == False:
- print(f"Login: {login} | Password: {password} not saved!")
- print("Try again!")
- continue
- def validate_password(self, password):
- if len(password) < 8:
- print("Password must be at least 8 characters long.")
- return False
- if not any(char.isdigit() for char in password):
- print("Password must contain at least one digit.")
- return False
- if not any(char.isalpha() for char in password):
- print("Password must contain at least one letter.")
- return False
- if not any(char in string.punctuation for char in password):
- print("Password must contain at least one special character.")
- return False
- print("Password is valid.")
- return True
- def delete_password(self, user_login):
- """Deleting a password by login"""
- if user_login in self.password_dict.keys():
- print(f"Are you sure you want to delete: Login: {user_login}"
- f" | Password: {self.password_dict[user_login]}?")
- user_answer = input("Enter y/n: ")
- if user_answer == 'y':
- deleted_login = self.password_dict.pop(user_login)
- print(f"Deleted Login: {deleted_login}")
- elif user_answer == 'n':
- print(f"Ok we dont delete a {user_login} login!")
- else:
- print("Invalid input. Enter y/n")
- else:
- print(f"Login: {user_login} not found!")
- def save_password_login_json(self):
- """Saving the password dictionary to a JSON file"""
- with open(self.filename, 'w') as f:
- json.dump(self.password_dict, f, indent=4)
- print("Password and login saved!")
- def show_all(self):
- """Show the password dictionary"""
- print("Here is all logins with passwords.")
- for login, password in self.password_dict.items():
- i = '*'
- result = 0
- for _ in password:
- result += 1
- i *= result
- print(f"\t-- Login: {login} | Password: {password.replace(str(password), str(i))}")
- class Admin(PasswordGenerator):
- """Class for admins"""
- ADMIN_PASSWORD = 'Hello_World!'
- def __init__(self):
- super().__init__()
- self.login_attempts = 0
- def open_admin_console(self, password_admina, filename_3='login_attempts.txt'):
- try:
- with open(filename_3, 'r') as f:
- self.login_attempts = json.load(f)
- except FileNotFoundError:
- with open(filename_3, 'w') as f:
- json.dump(self.login_attempts, f, indent=4)
- if self.login_attempts >= 3:
- print("Your admin console is blocked, please contact your manager."
- "\n\tBy mail >> ([email protected])\n\tBy mobile phone >> (+4901541077327)")
- raise RuntimeError("Admin account is blocked")
- if password_admina == self.ADMIN_PASSWORD:
- while True:
- print(f"Time: {now.hour}:{now.minute}")
- print(f"Date: {now}")
- print("Hello, Admin here is your console!")
- print("""
- 1 -- show all passwords
- 2 -- how many sessions
- 3 -- delete a login
- 4 -- back to user meny
- """)
- user_choice = int(input("Enter your choice: "))
- if user_choice == 1:
- self.show_all(password_admina)
- elif user_choice == 2:
- print(f"This is {session + 1} session | All sessions {session}.")
- elif user_choice == 3:
- user_login = input("Enter your login: ")
- if user_login in self.password_dict.keys():
- deleted_password = self.password_dict.pop(user_login)
- print(f"Deleted Login: {user_login} | Password: {deleted_password}")
- else:
- print(f"Login: {user_login} not found!")
- elif user_choice == 4:
- print("Thank you for using Admin Console!")
- break
- else:
- print("Invalid input.")
- continue
- elif password_admina != self.ADMIN_PASSWORD:
- print(f"Incorrect admin password."
- f"\n\tBe careful, after 3 attempts your account will be blocked. "
- f"Number of attempts: {self.login_attempts} it was {self.login_attempts + 1} attempt!!!")
- self.login_attempts += 1
- with open(filename_3, 'w') as f:
- json.dump(self.login_attempts, f, indent=4)
- def show_all(self, password_admina):
- if password_admina == self.env:
- for login, password in self.password_dict.items():
- print(f"\t-- Login: {login} | Password: {password}")
- else:
- print("You cant see passwords. You are not admin!")
- print(f"Date: {now.year}-{now.month}-{now.day} | Time: {now.hour}:{now.minute}")
- print("Hello to password generator!")
- # object of the class PasswordGenerator()
- user = PasswordGenerator()
- admin = Admin()
- # Loading files from JSON into Python to allow adding new passwords
- try:
- with open(user.filename, 'r') as f:
- user.password_dict = json.load(f)
- except FileNotFoundError:
- print(f"The file {user.filename} does not exist.")
- """Recording and exporting the number of sessions"""
- session = 0
- try:
- with open('session.json', "r") as f:
- session = json.load(f)
- except OSError:
- with open('session.json', 'w') as f:
- json.dump(session, f)
- admin.password_dict = user.password_dict
- # Console menu
- while True:
- time_start = time.time()
- print(f"Time: {now.hour}:{now.minute}")
- print("Here is all options:")
- print("""
- 1 — Create a password
- 2 — Show passwords
- 3 — Save the password
- 4 — Delete the password by login
- 5 — Admin console (only if you are an admin!!!)
- 6 — Exit
- """)
- try:
- user_choice = int(input("Enter your choice: "))
- except ValueError:
- print("Please enter a number.")
- continue
- if user_choice not in [1, 2, 3, 4, 5, 6]:
- print("Invalid choice. Please try again.")
- continue
- if user_choice == 1:
- login = input("Enter your login: ")
- user_answer = input("Do you want to give me a length of your password "
- "or i make 8-chars password? (y/n): ")
- if user_answer == 'y':
- try:
- user_length_password = int(input("How long would you like your password to be: "))
- user.create_password(login, user_length_password)
- except ValueError:
- print("Please enter a number.")
- continue
- elif user_answer == 'n':
- print("I generate a 8-chars password!")
- user.create_password(login)
- else:
- print("Please enter y or n.")
- continue
- elif user_choice == 2:
- if not user.password_dict:
- print("List is empty! Create a password first!")
- else:
- user.show_all()
- elif user_choice == 3:
- if not user.password_dict:
- print("Password is empty! Create a password first!")
- else:
- user.save_password_login_json()
- elif user_choice == 4:
- user_login = input("Enter your login: ")
- user.delete_password(user_login)
- elif user_choice == 5:
- user_login = input("Enter the administrator password: ")
- print("Authentication...")
- time.sleep(5)
- print("Authentication can take a 1-2 minute long. Thank you for waiting.")
- time.sleep(5)
- print("another 5 seconds and it's ready")
- time.sleep(5)
- admin.open_admin_console(user_login)
- elif user_choice == 6:
- try:
- with open(user.filename, 'w') as f:
- json.dump(user.password_dict, f, indent=4)
- except FileNotFoundError:
- print(f"The file {user.filename} does not exist.")
- session += 1
- with open('session.json', 'w') as f:
- json.dump(session, f)
- print("Thank you! See you next time!")
- break
- time_end = time.time()
- print(f"This was your {session + 1} session!")
- print(f"Current session time was: {time_end - time_start}")
Advertisement
Add Comment
Please, Sign In to add comment