-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
executable file
·144 lines (110 loc) · 4.33 KB
/
main.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
#!/usr/bin/env python3
import ssl
import time
import sqlite3
import json
import logging
from pathlib import Path
from http.server import BaseHTTPRequestHandler, HTTPServer
from customlog.customlog import ColoredLogger
from certificate.certificate import create_self_signed_cert
logging.setLoggerClass(ColoredLogger)
logger = logging.getLogger('SERVER - MAIN')
db = "db.sqlite"
def dict_factory(cursor, row):
""" Creates dictionaries from sqlite queries """
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
# HTTPRequestHandler class
class LunaHTTPServer_RequestHandler(BaseHTTPRequestHandler):
def log_message(self, formatting, *args):
logger.info("From {0[0]} - {1}".format(self.client_address, formatting % args))
# OPTIONS
def do_OPTIONS(self):
self.send_response(200, "ok")
self.send_header('Access-Control-Allow-Credentials', 'true')
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
self.send_header("Access-Control-Allow-Headers", "X-Requested-With, Content-type")
self.end_headers()
# GET
def do_GET(self):
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Content-type', 'application/json')
self.end_headers()
if self.path == "/check_gateway":
with sqlite3.connect(db) as conn:
conn.row_factory = dict_factory
cursor = conn.cursor()
cursor.execute("SELECT * FROM gateway")
query = cursor.fetchall()
data = bytes(json.dumps(query), "UTF-8")
self.wfile.write(data)
logger.debug(data)
return
elif self.path == "/check_subscriptors":
with sqlite3.connect(db) as conn:
conn.row_factory = dict_factory
cursor = conn.cursor()
cursor.execute("SELECT * FROM subscriptors")
query = cursor.fetchall()
data = bytes(json.dumps(query), "UTF-8")
self.wfile.write(data)
logger.debug(data)
return
return
# POST
def do_POST(self):
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Content-type', 'application/json')
self.end_headers()
if self.path == "/auth":
var_len = int(self.headers['Content-Length'])
json_data = self.rfile.read(var_len)
rdata = json.loads(json_data.decode("UTF-8"))
with sqlite3.connect(db) as conn:
conn.row_factory = dict_factory
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE username = ?", (rdata['user'],))
query = cursor.fetchone()
message = {'auth': False}
if query:
if rdata['pass'] == query['password']:
message = {'auth': True}
wdata = bytes(json.dumps(message), "UTF-8")
self.wfile.write(wdata)
return
elif self.path == "/subscriptor_create":
"""
var_len = int(self.headers['Content-Length'])
json_data = self.rfile.read(var_len)
data = json.loads(json_data.decode("UTF-8"))
with sqlite3.connect(db) as conn:
cursor = conn.cursor()
cursor.execute("INSERT INTO clients VALUES (NULL, ?, ?, ?, ?, ?)",
(data["name"], data["surname"], data["tlf"], data["email"], data["nif"],))
conn.commit()
"""
return
return
def main():
cert = "server.pem"
cert_file = Path(cert)
if not cert_file.is_file():
create_self_signed_cert(cert)
# Server settings
server_address = ('0.0.0.0', 8080)
httpd = HTTPServer(server_address, LunaHTTPServer_RequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile=cert, server_side=True)
try:
logger.info('Server start listening on {0[0]}:{0[1]}'.format(server_address))
httpd.serve_forever()
except KeyboardInterrupt as e:
logger.info('Server stops')
httpd.server_close()
if __name__ == "__main__":
main()