-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.py
More file actions
41 lines (28 loc) · 1.52 KB
/
middleware.py
File metadata and controls
41 lines (28 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
"""Middleware for Bearer token authentication."""
from starlette.authentication import AuthCredentials, AuthenticationBackend, AuthenticationError, SimpleUser
from starlette.requests import Request
from starlette.responses import JSONResponse
from api.settings import Server
NO_AUTHORIZATION_HEADER = "no `Authorization` header in request."
INVALID_CREDENTIALS = "invalid credentials."
class TokenAuthentication(AuthenticationBackend):
"""Simple token authentication."""
def __init__(self, token: str) -> None:
self.expected_auth_header = f"Token {token}"
async def authenticate(self, request: Request) -> tuple[AuthCredentials, SimpleUser]:
"""Authenticate the request based on the Authorization header."""
if Server.DEBUG:
credentials = AuthCredentials(scopes=["debug"])
user = SimpleUser(username="api_client")
return credentials, user
authorization_header = request.headers.get("Authorization")
if not authorization_header:
raise AuthenticationError(NO_AUTHORIZATION_HEADER)
if authorization_header != self.expected_auth_header:
raise AuthenticationError(INVALID_CREDENTIALS)
credentials = AuthCredentials(scopes=["authenticated"])
user = SimpleUser(username="api_client")
return credentials, user
def on_auth_error(_request: Request, exc: Exception) -> JSONResponse:
"""Send an authentication error message serialized as JSON."""
return JSONResponse({"error": str(exc)}, status_code=403)