Created
March 19, 2021 07:00
-
-
Save meepoSenpai/8a31e534e240e24fff87fdf65f17f1e8 to your computer and use it in GitHub Desktop.
FastAPI oAuth Demonstration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Entire auth.py for the Auth Routes | |
import jwt | |
from fastapi import APIRouter, Depends | |
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm | |
from ..models import User | |
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth") | |
jwt_secret = "somerandomjwtsecret" | |
router = APIRouter( | |
prefix="/auth", | |
tags=["Auth"] | |
) | |
def decode_token(token: str = Depends(oauth2_scheme)) -> User: | |
decoded_token = dict(jwt.decode(token, jwt_secret, algorithms=['HS256'])) | |
return User.find_by_id(decoded_token["id"]) | |
@router.post("/") | |
def authenticate(form_data: OAuth2PasswordRequestForm = Depends()): | |
if user := User.authenticate(username=form_data.username, password=form_data.password): | |
token = jwt.encode({"id": user.id, "name": user.name}, jwt_secret) | |
return {"access_token": token, "token_type": "bearer"} | |
return {"Error": "Username or Password incorrect"} | |
# Example of a function that requires Auth | |
@router.put("/create", response_model=schemas.Todo) | |
async def create_todo(todo: schemas.Todo, user: User = Depends(decode_token)): | |
todo = models.Todo.create(owner=user.id, title=todo.title, note=todo.note or "", todo_list=todo.todo_list or "") | |
return todo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment