44 lines
1.3 KiB
Python
44 lines
1.3 KiB
Python
import base64
|
|
import binascii
|
|
|
|
import hypercorn.logging
|
|
|
|
from starlette.authentication import AuthenticationBackend, AuthenticationError, AuthCredentials, SimpleUser
|
|
|
|
from pillar_tool.db.queries.auth_queries import verify_user
|
|
from pillar_tool.util import config
|
|
|
|
|
|
WHITELISTED_PATHS = [
|
|
"/health"
|
|
]
|
|
|
|
class BasicAuthBackend(AuthenticationBackend):
|
|
|
|
async def authenticate(self, conn):
|
|
# check for whitelisted paths
|
|
if conn.url.path in WHITELISTED_PATHS:
|
|
return
|
|
|
|
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, what, password = decoded.partition(":")
|
|
print(username, what, password)
|
|
user = verify_user(conn.state.db, username, password)
|
|
|
|
if user is None:
|
|
raise AuthenticationError('Invalid basic auth credentials')
|
|
|
|
conn.state.user = user
|
|
|