Need help with my code

**My code was working fine, but I broke it when adding a conditional statement to add a user “admin” to my (existing user) login subroutine.
My plan is to have an admin log in as Existing User, then once it inputs username & password (admin and admin01), it goes through a series of menu to choose from, like being able to access the whole database and view and delete other users.

I’ve been scratching my head if i should incorporate the condition in the main menu, or make a new subroutine, or just chuck it in the existing user login. Need a fresh set of eyes. Pardon my repl - its a chaos.

Repl link: https://replit.com/@QBrd1/ProjectLoginWithHash#main.py

def login():
  print("Loading...")
  time.sleep(2)
  os.system("clear")
  print("Existing user login")
  username=input("Username: ").strip().capitalize() 
  password=input("Password: ").strip()
  adminName="admin"
  adminPassword="admin01"
  keys=db.keys()
  if username not in keys:
    print("\033[34mIt appears the username is not found on our records. Please register for a new account\033[0m")
    return  #----------missing loop bk to menu
  salt=db[username] ["salt"]
  SaltedPassword=f"{password}{salt}"
  HashedSaltedPassword=hash(SaltedPassword) 
   if db[username]["password"]==HashedSaltedPassword:
      print("Login successful") 

    if #i need to insert a conditional statement here for admin

Based on your description, I would suggest incorporating the admin check within the existing user login subroutine.

Or something like this:

import os
import time

# Sample database dictionary to simulate user data
db = {
    "admin": {
        "password": "4dmin01",  # This should be the hashed password for 'admin01'
        "salt": "somesalt"
    }
}

def admin_menu():
    while True:
        os.system("clear")
        print("Admin menu:")
        print("1. Access the whole database")
        print("2. View users")
        print("3. Delete user")
        print("4. Logout")

        choice = input("Please enter your choice: ").strip()
        if choice == "1":
            print(db)
            input("Press enter to continue...")
        elif choice == "2":
            print("Users:")
            for user in db.keys():
                print(user)
            input("Press enter to continue...")
        elif choice == "3":
            user_to_delete = input("Enter the username to delete: ").strip().capitalize()
            if user_to_delete in db.keys():
                del db[user_to_delete]
                print(f"User '{user_to_delete}' has been deleted.")
            else:
                print("User not found.")
            input("Press enter to continue...")
        elif choice == "4":
            print("Logging out...")
            break
        else:
            print("Invalid choice. Please try again.")
            input("Press enter to continue...")

def login():
    print("Loading...")
    time.sleep(2)
    os.system("clear")
    print("Existing user login")
    username = input("Username: ").strip().capitalize()
    password = input("Password: ").strip()
    adminName = "admin"
    adminPassword = "admin01"
    keys = db.keys()

    if username not in keys:
        print("\033[34mIt appears the username is not found on our records. Please register for a new account\033[0m")
        return  # ----------missing loop bk to menu

    salt = db[username]["salt"]
    SaltedPassword = f"{password}{salt}"
    HashedSaltedPassword = hash(SaltedPassword)

    if db[username]["password"] == HashedSaltedPassword:
        print("Login successful")
        if username.lower() == adminName and password == adminPassword:
            admin_menu()
    else:
        print("Invalid credentials")

# Call the login function for testing
login()

Remember to replace the sample db dictionary with your actual user database.

4 Likes

Truly appreciate it! Been stuck for more than 6 hours on it. You made this look so easy! Thanks heaps!

1 Like

By any chance, will you be able to point me on the right direction again?
The admin password is not hashing. Although have found another key that is being hashed (which is odd).
Its most likely the placement of the db for admin or my logic for the hashing. What am i doing wrong?

Lines 37-65: https://replit.com/@QBrd1/test#main.py

def login():
    print("Loading...")
    time.sleep(2)
    os.system("clear")
    print("Existing user login")
    username = input("Username: ").strip().capitalize()
    password = input("Password: ").strip()
    adminName = "admin"
    adminPassword = "admin01"
    keys = db.keys()

    if username not in keys:
        print(f"{redColorBegin} It appears the username is not found on our records. Please register for a new account {redColorEnd}")
        return # ----------missing loop bk to menu

    salt = db[username]["salt"]
    SaltedPassword = f"{password}{salt}"
    HashedSaltedPassword = hash(SaltedPassword)

    AdminSalt=random.randint(1777,9999) #random admin salt
    AdminSaltedPassword = f"{adminPassword}{AdminSalt}" #userpassword + random salt 
    AdminHashedSaltedPassword=hash(AdminSaltedPassword)

    #db = {"admin": {"password": AdminHashedSaltedPassword, "salt": AdminSalt}}
 
    if db[username]["password"] == HashedSaltedPassword:
        print("Login successful")
        if username.lower() == adminName and password == AdminHashedSaltedPassword:
            adminMenu()

You are generating a new random salt for the admin password every time you run the login function, that makes it impossible to match the hashed password.

Store the admin salt and hashed password in the db dictionary beforehand, just like you would for any other user

It should go like this:

import os
import time
import random

# Your hash function should be defined here

# Sample database dictionary to simulate user data
db = {
    "admin": {
        "password": "4dmin01",  # This should be the hashed password for 'admin01'
        "salt": "somesalt"
    }
}

# ... (your other functions and code)

def login():
    print("Loading...")
    time.sleep(2)
    os.system("clear")
    print("Existing user login")
    username = input("Username: ").strip().capitalize()
    password = input("Password: ").strip()
    adminName = "admin"
    adminPassword = "admin01"
    keys = db.keys()

    if username not in keys:
        print(f"{redColorBegin} It appears the username is not found on our records. Please register for a new account {redColorEnd}")
        return # ----------missing loop bk to menu

    salt = db[username]["salt"]
    SaltedPassword = f"{password}{salt}"
    HashedSaltedPassword = hash(SaltedPassword)

    if db[username]["password"] == HashedSaltedPassword:
        print("Login successful")
        if username.lower() == adminName and password == adminPassword:
            adminMenu()

Also, I removed the admin salt and hashed password creation from the login function, as it should be handled when creating the admin account in the first place, not during the login process.

1 Like

Now, i get it. Wishing i get to be at the same level of expertise as you are in. A big thank you!! All the best!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.