Updated login

This commit is contained in:
2025-09-12 20:53:52 +03:00
parent 9fc32adb23
commit 6eab631604
4 changed files with 172 additions and 16 deletions

View File

@@ -0,0 +1,60 @@
import mariadb
import os
def get_external_db_connection():
"""Get MariaDB connection using external_server.conf"""
settings_file = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../instance/external_server.conf'))
settings = {}
with open(settings_file, 'r') as f:
for line in f:
key, value = line.strip().split('=', 1)
settings[key] = value
return mariadb.connect(
user=settings['username'],
password=settings['password'],
host=settings['server_domain'],
port=int(settings['port']),
database=settings['database_name']
)
def create_external_users_table():
"""Create users table and superadmin user in external MariaDB database"""
try:
conn = get_external_db_connection()
cursor = conn.cursor()
# Create users table if not exists (MariaDB syntax)
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
role VARCHAR(50) NOT NULL
)
''')
# Insert superadmin user if not exists
cursor.execute('''
INSERT IGNORE INTO users (username, password, role)
VALUES (%s, %s, %s)
''', ('superadmin', 'superadmin123', 'superadmin'))
# Check if user was created/exists
cursor.execute("SELECT username, password, role FROM users WHERE username = %s", ('superadmin',))
result = cursor.fetchone()
if result:
print(f"SUCCESS: Superadmin user exists in external database")
print(f"Username: {result[0]}, Password: {result[1]}, Role: {result[2]}")
else:
print("ERROR: Failed to create/find superadmin user")
conn.commit()
conn.close()
print("External MariaDB users table setup completed.")
except Exception as e:
print(f"ERROR: {e}")
if __name__ == "__main__":
create_external_users_table()

View File

@@ -0,0 +1,53 @@
import sqlite3
import os
def check_database(db_path, description):
"""Check if a database exists and show its users."""
if os.path.exists(db_path):
print(f"\n{description}: FOUND at {db_path}")
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Check if users table exists
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='users'")
if cursor.fetchone():
cursor.execute("SELECT id, username, password, role FROM users")
users = cursor.fetchall()
if users:
print("Users in this database:")
for user in users:
print(f" ID: {user[0]}, Username: {user[1]}, Password: {user[2]}, Role: {user[3]}")
else:
print(" Users table exists but is empty")
else:
print(" No users table found")
conn.close()
except Exception as e:
print(f" Error reading database: {e}")
else:
print(f"\n{description}: NOT FOUND at {db_path}")
if __name__ == "__main__":
# Check different possible locations for users.db
# 1. Root quality_recticel/instance/users.db
root_instance = "/home/ske087/quality_recticel/instance/users.db"
check_database(root_instance, "Root instance users.db")
# 2. App instance folder
app_instance = "/home/ske087/quality_recticel/py_app/instance/users.db"
check_database(app_instance, "App instance users.db")
# 3. Current working directory
cwd_db = "/home/ske087/quality_recticel/py_app/users.db"
check_database(cwd_db, "Working directory users.db")
# 4. Flask app database (relative to py_app)
flask_db = "/home/ske087/quality_recticel/py_app/app/users.db"
check_database(flask_db, "Flask app users.db")
print("\n" + "="*50)
print("RECOMMENDATION:")
print("The login should use the external MariaDB database.")
print("Make sure you have created the superadmin user in MariaDB using create_roles_table.py")

View File

@@ -11,8 +11,6 @@ import csv
from .warehouse import add_location
from .settings import settings_handler, edit_access_roles_handler
bp = Blueprint('main', __name__)
warehouse_bp = Blueprint('warehouse', __name__)
bp = Blueprint('main', __name__)
warehouse_bp = Blueprint('warehouse', __name__)
@@ -53,25 +51,70 @@ def get_db_connection():
@bp.route('/login', methods=['GET', 'POST'])
def login():
import sqlite3
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = None
print("Raw form input:", repr(username), repr(password))
# Only check external MariaDB for user authentication
try:
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SHOW TABLES LIKE 'users'")
if cursor.fetchone():
cursor.execute("SELECT username, password, role FROM users WHERE username=%s AND password=%s", (username.strip(), password.strip()))
row = cursor.fetchone()
print("External DB query result:", row)
if row:
user = {'username': row[0], 'password': row[1], 'role': row[2]}
conn.close()
except Exception as e:
print("External DB error:", e)
# Logic: If username starts with #, check internal SQLite database
if username.startswith('#'):
username_clean = username[1:].strip()
password_clean = password.strip()
print(f"Checking internal database for: {username_clean}")
# Check internal SQLite database (py_app/instance/users.db)
internal_db_path = os.path.join(os.path.dirname(__file__), '../instance/users.db')
try:
conn = sqlite3.connect(internal_db_path)
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='users'")
if cursor.fetchone():
cursor.execute("SELECT username, password, role FROM users WHERE username=? AND password=?", (username_clean, password_clean))
row = cursor.fetchone()
print("Internal DB query result:", row)
if row:
user = {'username': row[0], 'password': row[1], 'role': row[2]}
else:
print("No users table in internal database")
conn.close()
except Exception as e:
print("Internal DB error:", e)
else:
# Check external MariaDB database first
try:
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SHOW TABLES LIKE 'users'")
if cursor.fetchone():
cursor.execute("SELECT username, password, role FROM users WHERE username=%s AND password=%s", (username.strip(), password.strip()))
row = cursor.fetchone()
print("External DB query result:", row)
if row:
user = {'username': row[0], 'password': row[1], 'role': row[2]}
conn.close()
except Exception as e:
print("External DB error:", e)
# Fallback to internal database if external fails
print("Falling back to internal database")
internal_db_path = os.path.join(os.path.dirname(__file__), '../instance/users.db')
try:
conn = sqlite3.connect(internal_db_path)
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='users'")
if cursor.fetchone():
cursor.execute("SELECT username, password, role FROM users WHERE username=? AND password=?", (username.strip(), password.strip()))
row = cursor.fetchone()
print("Internal DB fallback query result:", row)
if row:
user = {'username': row[0], 'password': row[1], 'role': row[2]}
conn.close()
except Exception as e2:
print("Internal DB fallback error:", e2)
if user:
session['user'] = user['username']
session['role'] = user['role']