-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.py
124 lines (108 loc) · 3.69 KB
/
app.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
import os, sys
print ("Started as " + os.getlogin())
if os.geteuid() != 0:
os.execvp("sudo", ["sudo"] + [os.environ['_']] + sys.argv)
activate_this_file = os.path.abspath("venv/bin/activate_this.py")
with open(activate_this_file) as f:
exec(f.read(), {'__file__': activate_this_file})
import cherrypy
import logging
from API import APIRegistry
from json import JSONEncoder
import json
from copy import copy
import datetime
import re
from Tools.cp_jwtauth import JWTAuthTool, PAMAuthMech
#
# Monkey patches for JSON Serialisation
#
def _default(self, obj):
if type(obj) == datetime.datetime:
return obj.isoformat()
try:
out = getattr(obj.__class__, "serialise", _default.default)(obj)
except:
raise Exception("Cannot JSON Serialise object: " + obj.__class__.__name__)
return out
_default.default = JSONEncoder.default
JSONEncoder.default = _default
def iter(obj):
if getattr(obj.__class__, "as_dict", None) is not None:
obj = obj.as_dict()
if getattr(obj.__class__, "_asdict", None) is not None:
obj = obj._asdict()
if isinstance(obj, dict):
items = list(obj.items())
for k,v in items:
obj[k] = iter(v)
if isinstance(obj, list):
for i, v in enumerate(copy(obj)):
obj[i] = iter(v)
return obj
def _encode(obj):
return _encode.encode(iter(obj))
_encode.encode = cherrypy._json.encode
cherrypy._json.encode = _encode
class Root(object): pass
class Server(object):
default_conf = {
"theme": "default",
"host": "0.0.0.0",
"port": 8080
}
def __init__(self, conf):
self.conf = copy(self.__class__.default_conf)
self.conf.update(conf)
ip = self.validateIP()
port = self.validatePort()
cherrypy.tools.jwtauth = JWTAuthTool(
"SystemDashboard",
"mysupersecretpassphraseformytokens",
PAMAuthMech
)
cherrypy.config.update({
'server.socket_host': ip,
'server.socket_port': port,
'error_page.400': self.JSONErrorHandler,
'error_page.404': self.JSONErrorHandler,
'error_page.403': self.JSONErrorHandler,
'error_page.405': self.JSONErrorHandler,
'error_page.500': self.JSONErrorHandler,
'error_page.441': self.JSONErrorHandler,
'error_page.442': self.JSONErrorHandler
})
self.api = APIRegistry(self)
def validateIP(self):
if re.match(r"(([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4})", self.conf["host"]) or re.match(r"(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$", self.conf["host"]):
return self.conf["host"]
return "0.0.0.0"
def validatePort(self):
if re.match(r"^\d{1,5}$", str(self.conf["port"])):
return self.conf["port"]
return "8080"
def JSONErrorHandler(self, status, message, traceback, version):
response = cherrypy.response
response.headers['Content-Type'] = 'application/json'
statusi = str(status).strip()
r = re.compile("\d+")
results = r.findall(statusi)
statusi = int(results[0])
status = status.replace(str(statusi), "").strip()
return json.dumps({'status': statusi, 'message': message, 'error': status})
def run(self):
cherrypy.engine.start()
cherrypy.engine.block()
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
data = {}
try:
with open('config.json') as conf:
data = json.load(conf)
except:
data = {}
server = Server(data)
f = open("app.pid", "w")
f.write(str(os.getpid()))
f.close()
server.run()