From ea4ae48b234a2daa644b3d73be2d8d5b9b71d485 Mon Sep 17 00:00:00 2001 From: agatha Date: Sat, 6 Apr 2024 15:29:08 -0400 Subject: [PATCH] add jwt validation --- backend/routers/auth.py | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/backend/routers/auth.py b/backend/routers/auth.py index a5f1081..9d1aed4 100644 --- a/backend/routers/auth.py +++ b/backend/routers/auth.py @@ -1,12 +1,12 @@ from datetime import timedelta, datetime from typing import Annotated -from fastapi import APIRouter, Depends +from fastapi import APIRouter, Depends, HTTPException from pydantic import BaseModel from passlib.context import CryptContext from sqlalchemy.orm import Session from starlette import status -from fastapi.security import OAuth2PasswordRequestForm -from jose import jwt +from fastapi.security import OAuth2PasswordRequestForm, OAuth2PasswordBearer +from jose import jwt, JWTError from models import User from database import SessionLocal @@ -17,6 +17,7 @@ SECRET_KEY = '3b004eeae34b43bd05226f210d9bdc2ad99abdd3c52bf32802906085b762ff55' ALGORITHM = 'HS256' bcrypt_context = CryptContext(schemes=['bcrypt'], deprecated='auto') +oauth2_bearer = OAuth2PasswordBearer(tokenUrl='validate') def get_db(): @@ -58,6 +59,19 @@ class Token(BaseModel): token_type: str +async def get_current_user(token: Annotated[str, Depends(oauth2_bearer)]): + try: + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + username: str = payload.get('sub') + user_id: int = payload.get('id') + if username is None or user_id is None: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials") + + return {'username': username, 'user_id': user_id} + except JWTError: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials") + + @router.post('/auth/create', status_code=status.HTTP_201_CREATED) async def create_user(db: db_dependency, data: CreateUser): create_user_model = User(