async def startup(db: Session = Depends(get_db)): generate_secret_key(db=SessionLocal()) users_exist = get_users(db=SessionLocal()) print("DISABLE_AUTH = " + str(settings.DISABLE_AUTH) + " (" + str(type(settings.DISABLE_AUTH)) + ")") if users_exist: print("Users Exist") else: print("No Users. Creating the default user.") # This is where I'm having trouble user = UserCreate(username=settings.ADMIN_EMAIL, password=settings.ADMIN_PASSWORD) create_user(db=SessionLocal(), user=user) template_variables_exist = read_template_variables(SessionLocal()) if template_variables_exist: print("Template Variables Exist") else: print("No Variables yet!") t_vars = settings.BASE_TEMPLATE_VARIABLES t_var_list = [] for t in t_vars: template_variables = TemplateVariables( variable=t.get("variable"), replacement=t.get("replacement")) t_var_list.append(template_variables) set_template_variables(new_variables=t_var_list, db=SessionLocal())
async def startup(db: Session = Depends(get_db)): # await database.connect() # Clear old db migrations delete_alembic = "DROP TABLE IF EXISTS alembic_version;" # await database.execute(delete_alembic) users_exist = get_users(db=SessionLocal()) print("DISABLE_AUTH = " + str(settings.DISABLE_AUTH) + " (" + str(type(settings.DISABLE_AUTH)) + ")") if users_exist: print("Users Exist") else: print("No Users. Creating the default user.") # This is where I'm having trouble user = UserCreate(username=settings.ADMIN_EMAIL, password=settings.ADMIN_PASSWORD) create_user(db=SessionLocal(), user=user) template_variables_exist = read_template_variables(SessionLocal()) if template_variables_exist: print("Template Variables Exist") else: print("No Variables yet!") t_vars = settings.BASE_TEMPLATE_VARIABLES t_var_list = [] for t in t_vars: template_variables = TemplateVariables( variable=t.get("variable"), replacement=t.get("replacement")) t_var_list.append(template_variables) set_template_variables(new_variables=t_var_list, db=SessionLocal())
def conv_volumes2data(data): db = SessionLocal() t_variables = db.query(models.TemplateVariables).all() for volume in data: if volume.bind: for t_var in t_variables: if t_var.variable in volume.bind: new_path = volume.bind.replace(t_var.variable, t_var.replacement) volume.bind = new_path volume_data = dict((d.bind, {"bind": d.container, "mode": "rw"}) for d in data) return volume_data
def delete_cucm_cluster_name(cluster_name: str, db: Session = SessionLocal()): db.query(models.CUCM_Cluster).filter( models.CUCM_Cluster.cluster_name == cluster_name).delete() db.commit() db.close()
def get_all_phone_data(db: Session = SessionLocal()): """query all data from models.Phone""" results = db.query(models.Phone).all() db.close() return results
def merge_cucm_cluster(cucm_cluster: models.CUCM_Cluster, db: Session = SessionLocal()): # write CA certificate file cucm_cluster.pd = config.key.encrypt(cucm_cluster.pd.encode()) db.merge(cucm_cluster) db.commit() db.close()
def get_cucm_clusters(db: Session = SessionLocal()): results = db.query(models.CUCM_Cluster).all() db.close() for result in results: result.pd = config.key.decrypt(result.pd).decode() return results
def get_all_settings(db: Session = SessionLocal()): try: results = db.query(models.Settings).all() except sqlalchemy.orm.exc.NoResultFound: return None db.close() return results
def get_all_cucm_users(db: Session = SessionLocal()): try: results = db.query(models.CUCM_Users).all() except sqlalchemy.orm.exc.NoResultFound: return None db.close() return results
def delete_cucm_user(userid: str, db: Session = SessionLocal()): try: db.query(models.CUCM_Users).filter( models.CUCM_Users.userid == userid).delete() except sqlalchemy.orm.exc.NoResultFound: return None db.commit() db.close()
def merge_phonescraper_data_list(scraper_list: List[models.PhoneScraper], db: Session = SessionLocal()): """update models.Phone with list of models""" for scraped_data in scraper_list: db.merge(scraped_data) db.commit() db.close()
def get_all_scraper_data(db: Session = SessionLocal()): """query all phone scrape data from models""" results = db.query(models.Phone).options( joinedload(models.Phone.phonescrape), ).all() db.close() return results
def merge_phone_data(phone_list: List[models.Phone], db: Session = SessionLocal()): """update models.Phone with list of models""" for phone in phone_list: db.merge(phone) db.commit() db.close()
class jwtSettings(BaseModel): authjwt_secret_key: str = generate_secret_key(db=SessionLocal()) authjwt_token_location: set = {"headers", "cookies"} authjwt_cookie_secure: bool = False authjwt_cookie_csrf_protect: bool = True authjwt_access_token_expires: int = int(settings.ACCESS_TOKEN_EXPIRES) authjwt_refresh_token_expires: int = int(settings.REFRESH_TOKEN_EXPIRES) authjwt_cookie_samesite: str = settings.SAME_SITE_COOKIES authjwt_denylist_enabled: bool = True authjwt_denylist_token_checks: set = {"access", "refresh"}
def get_setting(name: str, db: Session = SessionLocal()): try: result = db.query( models.Settings).filter(models.Settings.name == name).one() except sqlalchemy.orm.exc.NoResultFound: return None db.close() return result.value
def change_setting(name: str, value: str, db: Session = SessionLocal()): try: result = db.query( models.Settings).filter(models.Settings.name == name).one() result.value = value except sqlalchemy.orm.exc.NoResultFound: db.merge(models.Settings(name=name, value=value)) db.commit() db.close()
def conv_env2data(data): # Set is depracated. Name is the actual value. Label is the name of the field. # Label is the label of the label field. db = SessionLocal() t_variables = db.query(models.TemplateVariables).all() for i, variable in enumerate(data): for t_var in t_variables: if variable.default: if t_var.variable in variable.default: new_var = data[i].default.replace(t_var.variable, t_var.replacement) variable.default = new_var break else: if variable.default.startswith("!"): raise HTTPException( 400, "Unset template variable used: " + variable.default ) delim = "=" return [delim.join((d.name, d.default)) for d in data if d.default]
def conv_labels2data(data): # grab template variables db = SessionLocal() t_variables = db.query(models.TemplateVariables).all() # if we have nothing return an empty dictionary if not data: return {} # iterate over template variables and labels and replace templated fields for label in data: for t_var in t_variables: if t_var.variable in label.label: label.label = label.label.replace(t_var.variable, t_var.replacement) if t_var.variable in label.value: label.value = label.value.replace(t_var.variable, t_var.replacement) # generate dictionary from de-templated local data return dict((d.label, d.value) for d in data)
def endjob(jobname: str, db: Session = SessionLocal()): """Insert/Update job end time into job status table. Called each time a scheduled or manual job ends to update the 'finished' timestamp Arguments: jobname {str} -- name of job """ current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") logger.info(f"Finished {jobname} at {current_time}") job_update = models.JobStatus(jobname=jobname, result=f"Finished at {current_time}") db.merge(job_update) db.commit() db.close()
def get_phone_data_for_phonescraper(cluster_name: str = None, db: Session = SessionLocal()): """query phone data to be used by phone scraper""" query = db.query(models.Phone) if cluster_name != None: query = query.filter(models.Phone.cluster == cluster_name) results = query.all() db.close() return results
def startjob(jobname: str, db: Session = SessionLocal()): """Insert/Update job start time into job status table. Called each time a scheduled or manual job is run to update the 'start' timestamp Arguments: jobname {str} -- name of job """ current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") logger.info(f"Starting {jobname} at {current_time}") job_update = models.JobStatus(jobname=jobname, laststarttime=current_time, result="running job..") db.merge(job_update) db.commit() db.close()
def updatepw(old_password: str, new_password: str, db: Session = SessionLocal()): old_real_password_hash = get_setting(name='localadmin') old_supplied_password_hash = hashlib.sha512( (old_password + str(config.salt)).encode()).hexdigest() if old_supplied_password_hash == old_real_password_hash: try: new_password_hash = hashlib.sha512( (new_password + str(config.salt)).encode()).hexdigest() change_setting(name='localadmin', value=new_password_hash) except Exception as e: return "Password change failed" else: return "Password successfully changed" else: return "Current password does not match"
def merge_phonescraper_data(phonescraper_data: models.PhoneScraper, db: Session = SessionLocal()): db.merge(phonescraper_data) db.commit() db.close()
def merge_cucm_user(userid: str, db: Session = SessionLocal()): db.merge(models.CUCM_Users(userid=userid)) db.commit() db.close()
def check_if_token_in_denylist(decrypted_token): db = SessionLocal() jti = decrypted_token["jti"] entry = db.query(TokenBlacklist).filter(TokenBlacklist.jti == jti).first() if entry: return True
def get_db(): try: db = SessionLocal() yield db finally: db.close()
def get_all_jobstatus(db: Session = SessionLocal()): """query all data from models.JobStatus""" result = db.query(models.JobStatus).all() db.close() return result
def delete_cucm_cluster(id: int, db: Session = SessionLocal()): db.query(models.CUCM_Cluster).filter(models.CUCM_Cluster.id == id).delete() db.commit() db.close()