46 lines
1.0 KiB
Python
46 lines
1.0 KiB
Python
from contextlib import contextmanager
|
|
import duckdb
|
|
import bcrypt
|
|
from rich import print
|
|
|
|
from lib import settings
|
|
|
|
|
|
@contextmanager
|
|
def get_db():
|
|
try:
|
|
conn = duckdb.connect(database=settings.db_url)
|
|
yield conn
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def db_run(sql):
|
|
with get_db() as conn:
|
|
result = conn.execute(sql)
|
|
return result
|
|
|
|
|
|
def init_db():
|
|
if settings.db_url.exists():
|
|
# TODO: Development feature. Remove this in production
|
|
from os import unlink
|
|
|
|
unlink(settings.db_url)
|
|
# return
|
|
sql = ""
|
|
with open("lib/database/database.sql") as f:
|
|
sql = f.read()
|
|
|
|
db_run(sql)
|
|
|
|
# Initialize default user
|
|
|
|
hashed_password = bcrypt.hashpw("password".encode("utf-8"), bcrypt.gensalt())
|
|
|
|
sql = f"INSERT INTO users (username, password, is_admin) VALUES ('admin', '{hashed_password.decode('utf-8')}', true)"
|
|
db_run(sql)
|
|
|
|
sql = f"INSERT INTO users (username, password, is_admin) VALUES ('test', '{hashed_password.decode('utf-8')}', false)"
|
|
db_run(sql)
|