How to create a login system in python using a text file

A basic part of programming is learning to break things down to pieces, then breaking the problem down into even smaller pieces, until you have something that you can solve. Eventually you get good enough, and experienced enough, that you see the pieces immediately.

You already have the first level breakdown shown above. You just need to break each of the steps into something that can be done. So your high level code is something like this:

def main():
    username, password = get_name_and_password()
    registered_users = read_pwdfile('pwd_filename')
    if usr_pass_registered(username, password, registered_users):
        registered = True
    else:
        registered = get_registration(username, password, 'pwd_filename')
    if registered:
        run_quiz(username)

Now you have four sub-problems that can be tackled independently. They can also be tested independently so that you can join them back together with confidence.

get_name_and_password() you indicate you have already written code for. Move it into a subroutine and at the end return a tuple of the two values entered.

read_pwd(filename) will need to open the file with the given name, read its contents into a data structure, close the file, and return the data structure. What structure to use for your data is another part of learning to program. Here I would suggest that you create an empty list and for each line read from the file append a tuple of (user, pwd) to the list. You will want to take care of the case where the file doesn't exist, so you will need to learn to code a try: ... except FileNotFoundError: code block.

usr_pass_registered(username, password, registered_users) will iterate over the list of registered users and, if they are found, will return True. This will give you experience in writing a for loop that will iterate over the registered_users data structure. You will also have to code a break in the loop when you have found the user (since there is no point in continuing to look through the rest of the file).

get_registration(username, password, 'pwd_filename') will ask for any further information needed to create an account, open the user and password file and append the information. Check the documentation on the built-in function open() for how to open the file so you can write at the end. Return True if they registered successfully or False if they chose not to register. You can either ask a question like 'Do you want to register?' or you can assume that they didn't want to register if they hit return to all your additional questions.

This seems like a good challenge for a beginning Python programmer. You will get to use a variety of code and data structures, you will learn to debug your program, and you will learn to use Python's documentation.

Photo by Chris Ried on Unsplash

This article will guide you through how to build a very basic CLI login system with python.

Concept

The program will accept the user’s email and password, hash the password, store it into a text file with the email, and complete the registration process.

In the login process, the program again will accept the user’s email and password, hash the password, verify it with the email and the password hash stored in the text file previously, print a success message confirming the email and the password entered is correct or print a failure message if email and password are incorrect.

Prerequisites

You should have installed python version 3.0 or above to use the built-in package hashlib.

Tutorial

First, we will import the integrated hashlib package required for our login system.

import hashlib

Then we will define the function signup( ), which will accept the user’s email and password and ask again for the password to confirm it.

If the password and confirmation password correspond, then the function will hash the confirmation password and store it in a text file with the email, and if it doesn’t, it will print an error message.

We will encode the confirmation password with the encode( ) function to convert it from the string to byte format acceptable for hashing.

Then, we will generate an md5 hash of encoded password using the hexdigest( ) function.

def signup():
email = input(“Enter email address: “)
pwd = input(“Enter password: “)
conf_pwd = input(“Confirm password: “)
if conf_pwd == pwd:
enc = conf_pwd.encode()
hash2 = hashlib.md5(enc).hexdigest()
with open(“credentials.txt”, “w”) as f:
f.write(email + “\n”)
f.write(hash2)
f.close()
print(“You have registered successfully!”)
else:
print(“Password is not same as above! \n”)

Now we will define our second function login( ), which will accept the user’s email and password, hash the entered password and verify it with the password hash stored in the text file along with the email.

If the entered email and password hash correspond with the one in the text file, then the function will print a success message, and if it doesn’t, it will print a failure message.

def login():
email = input(“Enter email: “)
pwd = input(“Enter password: “)
auth = pwd.encode()
auth_hash = hashlib.md5(auth).hexdigest()
with open(“credentials.txt”, “r”) as f:
stored_email, stored_pwd = f.read().split(“\n”)
f.close()
if email == stored_email and auth_hash == stored_pwd:
print(“Logged in Successfully!”)
else:
print(“Login failed! \n”)

Now we will combine the two functions and make a menu-driven program with an infinite while loop allowing users to choose to sign up, log in, and exit.

On exit, the loop will break and will terminate the program.

import hashlib
def signup():
email = input(“Enter email address: “)
pwd = input(“Enter password: “)
conf_pwd = input(“Confirm password: “)
if conf_pwd == pwd:
enc = conf_pwd.encode()
hash2 = hashlib.md5(enc).hexdigest()
with open(“credentials.txt”, “w”) as f:
f.write(email + “\n”)
f.write(hash2)
f.close()
print(“You have registered successfully!”)
else:
print(“Password is not same as above! \n”)
def login():
email = input(“Enter email: “)
pwd = input(“Enter password: “)
auth = pwd.encode()
auth_hash = hashlib.md5(auth).hexdigest()
with open(“credentials.txt”, “r”) as f:
stored_email, stored_pwd = f.read().split(“\n”)
f.close()
if email == stored_email and auth_hash == stored_pwd:
print(“Logged in Successfully!”)
else:
print(“Login failed! \n”)
while 1:
print("********** Login System **********")
print("1.Signup")
print("2.Login")
print("3.Exit")
ch = int(input("Enter your choice: "))
if ch == 1:
signup()
elif ch == 2:
login()
elif ch == 3:
break
else:
print("Wrong Choice!")

If you like this article, do leave a clap!

How do you make a login system in Python?

Learn step-by-step.
Create the main menu window..
Create the register window..
Register the user's info in a text file using Python..
Check whether the user's info already exists or not..
Create the login window and verify the user..

How do you code a username and password in Python?

Get User Name And Password At Runtime Using Python.
pip install getpass. Python. Copy..
userName = getpass. getuser() Python. Copy..
userName= input('Enter user name: ') Python. Copy..
password = getpass. getpass() Python. Copy..

How do I automatically login to a website using Python?

We will be using Selenium (python library) for making the auto-login bot..
First of all import the webdrivers from the selenium library..
Find the URL of the login page to which you want to logged in..
Provide the location executable chrome driver to selenium webdriver to access the chrome browser..