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
|
import sys
import time
import requests
from db.db import DictDB
from db.index import CouchIindex
from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
from fastapi_jwt_auth import AuthJWT
router = APIRouter()
for i in range(10):
try:
db = DictDB()
except requests.exceptions.ConnectionError:
print('Database not responding, will try again soon.' +
f'Attempt {i + 1} of 10.')
else:
break
time.sleep(10)
else:
print('Database did not respond after 10 attempts, quitting.')
sys.exit(-1)
def get_data(key=None, limit=25, skip=0, ip=None,
port=None, asn=None, domain=None):
if key:
return db.get(key)
selectors = dict()
indexes = CouchIindex().dict()
selectors['domain'] = domain
if ip and 'ip' in indexes:
selectors['ip'] = ip
if port and 'port' in indexes:
selectors['port'] = port
if asn and 'asn' in indexes:
selectors['asn'] = asn
data = db.search(**selectors, limit=limit, skip=skip)
return data
@router.get('/get')
async def get(key=None, limit=25, skip=0, ip=None, port=None,
asn=None, Authorize: AuthJWT = Depends()):
Authorize.jwt_required()
data = []
raw_jwt = Authorize.get_raw_jwt()
if 'domains' not in raw_jwt:
return JSONResponse(content={"status": "error",
"message": "Could not find domains" +
"claim in JWT token"},
status_code=400)
else:
domains = raw_jwt['domains']
for domain in domains:
data.extend(get_data(key, limit, skip, ip, port, asn, domain))
return JSONResponse(content={"status": "success", "docs": data})
@router.get('/get/{key}')
async def get_key(key=None, Authorize: AuthJWT = Depends()):
Authorize.jwt_required()
# TODO: Use JWT authz and check e.g. domain here
data = get_data(key)
return JSONResponse(content={"status": "success", "docs": data})
@router.post('/add')
async def add(data: Request, Authorize: AuthJWT = Depends()):
Authorize.jwt_required()
json_data = await data.json()
key = db.add(json_data)
return JSONResponse(content={"status": "success", "docs": key})
@router.delete('/delete/{key}')
async def delete(key, Authorize: AuthJWT = Depends()):
Authorize.jwt_required()
if db.delete(key) is None:
return JSONResponse(content={"status": "error",
"message": "Document not found"},
status_code=400)
return JSONResponse(content={"status": "success", "docs": {}})
|