PillarTool/pillar_tool/middleware/basicauth_backend.py
2025-12-21 17:38:38 +01:00

28 lines
1.0 KiB
Python

import base64
import binascii
import hypercorn.logging
from starlette.authentication import AuthenticationBackend, AuthenticationError, AuthCredentials, SimpleUser
class BasicAuthBackend(AuthenticationBackend):
async def authenticate(self, conn):
if "Authorization" not in conn.headers:
raise AuthenticationError('No Authorization Header')
auth = conn.headers["Authorization"]
try:
scheme, creds = auth.split()
if scheme.lower() != "basic":
raise AuthenticationError('Invalid Auth Scheme')
decoded = base64.b64decode(creds).decode("utf-8")
except (ValueError, UnicodeDecodeError, binascii.Error):
raise AuthenticationError('Invalid basic auth credentials')
username, _, password = decoded.partition(":")
if username == 'admin' and password == 'password':
return AuthCredentials(["authenticated"]), SimpleUser('admin')
raise AuthenticationError('Invalid basic auth credentials')