-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmodule.py
More file actions
474 lines (432 loc) · 16.8 KB
/
module.py
File metadata and controls
474 lines (432 loc) · 16.8 KB
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
#!/usr/bin/python3
# coding=utf-8
# Copyright 2021 getcarrier.io
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Module """
import re
import traceback
import uuid
from collections import defaultdict
import flask
from flask import redirect, url_for, g, request, Response
from pylon.core.tools import log, web, module # pylint: disable=E0611,E0401
from pylon.core.tools.context import Context as Holder # pylint: disable=E0401
from werkzeug.exceptions import NotFound
import tools # pylint: disable=E0401
from tools import auth, config as c
from .models.pd.google_analytics import GAConfiguration
class Module(module.ModuleModel):
""" Pylon module """
def __init__(self, context, descriptor):
self.context = context
self.descriptor = descriptor
# Registry
self.landing = self.descriptor.config.get("landing", {"kind": "holder"}) # {kind, prefix|route|url}
self.sections = dict() # section_key -> {name, kind, location, permissions, icon_class, prefix|route|url} # pylint: disable=C0301
self.subsections = dict() # section_key -> subsection_key -> {name, kind, permissions, icon_class, prefix|route|url} # pylint: disable=C0301
self.pages = dict() # section_key -> subsection_key -> page_key -> {kind, prefix|route|url} # pylint: disable=C0301
# Public routes
self._public = [
{
"uri": re.escape("/access_denied"),
},
{
"uri": f'{re.escape("/socket.io/")}.*',
},
{
"uri": f'{re.escape("/css/")}.*',
},
{
"uri": f'{re.escape("/img/")}.*',
},
{
"uri": f'{re.escape("/js/")}.*',
},
{
"uri": f'{re.escape("/vendor/")}.*',
},
{
"uri": re.escape("/robots.txt"),
},
{
"uri": re.escape("/favicon.ico"),
},
]
self.bp = None
def init(self):
""" Init module """
log.info('Initializing module')
# Init Blueprint
self.bp = self.descriptor.init_blueprint(
url_prefix='/',
static_url_prefix='/',
# use_template_prefix=False
)
# SocketIO events
self.context.sio.on("connect", handler=self.sio_connect)
self.context.sio.on("disconnect", handler=self.sio_disconnect)
log.info('SocketIO done')
# Public routes
log.info('Pinging auth...')
auth.ping()
log.info('Public routes init...')
for route in self._public:
auth.add_public_rule(route)
log.info('Public routes done')
# Hooks
self.context.app.context_processor(lambda: {"tools": tools})
self.context.app.errorhandler(Exception)(self._error_handler)
self.context.app.before_request(self._before_request_hook)
self.context.app.after_request(self._after_request_hook)
log.info('Hooks done')
# Init RPCs
self.descriptor.init_rpcs()
self.descriptor.init_slots()
self.descriptor.init_methods()
self.descriptor.init_inits()
#
log.info('RPCs done')
# log.info('%s descriptor %s', self.descriptor.name, self.__dict__)
# log.info('Theme descriptor module %s', self.descriptor.module.__dict__)
# log.info('Self func %s', self.register_section)
# log.info('Rpc func %s', self.context.rpc_manager.call.theme_register_section)
#
self.register_section(
"configuration",
"Configuration",
kind="holder",
location="left",
permissions={
"permissions": ["configuration"],
"recommended_roles": {
"administration": {"admin": True, "editor": False, "viewer": False},
"default": {"admin": True, "editor": False, "viewer": False},
}
},
weight=100,
)
#
# Register tool
self.descriptor.register_tool('theme', self)
log.info('Tools registration done')
def _error_handler(self, error):
resp_code = 400
if isinstance(error, NotFound):
resp_code = 404
log.error(
"Error: (%s) %s:\n%s",
type(error), error,
"".join(traceback.format_tb(error.__traceback__)),
)
return self.descriptor.render_template("access_denied.html"), resp_code
@property
def google_analytics_config(self) -> GAConfiguration:
return GAConfiguration(**self.descriptor.config.get('google_analytics', {}))
def _before_request_hook(self): # pylint: disable=R0201
g.theme = Holder()
g.theme.active_section = None
g.theme.active_subsection = None
g.theme.active_mode = c.DEFAULT_MODE
g.theme.active_parameter = None
#
g.ga_id = request.cookies.get(
self.google_analytics_config.cookie_name,
str(uuid.uuid4())
)
# Example of backend GA event post
# self.google_analytics_post(
# g.ga_id,
# [{'name': 'test', 'params': {'method': request.method, 'url': request.url}}]
# )
def _after_request_hook(self, response):
additional_headers = self.descriptor.config.get(
"additional_headers", dict()
)
for key, value in additional_headers.items():
response.headers[key] = value
#
try:
Response.set_cookie(
response,
self.google_analytics_config.cookie_name,
g.ga_id,
secure=c.APP_SCHEME == "https",
httponly=True,
)
except: # pylint: disable=W0702
pass
#
return response
def deinit(self): # pylint: disable=R0201
""" De-init module """
log.info('De-initializing module')
def get_visible_plugins(self) -> list:
sections = self.get_visible_sections()
# reading plugins list from session
plugins = tools.session_plugins.get()
# if not present in the session then look up from DB
if plugins is None:
project_id = tools.session_project.get()
if project_id:
project = self.context.rpc_manager.call.project_get_or_404()
plugins = project.plugins
tools.session_plugins.set(plugins)
plugins = list(filter(lambda sec: sec['key'] in plugins, sections))
return plugins
def get_visible_sections(self) -> list:
""" Get sections visible for current user """
result = list()
#
current_permissions = auth.resolve_permissions(mode=flask.g.theme.active_mode)
location_result = defaultdict(list)
#
for section_key, section_attrs in self.sections.items():
if section_attrs.get("hidden", False):
continue
#
required_permissions = section_attrs.get("permissions", [])
#
if auth.has_access(current_permissions, required_permissions):
#
item = {
"key": section_key,
**section_attrs
}
#
location_result[section_attrs["location"]].append(item)
#
# log.info('location_result items %s', location_result.items())
for i in location_result.values():
result.extend(sorted(i, key=lambda x: (-x["weight"], x["name"])))
#
# log.info('result %s', result)
return result
def get_visible_subsections(self, section):
""" Get subsections visible for current user """
result = list()
#
if section not in self.subsections:
return result
#
current_permissions = auth.resolve_permissions(mode=g.theme.active_mode)
#
# log.info(f"{self.subsections[section].items()=}")
for subsection_key, subsection_attrs in self.subsections[section].items():
if subsection_attrs.get("hidden", False):
continue
#
required_permissions = subsection_attrs.get("permissions", [])
#
if auth.has_access(current_permissions, required_permissions):
item = {
"key": subsection_key,
**subsection_attrs
}
#
result.append(item)
#
result.sort(key=lambda x: (-x["weight"], x["name"]))
#
return result
@auth.decorators.sio_connect()
def sio_connect(self, sid, environ):
""" Connect handler """
@auth.decorators.sio_disconnect()
def sio_disconnect(self, sid):
""" Disconnect handler """
# Routes
@web.route("/")
def index(self): # pylint: disable=R0201
""" Index route """
landing_kind = self.landing.get("kind", "default")
log.info('Index landing kind %s', landing_kind)
#
if landing_kind == "holder":
sections = self.get_visible_sections()
log.info('Index holder sections %s', sections)
if sections:
return redirect(
url_for(
"theme.route_section", section=sections[0]["key"]
)
)
elif landing_kind == "route":
return redirect(
url_for(
self.landing.get("route", "theme.access_denied")
)
)
elif landing_kind == "redirect":
return redirect(
self.landing.get("url", url_for("theme.access_denied"))
)
elif landing_kind == "slot":
return self.descriptor.render_template(
"index.html",
logout_url=self.descriptor.config.get("logout_url", "#"),
prefix=self.landing.get("prefix", "_"),
title=self.landing.get("title", "Index"),
)
#
return redirect(url_for("theme.access_denied"))
@web.route("/-/<section>/")
def route_section(self, section): # pylint: disable=R0201
""" Section route """
g.theme.active_section = section
#
if section not in self.sections:
return redirect(url_for("theme.access_denied"))
#
section_attrs = self.sections[section]
section_kind = section_attrs.get("kind", "default")
section_permissions = section_attrs.get("permissions", [])
if section_permissions and not auth.has_access(
auth.resolve_permissions(mode=g.theme.active_mode),
section_permissions):
log.info(f"Section {section} access denied")
return redirect(url_for("theme.access_denied"))
#
if section_kind == "holder":
subsections = self.get_visible_subsections(section)
if subsections:
return redirect(
url_for(
"theme.route_section_subsection",
section=section, subsection=subsections[0]["key"]
)
)
elif section_kind == "route":
return redirect(
url_for(
section_attrs.get("route", "theme.access_denied")
)
)
elif section_kind == "redirect":
return redirect(
section_attrs.get("url", url_for("theme.access_denied"))
)
elif section_kind == "slot":
return self.descriptor.render_template(
"index.html",
logout_url=self.descriptor.config.get("logout_url", "#"),
prefix=section_attrs.get("prefix", f"{section}_"),
title=section_attrs.get("title", section.capitalize()),
)
#
return redirect(url_for("theme.access_denied"))
@web.route("/-/<section>/<subsection>/")
def route_section_subsection(self, section, subsection): # pylint: disable=R0201
""" Subsection route """
g.theme.active_section = section
g.theme.active_subsection = subsection
#
# log.info(f"{self.subsections=}")
if section not in self.subsections:
return redirect(url_for("theme.access_denied"))
#
if subsection not in self.subsections[section]:
return redirect(url_for("theme.access_denied"))
#
subsection_attrs = self.subsections[section][subsection]
subsection_kind = subsection_attrs.get("kind", "default")
subsection_permissions = subsection_attrs.get("permissions", [])
if subsection_permissions and not auth.has_access(
auth.resolve_permissions(mode=g.theme.active_mode), subsection_permissions
):
return redirect(url_for("theme.access_denied"))
#
if subsection_kind == "route":
return redirect(
url_for(
subsection_attrs.get("route", "theme.access_denied")
)
)
elif subsection_kind == "redirect":
return redirect(
subsection_attrs.get("url", url_for("theme.access_denied"))
)
elif subsection_kind == "slot":
return self.descriptor.render_template(
"index.html",
logout_url=self.descriptor.config.get("logout_url", "#"),
prefix=subsection_attrs.get(
"prefix", f"{section}_{subsection}_"
),
title=subsection_attrs.get("title", subsection.capitalize()),
)
#
return redirect(url_for("theme.access_denied"))
@web.route("/-/<section>/<subsection>/<page>")
def route_section_subsection_page(self, section, subsection, page
): # pylint: disable=R0201
""" Page route """
g.theme.active_section = section
g.theme.active_subsection = subsection
#
# log.info(f"{self.pages=}")
if section not in self.pages:
return redirect(url_for("theme.access_denied"))
#
if subsection not in self.pages[section]:
return redirect(url_for("theme.access_denied"))
#
if page not in self.pages[section][subsection]:
return redirect(url_for("theme.access_denied"))
#
page_attrs = self.pages[section][subsection][page]
page_kind = page_attrs.get("kind", "default")
page_permissions = page_attrs.get("permissions", [])
log.info(f"{page_attrs=}")
#
if page_permissions and not auth.has_access(
auth.resolve_permissions(mode=g.theme.active_mode), page_permissions):
return redirect(url_for("theme.access_denied"))
if page_kind == "route":
return redirect(
url_for(
page_attrs.get("route", "theme.access_denied")
)
)
elif page_kind == "redirect":
return redirect(
page_attrs.get("url", url_for("theme.access_denied"))
)
elif page_kind == "slot":
return self.descriptor.render_template(
"index.html",
logout_url=self.descriptor.config.get("logout_url", "#"),
prefix=page_attrs.get(
"prefix", f"{section}_{subsection}_{page}_"
),
title=page_attrs.get("title", page.capitalize()),
)
#
return redirect(url_for("theme.access_denied"))
@web.route("/access_denied")
def access_denied(self): # pylint: disable=R0201
""" Access denied page """
return self.descriptor.render_template("access_denied.html")
@property
def access_denied_part(self):
""" Get 'Access denied' template part """
with self.context.app.app_context():
return self.descriptor.render_template("part/access_denied.html")
@property
def empty_content(self):
with self.context.app.app_context():
return self.descriptor.render_template("part/empty.html")
@web.route("/socket.io/")
def socketio(self): # pylint: disable=R0201
""" SocketIO reference """
return redirect(url_for("theme.index"))