Search code examples
pythonpython-3.xlogin-script

Simple login script multiple users from file


I have problem with my login script in Python 3.5.2.

The problem with my code is that only first user in file users.txt can pass login. Second and third users get "Wrong username/password" message. What am I missing here ?

Data in users.txt are formated like this:

Name|Surname|Role|ID|Username|Password

John|Johnson|Director|1|admin|admin

Mike|Madson|CFO|2|mike|mike

Problem is only John pass login and I need Mike as well.

def check():

    username = str(input("Username: "))
    password = str(input("Password: "))

    f = open("users.txt", "r")
    file_content = f.read()
    users = file_content.split("\n")
    for user in users:
        user_array = user.split("|")
        uname = user_array[4]
        pword = user_array[5]
        if uname == username and pword == password:
            print("Hello " + user_array[1] + ".")
            print("You are logged in as: " + user_array[2] + ".")
            main_menu()
        else:
            print("Wrong username/password.")
            print("Try again!\n\n")
            check()
check()

Thanks for help!


Solution

  • The logic was all wrong. You need something like that:

    def check():
        # You need to read it only once, not every loop
        users = open("users.txt").read().split("\n")
        for i in range(len(users)): users[i] = users[i].split("|")
    
        # Now what you want is to loop infinitely
        # until you get correct username/password
        # instead of recursive calling this
        # function over and over again
        while True:
            username = str(input("Username: "))
            password = str(input("Password: "))
    
            for user in users:
                uname = user[4]
                pword = user[5]
    
                if uname == username and pword == password:
                    print("Hello " + user[1] + ".")
                    print("You are logged in as: " + user[2] + ".")
                    main_menu()
    
            # If none of the records matched the input
            print("Wrong username/password.")
            print("Try again!\n\n")
    
    check()