Compare commits

...

2 Commits

Author SHA1 Message Date
tylen
b8a0fd9179 convert from connection to pools in mysql 2025-11-01 12:32:01 +02:00
tylen
014a8fc1ff make auth work correctly 2025-11-01 11:43:09 +02:00
8 changed files with 176 additions and 65 deletions

2
.gitignore vendored
View File

@ -130,3 +130,5 @@ dist
.yarn/install-state.gz
.pnp.*
frontend/src/assets/*

View File

@ -1,7 +1,7 @@
from enum import Enum
import sys
import mysql.connector
import os
from mysql.connector import pooling
STARTUP_TABLE_CREATION_QUERIES = {
"users": """CREATE TABLE IF NOT EXISTS users (
@ -21,7 +21,8 @@ class Severity(Enum):
ERROR = "ERROR"
class DBClient:
def __init__(self):
def __init__(self, app):
self.app = app
self.db_server = os.environ.get('DB_SERVER')
self.db_port = os.environ.get('DB_PORT')
self.user = 'root'
@ -29,57 +30,54 @@ class DBClient:
self.database = os.environ.get('DB_NAME')
self.validate_env_variables() # Check for required environment variables
self.connection = self.open()
self.cursor = self.connection.cursor()
self.pool = self.create_pool() # Create a connection pool
self.initialize_database()
def validate_env_variables(self):
if not self.db_server or not self.db_port or not self.password or not self.database:
self.error("Missing one or more environment variables.")
def open(self):
return mysql.connector.connect(
self.app.logger.error("Missing one or more environment variables.")
def create_pool(self):
return pooling.MySQLConnectionPool(
pool_name="mypool",
pool_size=5, # Adjust size as needed
host=self.db_server,
port=self.db_port,
user=self.user,
password=self.password,
database=self.database
database=self.database,
connection_timeout=10 # Timeout in seconds
)
def close(self):
self.cursor.close()
self.connection.close()
def initialize_database(self):
self.query(STARTUP_TABLE_CREATION_QUERIES['users'])
self.query(STARTUP_TABLE_CREATION_QUERIES['sessions'])
def query(self, query_str, params=None):
try:
self.info(f'Executing query: {query_str}')
self.cursor.execute(query_str, params)
if 'SELECT' in query_str:
return self.cursor.fetchall() # Return results for SELECT queries
else:
self.commit() # Commit if it's a non-SELECT query
except Exception as e:
self.error(f"Query failed: {str(e)}")
def commit(self):
self.info('Committing actions to DB')
self.connection.commit()
def info(self, message):
self.message(severity=Severity.INFO, message=message)
def warning(self, message):
self.message(severity=Severity.WARNING, message=message)
def error(self, message):
self.message(severity=Severity.ERROR, message=message)
def message(self, severity, message):
print(f'DBClient [{severity.value}]: {message}')
def query(self, query_str, params=None):
max_retries = 3
for attempt in range(max_retries):
try:
self.app.logger.info(f'Executing query: {query_str}')
# Get a connection from the pool
connection = self.pool.get_connection()
with connection.cursor() as cursor:
cursor.execute(query_str, params)
if 'SELECT' in query_str:
results = cursor.fetchall()
self.app.logger.info(f'Query results: {results}')
return results
else:
connection.commit()
self.app.logger.info('Query executed successfully, changes committed.')
break
except mysql.connector.Error as e:
if e.errno in (2013, 2006): # Lost connection or connection no longer available
self.app.logger.warning(f"Lost connection to MySQL, retrying... {attempt + 1}/{max_retries}")
continue # Retry the query
else:
self.app.logger.error(f"Query failed: {str(e)}")
return None # Handle the error accordingly
finally:
if connection.is_connected():
connection.close() # Close the connection to return it to the pool

View File

@ -10,16 +10,18 @@ from flask_cors import CORS
from dotenv import load_dotenv
from db_client import DBClient
from user import registerUserEndpoints
import logging
load_dotenv()
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False # Ensures non-ASCII characters are preserved
logging.basicConfig(level=logging.INFO)
allowed_origins = [
"https://nyipyatki.davydovcloud.com",
"https://nyipyatki-dev.davydovcloud.com",
]
CORS(app, resources={r"*": {"origins": allowed_origins}}) # Only allow example.com
database = DBClient()
database = DBClient(app)
registerUserEndpoints(app=app, database=database)
if __name__ == "__main__":

View File

@ -7,15 +7,18 @@ user.py is a source for all user endpoints.
from flask import request, jsonify
import os
import mysql.connector
def registerUserEndpoints(app, database):
@app.route('/users/isSet', methods=['GET'])
def user_is_set():
user_name = request.args.get('userName')
try:
app.logger.info(f'Searching for user {user_name}')
query = "SELECT * FROM users WHERE Name=%s"
result = database.query(query, params=(user_name,))
return jsonify(bool(result and result[0][2])), 200
app.logger.info(f'Got: {result}')
return jsonify(bool(result)), 200
except mysql.connector.Error as err:
# Log the error or handle it as necessary
app.logger.error(f"Error: {err}")
@ -78,6 +81,7 @@ def registerUserEndpoints(app, database):
query = "SELECT * FROM sessions WHERE Token=%s AND Name=%s"
try:
result = database.query(query, params=(token, user_name))
app.logger.info(f'Got result: {result}')
return jsonify(tokenValid=bool(result)), 200
except Exception as e:
return jsonify(success=False, message=str(e)), 500

View File

@ -3,6 +3,7 @@ services:
build:
context: backend
dockerfile: Dockerfile
restart: always
ports:
- "2027:5000"
container_name: "${BACKEND_CT_NAME:-nyi-backend}"

View File

@ -1,7 +1,78 @@
#root {
width: 100%;
max-width: 1280px;
text-align: center;
width: 100%;
max-width: 1280px;
text-align: center; /* Centered text alignment */
}
/* Overall Body Style */
body {
background-color: #ffffff; /* Light background for contrast */
color: #4b2e2e; /* Darker red brown for readability */
font-family: 'Arial', sans-serif;
margin: 0;
text-align: center; /* Centered text alignment */
padding: 20px;
}
/* Header Style */
header {
background-color: #a41e34; /* Christmas red */
color: white;
padding: 20px 0;
border-bottom: 5px solid #b7c9b5; /* Light green border */
}
header h1 {
font-size: 2.5em;
}
/* Section Style */
section {
background-color: #e4f7e0; /* Light green background */
padding: 20px;
border-radius: 10px;
margin: 15px 0;
}
/* Festive Buttons */
button {
background-color: #b77de5; /* Purple with a slight festive flair */
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
font-size: 1.1em;
display: inline-block; /* Centers button in the container */
}
button:hover {
background-color: #9b6bb5; /* Darker purple on hover */
}
button:disabled {
background-color: #d3d3d3; /* Light gray for disabled button */
color: #a9a9a9; /* Darker gray for text */
cursor: not-allowed; /* Show not-allowed cursor */
}
/* Footer Style */
footer {
text-align: center; /* Centered */
padding: 20px;
background-color: #a41e34; /* Same red as header */
color: white;
position: relative;
}
/* Snowflakes Background */
.snowflakes {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image: url('./assets/snowflakes.png'); /* Snowflakes pattern */
}
/* General table styles */
@ -11,26 +82,60 @@ table {
margin: 20px 0;
font-size: 1em;
font-family: 'Arial', sans-serif;
text-align: center; /* Centered table text */
}
/* Table header styles */
th {
background-color: #4CAF50; /* Green */
background-color: #060698; /* Christmas red */
color: white;
text-align: left;
padding: 10px 15px;
border-bottom: 3px solid #b7c9b5; /* Light green border for header */
}
/* Table cell styles */
td {
border: 1px solid #ddd;
padding: 10px 15px; /* Added padding for better spacing */
background-color: #e4f7e0; /* Light green background for cells */
}
/* Zebra striping for table rows */
tr:nth-child(even) {
background-color: #f2f2f2;
background-color: #f9f9f9; /* Light gray for even rows */
}
/* Hover effect for rows */
tr:hover {
background-color: #f1f1f1;
background-color: #c28f8f; /* Softer red when hovering */
}
/* Additional table styling for Christmas theme */
table {
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2); /* Shadow for depth */
border-radius: 8px; /* Rounded corners */
overflow: hidden; /* Ensures border radius works */
}
/* Add some festive decorations */
th::after {
content: '🎄'; /* Small Christmas tree icon in the header */
margin-left: 10px;
font-size: 1.2em; /* Slightly larger */
}
td {
position: relative; /* For potential decorations */
}
td::before {
content: ''; /* Placeholder for decoration */
position: absolute;
background-image: url('path/to/snowflake-icon.png'); /* Snowflake icon */
width: 16px; /* Adjust as necessary */
height: 16px;
opacity: 0.1; /* Very subtle */
top: 5px; /* Position it nicely */
left: 5px;
pointer-events: none; /* Ignore mouse events */
}

