Introduction
This tutorial covers how to create a simple login and registration system using Python. The system allows users to register with a username and password, and then log in using those credentials. Basic Authentication is implemented using simple file handling to store user data.
Objective
The objective of this program is to teach you how to implement a basic authentication system with a user-friendly interface using Python. The application will feature:
- User registration (username and password).
- Login functionality to verify credentials.
- Storing user data securely using Python file handling.
Code
# Basic Authentication System in Python import os # Function to register new user def register_user(): username = input("Enter username: ") password = input("Enter password: ") # Check if the user file exists if os.path.exists(f"{username}.txt"): print("Username already taken. Please choose another one.") else: # Create a new user file and save the password with open(f"{username}.txt", "w") as file: file.write(password) print("Registration successful!") # Function to log in with an existing user def login_user(): username = input("Enter username: ") password = input("Enter password: ") # Check if the user file exists if os.path.exists(f"{username}.txt"): with open(f"{username}.txt", "r") as file: stored_password = file.read() if stored_password == password: print("Login successful!") else: print("Incorrect password. Try again.") else: print("Username not found. Please register first.") # Main function def main(): print("Welcome to the Basic Authentication System!") while True: choice = input("\nEnter '1' for Register or '2' for Login or 'q' to Quit: ") if choice == '1': register_user() elif choice == '2': login_user() elif choice == 'q': print("Goodbye!") break else: print("Invalid option, please try again.") # Run the main function if __name__ == "__main__": main()
Program Structure and Explanation
The program consists of three main functions:
- register_user(): This function allows users to register by providing a username and password. It checks if the username is already taken, and if not, stores the password in a file named after the username.
- login_user(): This function allows users to log in by providing their username and password. It checks if the username exists, and if it does, compares the entered password with the stored password in the file.
- main(): The main loop of the program, where users can choose to register, log in, or quit. It continues running until the user chooses to quit by entering ‘q’.
How to Run the Program
To run this program:
-
- Ensure that Python is installed on your system.
- Save the code into a Python file, for example,
auth_system.py
. - Open a terminal or command prompt, navigate to the directory where the file is located, and run the program using the following command:
python auth_system.py
- Follow the prompts to register and log in.