Discussion about this post

User's avatar
Achanandhi M's avatar

import mysql.connector

import bcrypt

# Database configuration for Docker MySQL container

config = {

'user': 'root',

'password': 'my-secret-pw', # Root password set in Docker

'host': 'localhost', # Docker container exposed on localhost

'port': 3306,

'database': 'user_database' # Database created in Docker container

}

def create_connection():

"""Establish a connection to the database and create the users table if it doesn't exist."""

try:

connection = mysql.connector.connect(**config)

cursor = connection.cursor()

# Create the users table if it doesn't exist

create_table_query = """

CREATE TABLE IF NOT EXISTS users (

id INT AUTO_INCREMENT PRIMARY KEY,

username VARCHAR(50) UNIQUE NOT NULL,

password_hash VARCHAR(255) NOT NULL

)

"""

cursor.execute(create_table_query)

connection.commit()

return connection

except mysql.connector.Error as err:

print(f"Database error: {err}")

return None

def register(username, password):

"""Register a new user with a hashed password."""

connection = create_connection()

if not connection:

return "Error: Could not connect to the database."

try:

cursor = connection.cursor()

# Check if username is already taken

cursor.execute("SELECT username FROM users WHERE username = %s", (username,))

if cursor.fetchone():

return "Error: Username already taken."

# Hash the password

password_hash = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())

# Insert the new user into the database

# print("password_hash",password_hash)

cursor.execute("INSERT INTO users (username, password_hash) VALUES (%s, %s)", (username, password_hash))

connection.commit()

return "User registered successfully."

except mysql.connector.Error as err:

print(f"Database error: {err}")

return "Error: Could not register user."

finally:

cursor.close()

connection.close()

def login(username, password):

"""Authenticate a user by verifying the provided password."""

connection = create_connection()

if not connection:

return "Error: Could not connect to the database."

try:

cursor = connection.cursor()

# Retrieve the stored password hash for the given username

cursor.execute("SELECT password_hash FROM users WHERE username = %s", (username,))

result = cursor.fetchone()

if result is None:

return "Error: Username not found."

stored_password_hash = result[0]

# Verify the provided password against the stored hash

if bcrypt.checkpw(password.encode('utf-8'), stored_password_hash.encode('utf-8')):

return "Login successful!"

else:

return "Error: Invalid password."

except mysql.connector.Error as err:

print(f"Database error: {err}")

return "Error: Could not log in."

finally:

cursor.close()

connection.close()

#print(register("new", "mypassword123"))

#print(login("new","mypassword123"))

print(register("new1","pass")) is this correct sir?

Expand full comment

No posts