Python Forum
Login and register code - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Login and register code (/thread-13356.html)



Login and register code - Ameldan5 - Oct-11-2018

I have to make code that lets you create an account or log in and it must save the accounts to a text file, I have done the create account but its very badly done and don't have a clue how to do the login as I don't understand read files, thank you for any help




(Login code I wrote)
def reg():
    uname=input("Please a username: ")
    pword=input("Please a a passwrd: ")
    f = open("UNPW.txt", "a")
    f.write("\nUsername:"+uname)
    f.write("\nPasswod:"+pword)
    f.write("\n----------------------------")



RE: Login and register code - gruntfutuk - Oct-13-2018

Firstly, here's your definition of ref with a minor correct to the text your write to file (you mistyped Password):

def reg():
    uname = input("Please enter a username: ")
    pword = input("Please enter a password: ")
    with open("UNPW.txt", "a") as f:
        f.write("\nUsername:"+uname)
        f.write("\nPassword:"+pword)
The with open() saves you having to remember to close a file. Otherwise it is the same as you had.

Here's a new example function called login that returns True if it finds a matching username and password in the file. Otherwise, it returns False.

def login():
    uname = input("Please enter your username: ").lower()
    pword = input("Please enter your password: ")
    found = False
    with open("UNPW.txt", "r") as f:
        for line in f:
            if line.strip().startswith('Username:'):
                if line.strip().lower().endswith(uname):
                    line = next(f)
                    if line.strip().startswith('Password:'):
                        if line.strip().endswith(pword):
                            found = True
                    break
    return found
So, you use a for loop to read a line at a time from the file. The strip() modifies the string in the expression to ignore leading and trailing whitespace characters. next(f) reads the next line in the file before the next iteration of the for loop. We are assuming that the User line is followed by a Password line.

To test it, firstly, lets called reg() three times to add some usernames and passwords. Then lets see if we can find a match.

reg()
reg()
reg()
security_passed = login()
print(security_passed)
You have more work to do including adding some more error checking, allowing more than one attempt at login perhaps, disguising the passwords rather than saving them as plain text (look up hashing of passwords).