Compare commits
17
Commits
5a692f9dd9
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
087fed017a | ||
|
|
220a06208a | ||
|
|
d268cb01d5 | ||
|
|
98e9b28bae | ||
|
|
12485792d2 | ||
|
|
c3ce9b88a2 | ||
|
|
cfe8a0e22d | ||
|
|
c0108fd1e1 | ||
|
|
c105c36086 | ||
|
|
f5919b2845 | ||
|
|
83c288d490 | ||
|
|
f697a0aca3 | ||
|
|
1605757c80 | ||
|
|
06915f0758 | ||
|
|
7a87b0e793 | ||
|
|
89b8b246f9 | ||
|
|
da1d4e9e89 |
@@ -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"
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
#database
|
||||||
|
DB_NAME=
|
||||||
|
#Credentials
|
||||||
|
DB_PASSWORD=
|
||||||
|
DB_USER=
|
||||||
|
#Host Settings
|
||||||
|
DB_PORT= #standard 3306
|
||||||
|
DB_HOST=
|
||||||
+49
-1
@@ -1,3 +1,51 @@
|
|||||||
__pycache__/
|
start.sh
|
||||||
|
update.sh
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
Desktop.ini
|
||||||
|
|
||||||
|
# Editors / IDEs
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
|
||||||
|
# Logs
|
||||||
*.log
|
*.log
|
||||||
|
logs/
|
||||||
|
|
||||||
|
# Env / secrets
|
||||||
.env
|
.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
@@ -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
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
from fastapi import APIRouter, HTTPException
|
from fastapi import APIRouter, HTTPException, Depends, Header
|
||||||
import logging
|
import logging
|
||||||
import db
|
import db
|
||||||
|
import auth.api_security as auth
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
from api import tokens
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
#Logging
|
#Logging
|
||||||
@@ -42,8 +46,11 @@ class Item_weight(BaseModel):
|
|||||||
class Item_piece(BaseModel):
|
class Item_piece(BaseModel):
|
||||||
pieces: int
|
pieces: int
|
||||||
|
|
||||||
|
class Item_duration(BaseModel):
|
||||||
|
duration: str
|
||||||
|
|
||||||
@router.post("/insert", status_code=201)
|
@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()
|
name = item_name.name_of_clothes.upper()
|
||||||
weight = item_weight.weight
|
weight = item_weight.weight
|
||||||
pieces = item_pieces.pieces
|
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)
|
@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()
|
name = clothe_name.upper()
|
||||||
pieces = item_pieces.pieces
|
pieces = item_pieces.pieces
|
||||||
if db.check_clothe(name) != None:
|
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)
|
@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()
|
name = clothe_name.upper()
|
||||||
weight = item.weight
|
weight = item.weight
|
||||||
if db.check_clothe(name) != None:
|
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)
|
@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()
|
name = clothe_name.upper()
|
||||||
if db.check_clothe(name) != None:
|
if db.check_clothe(name) != None:
|
||||||
db.delete(name)
|
db.delete(name)
|
||||||
@@ -91,3 +98,5 @@ def delete(clothe_name: str):
|
|||||||
else:
|
else:
|
||||||
logging.error(f"Item {name} not found")
|
logging.error(f"Item {name} not found")
|
||||||
raise HTTPException(status_code=404, detail=f"Item {name} not found")
|
raise HTTPException(status_code=404, detail=f"Item {name} not found")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -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
@@ -1,7 +1,8 @@
|
|||||||
from fastapi import FastAPI
|
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(health.router)
|
||||||
app.include_router(db.router)
|
app.include_router(db.router)
|
||||||
app.include_router(query.router)
|
app.include_router(query.router)
|
||||||
|
app.include_router(tokens.router)
|
||||||
@@ -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)
|
||||||
@@ -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
|
||||||
@@ -3,6 +3,7 @@ import logging
|
|||||||
import time
|
import time
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
from flags import status
|
||||||
|
|
||||||
|
|
||||||
print("loading")
|
print("loading")
|
||||||
@@ -177,7 +178,7 @@ def menu():
|
|||||||
|
|
||||||
|
|
||||||
#The Terminal App Starts here
|
#The Terminal App Starts here
|
||||||
time.sleep(5)
|
time.sleep(2)
|
||||||
print(r"""
|
print(r"""
|
||||||
## ## ##########
|
## ## ##########
|
||||||
### ### ## ##
|
### ### ## ##
|
||||||
@@ -186,6 +187,8 @@ print(r"""
|
|||||||
## ## ## ## ##
|
## ## ## ## ##
|
||||||
## ## ## ##
|
## ## ## ##
|
||||||
""")
|
""")
|
||||||
|
while not status.get_migration():
|
||||||
|
time.sleep(0.5)
|
||||||
logging.info("Menu is starting")
|
logging.info("Menu is starting")
|
||||||
time.sleep(2.5)
|
time.sleep(2.5)
|
||||||
menu()
|
menu()
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
import mariadb
|
|
||||||
import logging
|
import logging
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
import os
|
import os
|
||||||
|
from models import Items
|
||||||
|
from sqlalchemy import create_engine, func
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
from urllib.parse import quote_plus
|
||||||
|
|
||||||
#Logging
|
#Logging
|
||||||
|
|
||||||
@@ -17,102 +20,6 @@ try:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.exception('An error occurred')
|
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
|
#using .env
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
db_name = os.getenv("DB_NAME")
|
db_name = os.getenv("DB_NAME")
|
||||||
@@ -123,4 +30,73 @@ db_host = os.getenv("DB_HOST")
|
|||||||
if db_host == None:
|
if db_host == None:
|
||||||
logging.error("no hostname provided")
|
logging.error("no hostname provided")
|
||||||
os._exit(1)
|
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
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -2,12 +2,17 @@ import logging
|
|||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import os
|
import os
|
||||||
|
import auth.api_security as auth
|
||||||
|
import time
|
||||||
|
import threading
|
||||||
|
from tests import db_test
|
||||||
|
|
||||||
|
try:
|
||||||
open("api.log", "w").close()
|
os.remove("api.log")
|
||||||
open("app.log", "w").close()
|
os.remove("api_server.log")
|
||||||
open("api_server.log", "w").close()
|
os.remove("app.log")
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(e)
|
||||||
#Logging
|
#Logging
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
filename='app.log', # Log to a file
|
filename='app.log', # Log to a file
|
||||||
@@ -25,15 +30,59 @@ except Exception as e:
|
|||||||
env = os.environ.copy()
|
env = os.environ.copy()
|
||||||
env["PYTHONIOENCODING"] = "utf-8"
|
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")
|
log_file = open("api_server.log", "w", encoding="utf-8")
|
||||||
api_process = subprocess.Popen(
|
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,
|
stdout=log_file,
|
||||||
stderr=log_file,
|
stderr=log_file,
|
||||||
env=env
|
env=env
|
||||||
)
|
)
|
||||||
cli_process = subprocess.Popen([sys.executable, "cli.py"])
|
cli_process = subprocess.Popen([sys.executable, "cli.py"])
|
||||||
|
|
||||||
api_process.wait()
|
db_thread = threading.Thread(target=run_db_test)
|
||||||
cli_process.wait()
|
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)
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
Generic single-database configuration.
|
||||||
@@ -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()
|
||||||
@@ -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)
|
||||||
@@ -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"}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
from .models import Items, Tokens, User, Base
|
||||||
@@ -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
@@ -1,3 +1,10 @@
|
|||||||
mariadb == 1.1.14
|
|
||||||
python-dotenv == 1.2.3
|
python-dotenv == 1.2.3
|
||||||
fastapi[standard] == 0.141.1
|
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
|
||||||
@@ -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()
|
||||||
|
|
||||||
@@ -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")
|
||||||
Reference in New Issue
Block a user