Skip to content

Commit

Permalink
fix type hints
Browse files Browse the repository at this point in the history
  • Loading branch information
deepmancer committed Aug 13, 2024
1 parent a8c7f1d commit 2bf67dd
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 5 deletions.
10 changes: 5 additions & 5 deletions fastapi_auth_jwt/repository/local.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from datetime import datetime, timedelta
from typing import Any, Optional
from typing import Any, Optional, Dict

from ..config.storage import StorageConfig
from ..config.types import EXPIRATION_DTYPE
Expand All @@ -16,8 +16,8 @@ class LocalRepository(BaseRepository):
allows retrieving and deleting stored values.
Attributes:
_store (dict): The dictionary that stores key-value pairs.
_expirations (dict): A dictionary that keeps track of expiration times for keys.
_store (Dict[str, Any]): The dictionary that stores key-value pairs.
_expirations (Dict[str, datetime]): A dictionary that keeps track of expiration times for keys.
_config (StorageConfig): Configuration object for the repository.
"""

Expand All @@ -28,8 +28,8 @@ def __init__(self, config: StorageConfig):
Args:
config (StorageConfig): The configuration object for the repository.
"""
self._store: dict[str, Any] = {}
self._expirations: dict[str, datetime] = {}
self._store: Dict[str, Any] = {}
self._expirations: Dict[str, datetime] = {}
self._config: StorageConfig = config

@property
Expand Down
78 changes: 78 additions & 0 deletions testing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@

from fastapi import FastAPI, HTTPException, Request
from typing import Optional
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from starlette.testclient import TestClient
from starlette.responses import Response
from starlette.requests import Request

from fastapi_auth_jwt import JWTAuthBackend
from fastapi_auth_jwt import JWTAuthenticationMiddleware


app = FastAPI()

# The application specific user schema
class User(BaseModel):
username: str
password: str

# just add a token field to the user schema if you want to persist the token
token: Optional[str] = Field(None)

class RegisterSchema(BaseModel):
username: str
password: str
# some other fields

class LoginSchema(BaseModel):
username: str
password: str

# in production you can use Settings management
# from pydantic to get secret key from .env
class AuthenticationSettings(BaseModel):
secret: str = "secret"
jwt_algorithm: str = "HS256"
expiration_seconds: int = 60 * 60 # 1 hour

auth_backend = JWTAuthBackend(
authentication_config=AuthenticationSettings(),
user_schema=User,
# if want to use redis, you can pass the storage_config using the fastapi_auth_jwt.RedisConfig
)

app.add_middleware(
JWTAuthenticationMiddleware,
backend=auth_backend,
exclude_urls=["/sign-up", "/login"],
)


@app.post("/sign-up")
async def sign_up(request_data: RegisterSchema):
return {"message": "User created"}

@app.post("/login")
async def login(request_data: LoginSchema):
# Check credentials
user = User(username=request_data.username, password=request_data.password)
token = await auth_backend.create_token(user) # creates and persists a token with expirtion of 1 hour
return {"token": token}

@app.get("/profile-info")
async def get_profile_info(request: Request):
user: User = request.state.user
# ptint(user)
# >>> User(username='some_username', password='some_password', token='some_token)
return {"username": user.username}

# api for logout which invalidates the token
@app.post("/logout")
async def logout(request: Request):
user: User = request.state.user
await auth_backend.invalidate_token(user.token)
return {"message": "Logged out"}


0 comments on commit 2bf67dd

Please sign in to comment.