import hashlib import random from src.backend.database import Database # 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 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 create_password(self, password:str)->tuple[str,str]: """Create a hashed password and a salt for the password. Args: password (str): the base password to be hashed. Returns: tuple[str,str]: a tuple containing the hashed password and the salt used to hash the password. """ salt = self.create_salt() hashed_password = self.hash_password(password) return (hashed_password,salt) def create_salt(self)->str: """Generate a random 16 digit long salt for the password. Returns: str: the randomized salt """ return "".join( random.choices( "abcdefghijklmnopqrstuvwxyzQWERTZUIOPLKJHGFDSAYXCVBNM0123456789", k=16 ) ) def create_admin(self): """Create the admin in the database. This is only used once, when the database is created. """ salt = self.create_salt() hashed_password = self.hash_password("admin") self.db.createUser("admin", salt+hashed_password, "admin", salt) def hash_password(self, password:str)->str: """Hash a password using SHA256. Args: password (str): the password to be hashed. Returns: str: the hashed password. """ hashed = hashlib.sha256((password).encode("utf-8")).hexdigest() return hashed def list_users(self)->list[tuple]: """List all available users in the database. Returns: list[tuple]: a list of all users, containing all stored data for each user in a tuple. """ return self.db.getUsers() def delete_user(self, username:str): """Delete a selected user from the database. Args: username (str): the username of the user to be deleted. """ self.db.deleteUser(username) def change_password(self, username, password): """change the password for a user. Args: username (str): username of the user to change the password for. password (str): the new, non-hashed password to change to. """ hashed_password = self.hash_password(password) self.db.changePassword(username, hashed_password)