Building a Secure User Authentication System with Python and MariaDB
Building a Secure User Authentication System with Python and MariaDB
Introduction
In today's digital landscape, user authentication is a critical aspect of any application or website to ensure the security and privacy of user data. In this blog post, we will walk through the process of creating a secure user authentication system using Python and MariaDB. Python, a powerful and versatile programming language, will handle the backend logic, while MariaDB, a popular open-source relational database, will store user information securely. By the end of this tutorial, you'll have a fully functional authentication system ready to be integrated into your web applications.
Prerequisites
Before getting started, ensure that you have Python and MariaDB installed on your machine. Additionally, we'll use the mysql-connector-python
library to communicate with the MariaDB database. Make sure to install it by running the following command:
pip install mysql-connector-python
Step 1: Setting Up the Database
Let's begin by creating a new database in MariaDB to store user information. You can use the following SQL commands to set up the user_auth
database and the users
table:
CREATE DATABASE user_auth;
USE user_auth;
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL
);
Step 2: Python Implementation
Now, let's build the Python backend that will handle user registration, authentication, and other related operations.
import mysql.connector
import hashlib
# Function to create a new user
def create_user(username, password):
# Establish a connection to the MariaDB database
connection = mysql.connector.connect(
host="localhost",
user="your_mysql_username", # Replace with your MariaDB username
password="your_mysql_password", # Replace with your MariaDB password
database="user_auth"
)
cursor = connection.cursor()
# Hash the password before storing it
password_hash = hashlib.sha256(password.encode()).hexdigest()
try:
# Insert user data into the 'users' table
cursor.execute("INSERT INTO users (username, password_hash) VALUES (%s, %s)", (username, password_hash))
connection.commit()
print("Registration successful!")
except mysql.connector.IntegrityError:
print("Username already exists. Please choose a different username.")
finally:
connection.close()
# Function to authenticate a user
def authenticate_user(username, password):
# Establish a connection to the MariaDB database
connection = mysql.connector.connect(
host="localhost",
user="your_mysql_username", # Replace with your MariaDB username
password="your_mysql_password", # Replace with your MariaDB password
database="user_auth"
)
cursor = connection.cursor()
# Hash the password to match the stored hash
password_hash = hashlib.sha256(password.encode()).hexdigest()
cursor.execute("SELECT * FROM users WHERE username = %s AND password_hash = %s", (username, password_hash))
user = cursor.fetchone()
connection.close()
if user:
return True
else:
return False
# Other functions for change password and user deletion can be added here
# User Interface
def user_interface():
while True:
print("Welcome to the CyberSec Authentication System!")
print("1. Register")
print("2. Login")
print("3. Logout")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == "1":
username = input("Enter a username: ")
password = input("Enter a password: ")
create_user(username, password)
elif choice == "2":
username = input("Enter your username: ")
password = input("Enter your password: ")
if authenticate_user(username, password):
print("Login successful!")
else:
print("Invalid username or password. Please try again.")
elif choice == "3":
print("Logout successful!")
elif choice == "4":
print("Goodbye!")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
user_interface()
Conclusion
Congratulations! You've successfully built a user authentication system using Python and MariaDB. This system allows users to register, log in, and log out securely. By leveraging the power of Python and MariaDB, you can now integrate this authentication system into your web applications to enhance security and protect user data. Remember to handle user inputs with care, use prepared statements to prevent SQL injection attacks, and employ other security best practices to fortify your application further.
In this blog post, we covered the essential steps to create a user authentication system from scratch. However, please note that this example serves for educational purposes and might require further refinement to meet the security demands of a production environment. Always prioritize security and consider consulting security experts to ensure your application is robust against potential threats.
Now you have a valuable tool to strengthen the security of your web applications!