Guest User

Untitled

a guest
Dec 18th, 2025
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.61 KB | None | 0 0
  1. import secrets
  2. import string
  3. import json
  4. import time
  5. from datetime import datetime
  6.  
  7. now = datetime.now()
  8. """Password generation"""
  9. class PasswordGenerator:
  10.     def __init__(self):
  11.         self.password_dict = {
  12.  
  13.         }
  14.         self.filename = 'password_login.json'
  15.         self.deleted_logins = []
  16.  
  17.     def create_password(self, login, length=8):
  18.         """Creating a password and saving it to a dictionary"""
  19.         if login in self.password_dict:
  20.             print(f"Login: {login} is already in password list.\nTake another login.")
  21.         alphabet = string.ascii_letters + string.digits + string.punctuation
  22.         password = ''.join(secrets.choice(alphabet) for _ in range(length))
  23.         while True:
  24.             if self.validate_password(password) == True:
  25.                 self.password_dict[login] = password
  26.                 print(f"Login: {login} | Password: {password} saved!")
  27.                 break
  28.             elif self.validate_password(password) == False:
  29.                 print(f"Login: {login} | Password: {password} not saved!")
  30.                 print("Try again!")
  31.                 continue
  32.  
  33.     def validate_password(self, password):
  34.         if len(password) < 8:
  35.             print("Password must be at least 8 characters long.")
  36.             return False
  37.         if not any(char.isdigit() for char in password):
  38.             print("Password must contain at least one digit.")
  39.             return False
  40.         if not any(char.isalpha() for char in password):
  41.             print("Password must contain at least one letter.")
  42.             return False
  43.         if not any(char in string.punctuation for char in password):
  44.             print("Password must contain at least one special character.")
  45.             return False
  46.         print("Password is valid.")
  47.         return True
  48.  
  49.     def delete_password(self, user_login):
  50.         """Deleting a password by login"""
  51.         if user_login in self.password_dict.keys():
  52.                 print(f"Are you sure you want to delete: Login: {user_login}"
  53.                       f" | Password: {self.password_dict[user_login]}?")
  54.                 user_answer = input("Enter y/n: ")
  55.                 if user_answer == 'y':
  56.                     deleted_login = self.password_dict.pop(user_login)
  57.                     print(f"Deleted Login: {deleted_login}")
  58.                 elif user_answer == 'n':
  59.                     print(f"Ok we dont delete a {user_login} login!")
  60.                 else:
  61.                     print("Invalid input. Enter y/n")
  62.         else:
  63.             print(f"Login: {user_login} not found!")
  64.  
  65.     def save_password_login_json(self):
  66.         """Saving the password dictionary to a JSON file"""
  67.         with open(self.filename, 'w') as f:
  68.             json.dump(self.password_dict, f, indent=4)
  69.         print("Password and login saved!")
  70.  
  71.     def show_all(self):
  72.         """Show the password dictionary"""
  73.         print("Here is all logins with passwords.")
  74.         for login, password in self.password_dict.items():
  75.             i = '*'
  76.             result = 0
  77.             for _ in password:
  78.                 result += 1
  79.             i *= result
  80.             print(f"\t-- Login: {login} | Password: {password.replace(str(password), str(i))}")
  81.  
  82. class Admin(PasswordGenerator):
  83.     """Class for admins"""
  84.     ADMIN_PASSWORD = 'Hello_World!'
  85.     def __init__(self):
  86.         super().__init__()
  87.         self.login_attempts = 0
  88.  
  89.  
  90.     def open_admin_console(self, password_admina, filename_3='login_attempts.txt'):
  91.         try:
  92.             with open(filename_3, 'r') as f:
  93.                 self.login_attempts = json.load(f)
  94.         except FileNotFoundError:
  95.             with open(filename_3, 'w') as f:
  96.                 json.dump(self.login_attempts, f, indent=4)
  97.         if self.login_attempts >= 3:
  98.             print("Your admin console is blocked, please contact your manager."
  99.                   "\n\tBy mail >> ([email protected])\n\tBy mobile phone >> (+4901541077327)")
  100.             raise RuntimeError("Admin account is blocked")
  101.         if password_admina == self.ADMIN_PASSWORD:
  102.                     while True:
  103.                         print(f"Time: {now.hour}:{now.minute}")
  104.                         print(f"Date: {now}")
  105.                         print("Hello, Admin here is your console!")
  106.                         print("""
  107. 1 -- show all passwords
  108. 2 -- how many sessions
  109. 3 -- delete a login
  110. 4 -- back to user meny
  111.                        """)
  112.                         user_choice = int(input("Enter your choice: "))
  113.                         if user_choice == 1:
  114.                             self.show_all(password_admina)
  115.                         elif user_choice == 2:
  116.                             print(f"This is {session + 1} session | All sessions {session}.")
  117.                         elif user_choice == 3:
  118.                             user_login = input("Enter your login: ")
  119.                             if user_login in self.password_dict.keys():
  120.                                 deleted_password = self.password_dict.pop(user_login)
  121.                                 print(f"Deleted Login: {user_login} | Password: {deleted_password}")
  122.                             else:
  123.                                 print(f"Login: {user_login} not found!")
  124.                         elif user_choice == 4:
  125.                             print("Thank you for using Admin Console!")
  126.                             break
  127.                         else:
  128.                             print("Invalid input.")
  129.                             continue
  130.         elif password_admina != self.ADMIN_PASSWORD:
  131.             print(f"Incorrect admin password."
  132.                   f"\n\tBe careful, after 3 attempts your account will be blocked. "
  133.                   f"Number of attempts: {self.login_attempts} it was {self.login_attempts + 1} attempt!!!")
  134.             self.login_attempts += 1
  135.             with open(filename_3, 'w') as f:
  136.                 json.dump(self.login_attempts, f, indent=4)
  137.  
  138.     def show_all(self, password_admina):
  139.         if password_admina == self.env:
  140.             for login, password in self.password_dict.items():
  141.                 print(f"\t-- Login: {login} | Password: {password}")
  142.         else:
  143.             print("You cant see passwords. You are not admin!")
  144.  
  145.  
  146.  
  147. print(f"Date: {now.year}-{now.month}-{now.day} | Time: {now.hour}:{now.minute}")
  148. print("Hello to password generator!")
  149. # object of the class PasswordGenerator()
  150. user = PasswordGenerator()
  151. admin = Admin()
  152. # Loading files from JSON into Python to allow adding new passwords
  153. try:
  154.     with open(user.filename, 'r') as f:
  155.         user.password_dict = json.load(f)
  156. except FileNotFoundError:
  157.     print(f"The file {user.filename} does not exist.")
  158.  
  159. """Recording and exporting the number of sessions"""
  160. session = 0
  161. try:
  162.     with open('session.json', "r") as f:
  163.         session = json.load(f)
  164. except OSError:
  165.     with open('session.json', 'w') as f:
  166.         json.dump(session, f)
  167. admin.password_dict = user.password_dict
  168. # Console menu
  169. while True:
  170.     time_start = time.time()
  171.     print(f"Time: {now.hour}:{now.minute}")
  172.     print("Here is all options:")
  173.     print("""
  174. 1 — Create a password
  175. 2 — Show passwords
  176. 3 — Save the password
  177. 4 — Delete the password by login
  178. 5 — Admin console (only if you are an admin!!!)
  179. 6 — Exit
  180. """)
  181.     try:
  182.         user_choice = int(input("Enter your choice: "))
  183.     except ValueError:
  184.         print("Please enter a number.")
  185.         continue
  186.     if user_choice not in [1, 2, 3, 4, 5, 6]:
  187.         print("Invalid choice. Please try again.")
  188.         continue
  189.     if user_choice == 1:
  190.         login = input("Enter your login: ")
  191.         user_answer = input("Do you want to give me a length of your password "
  192.                             "or i make 8-chars password? (y/n): ")
  193.         if user_answer == 'y':
  194.             try:
  195.                 user_length_password = int(input("How long would you like your password to be: "))
  196.                 user.create_password(login, user_length_password)
  197.             except ValueError:
  198.                 print("Please enter a number.")
  199.                 continue
  200.         elif user_answer == 'n':
  201.             print("I generate a 8-chars password!")
  202.             user.create_password(login)
  203.         else:
  204.             print("Please enter y or n.")
  205.             continue
  206.     elif user_choice == 2:
  207.         if not user.password_dict:
  208.             print("List is empty! Create a password first!")
  209.         else:
  210.             user.show_all()
  211.     elif user_choice == 3:
  212.         if not user.password_dict:
  213.             print("Password is empty! Create a password first!")
  214.         else:
  215.             user.save_password_login_json()
  216.     elif user_choice == 4:
  217.         user_login = input("Enter your login: ")
  218.         user.delete_password(user_login)
  219.     elif user_choice == 5:
  220.         user_login = input("Enter the administrator password: ")
  221.         print("Authentication...")
  222.         time.sleep(5)
  223.         print("Authentication can take a 1-2 minute long. Thank you for waiting.")
  224.         time.sleep(5)
  225.         print("another 5 seconds and it's ready")
  226.         time.sleep(5)
  227.         admin.open_admin_console(user_login)
  228.     elif user_choice == 6:
  229.         try:
  230.             with open(user.filename, 'w') as f:
  231.                 json.dump(user.password_dict, f, indent=4)
  232.         except FileNotFoundError:
  233.             print(f"The file {user.filename} does not exist.")
  234.         session += 1
  235.         with open('session.json', 'w') as f:
  236.             json.dump(session, f)
  237.         print("Thank you! See you next time!")
  238.         break
  239. time_end = time.time()
  240. print(f"This was your {session + 1} session!")
  241. print(f"Current session time was: {time_end - time_start}")
Advertisement
Add Comment
Please, Sign In to add comment