Files
sshecret/packages/sshecret-backend/src/sshecret_backend/db.py
2025-04-16 15:08:51 +02:00

55 lines
1.3 KiB
Python

#!/usr/bin/env python3
import secrets
from pathlib import Path
from sqlalchemy import Engine
from sqlmodel import Session, create_engine, text
import bcrypt
from dotenv import load_dotenv
from sqlalchemy.engine import URL
from .models import APIClient, init_db
load_dotenv()
def get_engine(filename: Path, echo: bool = False) -> Engine:
"""Initialize the engine."""
url = URL.create(drivername="sqlite", database=str(filename.absolute()))
engine = create_engine(url, echo=echo)
with engine.connect() as connection:
connection.execute(text("PRAGMA foreign_keys=ON")) # for SQLite only
return engine
def create_db_and_tables(filename: Path, echo: bool = True) -> bool:
"""Create database and tables.
Returns True if the database was created.
"""
created = False
if not filename.exists():
created = True
engine = get_engine(filename, echo)
init_db(engine)
return created
def create_api_token(session: Session, read_write: bool) -> str:
"""Create API token."""
token = secrets.token_urlsafe(32)
pwbytes = token.encode("utf-8")
salt = bcrypt.gensalt()
hashed_bytes = bcrypt.hashpw(password=pwbytes, salt=salt)
hashed = hashed_bytes.decode()
api_token = APIClient(token=hashed, read_write=read_write)
session.add(api_token)
session.commit()
return token