formatting

This commit is contained in:
WorldTeacher
2024-05-16 15:31:06 +02:00
parent 4f7b564352
commit ef5f862a2b
4 changed files with 39 additions and 26 deletions

View File

@@ -7,14 +7,13 @@ from src.backend.database import Database
# change passwords for apparats, change passwords for users, list users, create and delete users etc # change passwords for apparats, change passwords for users, list users, create and delete users etc
# create a class that has all commands. for each command, create a function that does the thing # create a class that has all commands. for each command, create a function that does the thing
class AdminCommands: 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. """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): def __init__(self):
"""Defaulf Constructor for the AdminCommands class. """Defaulf Constructor for the AdminCommands class."""
"""
self.db = Database() self.db = Database()
def create_password(self, password:str)->tuple[str,str]: def create_password(self, password: str) -> tuple[str, str]:
"""Create a hashed password and a salt for the password. """Create a hashed password and a salt for the password.
Args: Args:
@@ -25,8 +24,9 @@ class AdminCommands:
""" """
salt = self.create_salt() salt = self.create_salt()
hashed_password = self.hash_password(password) hashed_password = self.hash_password(password)
return (hashed_password,salt) return (hashed_password, salt)
def create_salt(self)->str:
def create_salt(self) -> str:
"""Generate a random 16 digit long salt for the password. """Generate a random 16 digit long salt for the password.
Returns: Returns:
@@ -39,13 +39,12 @@ class AdminCommands:
) )
def create_admin(self): def create_admin(self):
"""Create the admin in the database. This is only used once, when the database is created. """Create the admin in the database. This is only used once, when the database is created."""
"""
salt = self.create_salt() salt = self.create_salt()
hashed_password = self.hash_password("admin") hashed_password = self.hash_password("admin")
self.db.createUser("admin", salt+hashed_password, "admin", salt) self.db.createUser("admin", salt + hashed_password, "admin", salt)
def hash_password(self, password:str)->str: def hash_password(self, password: str) -> str:
"""Hash a password using SHA256. """Hash a password using SHA256.
Args: Args:
@@ -57,7 +56,7 @@ class AdminCommands:
hashed = hashlib.sha256((password).encode("utf-8")).hexdigest() hashed = hashlib.sha256((password).encode("utf-8")).hexdigest()
return hashed return hashed
def list_users(self)->list[tuple]: def list_users(self) -> list[tuple]:
"""List all available users in the database. """List all available users in the database.
Returns: Returns:
@@ -65,7 +64,7 @@ class AdminCommands:
""" """
return self.db.getUsers() return self.db.getUsers()
def delete_user(self, username:str): def delete_user(self, username: str):
"""Delete a selected user from the database. """Delete a selected user from the database.
Args: Args:
@@ -82,4 +81,3 @@ class AdminCommands:
""" """
hashed_password = self.hash_password(password) hashed_password = self.hash_password(password)
self.db.changePassword(username, hashed_password) self.db.changePassword(username, hashed_password)

View File

@@ -1,22 +1,25 @@
import os import os
from pathlib import Path from pathlib import Path
from omegaconf import OmegaConf from omegaconf import OmegaConf
from src.backend.database import Database from src.backend.database import Database
db = Database() db = Database()
config = OmegaConf.load("config.yaml") config = OmegaConf.load("config.yaml")
def recreateFile(name, app_id, filetype, open=True)->Path:
def recreateFile(name, app_id, filetype, open=True) -> Path:
""" """
recreateFile creates a file from the database and opens it in the respective program, if the open parameter is set to True. recreateFile creates a file from the database and opens it in the respective program, if the open parameter is set to True.
Args: Args:
---- ----
- name (str): The filename selected by the user. - name (str): The filename selected by the user.
- app_id (str): the id of the apparatus. - app_id (str): the id of the apparatus.
- filetype (str): the extension of the file to be created. - filetype (str): the extension of the file to be created.
- open (bool, optional): Determines if the file should be opened. Defaults to True. - open (bool, optional): Determines if the file should be opened. Defaults to True.
Returns: Returns:
------- -------
- Path: Absolute path to the file. - Path: Absolute path to the file.
@@ -30,4 +33,4 @@ def recreateFile(name, app_id, filetype, open=True)->Path:
else: else:
path = path.resolve() path = path.resolve()
os.system(f"open {path}") os.system(f"open {path}")
return path return path

View File

@@ -6,7 +6,7 @@ import tempfile
from pathlib import Path from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union from typing import Any, Dict, List, Optional, Tuple, Union
from icecream import ic # from icecream import ic
from omegaconf import OmegaConf from omegaconf import OmegaConf
from src.backend.db import ( from src.backend.db import (
@@ -250,7 +250,7 @@ class Database:
list[tuple[BookData, int]]: A list of tuples containing the wrapped Metadata and the id of the book list[tuple[BookData, int]]: A list of tuples containing the wrapped Metadata and the id of the book
""" """
rdata = self.query_db("SELECT * FROM media WHERE deleted=0") rdata = self.query_db("SELECT * FROM media WHERE deleted=0")
ic(rdata, len(rdata)) # ic(rdata, len(rdata))
mode = 0 mode = 0
if len(data) == 1: if len(data) == 1:
if "signature" in data.keys(): if "signature" in data.keys():
@@ -278,7 +278,7 @@ class Database:
and data["title"] in bookdata.title and data["title"] in bookdata.title
): ):
ret.append((bookdata, app_id, prof_id)) ret.append((bookdata, app_id, prof_id))
ic(ret) # ic(ret)
return ret return ret
def setAvailability(self, book_id: str, available: str): def setAvailability(self, book_id: str, available: str):
@@ -771,7 +771,7 @@ class Database:
self.createProf(apparat.get_prof_details()) self.createProf(apparat.get_prof_details())
prof_id = self.getProfId(apparat.profname) prof_id = self.getProfId(apparat.profname)
ic(prof_id) # ic(prof_id)
query = f"INSERT OR IGNORE INTO semesterapparat (appnr, name, erstellsemester, dauer, prof_id, fach,deletion_status,konto) VALUES ('{apparat.appnr}', '{apparat.appname}', '{apparat.semester}', '{apparat.dauerapp}', {prof_id}, '{apparat.app_fach}', '{0}', '{SEMAP_MEDIA_ACCOUNTS[apparat.appnr]}')" query = f"INSERT OR IGNORE INTO semesterapparat (appnr, name, erstellsemester, dauer, prof_id, fach,deletion_status,konto) VALUES ('{apparat.appnr}', '{apparat.appname}', '{apparat.semester}', '{apparat.dauerapp}', {prof_id}, '{apparat.app_fach}', '{0}', '{SEMAP_MEDIA_ACCOUNTS[apparat.appnr]}')"
logger.log_info(query) logger.log_info(query)
self.query_db(query) self.query_db(query)
@@ -909,14 +909,17 @@ class Database:
Args: Args:
apparat_data (ApparatData): the new metadata of the apparat apparat_data (ApparatData): the new metadata of the apparat
""" """
query = f"UPDATE semesterapparat SET name = ?, fach = ?, dauer = ?, prof_id = ? WHERE appnr = ?" query = "UPDATE semesterapparat SET name = ?, fach = ?, dauer = ?, prof_id = ?, prof_id_adis = ?, apparat_id_adis = ? WHERE appnr = ?"
params = ( params = (
apparat_data.appname, apparat_data.appname,
apparat_data.app_fach, apparat_data.app_fach,
apparat_data.dauerapp, apparat_data.dauerapp,
self.getProfId(apparat_data.profname), self.getProfId(apparat_data.profname),
apparat_data.prof_adis_id,
apparat_data.apparat_adis_id,
apparat_data.appnr, apparat_data.appnr,
) )
logger.log_info(f"Updating apparat with query {query} and params {params}")
self.query_db(query, params) self.query_db(query, params)
def checkApparatExists(self, apparat_name: str): def checkApparatExists(self, apparat_name: str):
@@ -1181,3 +1184,14 @@ class Database:
list[tuple]: a list of tuples containing the faculty members list[tuple]: a list of tuples containing the faculty members
""" """
return self.query_db("SELECT titel, fname,lname,mail,telnr,fullname FROM prof") return self.query_db("SELECT titel, fname,lname,mail,telnr,fullname FROM prof")
def restoreApparat(self, app_id: Union[str, int]):
"""restore an apparat from the database
Args:
app_id (Union[str, int]): the id of the apparat
"""
return self.query_db(
"UPDATE semesterapparat SET deletion_status=0, deleted_date=NULL WHERE appnr=?",
(app_id,),
)

View File

@@ -74,5 +74,3 @@ CREATE_TABLE_SUBJECTS = """CREATE TABLE subjects (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name TEXT NOT NULL UNIQUE name TEXT NOT NULL UNIQUE
)""" )"""