fix issue with database path falling back to faulty path

update logic in welcome wizard, add checks for qapplication instance
This commit is contained in:
2025-06-24 13:46:08 +02:00
parent 3d164898bf
commit c06ff40fd6
9 changed files with 515 additions and 358 deletions

View File

@@ -2,6 +2,14 @@ import hashlib
import random
from .database import Database
import loguru
import sys
from src import LOG_DIR
log = loguru.logger
log.remove()
log.add(sys.stdout, level="INFO")
log.add(f"{LOG_DIR}/application.log", rotation="1 MB", retention="10 days")
# change passwords for apparats, change passwords for users, list users, create and delete users etc
@@ -9,9 +17,14 @@ from .database import Database
class AdminCommands:
"""Basic Admin commands for the admin console. This class is used to create, delete, and list users. It also has the ability to change passwords for users."""
def __init__(self):
"""Defaulf Constructor for the AdminCommands class."""
self.db = Database()
def __init__(self, db_path=None):
"""Default Constructor for the AdminCommands class."""
if db_path is None:
self.db = Database()
else:
self.db = Database(db_path=db_path)
log.info("AdminCommands initialized with database connection.")
log.critical("location: {}", self.db.db_path)
def create_password(self, password: str) -> tuple[str, str]:
"""Create a hashed password and a salt for the password.
@@ -44,7 +57,7 @@ class AdminCommands:
hashed_password = self.hash_password("admin")
self.db.createUser("admin", salt + hashed_password, "admin", salt)
def create_user(self, username: str, password: str, role: str = "user"):
def create_user(self, username: str, password: str, role: str = "user") -> bool:
"""Create a new user in the database.
Args:
@@ -53,9 +66,10 @@ class AdminCommands:
role (str, optional): the role of the user to be created. Defaults to "user".
"""
hashed_password, salt = self.create_password(password)
self.db.createUser(
status = self.db.createUser(
user=username, password=salt + hashed_password, role=role, salt=salt
)
return status
def hash_password(self, password: str) -> str:
"""Hash a password using SHA256.

View File

@@ -12,7 +12,7 @@ from typing import Any, List, Optional, Tuple, Union
import loguru
from src import LOG_DIR, settings
from src import LOG_DIR, settings, DATABASE_DIR
from src.backend.db import (
CREATE_ELSA_FILES_TABLE,
CREATE_ELSA_MEDIA_TABLE,
@@ -44,12 +44,11 @@ ascii_lowercase = lower + digits + punctuation
# get the line that called the function
class Database:
database = settings.database
"""
Initialize the database and create the tables if they do not exist.
"""
def __init__(self, db_path: Path = None):
def __init__(self, db_path: Union[Path, None] = None):
"""
Default constructor for the database class
@@ -57,15 +56,32 @@ class Database:
db_path (str, optional): Optional Path for testing / specific purposes. Defaults to None.
"""
if db_path is None:
self.db_path = Path(self.database.path.expanduser(), self.database.name)
if settings.database.path is not None:
self.db_path = Path(
settings.database.path.expanduser(), settings.database.name
)
else:
self.db_path = None
# self.db_path = self.db_path.replace("~", str(Path.home()))
log.debug(self.db_path)
else:
self.db_path = db_path
self.checkDatabaseStatus()
log.debug(f"Database path: {self.db_path}")
self.db_initialized = False
def initializeDatabase(self):
if not self.db_initialized:
self.checkDatabaseStatus()
self.db_initialized = True
def overwritePath(self, new_db_path: str):
log.debug("got new path, overwriting")
self.db_path = Path(new_db_path)
def checkDatabaseStatus(self):
path = self.database.path.expanduser()
path = settings.database.path
if path is None:
path = Path(DATABASE_DIR)
# path = path.replace("~", str(Path.home()))
# path = os.path.abspath(path)
if not os.path.exists(path):
@@ -509,7 +525,7 @@ class Database:
str: The filename of the recreated file
"""
blob = self.getBlob(filename, app_id)
tempdir = self.database.temp.expanduser()
tempdir = settings.database.temp.expanduser()
if not tempdir.exists():
tempdir.mkdir(parents=True, exist_ok=True)
file = tempfile.NamedTemporaryFile(
@@ -1280,6 +1296,13 @@ class Database:
"INSERT OR IGNORE INTO user (username, password, role, salt) VALUES (?,?,?,?)",
(user, password, role, salt),
)
# check if user was created
return (
self.query_db(
"SELECT username FROM user WHERE username=?", (user,), one=True
)
is not None
)
def deleteUser(self, user):
"""delete an unser
@@ -1467,7 +1490,7 @@ class Database:
"SELECT fileblob FROM elsa_files WHERE filename=?", (filename,), one=True
)[0]
# log.debug(blob)
tempdir = self.database.temp.expanduser()
tempdir = settings.database.temp.expanduser()
if not tempdir.exists():
tempdir.mkdir(parents=True, exist_ok=True)