Skip to content

Commit

Permalink
Validate refresh token
Browse files Browse the repository at this point in the history
  • Loading branch information
jonra1993 committed Oct 7, 2022
1 parent c7c38d5 commit 33862a1
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 12 deletions.
3 changes: 2 additions & 1 deletion fastapi-alembic-sqlmodel-async/app/api/deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from app.utils.minio_client import MinioClient
import aioredis
from aioredis import Redis
from app.schemas.common_schema import TokenType

reusable_oauth2 = OAuth2PasswordBearer(
tokenUrl=f"{settings.API_V1_STR}/login/access-token"
Expand Down Expand Up @@ -58,7 +59,7 @@ async def current_user(
detail="Could not validate credentials",
)
user_id = payload["sub"]
access_token_key = f"user:{user_id}:access_token"
access_token_key = f"user:{user_id}:{TokenType.ACCESS}"
valid_access_tokens = await redis_client.smembers(access_token_key)
if valid_access_tokens and token not in valid_access_tokens:
raise HTTPException(
Expand Down
27 changes: 16 additions & 11 deletions fastapi-alembic-sqlmodel-async/app/api/v1/endpoints/login.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from datetime import timedelta
from typing import Any
from typing import Any, Optional
from fastapi import APIRouter, Body, Depends, HTTPException
from app.schemas.common_schema import TokenType
from app.core.security import get_password_hash
from app.core.security import verify_password
from app.models.user_model import User
Expand All @@ -21,19 +22,17 @@
router = APIRouter()


class TokenType(str, Enum):
ACCESS = "access_token"
REFRESH = "refresh_token"


async def add_token_to_redis(
redis_client: Redis, user: User, token: str, token_type: TokenType, expire_time: int
redis_client: Redis,
user: User,
token: str,
token_type: TokenType,
expire_time: Optional[int] = None,
):
token_key = f"user:{user.id}:{token_type}"
print("token_key", token_key)
await redis_client.sadd(token_key, token)
await redis_client.expire(token_key, expire_time)
print("done")
if expire_time:
await redis_client.expire(token_key, expire_time)


async def delete_tokens(redis_client: Redis, user: User, token_type: TokenType):
Expand Down Expand Up @@ -160,8 +159,14 @@ async def get_refresh_token(
raise HTTPException(status_code=403, detail="Refresh token invalid")

if payload["type"] == "refresh":
user_id = payload["sub"]
refresh_token_key = f"user:{user_id}:{TokenType.REFRESH}"
valid_refresh_tokens = await redis_client.smembers(refresh_token_key)
if valid_refresh_tokens and body.refresh_token not in valid_refresh_tokens:
raise HTTPException(status_code=403, detail="Refresh token invalid")

access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
user = await crud.user.get(id=payload["sub"])
user = await crud.user.get(id=user_id)
if user.is_active:
access_token = security.create_access_token(
payload["sub"], expires_delta=access_token_expires
Expand Down
5 changes: 5 additions & 0 deletions fastapi-alembic-sqlmodel-async/app/schemas/common_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,8 @@ class IMetaGeneral(BaseModel):
class IOrderEnum(str, Enum):
ascendent = "ascendent"
descendent = "descendent"


class TokenType(str, Enum):
ACCESS = "access_token"
REFRESH = "refresh_token"

0 comments on commit 33862a1

Please sign in to comment.