Skip to content

Commit 2df5597

Browse files
committed
JWT Implementation done
1 parent 21ba8d4 commit 2df5597

File tree

2 files changed

+26
-23
lines changed

2 files changed

+26
-23
lines changed

routes/api.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1+
from typing import Annotated
2+
13
from starlette.responses import JSONResponse
24

35
from app.controllers import authController
4-
from fastapi import APIRouter, status
6+
from fastapi import APIRouter, status, Depends
57

68
from app.dto.CreateUserDto import CreateUserDto
79
from app.dto.LoginUserDto import LoginUserDto
10+
from utilities.jwtUtils import validate_token
811

912
router = APIRouter(
1013
prefix="/api",
@@ -24,4 +27,10 @@ async def registerUser(bodyRequest: CreateUserDto):
2427
@router.post("/login", status_code=status.HTTP_200_OK, response_class=JSONResponse)
2528
async def login(bodyRequest: LoginUserDto):
2629
response = await authController.login(body=bodyRequest)
27-
return response
30+
return response
31+
32+
@router.post("/validate-token", status_code=status.HTTP_200_OK, response_class=JSONResponse, dependencies=[Depends(validate_token)])
33+
async def login():
34+
return {
35+
"message": "Token valid"
36+
}

utilities/jwtUtils.py

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
from datetime import datetime, timedelta, timezone
2-
from typing import Annotated, Union
2+
from typing import Annotated, Union, Any
33

44
import jwt, os
55
from dotenv import load_dotenv
66
from fastapi import Depends, FastAPI, HTTPException, status
7-
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
7+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
88
from jwt.exceptions import InvalidTokenError
99
from passlib.context import CryptContext
1010
from pydantic import BaseModel
@@ -15,7 +15,7 @@
1515
ALGORITHM = os.getenv("HASH_ALGORITHM")
1616
ACCESS_TOKEN_EXPIRE_MINUTES = 30
1717

18-
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
18+
oauth2_scheme = HTTPBearer(scheme_name="JWT")
1919

2020
class 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

Comments
 (0)