remove funding models, add check_admin decorator to views

This commit is contained in:
dni ⚡ 2022-10-04 13:49:32 +02:00
parent 02383261a4
commit 90243060f4
4 changed files with 34 additions and 155 deletions

View File

@ -6,7 +6,6 @@ from lnbits.settings import Settings
from lnbits.tasks import internal_invoice_queue
from . import db
from .models import Funding
async def update_wallet_balance(wallet_id: str, amount: int) -> str:
@ -29,45 +28,7 @@ async def update_wallet_balance(wallet_id: str, amount: int) -> str:
async def update_settings(user: str, **kwargs) -> Settings:
q = ", ".join([f"{field[0]} = ?" for field in kwargs.items()])
# print("UPDATE", q)
await db.execute(
f'UPDATE admin.settings SET {q} WHERE "user" = ?', (*kwargs.values(), user)
)
row = await db.fetchone('SELECT * FROM admin.settings WHERE "user" = ?', (user,))
await db.execute(f'UPDATE admin.settings SET {q}')
row = await db.fetchone('SELECT * FROM admin.settings')
assert row, "Newly updated settings couldn't be retrieved"
return Settings(**row) if row else None
async def update_funding(data: Funding) -> Funding:
await db.execute(
"""
UPDATE admin.settings SET funding_source = ? WHERE user = ?
""",
(data.backend_wallet, data.user),
)
await db.execute(
"""
UPDATE admin.funding
SET backend_wallet = ?, endpoint = ?, port = ?, read_key = ?, invoice_key = ?, admin_key = ?, cert = ?, balance = ?, selected = ?
WHERE id = ?
""",
(
data.backend_wallet,
data.endpoint,
data.port,
data.read_key,
data.invoice_key,
data.admin_key,
data.cert,
data.balance,
data.selected,
data.id,
),
)
row = await db.fetchone('SELECT * FROM admin.funding WHERE "id" = ?', (data.id,))
assert row, "Newly updated settings couldn't be retrieved"
return Funding(**row) if row else None
async def get_funding() -> List[Funding]:
rows = await db.fetchall("SELECT * FROM admin.funding")
return [Funding(**row) for row in rows]

View File

@ -4,76 +4,22 @@ from typing import List, Optional
from fastapi import Query
from pydantic import BaseModel, Field
class UpdateAdminSettings(BaseModel):
# users
admin_users: str = Query(None)
allowed_users: str = Query(None)
admin_ext: str = Query(None)
disabled_ext: str = Query(None)
funding_source: str = Query(None)
# ops
force_https: bool = Query(None)
reserve_fee_min: int = Query(None, ge=0)
reserve_fee_pct: float = Query(None, ge=0)
service_fee: float = Query(None, ge=0)
hide_api: bool = Query(None)
# Change theme
site_title: str = Query("LNbits")
site_tagline: str = Query("free and open-source lightning wallet")
site_description: str = Query(None)
default_wallet_name: str = Query("LNbits wallet")
denomination: str = Query("sats")
theme: str = Query(None)
custom_logo: str = Query(None)
ad_space: str = Query(None)
# class Admin(BaseModel):
# # users
# user: str
# admin_users: Optional[str]
# allowed_users: Optional[str]
# admin_ext: Optional[str]
# disabled_ext: Optional[str]
# funding_source: Optional[str]
# # ops
# data_folder: Optional[str]
# database_url: Optional[str]
# force_https: bool = Field(default=True)
# reserve_fee_min: Optional[int]
# reserve_fee_pct: Optional[float]
# service_fee: float = Optional[float]
# hide_api: bool = Field(default=False)
# # Change theme
# site_title: Optional[str]
# site_tagline: Optional[str]
# site_description: Optional[str]
# default_wallet_name: Optional[str]
# denomination: str = Field(default="sats")
# theme: Optional[str]
# custom_logo: Optional[str]
# ad_space: Optional[str]
# @classmethod
# def from_row(cls, row: Row) -> "Admin":
# data = dict(row)
# return cls(**data)
class Funding(BaseModel):
id: str
backend_wallet: str
endpoint: str = Query(None)
port: str = Query(None)
read_key: str = Query(None)
invoice_key: str = Query(None)
admin_key: str = Query(None)
cert: str = Query(None)
balance: int = Query(None)
selected: int
@classmethod
def from_row(cls, row: Row) -> "Funding":
data = dict(row)
return cls(**data)
class UpdateSettings(BaseModel):
lnbits_admin_users: str = Query(None)
lnbits_allowed_users: str = Query(None)
lnbits_admin_ext: str = Query(None)
lnbits_disabled_ext: str = Query(None)
lnbits_funding_source: str = Query(None)
lnbits_force_https: bool = Query(None)
lnbits_reserve_fee_min: int = Query(None, ge=0)
lnbits_reserve_fee_percent: float = Query(None, ge=0)
lnbits_service_fee: float = Query(None, ge=0)
lnbits_hide_api: bool = Query(None)
lnbits_site_title: str = Query("LNbits")
lnbits_site_tagline: str = Query("free and open-source lightning wallet")
lnbits_site_description: str = Query(None)
lnbits_default_wallet_name: str = Query("LNbits wallet")
lnbits_denomination: str = Query("sats")
lnbits_theme: str = Query(None)
lnbits_custom_logo: str = Query(None)
lnbits_ad_space: str = Query(None)

