11from datetime import datetime , timedelta , timezone
2- from typing import Annotated , Union
2+ from typing import Annotated , Union , Any
33
44import jwt , os
55from dotenv import load_dotenv
66from fastapi import Depends , FastAPI , HTTPException , status
7- from fastapi .security import OAuth2PasswordBearer , OAuth2PasswordRequestForm
7+ from fastapi .security import HTTPBearer , HTTPAuthorizationCredentials
88from jwt .exceptions import InvalidTokenError
99from passlib .context import CryptContext
1010from pydantic import BaseModel
1515ALGORITHM = os .getenv ("HASH_ALGORITHM" )
1616ACCESS_TOKEN_EXPIRE_MINUTES = 30
1717
18- oauth2_scheme = OAuth2PasswordBearer ( tokenUrl = "token " )
18+ oauth2_scheme = HTTPBearer ( scheme_name = "JWT " )
1919
2020class TokenData (BaseModel ):
2121 username : Union [str , None ] = None
@@ -33,21 +33,15 @@ def create_access_token(payload: dict, expires_delta: Union[timedelta, None] = N
3333 encoded_jwt = jwt .encode (to_encode , SECRET_KEY , algorithm = ALGORITHM )
3434 return encoded_jwt
3535
36- # async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
37- # credentials_exception = HTTPException(
38- # status_code=status.HTTP_401_UNAUTHORIZED,
39- # detail="Could not validate credentials",
40- # headers={"WWW-Authenticate": "Bearer"},
41- # )
42- # try:
43- # payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
44- # username: str = payload.get("sub")
45- # if username is None:
46- # raise credentials_exception
47- # token_data = TokenData(username=username)
48- # except InvalidTokenError:
49- # raise credentials_exception
50- # user = get_user(fake_users_db, username=token_data.username)
51- # if user is None:
52- # raise credentials_exception
53- # return user
36+ def validate_token (token : Annotated [HTTPAuthorizationCredentials , Depends (oauth2_scheme )]):
37+ try :
38+ payload = jwt .decode (token .credentials , SECRET_KEY , algorithms = [ALGORITHM ])
39+ user_id : int = payload .get ("user_id" )
40+ if user_id is None :
41+ raise InvalidTokenError
42+ except InvalidTokenError :
43+ raise HTTPException (
44+ status_code = status .HTTP_401_UNAUTHORIZED ,
45+ detail = "Token Invalid or Expired" ,
46+ headers = {"WWW-Authenticate" : "Bearer" },
47+ )
0 commit comments