#import sql libraries and encryption libraries from sqlalchemy import create_engine from sqlalchemy.orm import (sessionmaker, declarative_base ) import hashlib, binascii, hmac from dotenv import load_dotenv import os load_dotenv() # defining connection URL def connect() -> str: pg_url = os.getenv("POSTGRESQL_DATABASE_URL") if pg_url.startswith("postgresql://"): #format url for psyopg reading return pg_url.replace("postgresql://", "postgresql+psycopg://", 1 ) return pg_url DATABASE_URL = connect() # create a ping engine to the database engine = create_engine(DATABASE_URL, pool_pre_ping=True) #create a local connection session instance SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() def get_db(): db = SessionLocal() try: yield db finally: db.close() # Verify password function for authentication # compare plain password with stored hashed password # the below code was developed with the the help of AI tools def verify_password(plain_password: str, stored_hash: str) -> bool: try: #decode the stored hash algo, iter_s, salt_hex, hash_hex = stored_hash.split("$") if algo != "pbkdf2_sha256": return False iterations = int(iter_s) salt = binascii.unhexlify(salt_hex) expected = binascii.unhexlify(hash_hex) # apply encryption method to plain password calc = hashlib.pbkdf2_hmac("sha256", plain_password.encode(), salt, iterations) #compare the calculated hash with the stored hash return hmac.compare_digest(calc, expected) except Exception: return False