Добавил авторизацию

This commit is contained in:
2024-12-16 12:14:18 +03:00
parent b2699db727
commit bb60b5509c
3 changed files with 49 additions and 7 deletions

3
.gitignore vendored
View File

@@ -4,4 +4,5 @@ __pycache__
*.log
venv
.venv
.venv
token.json

50
main.py
View File

@@ -1,8 +1,11 @@
from fastapi import FastAPI, HTTPException, Depends
from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError
from database import engine, SessionLocal, Base
from fastapi import FastAPI, HTTPException, Depends, Security
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
import json
import models
import os
import schemas
from sqlalchemy import select, update
@@ -25,8 +28,31 @@ def get_db():
finally:
db.close()
# Базовая авторизация через Bearer токен
security = HTTPBearer()
TOKEN: str = None
THIS_SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(THIS_SCRIPT_PATH, "token.json"), 'r') as f:
t = json.load(f)
TOKEN = t["auth.token"]
def get_current_user(credentials: HTTPAuthorizationCredentials = Security(security)):
if credentials.credentials != TOKEN:
raise HTTPException(status_code=401, detail="Invalid or missing token")
return credentials.credentials
@app.post("/{namespace}/{application}/{version}", response_model=schemas.CounterResponse, summary="Инкрементировать счетчик и получить новое значение")
def increment_counter(namespace: str, application: str, version: str, db: Session = Depends(get_db)):
def increment_counter(
namespace: str,
application: str,
version: str,
db: Session = Depends(get_db),
user: str = Depends(get_current_user)
):
try:
# Попытка найти существующий счетчик
counter = db.query(models.Counter).filter_by(
@@ -56,7 +82,13 @@ def increment_counter(namespace: str, application: str, version: str, db: Sessio
raise HTTPException(status_code=500, detail="Ошибка при доступе к базе данных.")
@app.get("/{namespace}/{application}/{version}", response_model=schemas.CounterResponse, summary="Получить текущее значение счетчика")
def get_counter(namespace: str, application: str, version: str, db: Session = Depends(get_db)):
def get_counter(
namespace: str,
application: str,
version: str,
db: Session = Depends(get_db),
user: str = Depends(get_current_user)
):
counter = db.query(models.Counter).filter_by(
namespace=namespace,
application=application,
@@ -75,7 +107,13 @@ def get_counter(namespace: str, application: str, version: str, db: Session = De
return counter
@app.delete("/{namespace}/{application}/{version}", response_model=schemas.CounterResponse, summary="Сбросить счетчик до 0")
def reset_counter(namespace: str, application: str, version: str, db: Session = Depends(get_db)):
def reset_counter(
namespace: str,
application: str,
version: str,
db: Session = Depends(get_db),
user: str = Depends(get_current_user)
):
counter = db.query(models.Counter).filter_by(
namespace=namespace,
application=application,

3
token.json.in Normal file
View File

@@ -0,0 +1,3 @@
{
"auth.token": ""
}