View File

@ -12,7 +12,6 @@ from lnbits.requestvars import g
from lnbits.settings import WALLET, settings
from . import admin_ext, admin_renderer
from .crud import get_funding
templates = Jinja2Templates(directory="templates")

View File

@ -1,38 +1,38 @@
from http import HTTPStatus
from loguru import logger
from fastapi import Body, Depends, Request
from starlette.exceptions import HTTPException
from lnbits.core.crud import get_wallet
from lnbits.core.models import User
from lnbits.decorators import WalletTypeInfo, check_admin, require_admin_key
from lnbits.decorators import check_admin
from lnbits.extensions.admin import admin_ext
from lnbits.extensions.admin.models import Funding, UpdateAdminSettings
from lnbits.helpers import removeEmptyString
from lnbits.extensions.admin.models import UpdateSettings
from lnbits.requestvars import g
from lnbits.server import server_restart
from lnbits.settings import settings
from .crud import update_funding, update_settings, update_wallet_balance
from .crud import update_settings, update_wallet_balance
@admin_ext.get("/api/v1/admin/restart/", status_code=HTTPStatus.OK)
async def api_restart_server(
g: WalletTypeInfo = Depends(require_admin_key), # type: ignore
user: User = Depends(check_admin)
):
server_restart.set()
return {"status": "Success"}
@admin_ext.get("/api/v1/admin/{wallet_id}/{topup_amount}", status_code=HTTPStatus.OK)
@admin_ext.put("/api/v1/admin/topup/", status_code=HTTPStatus.OK)
async def api_update_balance(
wallet_id, topup_amount: int, g: WalletTypeInfo = Depends(require_admin_key)
wallet_id, topup_amount: int, user: User = Depends(check_admin)
):
try:
wallet = await get_wallet(wallet_id)
except:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="Not allowed: not an admin"
status_code=HTTPStatus.FORBIDDEN, detail="wallet: {wallet_id} does not exist."
)
await update_wallet_balance(wallet_id=wallet_id, amount=int(topup_amount))
@ -40,40 +40,13 @@ async def api_update_balance(
return {"status": "Success"}
@admin_ext.post("/api/v1/admin/", status_code=HTTPStatus.OK)
@admin_ext.put("/api/v1/admin/", status_code=HTTPStatus.OK)
async def api_update_admin(
request: Request,
data: UpdateAdminSettings = Body(...),
w: WalletTypeInfo = Depends(require_admin_key),
user: User = Depends(check_admin),
data: UpdateSettings = Body(...),
):
if not settings.user == w.wallet.user:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="Not allowed: not an admin"
)
updated = await update_admin(user=w.wallet.user, **data.dict())
updated.admin_users = removeEmptyString(updated.admin_users.split(","))
updated.allowed_users = removeEmptyString(updated.allowed_users.split(","))
updated.admin_ext = removeEmptyString(updated.admin_ext.split(","))
updated.disabled_ext = removeEmptyString(updated.disabled_ext.split(","))
updated.theme = removeEmptyString(updated.theme.split(","))
updated.ad_space = removeEmptyString(updated.ad_space.split(","))
g().admin_conf = g().admin_conf.copy(update=updated.dict())
updated = await update_settings(data)
g().settings = g().settings.copy(update=updated.dict())
return {"status": "Success"}
@admin_ext.post("/api/v1/admin/funding/", status_code=HTTPStatus.OK)
async def api_update_funding(
request: Request,
data: Funding = Body(...),
w: WalletTypeInfo = Depends(require_admin_key),
):
if not settings.user == w.wallet.user:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="Not allowed: not an admin"
)
funding = await update_funding(data=data)
return funding