-
Notifications
You must be signed in to change notification settings - Fork 1
/
views_api.py
207 lines (168 loc) · 6.35 KB
/
views_api.py
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
from http import HTTPStatus
from typing import Optional
from fastapi import APIRouter, Depends, Query
from fastapi.exceptions import HTTPException
from lnbits.core.crud import get_user
from lnbits.core.models import WalletTypeInfo
from lnbits.core.services import check_transaction_status, create_invoice
from lnbits.decorators import require_admin_key, require_invoice_key
from loguru import logger
from .cloudflare import cloudflare_create_subdomain, cloudflare_deletesubdomain
from .crud import (
create_domain,
create_subdomain,
delete_domain,
delete_subdomain,
get_domain,
get_domains,
get_subdomain,
get_subdomain_by_subdomain,
get_subdomains,
update_domain,
)
from .models import CreateDomain, CreateSubdomain, Domain, Subdomain
subdomains_api_router: APIRouter = APIRouter()
@subdomains_api_router.get("/api/v1/domains")
async def api_domains(
key_info: WalletTypeInfo = Depends(require_admin_key),
all_wallets: bool = Query(False),
) -> list[Domain]:
wallet_ids = [key_info.wallet.id]
if all_wallets:
user = await get_user(key_info.wallet.user)
if user:
wallet_ids = user.wallet_ids
return await get_domains(wallet_ids)
@subdomains_api_router.post("/api/v1/domains")
@subdomains_api_router.put("/api/v1/domains/{domain_id}")
async def api_domain_create(
data: CreateDomain,
domain_id: Optional[str] = None,
key_info: WalletTypeInfo = Depends(require_admin_key),
) -> Domain:
if domain_id:
domain = await get_domain(domain_id)
if not domain:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Domain does not exist."
)
if domain.wallet != key_info.wallet.id:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="Not your domain."
)
for k, v in data.dict().items():
setattr(domain, k, v)
domain = await update_domain(domain)
else:
domain = await create_domain(data)
return domain
@subdomains_api_router.delete("/api/v1/domains/{domain_id}")
async def api_domain_delete(
domain_id: str, key_info: WalletTypeInfo = Depends(require_admin_key)
):
domain = await get_domain(domain_id)
if not domain:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Domain does not exist."
)
if domain.wallet != key_info.wallet.id:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Not your domain.")
await delete_domain(domain_id)
@subdomains_api_router.get("/api/v1/subdomains")
async def api_subdomains(
all_wallets: bool = Query(False),
key_info: WalletTypeInfo = Depends(require_invoice_key),
) -> list[Subdomain]:
wallet_ids = [key_info.wallet.id]
if all_wallets:
user = await get_user(key_info.wallet.user)
if user is not None:
wallet_ids = user.wallet_ids
return await get_subdomains(wallet_ids)
@subdomains_api_router.post("/api/v1/subdomains/{domain_id}")
async def api_subdomain_make_subdomain(domain_id, data: CreateSubdomain):
domain = await get_domain(domain_id)
# If the request is coming for the non-existant domain
if not domain:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="LNsubdomain does not exist."
)
## If record_type is not one of the allowed ones reject the request
if data.record_type not in domain.allowed_record_types:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
detail=f"{data.record_type} not a valid record.",
)
## If domain already exist in our database reject it
if await get_subdomain_by_subdomain(data.subdomain) is not None:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
detail=f"{data.subdomain}.{domain.domain} domain already taken.",
)
## Dry run cloudflare... (create and if create is successful delete it)
try:
res_json = await cloudflare_create_subdomain(
domain=domain,
subdomain=data.subdomain,
record_type=data.record_type,
ip=data.ip,
)
await cloudflare_deletesubdomain(
domain=domain, domain_id=res_json["result"]["id"]
)
except Exception as exc:
logger.warning(exc)
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
detail="Problem with cloudflare.",
) from exc
## ALL OK - create an invoice and return it to the user
sats = data.sats
try:
payment_hash, payment_request = await create_invoice(
wallet_id=domain.wallet,
amount=sats,
memo=f"""
subdomain {data.subdomain}.{domain.domain}
for {sats} sats for {data.duration} days
""",
extra={"tag": "lnsubdomain"},
)
except Exception as exc:
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(exc)
) from exc
subdomain = await create_subdomain(
payment_hash=payment_hash, wallet=domain.wallet, data=data
)
if not subdomain:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="LNsubdomain could not be fetched."
)
return {"payment_hash": payment_hash, "payment_request": payment_request}
@subdomains_api_router.get("/api/v1/subdomains/{payment_hash}")
async def api_subdomain_send_subdomain(payment_hash):
subdomain = await get_subdomain(payment_hash)
assert subdomain
try:
status = await check_transaction_status(subdomain.wallet, payment_hash)
is_paid = not status.pending
except Exception:
return {"paid": False}
if is_paid:
return {"paid": True}
return {"paid": False}
@subdomains_api_router.delete("/api/v1/subdomains/{subdomain_id}")
async def api_subdomain_delete(
subdomain_id: str, key_info: WalletTypeInfo = Depends(require_admin_key)
) -> None:
subdomain = await get_subdomain(subdomain_id)
if not subdomain:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="LNsubdomain does not exist."
)
if subdomain.wallet != key_info.wallet.id:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="Not your subdomain."
)
await delete_subdomain(subdomain_id)