-
Notifications
You must be signed in to change notification settings - Fork 2
/
FlaskModule.py
278 lines (220 loc) · 9.03 KB
/
FlaskModule.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# Flask
from flask import Flask, request, g, url_for
from flask_restx import Api
from flask_babel import Babel
# OpenTera
from opentera.modules.BaseModule import BaseModule
from ConfigManager import ConfigManager
# WebSockets
from autobahn.twisted.resource import WSGIRootResource
# Twisted
from twisted.internet import reactor
from twisted.web.http import HTTPChannel
from twisted.web.server import Site
from twisted.web.static import File
from twisted.web.wsgi import WSGIResource
import os
# API
# TODO - Fix auth
authorizations = {
'HTTPAuth': {
'type': 'basic',
'in': 'header'
},
'Token Authentication': {
'type': 'apiKey',
'in': 'header',
'name': 'OpenTera'
}
}
# Flask application
flask_app = Flask("TeleopService")
def get_locale():
# if a user is logged in, use the locale from the user settings
user = getattr(g, 'user', None)
if user is not None:
return user.locale
# otherwise try to guess the language from the user accept
# header the browser transmits. We support fr/en in this
# example. The best match wins.
return request.accept_languages.best_match(['fr', 'en'])
def get_timezone():
user = getattr(g, 'user', None)
if user is not None:
return user.timezone
# Translations
babel = Babel(flask_app, locale_selector=get_locale,
timezone_selector=get_timezone,
default_domain='teleop_service')
# API
# TODO - Fix auth
authorizations = {
'HTTPAuth': {
'type': 'basic',
'in': 'header'
},
'Token Authentication': {
'type': 'apiKey',
'in': 'header',
'name': 'OpenTera'
}
}
class MyHTTPChannel(HTTPChannel):
def allHeadersReceived(self):
# Verify if we have a client with a certificate...
# cert = self.transport.getPeerCertificate()
cert = None
if getattr(self.transport, "getPeerCertificate", None):
cert = self.transport.getPeerCertificate()
# Current request
req = self.requests[-1]
# SAFETY X-Device-UUID, X-Participant-UUID must not be set in header before testing certificate
if req.requestHeaders.hasHeader('X-Device-UUID'):
req.requestHeaders.removeHeader('X-Device-UUID')
# TODO raise error?
if req.requestHeaders.hasHeader('X-Participant-UUID'):
req.requestHeaders.removeHeader('X-Participant-UUID')
# TODO raise error ?
if cert is not None:
# Certificate found, add information in header
subject = cert.get_subject()
# Get UID if possible
if 'Device' in subject.CN and hasattr(subject, 'UID'):
user_id = subject.UID
req.requestHeaders.addRawHeader('X-Device-UUID', user_id)
if 'Participant' in subject.CN and hasattr(subject, 'UID'):
user_id = subject.UID
req.requestHeaders.addRawHeader('X-Participant-UUID', user_id)
HTTPChannel.allHeadersReceived(self)
class MySite(Site):
protocol = MyHTTPChannel
def __init__(self, resource, requestFactory=None, *args, **kwargs):
super().__init__(resource, requestFactory, *args, **kwargs)
# Simple fix for API documentation used with reverse proxy
class CustomAPI(Api):
@property
def specs_url(self):
'''
The Swagger specifications absolute url (ie. `swagger.json`)
:rtype: str
'''
if 'X-Script-Name' in request.headers:
return request.headers['X-Script-Name'] + url_for(self.endpoint('specs'), _external=False)
else:
return url_for(self.endpoint('specs'), _external=False)
@property
def base_url(self):
'''
The API base absolute url
:rtype: str
'''
if 'X-Script-Name' in request.headers:
return request.headers['X-Script-Name'] + url_for(self.endpoint('root'), _external=True)
else:
return url_for(self.endpoint('root'), _external=True)
@property
def base_path(self):
'''
The API path
:rtype: str
'''
if 'X-Script-Name' in request.headers:
return request.headers['X-Script-Name'] + url_for(self.endpoint('root'), _external=False)
else:
return url_for(self.endpoint('root'), _external=False)
api = CustomAPI(flask_app, version='1.0.0', title='TeleopService API',
description='TeleopService API Documentation', doc='/doc', prefix='/api',
authorizations=authorizations)
# Namespaces
default_api_ns = api.namespace('', description='default API')
class FlaskModule(BaseModule):
def __init__(self, config: ConfigManager):
# Warning, the name must be unique!
BaseModule.__init__(self, config.service_config['name'] + '.FlaskModule', config)
flask_app.debug = config.service_config['debug_mode']
flask_app.config.update({'SESSION_TYPE': 'redis'})
import redis
redis_url = redis.from_url('redis://%(username)s:%(password)s@%(hostname)s:%(port)s/%(db)s'
% self.config.redis_config)
flask_app.config.update({'SESSION_REDIS': redis_url})
# This is used for session encryption
flask_app.secret_key = config.service_config['ServiceUUID']
flask_app.config.update({'BABEL_DEFAULT_LOCALE': 'fr'})
flask_app.config.update({'SESSION_COOKIE_SECURE': True})
flask_app.config.update({'UPLOAD_FOLDER': 'uploads'})
# Not sure.
# flask_app.config.update({'BABEL_DEFAULT_TIMEZONE': 'UTC'})
# Init API
self.init_api()
# Init Views
self.init_views()
def create_service(self):
# create a Twisted Web WSGI resource for our Flask server
wsgi_resource = WSGIResource(reactor, reactor.getThreadPool(), flask_app)
# create resource for static assets
# static_resource = File(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates', 'assets'))
base_folder = os.path.dirname(os.path.abspath(__file__))
static_resource = File(os.path.join(base_folder, 'static'))
static_resource.contentTypes['.js'] = 'text/javascript'
static_resource.contentTypes['.css'] = 'text/css'
static_resource.forbidden = False
assets_resource = File(os.path.join(base_folder, 'webportal/dist/assets'))
assets_resource.contentTypes['.js'] = 'text/javascript'
assets_resource.contentTypes['.css'] = 'text/css'
assets_resource.forbidden = False
# the path "/assets" served by our File stuff and
root_resource = WSGIRootResource(wsgi_resource, {b'static': static_resource, b'assets': assets_resource})
# Create a Twisted Web Site
site = MySite(root_resource)
# val = internet.TCPServer(self.config.service_config['port'], site)
val = reactor.listenTCP(self.config.service_config['port'], site)
return val
def __del__(self):
pass
def verifyCallback(self, connection, x509, errnum, errdepth, ok):
if not ok:
print('Invalid cert from subject:', connection, x509.get_subject(), errnum, errdepth, ok)
return False
else:
print("Certs are fine", connection, x509.get_subject(), errnum, errdepth, ok)
return True
def setup_module_pubsub(self):
# Additional subscribe
pass
def notify_module_messages(self, pattern, channel, message):
"""
We have received a published message from redis
"""
print('TeleopService.FlaskModule - Received message ', pattern, channel, message)
pass
def init_api(self):
# Default arguments
kwargs = {'flaskModule': self}
from API.QueryVersion import QueryVersion
from API.QueryManageSession import QueryManageSession
# Resources
default_api_ns.add_resource(QueryVersion, '/version', resource_class_kwargs=kwargs)
default_api_ns.add_resource(QueryManageSession, '/session/manager', resource_class_kwargs=kwargs)
def init_views(self):
from Views.Index import Index
# Default arguments
args = []
kwargs = {'flaskModule': self}
# Will create a function that calls the __index__ method with args, kwargs
flask_app.add_url_rule('/', view_func=Index.as_view('index', *args, **kwargs))
@flask_app.errorhandler(404)
def page_not_found(e):
# This might occur in Angular if the user is refreshing the page with the web browser
#return e;
try:
return flask_app.send_static_file('index.html')
except NotFound:
# If the file was not found, send the default index file
return flask_app.send_static_file('default_index.html')
@flask_app.after_request
def apply_caching(response):
# This is required to expose the backend API to rendered webpages from other sources, such as services
response.headers["Access-Control-Allow-Origin"] = "*"
response.headers["Access-Control-Allow-Headers"] = "*"
response.headers["Access-Control-Allow-Methods"] = "*"
return response