Skip to content

Commit

Permalink
👽 Add auto-error param which can turn on exceptions
Browse files Browse the repository at this point in the history
I just checked how fastapi builtin security dependencies works and thought that it's a good idea to follow protocol
  • Loading branch information
b0g3r committed Mar 2, 2020
1 parent eddaf0e commit b766bc8
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
27 changes: 19 additions & 8 deletions fastapi_security_typeform/security.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
from typing import Union
from typing import (
Union,
Optional,
)

from fastapi import HTTPException
from fastapi.openapi.models import HTTPBearer
Expand All @@ -23,31 +26,39 @@ def __init__(
secret: Union[bytes, bytearray],
signature_prefix: str = "sha256=",
header_name: str = "Typeform-Signature",
hash_method: HashMethodType = hmac_sha256
hash_method: HashMethodType = hmac_sha256,
auto_error: bool = True
):
self.model = HTTPBearer(scheme=self.scheme_name)
self.signature_prefix = signature_prefix
self.secret = secret
self.header_name = header_name
self.hash_method = hash_method
self.auto_error = auto_error

async def __call__(self, request: Request) -> None:
async def __call__(self, request: Request) -> Optional[str]:
"""
Extract signature from headers and validate it.
:raises HTTPException: raise 403 error if signature is empty or signature check is failed
"""
signature: str = request.headers.get(self.header_name)
if not signature:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
)
if self.auto_error:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
)
else:
return None

payload = await request.body()
payload_hash = self.hash_method(payload, self.secret,)
check_signature = self.signature_prefix + payload_hash

if signature != check_signature:
raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Bad signature")
if self.auto_error:
raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Bad signature")
else:
return None

return None
return signature
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "fastapi-security-typeform"
version = "1.0.0"
version = "1.0.1"
description = ""
authors = ["Dima Boger <[email protected]>"]
license = "MIT"
Expand Down

0 comments on commit b766bc8

Please sign in to comment.