add user auth boilerplate
This commit is contained in:
parent
4a65664f4a
commit
4ad04775c9
8 changed files with 275 additions and 4 deletions
|
|
@ -1,14 +1,31 @@
|
|||
from fastapi import FastAPI
|
||||
from typing import Annotated
|
||||
from fastapi import Depends, FastAPI, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from models.user import User
|
||||
from repositories.listing_repository import ListingRepository
|
||||
from repositories.listing_repository import ListingRepository
|
||||
from database import engine
|
||||
from repositories.user_repository import UserRepository
|
||||
|
||||
|
||||
app = FastAPI()
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
||||
|
||||
|
||||
async def decode_token(token: Annotated[str, Depends(oauth2_scheme)]):
|
||||
repository = UserRepository(engine)
|
||||
user = await repository.get_user_from_token(token)
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid authentication credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
@app.get("/listing")
|
||||
async def get_listing():
|
||||
async def get_listing(user: Annotated[User | None, Depends(decode_token)]):
|
||||
repository = ListingRepository(engine)
|
||||
listings = await repository.get_listings()
|
||||
return {"listings": listings}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue