How to write log in Python?

Writing a Login System in Python: A Step-by-Step Guide

Introduction

Writing a login system in Python can be a challenging task, but with the right approach, it can be achieved efficiently. In this article, we will guide you through the process of writing a basic login system in Python, covering the essential components and best practices.

Step 1: Setting Up the Project

Before we begin, let’s set up our project. We will create a new Python file called login_system.py and add the following code to get us started:

# login_system.py

import tkinter as tk
from tkinter import messagebox

class LoginSystem:
def __init__(self):
self.root = tk.Tk()
self.root.title("Login System")
self.label = tk.Label(self.root, text="Login System")
self.label.pack()
self.entry = tk.Entry(self.root)
self.entry.pack()
self.button = tk.Button(self.root, text="Login", command=self.login)
self.button.pack()

def login(self):
username = self.entry.get()
password = self.entry.get("1.0", "end-1c")
if username == "admin" and password == "password":
messagebox.showinfo("Login Success", "Welcome, admin!")
else:
messagebox.showerror("Login Failed", "Invalid username or password")

def run(self):
self.root.mainloop()

if __name__ == "__main__":
login_system = LoginSystem()
login_system.run()

This code creates a simple login system with a GUI using Tkinter. The LoginSystem class has an __init__ method to set up the GUI, an entry field for the username, and a button to trigger the login process. The login method retrieves the username and password from the entry field and checks if they match the hardcoded credentials. If the credentials are valid, it shows a success message; otherwise, it shows an error message.

Step 2: Handling User Input

To handle user input, we need to add some error checking and validation. We can use the get method to retrieve the username and password from the entry field. However, this method returns a string, so we need to convert it to a list of strings using the split method:

# login_system.py

import tkinter as tk
from tkinter import messagebox

class LoginSystem:
def __init__(self):
self.root = tk.Tk()
self.root.title("Login System")
self.label = tk.Label(self.root, text="Login System")
self.label.pack()
self.entry = tk.Entry(self.root)
self.entry.pack()
self.button = tk.Button(self.root, text="Login", command=self.login)
self.button.pack()

def login(self):
username = self.entry.get().split()
if len(username) != 2:
messagebox.showerror("Invalid Input", "Please enter a username and password")
return
username = username[0]
password = username + "123"
if username == "admin" and password == "password":
messagebox.showinfo("Login Success", "Welcome, admin!")
else:
messagebox.showerror("Login Failed", "Invalid username or password")

def run(self):
self.root.mainloop()

if __name__ == "__main__":
login_system = LoginSystem()
login_system.run()

This code adds some error checking and validation to the login method. It checks if the username is a string with exactly two elements; if not, it shows an error message. It also checks if the password is a string with exactly two elements; if not, it shows an error message.

Step 3: Storing User Credentials

To store user credentials securely, we can use a database or a file. For this example, we will use a simple file to store the credentials. We can create a new file called credentials.txt and add the following code:

# credentials.txt

username = "admin"
password = "password"

def load_credentials():
try:
with open("credentials.txt", "r") as f:
return f.read().splitlines()
except FileNotFoundError:
return []

def save_credentials():
with open("credentials.txt", "w") as f:
for username, password in load_credentials():
f.write(f"{username}:{password}n")

def login():
username = input("Enter username: ")
password = input("Enter password: ")
credentials = load_credentials()
if username in credentials and credentials[username] == password:
messagebox.showinfo("Login Success", "Welcome, admin!")
else:
messagebox.showerror("Login Failed", "Invalid username or password")

def main():
while True:
print("1. Login")
print("2. Exit")
choice = input("Enter your choice: ")
if choice == "1":
login()
elif choice == "2":
break
else:
messagebox.showerror("Invalid Input", "Please enter a valid choice")

if __name__ == "__main__":
main()

This code creates a simple login system with a GUI using Tkinter. The load_credentials function loads the credentials from the credentials.txt file; the save_credentials function saves the credentials to the credentials.txt file; the login function checks if the username and password match the hardcoded credentials; and the main function provides a simple menu-based interface.

Step 4: Implementing a Secure Login System

To implement a secure login system, we need to add some additional security measures. We can use a password hashing algorithm like bcrypt to store the password securely. We can also use a salt to add an extra layer of security.

Here is an updated version of the code that implements a secure login system:

# login_system.py

import tkinter as tk
from tkinter import messagebox
import bcrypt

class LoginSystem:
def __init__(self):
self.root = tk.Tk()
self.root.title("Login System")
self.label = tk.Label(self.root, text="Login System")
self.label.pack()
self.entry = tk.Entry(self.root)
self.entry.pack()
self.button = tk.Button(self.root, text="Login", command=self.login)
self.button.pack()

def login(self):
username = self.entry.get().split()
if len(username) != 2:
messagebox.showerror("Invalid Input", "Please enter a username and password")
return
username = username[0]
password = username + "123"
hashed_password = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt())
if username == "admin" and hashed_password == "password":
messagebox.showinfo("Login Success", "Welcome, admin!")
else:
messagebox.showerror("Login Failed", "Invalid username or password")

def run(self):
self.root.mainloop()

if __name__ == "__main__":
login_system = LoginSystem()
login_system.run()

This code uses the bcrypt library to hash the password securely. The bcrypt.hashpw function takes the password and a salt as input and returns the hashed password. The bcrypt.gensalt function generates a random salt for the password.

Conclusion

Writing a login system in Python can be a challenging task, but with the right approach, it can be achieved efficiently. In this article, we have covered the essential components of a login system, including setting up the project, handling user input, storing user credentials, and implementing a secure login system. We have also provided an updated version of the code that uses a password hashing algorithm to store the password securely.

Unlock the Future: Watch Our Essential Tech Videos!


Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top