View File

@ -7,11 +7,13 @@ import Program from './components/Program'
function App() {
return (
<>
<div className='snowflakes'>
<InitialSetup/>
<Greeting/>
<br/>
<Hosting/>
<Program/>
</div>
</>
)
}

View File

@ -15,17 +15,10 @@ const InitialSetup = () => {
const { userSet, passwordCreate, signUser, validToken } = useFetchUser(); // Destructure functions from the hook
const notify = useNotification();
useEffect(() => {
const validateToken = async () => {
const isTokenValid = await validToken(token, selectedName);
setIsSubmitted(isTokenValid);
};
validateToken();
if (selectedName) {
checkUserPassword(selectedName)
}
}, [selectedName]);
const checkUserPassword = async (name: string) => {
const passwordStatus = await userSet(name);
setIsPasswordSet(passwordStatus);
};
const handleSelect = (event: React.ChangeEvent<HTMLSelectElement>) => {
const name = event.target.value;
@ -34,10 +27,14 @@ const InitialSetup = () => {
checkUserPassword(name);
};
const checkUserPassword = async (name: string) => {
const passwordStatus = await userSet(name);
setIsPasswordSet(passwordStatus);
};
useEffect(() => {
const validateToken = async () => {
const isTokenValid = await validToken(token, selectedName);
setIsSubmitted(isTokenValid);
};
if (token !== undefined && selectedName !== undefined) validateToken();
}, []);
const handlePasswordCreate = async () => {
const message= await passwordCreate(selectedName!, password);