Compare commits

...
17 Commits
Author SHA1 Message Date
Mabe 087fed017a Implement flag handling and migration status checks; refactor database test functions and update requirements 2026-09-26 16:21:44 -07:00
Mabe 220a06208a Refactor start.py to remove dotenv and db dependencies; implement new_table function for table creation and streamline admin function 2026-09-24 19:40:30 -07:00
Mabe d268cb01d5 Add check_clothe function to verify clothing existence in the database 2026-09-24 19:33:43 -07:00
Mabe 98e9b28bae Remove migration_status.flag on exit and during initialization; log any exceptions 2026-09-23 20:53:42 -07:00
Mabe 12485792d2 Add migration support with Alembic; implement migration scripts and configuration 2026-09-23 20:47:58 -07:00
Mabe c3ce9b88a2 Update .gitignore and requirements.txt; remove mariadb dependency and add SQLAlchemy 2026-09-23 19:56:12 -07:00
Mabe cfe8a0e22d Refactor database interactions to use SQLAlchemy ORM; update user and token management in api_security.py and user.py; add models for Items, Tokens, and User 2026-09-23 19:54:20 -07:00
Mabe c0108fd1e1 Add username availability check and fix cursor initialization in user.py; update token validation in api_security.py 2026-09-19 16:48:56 -07:00
Mabe c105c36086 Remove unused import of mariadb in user.py 2026-09-19 13:16:55 -07:00
Mabe f5919b2845 Refactor import paths and enhance logging in various modules; add user table creation in start.py 2026-09-19 13:13:03 -07:00
Mabe 83c288d490 Implement token management and authentication features with logging 2026-08-30 21:42:21 +02:00
Mabe f697a0aca3 Add start.py to initialize logging and create database tables 2026-08-30 17:37:36 +02:00
Mabe 1605757c80 Update .gitignore to include venv/pyvenv.cfg and venv/* directories 2026-08-29 12:31:45 +02:00
Mabe 06915f0758 Update .gitignore to include update.sh and update.ps1 files 2026-08-29 12:29:47 +02:00
Mabe 7a87b0e793 Update .gitignore to include start.sh and venv/ directories 2026-08-29 12:27:48 +02:00
Mabe 89b8b246f9 Add example environment configuration file (.env.example) 2026-08-28 21:29:24 +02:00
Mabe da1d4e9e89 Remove .env file and update .gitignore to exclude it 2026-08-28 21:27:28 +02:00
23 changed files with 955 additions and 127 deletions
-8
View File
@@ -1,8 +0,0 @@
#database
DB_NAME="canada_luggage"
#Credentials
DB_PASSWORD=
DB_USER="luggage"
#Host Settings
DB_PORT="3307"
DB_HOST="192.168.1.74"
+8
View File
@@ -0,0 +1,8 @@
#database
DB_NAME=
#Credentials
DB_PASSWORD=
DB_USER=
#Host Settings
DB_PORT= #standard 3306
DB_HOST=
+49 -1
View File
@@ -1,3 +1,51 @@
__pycache__/
start.sh
update.sh
# OS
.DS_Store
Thumbs.db
Desktop.ini
# Editors / IDEs
.vscode/
.idea/
*.swp
*.swo
*~
# Logs
*.log
logs/
# Env / secrets
.env
.env.*
!.env.example
# Dependencies
node_modules/
vendor/
venv/
.venv/
__pycache__/
*.pyc
# Build output
dist/
build/
out/
*.egg-info/
target/
bin/
obj/
# Testing / coverage
coverage/
.nyc_output/
.pytest_cache/
# Misc
*.tmp
*.bak
*.old
.cache/
migration_status.flag
+152
View File
@@ -0,0 +1,152 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts.
# this is typically a path given in POSIX (e.g. forward slashes)
# format, relative to the token %(here)s which refers to the location of this
# ini file
script_location = %(here)s/migration
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python>=3.9 or backports.zoneinfo library and tzdata library.
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to <script_location>/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# the special token `%(here)s` is available which indicates the absolute path
# to this configuration file.
#
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
# path_separator (New in Alembic 1.16.0, supersedes version_path_separator);
# This indicates what character is used to
# split lists of file paths, including version_locations and prepend_sys_path
# within configparser files such as alembic.ini.
#
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
# to provide os-dependent path splitting.
#
# Note that in order to support legacy alembic.ini files, this default does NOT
# take place if path_separator is not present in alembic.ini. If this
# option is omitted entirely, fallback logic is as follows:
#
# 1. Parsing of the version_locations option falls back to using the legacy
# "version_path_separator" key, which if absent then falls back to the legacy
# behavior of splitting on spaces and/or commas.
# 2. Parsing of the prepend_sys_path option falls back to the legacy
# behavior of splitting on spaces, commas, or colons.
#
# Valid values for path_separator are:
#
# path_separator = :
# path_separator = ;
# path_separator = space
# path_separator = newline
#
# Use os.pathsep. Default configuration used for new projects.
path_separator = os
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# database URL. This is consumed by the user-maintained env.py script only.
# other means of configuring database URLs may be customized within the env.py
# file.
# See notes in "escaping characters in ini files" for guidelines on
# passwords
sqlalchemy.url = driver://user:pass@localhost/dbname
# [post_write_hooks]
# This section defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner,
# against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
# hooks = ruff
# ruff.type = module
# ruff.module = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Alternatively, use the exec runner to execute a binary found on your PATH
# hooks = ruff
# ruff.type = exec
# ruff.executable = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Logging configuration. This is also consumed by the user-maintained
# env.py script only.
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARNING
handlers = console
qualname =
[logger_sqlalchemy]
level = WARNING
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
+14 -5
View File
@@ -1,7 +1,11 @@
from fastapi import APIRouter, HTTPException
from fastapi import APIRouter, HTTPException, Depends, Header
import logging
import db
import auth.api_security as auth
from pydantic import BaseModel
from api import tokens
#Logging
@@ -42,8 +46,11 @@ class Item_weight(BaseModel):
class Item_piece(BaseModel):
pieces: int
class Item_duration(BaseModel):
duration: str
@router.post("/insert", status_code=201)
def insert(item_name: Item_name, item_weight: Item_weight, item_pieces: Item_piece):
def insert(item_name: Item_name, item_weight: Item_weight, item_pieces: Item_piece, token: str = Depends(tokens.check_token)):
name = item_name.name_of_clothes.upper()
weight = item_weight.weight
pieces = item_pieces.pieces
@@ -54,7 +61,7 @@ def insert(item_name: Item_name, item_weight: Item_weight, item_pieces: Item_pie
@router.put("/update/{clothe_name}/pieces", status_code=202)
def update_pieces(clothe_name: str, item_pieces: Item_piece):
def update_pieces(clothe_name: str, item_pieces: Item_piece, token: str = Depends(tokens.check_token)):
name = clothe_name.upper()
pieces = item_pieces.pieces
if db.check_clothe(name) != None:
@@ -68,7 +75,7 @@ def update_pieces(clothe_name: str, item_pieces: Item_piece):
@router.put("/update/{clothe_name}/weight", status_code=202)
def update_weight(clothe_name: str, item: Item_weight):
def update_weight(clothe_name: str, item: Item_weight, token: str = Depends(tokens.check_token)):
name = clothe_name.upper()
weight = item.weight
if db.check_clothe(name) != None:
@@ -82,7 +89,7 @@ def update_weight(clothe_name: str, item: Item_weight):
@router.delete("/{clothe_name}/delete", status_code=204)
def delete(clothe_name: str):
def delete(clothe_name: str, token: str = Depends(tokens.check_token)):
name = clothe_name.upper()
if db.check_clothe(name) != None:
db.delete(name)
@@ -91,3 +98,5 @@ def delete(clothe_name: str):
else:
logging.error(f"Item {name} not found")
raise HTTPException(status_code=404, detail=f"Item {name} not found")
+60
View File
@@ -0,0 +1,60 @@
from fastapi import APIRouter, HTTPException, Depends, Header
import logging
import db
import auth.api_security as auth
from pydantic import BaseModel
def check_token(token:str = Header(...)):
if not auth.check_token(token):
raise HTTPException(status_code=401, detail="Invalid token")
return token
def check_admin_token(admin_token: str = Header(...)):
if not auth.check_admin_token(admin_token):
raise HTTPException(status_code=401, detail="No admin token")
return admin_token
#Logging
logging.basicConfig(
filename='api.log', # Log to a file
level=logging.DEBUG, # Log everything (DEBUG and above)
format='%(asctime)s %(levelname)s %(message)s'
)
logging.info('Application started')
try:
logging.debug('Debug info here')
except Exception as e:
logging.exception('An error occurred')
router = APIRouter(prefix="/tokens", tags=["tokens"])
class Item_duration(BaseModel):
duration: str | int
class Item_token(BaseModel):
token: str
@router.get("/help")
def help():
return{"duration": "string or int"}
@router.post("/create")
def create_token(duration: Item_duration, admin_token: str = Depends(check_admin_token)):
new_token = auth.generate_token(duration.duration)
return {"new token": new_token}
@router.delete("/delete")
def delete(token: Item_token, admin_token: str = Depends(check_admin_token)):
auth.delete_token(token.token)
return {"messages": "token deleted"}
@router.get("/test")
def test(token: str = Depends(check_token)):
return {"message": "you can authenticate", "status": "ok"}
+3 -2
View File
@@ -1,7 +1,8 @@
from fastapi import FastAPI
from api import health, db, query
from api import health, db, query, tokens
app =FastAPI()
app = FastAPI()
app.include_router(health.router)
app.include_router(db.router)
app.include_router(query.router)
app.include_router(tokens.router)
+122
View File
@@ -0,0 +1,122 @@
import time
from dotenv import load_dotenv
import db
import os
from datetime import datetime, timedelta
import logging
from argon2 import PasswordHasher
import random
import string
from models import Tokens
#Logging
logging.basicConfig(
filename='api.log', # Log to a file
level=logging.DEBUG, # Log everything (DEBUG and above)
format='%(asctime)s %(levelname)s %(message)s'
)
logging.info('Application started')
try:
logging.debug('Debug info here')
except Exception as e:
logging.exception('An error occurred')
session = db.session
def generate_token(duration):
ph = PasswordHasher()
token = "".join(random.choices(string.ascii_lowercase + string.digits, k=32))
print(token)
hash = ph.hash(token)
end_date = enddate(duration)
time = datetime.now()
new_item = Tokens(tokens=hash, time=time, end_date=end_date)
session.add(new_item)
session.commit()
logging.info(f"Token till {end_date} created")
return token
def enddate(duration):
if duration == "week":
return datetime.now() + timedelta(days=7)
if duration == "day":
return datetime.now() + timedelta(days=1)
if duration == "year":
return datetime.now() + timedelta(days=365)
if isinstance(duration, int):
return datetime.now() + timedelta(days=duration)
if duration == "forever":
return datetime.now() + timedelta(days=4000)
raise ValueError(f"Invalid duration: {duration}")
def check_token(token):
ph = PasswordHasher()
valid = False
hashes = [row[0] for row in session.query(Tokens.tokens).all()]
for hash in hashes:
try:
valid = ph.verify(hash, token)
if valid == True:
return valid
except Exception as e:
logging.error("Token not the same")
logging.error(e)
return valid
def check_validaty():
end_dates = [row[0] for row in session.query(Tokens.end_date).all()]
for end_date in end_dates:
end_date_dt = datetime.strptime(end_date, "%Y-%m-%d %H:%M:%S")
if datetime.now() > end_date_dt:
session.query(Tokens).filter_by(end_date=end_date).delete()
session.commit()
def admin_token():
ph = PasswordHasher()
token = "".join(random.choices(string.ascii_lowercase + string.digits, k=64))
hash = ph.hash(token)
time = datetime.now()
end_date = enddate("forever")
new_item = Tokens(tokens=hash, time=time, end_date=end_date)
session.add(new_item)
session.commit()
logging.info(f"Token till {end_date} created")
return token
def check_admin_token(token):
valid = False
if len(token) == 64:
ph = PasswordHasher()
cursor = db.connection.cursor()
hashes = [row[0] for row in session.query(Tokens.tokens).all()]
for hash in hashes:
try:
valid = ph.verify(hash, token)
if valid == True:
return valid
except Exception as e:
logging.info(e)
def delete_token(token):
if not len(token) == 64:
ph = PasswordHasher()
hashes = [row[0] for row in session.query(Tokens.tokens).all()]
for hash in hashes:
try:
valid = ph.verify(hash, token)
if valid == True:
session.query(Tokens).filter_by(tokens=hash).delete()
db.connection.commit()
logging.critical("token deleted")
except Exception as e:
logging.error(e)
+65
View File
@@ -0,0 +1,65 @@
from argon2 import PasswordHasher
import db
from models import User
import logging
#Logging
logging.basicConfig(
filename='auth/user.log', # Log to a file
level=logging.DEBUG, # Log everything (DEBUG and above)
format='%(asctime)s %(levelname)s %(message)s'
)
logging.info('Application started')
try:
logging.debug('Debug info here')
except Exception as e:
logging.exception('An error occurred')
session = db.session
def create_user(username, password, role):
user = username
passwd = PasswordHasher().hash(password)
new_item = User(username=user, password=passwd, role=role)
def check_login(username, password):
result = session.query(User.password).filter_by(username=username).first()
hash_passwd = result[0] if result else None
valid = False
try:
valid = PasswordHasher().verify(hash_passwd, password)
if valid == True:
return valid
except Exception as e:
logging.error(e)
return False
def delete_user(username, password):
result = session.query(User.password).filter_by(username=username).first()
hash_password = result[0] if result else None
valid = False
try:
valid = PasswordHasher().verify(hash_password, password)
except Exception as e:
logging.error(e)
if valid == True:
try:
session.query(User).filter_by(username=username).delete()
session.commit()
logging.info(f"User {username} was successfully deleted")
except Exception as e:
logging.error(e)
def check_username(username):
try:
exists = session.query(User).filter_by(username=username).first() is not None
return exists # True if taken, False if available
except db.IntegrityError as e:
if e.errno == 1062:
logging.error("Username taken")
return True #If the username is not available it returns True
def get_role(username):
result = session.query(User.role).filter_by(username=username).first()
return result[0] if result else None
+4 -1
View File
@@ -3,6 +3,7 @@ import logging
import time
import os
import sys
from flags import status
print("loading")
@@ -177,7 +178,7 @@ def menu():
#The Terminal App Starts here
time.sleep(5)
time.sleep(2)
print(r"""
## ## ##########
### ### ## ##
@@ -186,6 +187,8 @@ print(r"""
## ## ## ## ##
## ## ## ##
""")
while not status.get_migration():
time.sleep(0.5)
logging.info("Menu is starting")
time.sleep(2.5)
menu()
+74 -98
View File
@@ -1,7 +1,10 @@
import mariadb
import logging
from dotenv import load_dotenv
import os
from models import Items
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
from urllib.parse import quote_plus
#Logging
@@ -17,102 +20,6 @@ try:
except Exception as e:
logging.exception('An error occurred')
def connect(db_user, db_psswd, db_host, db_port, db_name):
try:
global connection
connection = mariadb.connect(user=db_user,
password=db_psswd,
host=db_host,
port=db_port,
database=db_name)
print("Connected to MariaDB successfully!")
logging.info("Connected to MariaDB successfully!")
except mariadb.Error as e:
print(f"Error connecting to DB: {e}")
logging.error("Error connecting")
logging.debug(f"Error connecting to DB: {e}")
def new_part(cloth_type, weight, pieces):
if type(pieces) is not int:
print("only ints allowed")
logging.error("only ints allowed")
else:
cursor = connection.cursor()
executed = "INSERT INTO luggage (clothes, weight, pieces) VALUES (?, ?, ?)"
executed_data = (cloth_type, weight, pieces)
cursor.execute(executed, executed_data)
connection.commit()
logging.info("new Insert is in DB")
def fetch_clothes():
cursor = connection.cursor()
cursor.execute("SELECT clothes FROM luggage")
clothes = [str(row[0]) for row in cursor.fetchall()]
logging.info("fetched clothes")
return clothes
def update_weight(cloth_type, weight):
cursor = connection.cursor()
executed = "UPDATE luggage SET weight = ? WHERE clothes = ?"
executed_data = (weight, cloth_type)
cursor.execute(executed, executed_data)
connection.commit()
logging.info("weight updated")
def update_pieces(cloth_type, pieces):
if type(pieces) is not int:
logging.error("only ints allowed")
else:
cursor = connection.cursor()
executed = "UPDATE luggage SET pieces = ? WHERE clothes = ?"
executed_data = (pieces, cloth_type)
cursor.execute(executed, executed_data)
connection.commit()
logging.info("pieces updated")
def fetch_weight(cloth_type):
cursor = connection.cursor()
cursor.execute("SELECT weight FROM luggage WHERE clothes = ?", (cloth_type,))
weight = cursor.fetchone()[0]
logging.info("fetched weight")
return weight
def fetch_luggage_weight():
cursor = connection.cursor()
cursor.execute("SELECT sum(weight) FROM luggage")
weight = cursor.fetchone()[0]
logging.info("fetched luggage weight")
return weight
def fetch_piece(cloth_type):
cursor = connection.cursor()
cursor.execute("SELECT pieces FROM luggage WHERE clothes = ?", (cloth_type,))
pieces = cursor.fetchone()[0]
logging.info("fetched luggage pieces")
return pieces
def fetch_all_pieces():
cursor = connection.cursor()
cursor.execute("SELECT sum(pieces) FROM luggage")
pieces = cursor.fetchone()[0]
logging.info("fetched all luggage pieces")
return pieces
def delete(cloth_type):
cursor = connection.cursor()
cursor.execute("DELETE FROM luggage WHERE clothes = ?;", (cloth_type,))
logging.critical(f"{cloth_type} was deleted")
connection.commit()
def check_clothe(clothe_type):
cursor = connection.cursor()
cursor.execute("SELECT (SELECT clothes FROM luggage WHERE clothes = ? LIMIT 1) AS clothes", (clothe_type,))
check = cursor.fetchone()[0]
return check
#using .env
load_dotenv()
db_name = os.getenv("DB_NAME")
@@ -123,4 +30,73 @@ db_host = os.getenv("DB_HOST")
if db_host == None:
logging.error("no hostname provided")
os._exit(1)
connect(db_user, db_psswd, db_host, int(db_port), db_name)
engine = create_engine(f"mariadb+mariadbconnector://{db_user}:{quote_plus(db_psswd)}@{db_host}:{db_port}/{db_name}")
Session = sessionmaker(bind=engine)
session = Session()
def new_part(cloth_type, weight, pieces):
existing = session.query(Items).filter_by(clothes=cloth_type).first()
if existing:
logging.debug("Item already inserted")
else:
if type(pieces) is not int:
print("only ints allowed")
logging.error("only ints allowed")
else:
new_item = Items(clothes=cloth_type, weight=weight, pieces=pieces)
session.add(new_item)
session.commit()
logging.info("new Insert is in DB")
def update_weight(cloth_type, weight):
item = session.query(Items).filter_by(clothes=cloth_type).first()
item.weight = weight
session.commit()
logging.info("weight updated")
def update_pieces(cloth_type, pieces):
if type(pieces) is not int:
logging.error("only ints allowed")
else:
item = session.query(Items).filter_by(clothes=cloth_type).first()
item.pieces = pieces
session.commit()
logging.info("pieces updated")
def delete(cloth_type):
logging.critical(f"{cloth_type} was deleted")
session.query(Items).filter_by(clothes=cloth_type).delete()
session.commit()
def fetch_clothes():
logging.info("fetched clothes")
return [row[0] for row in session.query(Items.clothes).all()]
def fetch_weight(cloth_type):
logging.info("fetched weight")
result = session.query(Items.weight).filter_by(clothes=cloth_type).first()
return result[0] if result else None
def fetch_luggage_weight():
logging.info("fetched whole weight")
result = session.query(func.sum(Items.weight)).scalar()
return result if result else None
def fetch_piece(cloth_type):
logging.info("fetched pieces")
result = session.query(Items.pieces).filter_by(clothes=cloth_type).first()
return result[0] if result else None
def fetch_all_pieces():
logging.info("fetched all pieces")
result = session.query(Items.pieces).all()
return [row[0] for row in session.query(Items.pieces).all()]
#Checks if clothe is in db
def check_clothe(clothe_type):
exists = session.query(Items.clothes).filter_by(clothes=clothe_type).first() is not None
return exists
View File
+50
View File
@@ -0,0 +1,50 @@
import threading
from watchdog.events import PatternMatchingEventHandler
from watchdog.observers import Observer
import os
import time
FLAGS_DIR = os.path.dirname(os.path.abspath(__file__))
class FlagHandler(PatternMatchingEventHandler):
def __init__(self, shared_state, lock):
super().__init__(patterns=["*.flag"], ignore_directories=True)
self.shared_state = shared_state
self.lock = lock
def on_created(self, event):
try:
with open(event.src_path, "r") as f:
content = f.read().strip()
except FileNotFoundError:
return
try:
os.remove(event.src_path)
except FileNotFoundError:
pass
with self.lock:
self.shared_state["current"] = content
time.sleep(2)
shared_state = {"current": None}
lock = threading.Lock()
observer = Observer()
observer.schedule(FlagHandler(shared_state, lock), path=FLAGS_DIR, recursive=False)
observer.start()
def get_status():
with lock:
current = shared_state["current"]
if current == "db_check_done":
return False
return current
def get_migration():
with lock:
current = shared_state["current"]
if current == "migration_done":
return True
return False
+57 -8
View File
@@ -2,12 +2,17 @@ import logging
import subprocess
import sys
import os
import auth.api_security as auth
import time
import threading
from tests import db_test
open("api.log", "w").close()
open("app.log", "w").close()
open("api_server.log", "w").close()
try:
os.remove("api.log")
os.remove("api_server.log")
os.remove("app.log")
except Exception as e:
logging.error(e)
#Logging
logging.basicConfig(
filename='app.log', # Log to a file
@@ -25,15 +30,59 @@ except Exception as e:
env = os.environ.copy()
env["PYTHONIOENCODING"] = "utf-8"
try:
os.remove("migration_status.flag")
except Exception as e:
logging.info(e)
#migration
def run_migration():
global migration_done
process = subprocess.Popen(
["python", "migration/alembic_scipt.py"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
process.wait()
migration_done = (process.returncode == 0)
with open("flags/migration_status.flag", "w") as f:
f.write("migration_done" if migration_done else "failed")
#DB test
def run_db_test():
tokens = db_test.test_table("tokens", ["tokens", "time", "end_date"])
user = db_test.test_table("user", ["username", "password", "role"])
items = db_test.test_table("luggage", ["clothes", "weight", "pieces"])
time.sleep(5)
if tokens == True & user == True & items == True:
with open("flags/db.flag", "w") as f:
f.write("db_check_done")
else:
os._exit(1)
#cli and api
log_file = open("api_server.log", "w", encoding="utf-8")
api_process = subprocess.Popen(
["fastapi", "dev", "api_server.py"],
["fastapi", "dev", "api_server.py", "--reload-dir", "web", "--reload-dir", "api", "--reload-dir", "api_server.py",],
stdout=log_file,
stderr=log_file,
env=env
)
cli_process = subprocess.Popen([sys.executable, "cli.py"])
api_process.wait()
cli_process.wait()
db_thread = threading.Thread(target=run_db_test)
db_thread.start()
thread = threading.Thread(target=run_migration)
thread.start()
threading.Thread(target=api_process.wait, daemon=True).start()
threading.Thread(target=cli_process.wait, daemon=True).start()
# automatic durataion validation check
while True:
time.sleep(300)
try:
auth.check_validaty()
except Exception as e:
logging.info(e)
+1
View File
@@ -0,0 +1 @@
Generic single-database configuration.
+67
View File
@@ -0,0 +1,67 @@
import os
from alembic.config import Config
from alembic.script import ScriptDirectory
from alembic.runtime.migration import MigrationContext
from alembic import command
from sqlalchemy import create_engine
from alembic import command
from dotenv import load_dotenv
import logging
#Logging
logging.basicConfig(
filename='app.log', # Log to a file
level=logging.DEBUG, # Log everything (DEBUG and above)
format='%(asctime)s %(levelname)s %(message)s'
)
logging.info('Application started')
try:
logging.debug('Debug info here')
except Exception as e:
logging.exception('An error occurred')
load_dotenv()
db_name = os.getenv("DB_NAME")
db_psswd = os.getenv("DB_PASSWORD")
db_user = os.getenv("DB_USER")
db_port = os.getenv("DB_PORT") or "3306"
db_host = os.getenv("DB_HOST")
if db_host == None:
os._exit(1)
engine_url = f"mariadb+mariadbconnector://{db_user}:{db_psswd}@{db_host}:{db_port}/{db_name}"
base_dir = os.path.dirname(__file__)
ini_path = os.path.join(base_dir, "..", "alembic.ini")
alembic_cfg = Config(ini_path)
alembic_cfg.set_section_option(alembic_cfg.config_ini_section, "sqlalchemy.url", engine_url)
script = ScriptDirectory.from_config(alembic_cfg)
engine = create_engine(engine_url)
def check_db():
with engine.connect() as conn:
context = MigrationContext.configure(conn)
current_rev = context.get_current_revision()
head_rev = script.get_current_head()
if current_rev != head_rev:
command.upgrade(alembic_cfg, "head")
return False
def auto_lookup():
command.revision(alembic_cfg, message="add tables and rows", autogenerate=True)
script = ScriptDirectory.from_config(alembic_cfg)
head_rev = script.get_revision(script.get_current_head())
with open(head_rev.path) as f:
content = f.read()
if "pass\n # ### end Alembic commands ###" in content:
os.remove(head_rev.path)
command.stamp(alembic_cfg, "head")
logging.info("No changes DB detected")
else:
command.upgrade(alembic_cfg, "head")
logging.info("New DB changes, upgrade table")
auto_lookup()
+84
View File
@@ -0,0 +1,84 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from models import Base
metadata = Base.metadata
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
if config.config_file_name is not None:
fileConfig(config.config_file_name)
+28
View File
@@ -0,0 +1,28 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}
+1
View File
@@ -0,0 +1 @@
from .models import Items, Tokens, User, Base
+23
View File
@@ -0,0 +1,23 @@
from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, String, Numeric, Integer
Base = declarative_base()
class Tokens(Base):
__tablename__ = "tokens"
tokens = Column(String(255), primary_key=True)
time = Column(String(255))
end_date = Column(String(255))
class Items(Base):
__tablename__ = "luggage"
clothes = Column(String(50), primary_key=True)
weight = Column(Numeric(20, 2))
pieces = Column(Integer)
class User(Base):
__tablename__ = "user"
username = Column(String(50), primary_key=True)
password = Column(String(255))
role = Column(String(50))
+8 -1
View File
@@ -1,3 +1,10 @@
mariadb == 1.1.14
python-dotenv == 1.2.3
fastapi[standard] == 0.141.1
argon2-cffi == 25.1.0
Jinja2==3.1.6
MarkupSafe==3.0.3
itsdangerous==2.2.0
alembic==1.20.0
SQLAlchemy==2.0.54
watchdog==6.0.0
#watchfiles==1.2.0
+36
View File
@@ -0,0 +1,36 @@
from migration.alembic_scipt import auto_lookup
import time
import logging
import auth.api_security as auth
import os
#Logging
logging.basicConfig(
filename='app.log', # Log to a file
level=logging.DEBUG, # Log everything (DEBUG and above)
format='%(asctime)s %(levelname)s %(message)s'
)
logging.info('Application started')
try:
logging.debug('Debug info here')
except Exception as e:
logging.exception('An error occurred')
def new_table():
auto_lookup()
def admin():
token = auth.admin_token()
print(token)
logging.info(token)
time.sleep(300)
os.remove("app.log")
os._exit(1)
new_table()
admin()
+46
View File
@@ -0,0 +1,46 @@
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
import os
import db
import logging
import sys
from migration import alembic_scipt as alembic
from sqlalchemy import inspect
session = db.session
engine = db.engine
def test_column(engine, tablename, row):
try:
inspector = inspect(engine)
columns = [col["name"] for col in inspector.get_columns(tablename)]
return row in columns
except Exception as e:
logging.error(e)
def test_table(table, columns):
for column in columns:
try:
exists = test_column(engine, table, column)
if exists == False:
logging.error(f"DB has not all columns. {column} is missing")
print(f"Column {column} is missing")
sys.exit()
os._exit(1)
return False
else:
logging.info("Column fine")
except Exception as e:
logging.error(e)
return True
def migration_check():
if alembic.check_db() == False:
print("migrating")
logging.info("DB is migrating")