Ethan Mort
Ethan Mort

Reputation: 1

Why is this simple authentication not working

Ok, so I have this code that I have written:

Authorised = False
while not Authorised:
    useri = input("Enter your username: ")
    passi = input("Enter your password: ")
    users = open("Users.txt", "r")
    EndOfFile = False
    while not EndOfFile:
        userr = ""
        passr = ""
        line = users.readline()
        if line == "":
            EndOfFile = True
            continue
        splitlines = line.split(",")
        userr = splitlines[0]
        passr = splitlines[1]
        if useri == userr:
            if passi == passr:
                username = userr
                EndOfFile = True
                Authorised = True
                users.close()
            else:
                print("Wrong Password")
                EndOfFile = True
                users.close()
    if userr == "":
        print("Invalid username")

Users.txt:

A,B,
B,A,

For some reason when I run it it says that the password is wrong. I’m not sure why. If anybody could explain this to me it would be greatly appreciated.

Thanks

Upvotes: 0

Views: 41

Answers (2)

thekid77777
thekid77777

Reputation: 391

Sorry haha I had already re written your code when I posted the comment, got up to get a coffee and got talking, but your going to get the post. Anyway, here's a few tips.

  • You read the passwords in every loop, you don't need to do this.
  • You can break your while loop much cleaner
  • You have things that execute inside both the if and else sections of a selection, i.e. users.close()
  • In python it's easier to use a context manager to handle file i/o.

Take a look at something like this:

with open('Users.txt', 'r') as pass_file:
    users = {}
    lines = [line.replace("\n", "") for line in pass_file.readlines()]
    for line in lines:
        split_line = line.split(',')
        users[split_line[0]] = split_line[1]

while True:
    useri = input("Enter your username: ")
    passi = input("Enter your password: ")
        
    if useri in users:
        if users[useri] == passi:
            print('Valid User')
            break
        else:
            print('Invadlid Login')
    else:
        print('Invalid Login')

This way you can build an initial dict objects with all your users and then just check that.

Upvotes: 1

Ethan Mort
Ethan Mort

Reputation: 1

Weird transferring error. I had Users.txt stored on onedrive, took it off onedrive, onto my iPad and was using Pythonista as the IDE. I’m not sure exactly what happened.

Upvotes: 0

Related Questions