Compare commits
3 Commits
92c545384a
...
19e115c926
| Author | SHA1 | Date |
|---|---|---|
|
|
19e115c926 | |
|
|
1a517ee78f | |
|
|
f91bca2af4 |
|
|
@ -0,0 +1,191 @@
|
||||||
|
import sqlalchemy
|
||||||
|
from sqlalchemy import create_engine, String, Integer, Text, DateTime
|
||||||
|
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
from datetime import datetime
|
||||||
|
import time
|
||||||
|
import os
|
||||||
|
from cryptography.fernet import Fernet
|
||||||
|
from cryptography.hazmat.primitives import hashes
|
||||||
|
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
||||||
|
import base64
|
||||||
|
|
||||||
|
# Encryption setup
|
||||||
|
SALT = b'salt_123456789'
|
||||||
|
PASSWORD = b'chat_secret_key_123'
|
||||||
|
|
||||||
|
def get_cipher():
|
||||||
|
kdf = PBKDF2HMAC(
|
||||||
|
algorithm=hashes.SHA256(),
|
||||||
|
length=32,
|
||||||
|
salt=SALT,
|
||||||
|
iterations=100000,
|
||||||
|
)
|
||||||
|
key = base64.urlsafe_b64encode(kdf.derive(PASSWORD))
|
||||||
|
return Fernet(key)
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
class Messages(Base):
|
||||||
|
__tablename__ = "messages"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
ip: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
content: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
timestamp: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
|
|
||||||
|
# MariaDB configuration
|
||||||
|
DB_USER = 'chat'
|
||||||
|
DB_PASSWORD = 'uqhyUb5eBGg3qad.'
|
||||||
|
DB_HOST = 'localhost'
|
||||||
|
DB_PORT = '3306'
|
||||||
|
DB_NAME = 'chat_db'
|
||||||
|
|
||||||
|
# Create engine for MariaDB
|
||||||
|
DATABASE_URL = f"mariadb+mariadbconnector://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
|
||||||
|
# Alternative with pymysql (uncomment if needed):
|
||||||
|
# DATABASE_URL = f"mysql+pymysql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
|
||||||
|
|
||||||
|
engine = create_engine(
|
||||||
|
DATABASE_URL,
|
||||||
|
echo=False,
|
||||||
|
pool_size=10,
|
||||||
|
max_overflow=20,
|
||||||
|
pool_pre_ping=True,
|
||||||
|
pool_recycle=3600
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create tables
|
||||||
|
Base.metadata.create_all(engine)
|
||||||
|
|
||||||
|
class DBfrontend():
|
||||||
|
def __init__(self):
|
||||||
|
self.Session = sessionmaker(bind=engine)
|
||||||
|
self.cipher = get_cipher()
|
||||||
|
|
||||||
|
def encrypt_message(self, message: str) -> str:
|
||||||
|
"""Encrypt message before storing"""
|
||||||
|
return self.cipher.encrypt(message.encode()).decode()
|
||||||
|
|
||||||
|
def decrypt_message(self, encrypted_message: str) -> str:
|
||||||
|
"""Decrypt message after retrieval"""
|
||||||
|
try:
|
||||||
|
return self.cipher.decrypt(encrypted_message.encode()).decode()
|
||||||
|
except:
|
||||||
|
return "[Decryption failed]"
|
||||||
|
|
||||||
|
def add_message(self, ip: str, content: str) -> int:
|
||||||
|
"""Add a new message to the database and return its ID"""
|
||||||
|
with self.Session() as session:
|
||||||
|
encrypted_content = self.encrypt_message(content)
|
||||||
|
new_message = Messages(
|
||||||
|
ip=ip,
|
||||||
|
content=encrypted_content,
|
||||||
|
timestamp=int(time.time() * 1000)
|
||||||
|
)
|
||||||
|
session.add(new_message)
|
||||||
|
session.commit()
|
||||||
|
return new_message.id
|
||||||
|
|
||||||
|
def get_all_messages(self) -> list:
|
||||||
|
"""Get all messages from the database"""
|
||||||
|
with self.Session() as session:
|
||||||
|
messages = session.query(Messages).all()
|
||||||
|
for msg in messages:
|
||||||
|
msg.content = self.decrypt_message(msg.content)
|
||||||
|
return messages
|
||||||
|
|
||||||
|
def get_message_by_id(self, message_id: int) -> Messages | None:
|
||||||
|
"""Get a specific message by its ID"""
|
||||||
|
with self.Session() as session:
|
||||||
|
message = session.query(Messages).get(message_id)
|
||||||
|
if message:
|
||||||
|
message.content = self.decrypt_message(message.content)
|
||||||
|
return message
|
||||||
|
|
||||||
|
def get_messages_by_ip(self, ip: str) -> list:
|
||||||
|
"""Get all messages from a specific IP address"""
|
||||||
|
with self.Session() as session:
|
||||||
|
messages = session.query(Messages).filter(Messages.ip == ip).all()
|
||||||
|
for msg in messages:
|
||||||
|
msg.content = self.decrypt_message(msg.content)
|
||||||
|
return messages
|
||||||
|
|
||||||
|
def update_message(self, message_id: int, new_content: str) -> bool:
|
||||||
|
"""Update the content of a message"""
|
||||||
|
with self.Session() as session:
|
||||||
|
message = session.query(Messages).get(message_id)
|
||||||
|
if message:
|
||||||
|
message.content = self.encrypt_message(new_content)
|
||||||
|
session.commit()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def delete_message(self, message_id: int) -> bool:
|
||||||
|
"""Delete a message by its ID"""
|
||||||
|
with self.Session() as session:
|
||||||
|
message = session.query(Messages).get(message_id)
|
||||||
|
if message:
|
||||||
|
session.delete(message)
|
||||||
|
session.commit()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def delete_messages_by_ip(self, ip: str) -> int:
|
||||||
|
"""Delete all messages from a specific IP address and return count"""
|
||||||
|
with self.Session() as session:
|
||||||
|
messages = session.query(Messages).filter(Messages.ip == ip).all()
|
||||||
|
count = len(messages)
|
||||||
|
for message in messages:
|
||||||
|
session.delete(message)
|
||||||
|
session.commit()
|
||||||
|
return count
|
||||||
|
|
||||||
|
def get_message_count(self) -> int:
|
||||||
|
"""Get total number of messages"""
|
||||||
|
with self.Session() as session:
|
||||||
|
return session.query(Messages).count()
|
||||||
|
|
||||||
|
def get_latest_messages(self, limit: int = 10) -> list:
|
||||||
|
"""Get the latest N messages"""
|
||||||
|
with self.Session() as session:
|
||||||
|
messages = session.query(Messages).order_by(Messages.id.desc()).limit(limit).all()
|
||||||
|
for msg in messages:
|
||||||
|
msg.content = self.decrypt_message(msg.content)
|
||||||
|
return messages
|
||||||
|
|
||||||
|
def clear_all_messages(self) -> int:
|
||||||
|
"""Delete all messages and return count"""
|
||||||
|
with self.Session() as session:
|
||||||
|
count = session.query(Messages).count()
|
||||||
|
session.query(Messages).delete()
|
||||||
|
session.commit()
|
||||||
|
return count
|
||||||
|
|
||||||
|
def get_messages_by_date_range(self, start_timestamp: int, end_timestamp: int) -> list:
|
||||||
|
"""Get messages within a timestamp range"""
|
||||||
|
with self.Session() as session:
|
||||||
|
messages = session.query(Messages).filter(
|
||||||
|
Messages.timestamp >= start_timestamp,
|
||||||
|
Messages.timestamp <= end_timestamp
|
||||||
|
).order_by(Messages.timestamp.desc()).all()
|
||||||
|
for msg in messages:
|
||||||
|
msg.content = self.decrypt_message(msg.content)
|
||||||
|
return messages
|
||||||
|
|
||||||
|
# Optional: Test connection function
|
||||||
|
def test_connection():
|
||||||
|
"""Test if MariaDB connection is working"""
|
||||||
|
try:
|
||||||
|
with engine.connect() as conn:
|
||||||
|
result = conn.execute(sqlalchemy.text("SELECT 1"))
|
||||||
|
print("✅ MariaDB connection successful!")
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ MariaDB connection failed: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Run test if executed directly
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_connection()
|
||||||
|
|
@ -0,0 +1,461 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Secure Chat</title>
|
||||||
|
<style>
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
|
||||||
|
background: #2c2c2c;
|
||||||
|
color: #d4d4d4;
|
||||||
|
min-height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-container {
|
||||||
|
background: #3a3a3a;
|
||||||
|
border-radius: 12px;
|
||||||
|
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
|
||||||
|
width: 100%;
|
||||||
|
max-width: 800px;
|
||||||
|
height: 90vh;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header {
|
||||||
|
background: #2f2f2f;
|
||||||
|
padding: 20px;
|
||||||
|
border-bottom: 1px solid #4a4a4a;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header h1 {
|
||||||
|
color: #e0e0e0;
|
||||||
|
font-size: 20px;
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header .status {
|
||||||
|
color: #888;
|
||||||
|
font-size: 12px;
|
||||||
|
background: #3f3f3f;
|
||||||
|
padding: 4px 12px;
|
||||||
|
border-radius: 12px;
|
||||||
|
border: 1px solid #4a4a4a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-messages {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 20px;
|
||||||
|
background: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-messages::-webkit-scrollbar {
|
||||||
|
width: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-messages::-webkit-scrollbar-track {
|
||||||
|
background: #2c2c2c;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-messages::-webkit-scrollbar-thumb {
|
||||||
|
background: #555;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-messages::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-ip {
|
||||||
|
font-size: 11px;
|
||||||
|
color: #888;
|
||||||
|
margin-bottom: 4px;
|
||||||
|
font-family: 'Courier New', monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-content {
|
||||||
|
background: #404040;
|
||||||
|
padding: 10px 14px;
|
||||||
|
border-radius: 8px;
|
||||||
|
border-left: 3px solid #666;
|
||||||
|
word-wrap: break-word;
|
||||||
|
line-height: 1.5;
|
||||||
|
position: relative;
|
||||||
|
padding-right: 60px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-content .timestamp {
|
||||||
|
font-size: 10px;
|
||||||
|
color: #777;
|
||||||
|
position: absolute;
|
||||||
|
right: 10px;
|
||||||
|
bottom: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-actions {
|
||||||
|
margin-top: 4px;
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-actions button {
|
||||||
|
background: #4a4a4a;
|
||||||
|
border: none;
|
||||||
|
color: #aaa;
|
||||||
|
padding: 2px 10px;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 11px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s;
|
||||||
|
border: 1px solid #555;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-actions button:hover {
|
||||||
|
background: #555;
|
||||||
|
color: #ddd;
|
||||||
|
border-color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-actions button.delete-btn:hover {
|
||||||
|
background: #5a3a3a;
|
||||||
|
border-color: #8a4a4a;
|
||||||
|
color: #ff8888;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-input-area {
|
||||||
|
background: #2f2f2f;
|
||||||
|
padding: 20px;
|
||||||
|
border-top: 1px solid #4a4a4a;
|
||||||
|
display: flex;
|
||||||
|
gap: 12px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-input-area input {
|
||||||
|
flex: 1;
|
||||||
|
padding: 10px 14px;
|
||||||
|
background: #3f3f3f;
|
||||||
|
border: 1px solid #4a4a4a;
|
||||||
|
border-radius: 8px;
|
||||||
|
color: #e0e0e0;
|
||||||
|
font-size: 14px;
|
||||||
|
min-width: 150px;
|
||||||
|
transition: border-color 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-input-area input:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: #666;
|
||||||
|
background: #454545;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-input-area input::placeholder {
|
||||||
|
color: #777;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-input-area button {
|
||||||
|
padding: 10px 24px;
|
||||||
|
background: #4a4a4a;
|
||||||
|
border: 1px solid #5a5a5a;
|
||||||
|
border-radius: 8px;
|
||||||
|
color: #e0e0e0;
|
||||||
|
font-size: 14px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-input-area button:hover {
|
||||||
|
background: #555;
|
||||||
|
border-color: #666;
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-input-area button:active {
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading {
|
||||||
|
color: #666;
|
||||||
|
text-align: center;
|
||||||
|
padding: 20px;
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state {
|
||||||
|
color: #666;
|
||||||
|
text-align: center;
|
||||||
|
padding: 40px;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast {
|
||||||
|
position: fixed;
|
||||||
|
bottom: 30px;
|
||||||
|
left: 50%;
|
||||||
|
transform: translateX(-50%);
|
||||||
|
background: #4a4a4a;
|
||||||
|
color: #e0e0e0;
|
||||||
|
padding: 10px 24px;
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px solid #5a5a5a;
|
||||||
|
font-size: 14px;
|
||||||
|
opacity: 0;
|
||||||
|
transition: opacity 0.3s;
|
||||||
|
pointer-events: none;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast.visible {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast.success {
|
||||||
|
border-color: #5a8a5a;
|
||||||
|
background: #3a5a3a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toast.error {
|
||||||
|
border-color: #8a5a5a;
|
||||||
|
background: #5a3a3a;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 600px) {
|
||||||
|
.chat-container {
|
||||||
|
height: 100vh;
|
||||||
|
border-radius: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-input-area {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-input-area input {
|
||||||
|
min-width: unset;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-input-area button {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header h1 {
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-content {
|
||||||
|
padding-right: 50px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="chat-container">
|
||||||
|
<div class="chat-header">
|
||||||
|
<h1>🔒 Secure Chat</h1>
|
||||||
|
<span class="status">● Encrypted</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="chat-messages" id="messageContainer">
|
||||||
|
<div class="loading">Loading messages...</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="message-input-area">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
id="messageInput"
|
||||||
|
placeholder="Type your message..."
|
||||||
|
maxlength="500"
|
||||||
|
autocomplete="off"
|
||||||
|
>
|
||||||
|
<button id="sendButton">Send</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="toast" id="toast"></div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
class ChatApp {
|
||||||
|
constructor() {
|
||||||
|
this.messageContainer = document.getElementById('messageContainer');
|
||||||
|
this.messageInput = document.getElementById('messageInput');
|
||||||
|
this.sendButton = document.getElementById('sendButton');
|
||||||
|
this.toast = document.getElementById('toast');
|
||||||
|
this.toastTimeout = null;
|
||||||
|
this.encryptionEnabled = true;
|
||||||
|
|
||||||
|
this.init();
|
||||||
|
}
|
||||||
|
|
||||||
|
init() {
|
||||||
|
this.loadMessages();
|
||||||
|
this.setupEventListeners();
|
||||||
|
|
||||||
|
// Auto-refresh every 10 seconds
|
||||||
|
setInterval(() => this.loadMessages(), 10000);
|
||||||
|
}
|
||||||
|
|
||||||
|
setupEventListeners() {
|
||||||
|
this.sendButton.addEventListener('click', () => this.sendMessage());
|
||||||
|
this.messageInput.addEventListener('keypress', (e) => {
|
||||||
|
if (e.key === 'Enter') this.sendMessage();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendMessage() {
|
||||||
|
const message = this.messageInput.value.trim();
|
||||||
|
if (!message) {
|
||||||
|
this.showToast('Please enter a message', 'error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.sendButton.disabled = true;
|
||||||
|
this.sendButton.textContent = 'Sending...';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/messages', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ message })
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (data.success) {
|
||||||
|
this.messageInput.value = '';
|
||||||
|
this.showToast('Message sent! ✓', 'success');
|
||||||
|
this.loadMessages(); // Refresh messages
|
||||||
|
} else {
|
||||||
|
this.showToast('Error: ' + (data.error || 'Unknown error'), 'error');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
this.showToast('Network error: ' + error.message, 'error');
|
||||||
|
} finally {
|
||||||
|
this.sendButton.disabled = false;
|
||||||
|
this.sendButton.textContent = 'Send';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async loadMessages() {
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/messages?limit=50');
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (data.success) {
|
||||||
|
this.renderMessages(data.messages || []);
|
||||||
|
} else {
|
||||||
|
this.showToast('Failed to load messages', 'error');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
this.showToast('Network error loading messages', 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
renderMessages(messages) {
|
||||||
|
if (messages.length === 0) {
|
||||||
|
this.messageContainer.innerHTML = `
|
||||||
|
<div class="empty-state">💬 No messages yet. Start the conversation!</div>
|
||||||
|
`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let html = '';
|
||||||
|
// Show newest messages at bottom
|
||||||
|
messages.slice().reverse().forEach(msg => {
|
||||||
|
const time = new Date(msg.timestamp).toLocaleTimeString('en-US', {
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit'
|
||||||
|
});
|
||||||
|
|
||||||
|
html += `
|
||||||
|
<div class="message" data-id="${msg.id}">
|
||||||
|
<div class="message-ip">🔑 ${msg.ip}</div>
|
||||||
|
<div class="message-content">
|
||||||
|
${this.escapeHtml(msg.content)}
|
||||||
|
<span class="timestamp">${time}</span>
|
||||||
|
</div>
|
||||||
|
<div class="message-actions">
|
||||||
|
<button onclick="chatApp.deleteMessage(${msg.id})" class="delete-btn">Delete</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
});
|
||||||
|
|
||||||
|
this.messageContainer.innerHTML = html;
|
||||||
|
this.scrollToBottom();
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteMessage(id) {
|
||||||
|
if (!confirm('Delete this message?')) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/messages/${id}`, {
|
||||||
|
method: 'DELETE'
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (data.success) {
|
||||||
|
this.showToast('Message deleted ✓', 'success');
|
||||||
|
this.loadMessages();
|
||||||
|
} else {
|
||||||
|
this.showToast('Failed to delete message', 'error');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
this.showToast('Network error deleting message', 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
escapeHtml(text) {
|
||||||
|
const div = document.createElement('div');
|
||||||
|
div.textContent = text;
|
||||||
|
return div.innerHTML;
|
||||||
|
}
|
||||||
|
|
||||||
|
scrollToBottom() {
|
||||||
|
this.messageContainer.scrollTop = this.messageContainer.scrollHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
showToast(message, type = 'info') {
|
||||||
|
this.toast.textContent = message;
|
||||||
|
this.toast.className = 'toast visible ' + type;
|
||||||
|
|
||||||
|
if (this.toastTimeout) {
|
||||||
|
clearTimeout(this.toastTimeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.toastTimeout = setTimeout(() => {
|
||||||
|
this.toast.classList.remove('visible');
|
||||||
|
}, 3000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize the chat app
|
||||||
|
const chatApp = new ChatApp();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
@ -0,0 +1,240 @@
|
||||||
|
from bottle import route, request, response, run, static_file
|
||||||
|
import hashlib
|
||||||
|
import time
|
||||||
|
import json
|
||||||
|
from cryptography.fernet import Fernet
|
||||||
|
from cryptography.hazmat.primitives import hashes
|
||||||
|
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
||||||
|
import base64
|
||||||
|
import sqlalchemy
|
||||||
|
from sqlalchemy import create_engine, String, Integer, DateTime
|
||||||
|
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
# Encryption setup
|
||||||
|
SALT = b'salt_123456789' # In production, use a random salt
|
||||||
|
PASSWORD = b'chat_secret_key_123' # In production, use environment variable
|
||||||
|
|
||||||
|
def get_cipher():
|
||||||
|
kdf = PBKDF2HMAC(
|
||||||
|
algorithm=hashes.SHA256(),
|
||||||
|
length=32,
|
||||||
|
salt=SALT,
|
||||||
|
iterations=100000,
|
||||||
|
)
|
||||||
|
key = base64.urlsafe_b64encode(kdf.derive(PASSWORD))
|
||||||
|
return Fernet(key)
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
class Messages(Base):
|
||||||
|
__tablename__ = "messages"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
ip: Mapped[str] = mapped_column(String, nullable=False)
|
||||||
|
content: Mapped[str] = mapped_column(String, nullable=False)
|
||||||
|
timestamp: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
|
|
||||||
|
engine = create_engine("sqlite:///chat.db", echo=False)
|
||||||
|
Base.metadata.create_all(engine)
|
||||||
|
|
||||||
|
class DBfrontend():
|
||||||
|
def __init__(self):
|
||||||
|
self.Session = sessionmaker(bind=engine)
|
||||||
|
self.cipher = get_cipher()
|
||||||
|
|
||||||
|
def encrypt_message(self, message: str) -> str:
|
||||||
|
"""Encrypt message before storing"""
|
||||||
|
return self.cipher.encrypt(message.encode()).decode()
|
||||||
|
|
||||||
|
def decrypt_message(self, encrypted_message: str) -> str:
|
||||||
|
"""Decrypt message after retrieval"""
|
||||||
|
try:
|
||||||
|
return self.cipher.decrypt(encrypted_message.encode()).decode()
|
||||||
|
except:
|
||||||
|
return "[Decryption failed]"
|
||||||
|
|
||||||
|
def add_message(self, ip: str, content: str) -> int:
|
||||||
|
"""Add a new encrypted message to the database"""
|
||||||
|
with self.Session() as session:
|
||||||
|
encrypted_content = self.encrypt_message(content)
|
||||||
|
new_message = Messages(
|
||||||
|
ip=ip,
|
||||||
|
content=encrypted_content,
|
||||||
|
timestamp=int(time.time() * 1000)
|
||||||
|
)
|
||||||
|
session.add(new_message)
|
||||||
|
session.commit()
|
||||||
|
return new_message.id
|
||||||
|
|
||||||
|
def get_all_messages(self) -> list:
|
||||||
|
"""Get all messages and decrypt them"""
|
||||||
|
with self.Session() as session:
|
||||||
|
messages = session.query(Messages).all()
|
||||||
|
for msg in messages:
|
||||||
|
msg.content = self.decrypt_message(msg.content)
|
||||||
|
return messages
|
||||||
|
|
||||||
|
def get_message_by_id(self, message_id: int) -> Messages | None:
|
||||||
|
"""Get a specific message by its ID"""
|
||||||
|
with self.Session() as session:
|
||||||
|
message = session.query(Messages).get(message_id)
|
||||||
|
if message:
|
||||||
|
message.content = self.decrypt_message(message.content)
|
||||||
|
return message
|
||||||
|
|
||||||
|
def get_messages_by_ip(self, ip: str) -> list:
|
||||||
|
"""Get all messages from a specific IP address"""
|
||||||
|
with self.Session() as session:
|
||||||
|
messages = session.query(Messages).filter(Messages.ip == ip).all()
|
||||||
|
for msg in messages:
|
||||||
|
msg.content = self.decrypt_message(msg.content)
|
||||||
|
return messages
|
||||||
|
|
||||||
|
def update_message(self, message_id: int, new_content: str) -> bool:
|
||||||
|
"""Update the content of a message"""
|
||||||
|
with self.Session() as session:
|
||||||
|
message = session.query(Messages).get(message_id)
|
||||||
|
if message:
|
||||||
|
message.content = self.encrypt_message(new_content)
|
||||||
|
session.commit()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def delete_message(self, message_id: int) -> bool:
|
||||||
|
"""Delete a message by its ID"""
|
||||||
|
with self.Session() as session:
|
||||||
|
message = session.query(Messages).get(message_id)
|
||||||
|
if message:
|
||||||
|
session.delete(message)
|
||||||
|
session.commit()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def delete_messages_by_ip(self, ip: str) -> int:
|
||||||
|
"""Delete all messages from a specific IP address"""
|
||||||
|
with self.Session() as session:
|
||||||
|
messages = session.query(Messages).filter(Messages.ip == ip).all()
|
||||||
|
count = len(messages)
|
||||||
|
for message in messages:
|
||||||
|
session.delete(message)
|
||||||
|
session.commit()
|
||||||
|
return count
|
||||||
|
|
||||||
|
def get_message_count(self) -> int:
|
||||||
|
"""Get total number of messages"""
|
||||||
|
with self.Session() as session:
|
||||||
|
return session.query(Messages).count()
|
||||||
|
|
||||||
|
def get_latest_messages(self, limit: int = 10) -> list:
|
||||||
|
"""Get the latest N messages"""
|
||||||
|
with self.Session() as session:
|
||||||
|
messages = session.query(Messages).order_by(Messages.id.desc()).limit(limit).all()
|
||||||
|
for msg in messages:
|
||||||
|
msg.content = self.decrypt_message(msg.content)
|
||||||
|
return messages
|
||||||
|
|
||||||
|
# Initialize database
|
||||||
|
db = DBfrontend()
|
||||||
|
|
||||||
|
# Routes
|
||||||
|
import os
|
||||||
|
|
||||||
|
@route('/')
|
||||||
|
def serve_frontend():
|
||||||
|
# Получаем путь к директории, где находится index.py
|
||||||
|
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
return static_file('index.html', root=current_dir)
|
||||||
|
|
||||||
|
@route('/api/messages', method='POST')
|
||||||
|
def post_message():
|
||||||
|
ip = request.environ.get('REMOTE_ADDR', '127.0.0.1')
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = request.json
|
||||||
|
if not data or 'message' not in data:
|
||||||
|
response.status = 400
|
||||||
|
return {'success': False, 'error': 'No message provided'}
|
||||||
|
|
||||||
|
message = data.get('message', '').strip()
|
||||||
|
if not message:
|
||||||
|
response.status = 400
|
||||||
|
return {'success': False, 'error': 'Empty message'}
|
||||||
|
|
||||||
|
# Get IP hash for privacy
|
||||||
|
ip_hash = hashlib.sha256(('salt' + ip).encode('utf-8')).hexdigest()[:16]
|
||||||
|
|
||||||
|
# Save message with encrypted content
|
||||||
|
message_id = db.add_message(ip_hash, message)
|
||||||
|
|
||||||
|
response.content_type = 'application/json'
|
||||||
|
return {
|
||||||
|
'success': True,
|
||||||
|
'message_id': message_id,
|
||||||
|
'ip': ip_hash
|
||||||
|
}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
response.status = 500
|
||||||
|
return {'success': False, 'error': str(e)}
|
||||||
|
|
||||||
|
@route('/api/messages', method='GET')
|
||||||
|
def get_messages():
|
||||||
|
try:
|
||||||
|
limit = int(request.query.get('limit', 20))
|
||||||
|
messages = db.get_latest_messages(limit)
|
||||||
|
|
||||||
|
result = []
|
||||||
|
for msg in messages:
|
||||||
|
result.append({
|
||||||
|
'id': msg.id,
|
||||||
|
'ip': msg.ip,
|
||||||
|
'content': msg.content,
|
||||||
|
'timestamp': msg.timestamp
|
||||||
|
})
|
||||||
|
|
||||||
|
response.content_type = 'application/json'
|
||||||
|
return {'success': True, 'messages': result}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
response.status = 500
|
||||||
|
return {'success': False, 'error': str(e)}
|
||||||
|
|
||||||
|
@route('/api/messages/<message_id>', method='PUT')
|
||||||
|
def update_message(message_id):
|
||||||
|
try:
|
||||||
|
data = request.json
|
||||||
|
if not data or 'message' not in data:
|
||||||
|
response.status = 400
|
||||||
|
return {'success': False, 'error': 'No message provided'}
|
||||||
|
|
||||||
|
new_content = data.get('message', '').strip()
|
||||||
|
if not new_content:
|
||||||
|
response.status = 400
|
||||||
|
return {'success': False, 'error': 'Empty message'}
|
||||||
|
|
||||||
|
success = db.update_message(int(message_id), new_content)
|
||||||
|
|
||||||
|
response.content_type = 'application/json'
|
||||||
|
return {'success': success}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
response.status = 500
|
||||||
|
return {'success': False, 'error': str(e)}
|
||||||
|
|
||||||
|
@route('/api/messages/<message_id>', method='DELETE')
|
||||||
|
def delete_message(message_id):
|
||||||
|
try:
|
||||||
|
success = db.delete_message(int(message_id))
|
||||||
|
|
||||||
|
response.content_type = 'application/json'
|
||||||
|
return {'success': success}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
response.status = 500
|
||||||
|
return {'success': False, 'error': str(e)}
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
run(host='localhost', port=8080, debug=True)
|
||||||
|
|
@ -0,0 +1,2 @@
|
||||||
|
[tool.pyright]
|
||||||
|
python.pythonPath = "~/myenv/bin/python"
|
||||||
Loading…
Reference in New Issue