1
1
from datetime import datetime , timedelta , timezone
2
- from typing import Annotated , Union
2
+ from typing import Annotated , Union , Any
3
3
4
4
import jwt , os
5
5
from dotenv import load_dotenv
6
6
from fastapi import Depends , FastAPI , HTTPException , status
7
- from fastapi .security import OAuth2PasswordBearer , OAuth2PasswordRequestForm
7
+ from fastapi .security import HTTPBearer , HTTPAuthorizationCredentials
8
8
from jwt .exceptions import InvalidTokenError
9
9
from passlib .context import CryptContext
10
10
from pydantic import BaseModel
15
15
ALGORITHM = os .getenv ("HASH_ALGORITHM" )
16
16
ACCESS_TOKEN_EXPIRE_MINUTES = 30
17
17
18
- oauth2_scheme = OAuth2PasswordBearer ( tokenUrl = "token " )
18
+ oauth2_scheme = HTTPBearer ( scheme_name = "JWT " )
19
19
20
20
class TokenData (BaseModel ):
21
21
username : Union [str , None ] = None
@@ -33,21 +33,15 @@ def create_access_token(payload: dict, expires_delta: Union[timedelta, None] = N
33
33
encoded_jwt = jwt .encode (to_encode , SECRET_KEY , algorithm = ALGORITHM )
34
34
return encoded_jwt
35
35
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