2021-12-03 12:53:55 +00:00
|
|
|
from datetime import timedelta
|
2021-09-13 07:40:43 +00:00
|
|
|
|
|
|
|
|
2021-12-03 12:53:55 +00:00
|
|
|
from fastapi import Depends, FastAPI, HTTPException, status
|
|
|
|
from fastapi.security import OAuth2PasswordRequestForm
|
2021-09-13 07:40:43 +00:00
|
|
|
|
2021-12-03 12:53:55 +00:00
|
|
|
from models import Token, User
|
|
|
|
from auth import get_current_active_user, create_access_token, authenticate_user, fake_users_db, ACCESS_TOKEN_EXPIRE_MINUTES
|
2021-09-12 08:45:44 +00:00
|
|
|
|
|
|
|
app = FastAPI()
|
|
|
|
|
2021-09-13 07:40:43 +00:00
|
|
|
@app.post("/token", response_model=Token)
|
|
|
|
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
|
|
|
|
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
|
|
|
|
if not user:
|
|
|
|
raise HTTPException(
|
|
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
|
|
detail="Incorrect username or password",
|
|
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
|
|
)
|
|
|
|
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
|
|
access_token = create_access_token(
|
|
|
|
data={"sub": user.username}, expires_delta=access_token_expires
|
|
|
|
)
|
|
|
|
return {"access_token": access_token, "token_type": "bearer"}
|
|
|
|
|
|
|
|
|
|
|
|
@app.get("/users/me/", response_model=User)
|
|
|
|
async def read_users_me(current_user: User = Depends(get_current_active_user)):
|
|
|
|
return current_user
|
|
|
|
|
|
|
|
|
|
|
|
@app.get("/users/me/items/")
|
|
|
|
async def read_own_items(current_user: User = Depends(get_current_active_user)):
|
|
|
|
return [{"item_id": "Foo", "owner": current_user.username}]
|