Add sub-projects
This commit is contained in:
54
packages/sshecret-backend/src/sshecret_backend/db.py
Normal file
54
packages/sshecret-backend/src/sshecret_backend/db.py
Normal file
@ -0,0 +1,54 @@
|
||||
#!/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
|
||||
Reference in New Issue
Block a user