Skip to content

Commit

Permalink
On auth success, store user token
Browse files Browse the repository at this point in the history
  • Loading branch information
raphodn committed Nov 12, 2023
1 parent eddcc5f commit 9b92767
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
4 changes: 4 additions & 0 deletions app/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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
Expand Down
36 changes: 36 additions & 0 deletions app/crud.py
Original file line number Diff line number Diff line change
@@ -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
9 changes: 9 additions & 0 deletions app/schemas.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 9b92767

Please sign in to comment.