lnbits-legend/lnbits/extensions/lndhub/decorators.py

45 lines
1.3 KiB
Python
Raw Normal View History

2021-10-13 16:47:24 +01:00
from base64 import b64decode
2021-10-15 19:55:24 +02:00
from fastapi.param_functions import Security
from fastapi.security.api_key import APIKeyHeader
2021-10-13 16:47:24 +01:00
2021-10-15 19:55:24 +02:00
from fastapi import Request, status
2021-10-13 16:47:24 +01:00
from starlette.exceptions import HTTPException
2021-10-15 19:55:24 +02:00
from lnbits.decorators import WalletTypeInfo, get_key_type # type: ignore
2021-10-17 18:33:29 +01:00
api_key_header_auth = APIKeyHeader(
name="AUTHORIZATION",
auto_error=False,
description="Admin or Invoice key for LNDHub API's",
)
async def check_wallet(
r: Request, api_key_header_auth: str = Security(api_key_header_auth)
) -> WalletTypeInfo:
2021-10-15 19:55:24 +02:00
if not api_key_header_auth:
raise HTTPException(
2021-10-17 18:33:29 +01:00
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid auth key"
)
2021-10-15 19:55:24 +02:00
t = api_key_header_auth.split(" ")[1]
_, token = b64decode(t).decode("utf-8").split(":")
return await get_key_type(r, api_key_header=token)
2021-10-17 18:33:29 +01:00
async def require_admin_key(
r: Request, api_key_header_auth: str = Security(api_key_header_auth)
):
wallet = await check_wallet(r, api_key_header_auth)
if wallet.wallet_type != 0:
# If wallet type is not admin then return the unauthorized status
# This also covers when the user passes an invalid key type
raise HTTPException(
2021-10-17 18:33:29 +01:00
status_code=status.HTTP_401_UNAUTHORIZED, detail="Admin key required."
)
2021-10-17 18:33:29 +01:00
else:
return wallet