0% found this document useful (0 votes)
6 views

D

This document outlines a Flask web application that manages user accounts, login sessions, and chat messages using a MySQL database and JSON files for data storage. It includes routes for creating accounts, logging in, managing chat messages, and downloading chat history. The application also implements password hashing for security and session management for user authentication.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

D

This document outlines a Flask web application that manages user accounts, login sessions, and chat messages using a MySQL database and JSON files for data storage. It includes routes for creating accounts, logging in, managing chat messages, and downloading chat history. The application also implements password hashing for security and session management for user authentication.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

from flask import Flask, request, jsonify, render_template, session

import mysql.connector
from mysql.connector import Error
import json
import os
import bcrypt

app = Flask(__name__)
app.secret_key = 'your_secret_key' # Required for session management

# Database configuration
DB_CONFIG = {
'host': 'localhost',
'database': 'p_db', # Updated database name
'user': 'root',
'password': '' # Replace with your MySQL password if set
}

USER_DATA_FILE = 'users.json'
LOGIN_DATA_FILE = 'login.json'

# Load or initialize the user data file


if not os.path.exists(USER_DATA_FILE):
with open(USER_DATA_FILE, 'w') as file:
json.dump({}, file)

# Load or initialize the login data file


if not os.path.exists(LOGIN_DATA_FILE):
with open(LOGIN_DATA_FILE, 'w') as file:
json.dump({}, file)

# Load or initialize the history data file


if not os.path.exists(HISTORY_FILE):
with open(HISTORY_FILE, 'w') as file:
json.dump({}, file)

# Utility functions for data storage


def load_user_data():
with open(USER_DATA_FILE, 'r') as file:
return json.load(file)

def save_user_data(data):
with open(USER_DATA_FILE, 'w') as file:
json.dump(data, file, indent=4)

def load_login_data():
with open(LOGIN_DATA_FILE, 'r') as file:
return json.load(file)

def save_login_data(data):
with open(LOGIN_DATA_FILE, 'w') as file:
json.dump(data, file, indent=4)

def load_history_data():
with open(HISTORY_FILE, 'r') as file:
return json.load(file)

def save_history_data(data):
with open(HISTORY_FILE, 'w') as file:
json.dump(data, file, indent=4)

def get_db_connection():
try:
connection = mysql.connector.connect(**DB_CONFIG)
return connection
except Error as e:
print(f"Error: {e}")
return None

@app.route('/')

def home():
return render_template('index.html')
# Login and registration routes
@app.route('/create_account', methods=['POST'])
def create_account():
data = request.json
username = data.get('username')
email = data.get('email')
password = data.get('password')
full_name = data.get('full_name')

# Validate input data


if not username or not email or not password or not full_name:
return jsonify({"success": False, "message": "All fields are required."}),
400

# Load existing data


user_data = load_user_data()

# Check if the username or email already exists


if username in user_data:
return jsonify({"success": False, "message": "Username already exists."}),
400

# Hash the password


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

# Store user details in users.json


user_data[username] = {
"username": username,
"email": email,
"full_name": full_name,
"password_hash": hashed_password.decode('utf-8') # Store the hashed
password here
}
save_user_data(user_data)

return jsonify({"success": True, "message": "Account created successfully."})

@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
email = data.get('email')
password = data.get('password')

if not email or not password:


return jsonify({"success": False, "message": "Email and password are
required."}), 400

# Load user data from JSON file


user_data = load_user_data()

# Check if the data structure is as expected


if not isinstance(user_data, dict):
return jsonify({"success": False, "message": "Invalid user data
structure."}), 500

# Find the user by email


user = None
for username, details in user_data.items():
if isinstance(details, dict) and 'email' in details and details['email'] ==
email:
user = details
break

if user and 'password_hash' in user:


if bcrypt.checkpw(password.encode('utf-8'),
user['password_hash'].encode('utf-8')):
session['username'] = user['username']
return jsonify({"success": True, "message": "Logged in successfully"})
else:
return jsonify({"success": False, "message": "Invalid email or
password"}), 401
else:
return jsonify({"success": False, "message": "Invalid email or password"}),
401

# API for managing chat messages


@app.route('/api/chat_messages/<int:conversation_id>', methods=['GET', 'POST'])
def manage_chat_messages(conversation_id):
connection = get_db_connection()
if not connection:
return jsonify({"error": "Unable to connect to the database"}), 500

cursor = connection.cursor(dictionary=True)
username = session.get('username')

if not username:
return jsonify({"error": "User not logged in"}), 403

if request.method == 'GET':
# Fetch all messages for the conversation
cursor.execute("""
SELECT * FROM chat_messages
WHERE conversation_id = %s
ORDER BY id ASC
""", (conversation_id,))
messages = cursor.fetchall()
cursor.close()
connection.close()

# Save or update the chat history for the logged-in user


history_data = load_history_data()
if username not in history_data:
history_data[username] = {}
history_data[username][conversation_id] = messages
save_history_data(history_data)

return jsonify(messages)

elif request.method == 'POST':


data = request.json
user_message = data['content']

# Simulated AI response
ai_response = f"You said: {user_message}"

# Insert the new user and AI message


cursor.execute("INSERT INTO chat_messages (conversation_id, role, content)
VALUES (%s, %s, %s)",
(conversation_id, 'user', user_message))
cursor.execute("INSERT INTO chat_messages (conversation_id, role, content)
VALUES (%s, %s, %s)",
(conversation_id, 'bot', ai_response))
connection.commit()

cursor.close()
connection.close()

# Save the new chat message to history.json


history_data = load_history_data()
if username not in history_data:
history_data[username] = {}
if conversation_id not in history_data[username]:
history_data[username][conversation_id] = []

history_data[username][conversation_id].append({"role": "user", "content":


user_message})
history_data[username][conversation_id].append({"role": "bot", "content":
ai_response})
save_history_data(history_data)

return jsonify({"message": "Message added", "response": ai_response}), 201

# Download chat history route


@app.route('/api/chat_history/<username>', methods=['GET'])
def download_chat_history(username):
# Check if the current user matches the requested username
if session.get('username') != username:
return jsonify({"error": "Unauthorized access"}), 403

# Load the chat history


history_data = load_history_data()
if username in history_data:
return jsonify(history_data[username])
else:
return jsonify({"error": "No chat history found for this user"}), 404
if __name__ == '__main__':
app.run(debug=True)

You might also like