diff --git a/app/api.py b/app/api.py index 83b6ebea..e3a4d035 100644 --- a/app/api.py +++ b/app/api.py @@ -17,8 +17,10 @@ from fastapi.templating import Jinja2Templates from openfoodfacts.utils import get_logger +from app import crud from app.config import settings from app.db import session +from app.schemas import UserBase from app.utils import init_sentry @@ -97,6 +99,8 @@ async def authentication(form_data: Annotated[OAuth2PasswordRequestForm, Depends r = requests.post(settings.oauth2_server_url, data=data) # type: ignore if r.status_code == 200: token = await create_token(form_data.username) + user: UserBase = {"user_id": form_data.username, "token": token} # type: ignore + crud.create_user(db, user=user) # type: ignore return {"access_token": token, "token_type": "bearer"} elif r.status_code == 403: time.sleep(2) # prevents brute-force diff --git a/app/crud.py b/app/crud.py new file mode 100644 index 00000000..16ca652f --- /dev/null +++ b/app/crud.py @@ -0,0 +1,36 @@ +from sqlalchemy.orm import Session + +from app.models import User +from app.schemas import UserBase + + +def get_user(db: Session, user_id: str): + return db.query(User).filter(User.user_id == user_id).first() + + +def get_user_by_user_id(db: Session, user_id: str): + return db.query(User).filter(User.user_id == user_id).first() + + +def get_user_by_token(db: Session, token: str): + return db.query(User).filter(User.token == token).first() + + +def create_user(db: Session, user: UserBase): + # first we delete any existing user + delete_user(db, user_id=user["user_id"]) + # then we (re)create a user + db_user = User(user_id=user["user_id"], token=user["token"]) + db.add(db_user) + db.commit() + db.refresh(db_user) + return db_user + + +def delete_user(db: Session, user_id: UserBase): + db_user = get_user_by_user_id(db, user_id=user_id) + if db_user: + db.delete(db_user) + db.commit() + return True + return False diff --git a/app/schemas.py b/app/schemas.py new file mode 100644 index 00000000..b795f3bc --- /dev/null +++ b/app/schemas.py @@ -0,0 +1,9 @@ +from pydantic import BaseModel +from pydantic import ConfigDict + + +class UserBase(BaseModel): + model_config = ConfigDict(from_attributes=True) + + user_id: str + token: str