Coverage for app/core/depends/jwt_data_depends.py: 100%
18 statements
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-15 01:44 +0000
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-15 01:44 +0000
1from datetime import timedelta
2from typing import Annotated, Any
4from fastapi import Depends, Request
6# from fastapi.security import OAuth2PassewordBearer # 余計なものが多いので一旦使わない
7from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
8from fastapi.security.utils import get_authorization_scheme_param
10from app.ddd.infrastructure.auth import create_access_token, get_jwt_data
13class DummyHTTPBearer(HTTPBearer):
14 async def __call__(
15 self, request: Request
16 ) -> HTTPAuthorizationCredentials | None:
17 """
18 開発用認証.
20 認証がないときはguestのインスタントトークン認証を使う
21 """
22 authorization = request.headers.get("Authorization")
23 scheme, credentials = get_authorization_scheme_param(authorization)
24 if not (authorization and scheme and credentials):
25 access_token_expires = timedelta(minutes=1)
26 access_token = create_access_token(
27 data={"sub": "guest"},
28 expires_delta=access_token_expires
29 )
30 return HTTPAuthorizationCredentials(scheme="bearer", credentials=access_token)
31 return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
33# schema = OAuth2PasswordBearer(tokenUrl="token") # 余計なものが多いので一旦使わない
34# schema = HTTPBearer() # 本番用
35schema = DummyHTTPBearer() # 開発用
37def jwt_data_depends(token: Annotated[HTTPAuthorizationCredentials, Depends(schema)]) -> dict[str, Any]:
38 return get_jwt_data(token.credentials) # HTTPBearer -> HTTPAuthorizationCredentials(schema, params:str)