/
part.py
2412 lines (2132 loc) · 88.5 KB
/
part.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
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Appier Framework
# Copyright (c) 2008-2018 Hive Solutions Lda.
#
# This file is part of Hive Appier Framework.
#
# Hive Appier Framework is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apache
# Foundation, either version 2.0 of the License, or (at your option) any
# later version.
#
# Hive Appier Framework is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# Apache License for more details.
#
# You should have received a copy of the Apache License along with
# Hive Appier Framework. If not, see <http://www.apache.org/licenses/>.
__author__ = "João Magalhães <joamag@hive.pt>"
""" The author(s) of the module """
__version__ = "1.0.0"
""" The version of the module """
__revision__ = "$LastChangedRevision$"
""" The revision number of the module """
__date__ = "$LastChangedDate$"
""" The last change date of the module """
__copyright__ = "Copyright (c) 2008-2018 Hive Solutions Lda."
""" The copyright for the module """
__license__ = "Apache License, Version 2.0"
""" The license for the module """
import os
import json
import time
import datetime
import tempfile
import appier
from appier_extras import base
from appier_extras import utils
from appier_extras.parts.admin import models
from appier_extras.parts.admin import social
OAUTH_ERROR_CODES = {
400 : "invalid_request",
403 : "access_denied",
500 : "server_error"
}
""" Dictionary that maps the typical HTTP error codes into
the string based OAuth error codes to be returned to the
redirect URI on the authorize call (in case of error) """
class AdminPart(
appier.Part,
social.Facebook,
social.Twitter,
social.Google,
social.Github,
social.Live
):
"""
Modular part class providing the automation functionality for
the generation of a web interface based on the application
data model for fast prototyping.
The interface configuration should be done by the way of
"annotations" in the data model attributes.
"""
def __init__(
self,
account_c = models.Account,
role_c = models.Role,
*args,
**kwargs
):
appier.Part.__init__(self, *args, **kwargs)
self.account_c = account_c
self.role_c = role_c
self.layout = kwargs.get("layout", "fluid")
self.theme = kwargs.get("theme", "flat")
self.style = kwargs.get("style", "")
self.libs = kwargs.get("libs", "current")
self.social_libs = kwargs.get("libs", [])
self.available = kwargs.get("available", True)
self.open = kwargs.get("open", False)
self.oauth = kwargs.get("oauth", True)
self.avatar_default = kwargs.get("avatar_default", False)
self.layout = appier.conf("ADMIN_LAYOUT", self.layout)
self.theme = appier.conf("ADMIN_THEME", self.theme)
self.style = appier.conf("ADMIN_STYLE", self.style)
self.libs = appier.conf("ADMIN_LIBS", self.libs)
self.social_libs = appier.conf("ADMIN_SOCIAL_LIBS", self.social_libs, cast = list)
self.available = appier.conf("ADMIN_AVAILABLE", self.available, cast = bool)
self.open = appier.conf("ADMIN_OPEN", self.open, cast = bool)
self.oauth = appier.conf("ADMIN_OAUTH", self.oauth, cast = bool)
self.avatar_default = appier.conf(
"ADMIN_AVATAR_DEFAULT",
self.avatar_default,
cast = bool
)
self._last_login = None
self._login_count = 0
self._sections = appier.OrderedDict()
self._operations = appier.OrderedDict()
def version(self):
return base.VERSION
def info(self):
info = appier.Part.info(self)
info.update(
last_login = self._last_login_s,
login_count = self._login_count
)
return info
def load(self):
appier.Part.load(self)
self.logger.debug("Registering pre request handler ...")
appier.App.add_custom("before_request", self.before_request)
appier.App.add_exception(
BaseException,
self.exception_handler,
scope = AdminPart
)
self.logger.debug("Updating pre-defined application routes ...")
self.owner.login_route = "admin.login"
self.owner.login_route_admin = "admin.login"
self.owner.login_redirect = "admin.index"
self.owner.logout_redirect = "admin.login"
self.owner.admin_account = self.account_c
self.owner.admin_role = self.role_c
self.owner.admin_login_redirect = "admin.index"
self.owner.admin_logout_redirect = "admin.login"
self.owner.admin_facebook_scope = ("email",)
self.owner.admin_github_scope = ("user:email",)
self.owner.admin_google_scope = ("email",)
self.owner.admin_live_scope = ("wl.basic", "wl.emails")
self.owner.admin_available = self.available
self.owner.admin_open = self.open
self.owner.admin_oauth = self.oauth
self.owner.admin_avatar_default = self.avatar_default
self.owner.admin_layout_fluid = "admin/layout.fluid.html.tpl"
self.owner.admin_layout_static = "admin/layout.static.html.tpl"
self.owner.admin_email_layout = "admin/email/layout.app.html.tpl"
self.owner.lib_loaders["appier_extras"] = self._appier_extras_loader
self.owner.lib_loaders["netius"] = self._netius_loader
self.owner.lib_loaders["pconvert"] = self._pconvert_loader
self.owner.lib_loaders["PIL"] = self._pil_loader
self.owner.lib_loaders["pymongo"] = self._pymongo_loader
self.owner.lib_loaders["redis"] = self._redis_loader
self.owner.lib_loaders["jinja2"] = self._jinja2_loader
self.owner.lib_loaders["ssl"] = self._ssl_loader
self.owner.add_filter(self.markdown_jinja, "markdown")
if self.owner.allow_headers: self.owner.allow_headers += ", X-Secret-Key"
self.logger.debug("Generating admin interfaces ...")
for model_c in self.models_r:
if not model_c.is_attached(): continue
if not model_c.is_concrete(): continue
if not model_c.is_child(models.Base): continue
self.logger.debug(model_c)
for social_lib in self.social_libs:
method = getattr(self, "ensure_" + social_lib)
method()
self.load_settings()
self.load_operations()
self.account_c.bind_g("touch_login", self._on_touch_login)
def unload(self):
appier.Part.unload(self)
self.account_c.unbind_g("touch_login", self._on_touch_login)
self.unload_operations()
self.unload_settings()
self.owner.remove_filter("markdown")
def routes(self):
return [
(("GET",), "/admin", self.index),
(("GET",), "/admin/signin", self.signin),
(("POST",), "/admin/signin", self.login),
(("GET", "POST"), "/admin/signout", self.logout),
(("GET"), "/admin/confirm", self.confirm),
(("GET"), "/admin/recover", self.recover),
(("POST"), "/admin/recover", self.recover_do),
(("GET"), "/admin/reset", self.reset),
(("POST"), "/admin/reset", self.reset_do),
(("GET",), "/admin/options", self.options),
(("POST",), "/admin/options", self.options_action),
(("GET",), "/admin/social", self.social),
(("GET",), "/admin/operations", self.operations),
(("GET",), "/admin/status", self.status),
(("GET",), "/admin/routes", self.list_routes),
(("GET",), "/admin/configs", self.list_configs),
(("GET",), "/admin/parts", self.list_parts),
(("GET",), "/admin/parts/<str:name>", self.show_part),
(("GET",), "/admin/parts/<str:name>/load", self.load_part),
(("GET",), "/admin/parts/<str:name>/unload", self.unload_part),
(("GET",), "/admin/libraries", self.list_libraries),
(("GET",), "/admin/oauth/authorize", self.oauth_authorize),
(("POST",), "/admin/oauth/authorize", self.do_oauth_authorize),
(("GET",), "/admin/oauth/deny", self.oauth_deny),
(("GET", "POST"), "/admin/oauth/access_token", self.oauth_access_token, None, True),
(("GET", "POST"), "/admin/oauth/login", self.oauth_login, None, True),
(("GET",), "/admin/operations/restart_app", self.restart_app),
(("GET",), "/admin/operations/build_index", self.build_index),
(("GET",), "/admin/operations/build_index_db", self.build_index_db),
(("GET",), "/admin/operations/test_email", self.test_email),
(("GET",), "/admin/operations/test_event", self.test_event),
(("GET",), "/admin/sessions", self.list_sessions),
(("GET",), "/admin/sessions/empty", self.empty_sessions),
(("GET",), "/admin/sessions/me", self.show_session_me),
(("GET",), "/admin/sessions/me/delete", self.delete_session_me),
(("GET",), "/admin/sessions/<str:sid>", self.show_session),
(("GET",), "/admin/sessions/<str:sid>/delete", self.delete_session),
(("GET",), "/admin/peers", self.list_peers),
(("GET",), "/admin/counters", self.list_counters),
(("GET",), "/admin/events.csv", self.list_events_csv),
(("GET",), "/admin/locales/<int:id>/bundle.json", self.bundle_locale_json, None, True),
(("GET",), "/admin/database", self.database),
(("GET",), "/admin/database/export", self.database_export),
(("GET",), "/admin/database/import", self.database_import),
(("POST",), "/admin/database/import", self.database_import_do),
(("GET",), "/admin/database/reset", self.database_reset),
(("GET",), "/admin/search", self.search),
(("GET",), "/admin/accounts/new", self.new_account),
(("POST",), "/admin/accounts", self.create_account),
(("GET",), "/admin/accounts/me", self.me_account),
(("GET",), "/admin/accounts/<str:username>", self.show_account),
(("GET",), "/admin/accounts/<str:username>/mail", self.mail_account),
(("GET",), "/admin/accounts/<str:username>/avatar", self.avatar_account),
(("GET",), "/admin/models", self.list_models),
(("GET",), "/admin/models/<str:model>.json", self.show_model_json, None, True),
(("GET",), "/admin/models/<str:model>.csv", self.show_model_csv),
(("GET",), "/admin/models/<str:model>", self.show_model),
(("GET", "POST"), "/admin/models/<str:model>/links/<str:link>", self.link_model),
(("GET", "POST"), "/admin/models/<str:model>/operations/<str:operation>", self.operation_model),
(("GET", "POST"), "/admin/models/<str:model>/view/<str:view>", self.view_model),
(("GET",), "/admin/models/<str:model>/new", self.new_entity),
(("POST",), "/admin/models/<str:model>", self.create_entity),
(("GET",), "/admin/models/<str:model>/<str:_id>.json", self.show_entity_json, None, True),
(("GET",), "/admin/models/<str:model>/<str:_id>", self.show_entity),
(("GET",), "/admin/models/<str:model>/<str:_id>/edit", self.edit_entity),
(("POST",), "/admin/models/<str:model>/<str:_id>/edit", self.update_entity),
(("GET",), "/admin/models/<str:model>/<str:_id>/delete", self.delete_entity),
(("GET",), "/admin/facebook", self.facebook),
(("GET",), "/admin/facebook/unlink", self.unlink_facebook),
(("GET",), "/admin/facebook/unset", self.unset_facebook),
(("GET",), "/admin/facebook/oauth", self.oauth_facebook),
(("GET",), "/admin/github", self.github),
(("GET",), "/admin/github/unlink", self.unlink_github),
(("GET",), "/admin/github/unset", self.unset_github),
(("GET",), "/admin/github/oauth", self.oauth_github),
(("GET",), "/admin/google", self.google),
(("GET",), "/admin/google/unlink", self.unlink_google),
(("GET",), "/admin/google/unset", self.unset_google),
(("GET",), "/admin/google/oauth", self.oauth_google),
(("GET",), "/admin/live", self.live),
(("GET",), "/admin/live/unlink", self.unlink_live),
(("GET",), "/admin/live/unset", self.unset_live),
(("GET",), "/admin/live/oauth", self.oauth_live),
(("GET",), "/admin/twitter", self.twitter),
(("GET",), "/admin/twitter/unlink", self.unlink_twitter),
(("GET",), "/admin/twitter/unset", self.unset_twitter),
(("GET",), "/admin/twitter/oauth", self.oauth_twitter),
(("GET",), "/admin/log.json", self.show_log, None, True),
(("GET",), "/admin/configs.json", self.show_configs, None, True),
(("GET",), "/api/admin/ping", self.ping_api, None, True),
(("GET", "POST"), "/api/admin/login", self.login_api, None, True),
(("GET", "POST"), "/api/admin/oauth/access_token", self.oauth_access_token_api, None, True),
(("GET", "POST"), "/api/admin/oauth/login", self.oauth_login_api, None, True),
(("GET",), "/api/admin/accounts/me", self.me_account_api, None, True),
(("GET",), "/api/admin/models/<str:model>", self.show_model_json, None, True),
(("GET",), "/api/admin/models/<str:model>/<str:_id>", self.show_entity_json, None, True)
]
def models(self):
if not self.available: return None
return models
def template(self, template, layout = True, *args, **kwargs):
layout = self.session.get("layout", self.layout) if layout else None
template = "%s/%s" % (layout, template) if layout else template
return appier.Part.template(
self,
template,
*args,
**kwargs
)
def before_request(self):
key = self.field("skey", None)
key = self.field("secret_key", key)
key = self.request.get_header("X-Secret-Key", key)
if not key: return
try: account = self.account_c.login_key(key)
except appier.OperationalError: pass
else: account._set_session(method = "set_t")
def exception_handler(self, error):
import traceback
lines = traceback.format_exc().splitlines()
lines = appier.App._lines(lines)
lines = lines if self.owner.is_devel() else []
return self.template(
"error.html.tpl",
error = error,
lines = lines
)
def load_settings(self):
settings = self.owner.get_preference(self.name() + ":settings")
if not settings: return
for name in self.settings_l:
current = getattr(self, name)
value = settings.get(name, current)
setattr(self, name, value)
def unload_settings(self):
settings = self.owner.get_preference(self.name() + ":settings")
if not settings: return
for name in self.settings_l:
delattr(self, name)
def dump_settings(self):
settings = dict()
for name in self.settings_l:
value = getattr(self, name)
settings[name] = value
self.owner.set_preference(self.name() + ":settings", settings)
def flush_settings(self):
self.dump_settings()
def load_operations(self):
self.add_operation(
"restart_app", "admin.restart_app",
description = "Restart application",
message = "Are you really sure you want to restart the application?",
note = "Restarting the application, may delete the system state",
level = 3
)
self.add_operation(
"build_index", "admin.build_index",
description = "Build search index",
message = "Are you really sure you want to rebuild the search index?",
note = "Rebuilding the complete search index, may take some time",
level = 3
)
self.add_operation(
"build_index_db", "admin.build_index_db",
description = "Build database index",
message = "Are you really sure you want to rebuild the database index?",
note = "Rebuilding the complete database index, may take some time",
level = 3
)
self.add_operation(
"test_email", "admin.test_email",
description = "Send test email",
note = "Sending this email is going to use loaded SMTP configuration"
)
self.add_operation(
"test_event", "admin.test_event",
description = "Trigger test event",
note = "All handlers for the event are going to be triggered"
)
def unload_operations(self):
self.remove_operation("restart_app")
self.remove_operation("build_index")
self.remove_operation("build_index_db")
self.remove_operation("test_email")
self.remove_operation("test_event")
def add_section(self, name):
self._sections[name] = appier.OrderedDict()
def remove_section(self, name):
del self._sections[name]
def add_section_item(self, name, route, section = None):
if not section in self._sections:
self.add_section(section)
self._sections[section][name] = route
def remove_section_item(self, name, section = None):
del self._sections[section][name]
if self._sections[section]: return
del self._sections[section]
def add_operation(
self,
name,
route,
description = None,
message = None,
note = None,
parameters = (),
level = 1,
args = [],
kwargs = {}
):
self._operations[name] = dict(
name = name,
route = route,
description = description,
message = message,
note = note,
parameters = parameters,
level = level,
args = args,
kwargs = kwargs
)
def remove_operation(self, name):
del self._operations[name]
def index(self):
return self.list_models()
def signin(self):
next = self.field("next")
error = self.field("error")
socials = self.socials()
return self.template(
"signin.html.tpl",
next = next,
error = error,
socials = socials
)
def login(self):
# verifies if the current administration interface is
# available and if that's not the cases raises an error
if not self.owner.admin_available: raise appier.SecurityError(
message = "Administration not available"
)
# retrieves the various fields that are going to be
# used for the validation of the user under the current
# authentication/authorization process
username = self.field("username", mandatory = True)
password = self.field("password", mandatory = True)
next = self.field("next")
socials = self.socials()
try: account = self.account_c.login(username, password)
except appier.AppierException as error:
return self.template(
"signin.html.tpl",
next = next,
socials = socials,
username = username,
error = error.message
)
# updates the current session with the proper
# values to correctly authenticate the user
account._set_session()
# redirects the current operation to the next URL or in
# alternative to the root index of the administration
return self.redirect(
next or self.url_for(self.owner.admin_login_redirect)
)
def logout(self):
# tries to retrieve the next field as it's going to be used for
# the redirection operation at the end of the logout operation
next = self.field("next")
# verifies the existence of the various account related session
# attributes and in case they exist removes them from session as
# the user is currently logging out from session
self.account_c._unset_account()
# runs the proper redirect operation, taking into account if the
# next value has been provided or not
return self.redirect(
next or self.url_for(self.owner.admin_logout_redirect)
)
def recover(self):
return self.template("recover.html.tpl")
def recover_do(self):
identifier = self.field("identifier")
send_email = self.field("send_email", True, cast = bool)
try: self.account_c.recover(identifier, send_email = send_email)
except appier.AppierException as error:
return self.template(
"recover.html.tpl",
identifier = identifier,
error = error.message
)
return self.template("done.html.tpl")
def reset(self):
next = self.field("next")
reset_token = self.field(
"reset_token",
mandatory = True,
not_empty = True
)
self.account_c.validate_reset(reset_token)
return self.template(
"reset.html.tpl",
next = next,
reset_token = reset_token
)
def reset_do(self):
next = self.field("next")
reset_token = self.field(
"reset_token",
mandatory = True,
not_empty = True
)
password = self.field(
"password",
mandatory = True
)
password_confirm = self.field(
"password_confirm",
mandatory = True
)
try: self.account_c.reset(reset_token, password, password_confirm)
except appier.AppierException as error:
return self.template(
"reset.html.tpl",
next = next,
reset_token = reset_token,
password = password,
password_confirm = password_confirm,
error = error.message
)
return self.redirect(
next or self.url_for(self.login_route_admin)
)
def confirm(self):
next = self.field("next")
confirmation_token = self.field(
"confirmation_token",
mandatory = True,
not_empty = True
)
send_email = self.field("send_email", True, cast = bool)
self.account_c.confirm(confirmation_token, send_email = send_email)
return self.redirect(
next or self.url_for(self.login_route_admin)
)
def new_account(self):
if not self.owner.admin_available: raise appier.SecurityError(
message = "Administration not available"
)
if not self.owner.admin_open: raise appier.SecurityError(
message = "Signup not allowed"
)
return self.template(
"account/new.html.tpl",
account = dict(),
errors = dict()
)
def create_account(self):
if not self.owner.admin_available: raise appier.SecurityError(
message = "Administration not available"
)
if not self.owner.admin_open: raise appier.SecurityError(
message = "Signup not allowed"
)
account = self.account_c.new()
account.type = self.account_c.USER_TYPE
account.enabled = False
try: account.save()
except appier.ValidationError as error:
return self.template(
"account/new.html.tpl",
error = "Problems occurred creating account",
account = error.model,
errors = error.errors
)
return self.redirect(
self.url_for(
"admin.mail_account",
username = account.username
)
)
@appier.ensure(context = "admin")
def me_account(self):
account_c = self._get_cls(self.account_c)
account = account_c.from_session(meta = True)
return self.template(
"account/show.html.tpl",
account = account
)
@appier.ensure(token = "admin.accounts", context = "admin")
def show_account(self, username):
account_c = self._get_cls(self.account_c)
account = account_c.get(
username = username,
meta = True
)
return self.template(
"account/show.html.tpl",
account = account
)
@appier.ensure(token = "admin.accounts", context = "admin")
def mail_account(self, username):
raise appier.NotImplementedError()
def avatar_account(self, username):
strict = self.field("strict", False, cast = bool)
cache = self.field("cache", False, cast = bool)
account_c = self._get_cls(self.account_c)
account = account_c.get(
username = username,
rules = False
)
return account._send_avatar(
strict = strict,
cache = cache
)
@appier.ensure(token = "admin.options", context = "admin")
def options(self):
return self.template(
"options.html.tpl",
section = "options",
labels = self._labels(),
errors = dict()
)
@appier.ensure(token = "admin.options", context = "admin")
def options_action(self):
layout = self.field("layout")
theme = self.field("theme")
libs = self.field("libs")
layout_s = layout.split("-", 1)
theme_s = theme.split("-", 1)
layout_l = len(layout_s)
theme_l = len(theme_s)
if layout_l == 1: layout_s.append("")
layout_s, sub_layout_s = layout_s
if theme_l == 1: theme_s.append("")
theme_s, style_s = theme_s
layout_s = layout_s.lower().strip()
sub_layout_s = sub_layout_s.lower().strip()
theme_s = theme_s.lower().strip()
style_s = style_s.lower().strip()
libs_s = libs.lower().strip()
self.session["layout"] = layout_s
self.session["sub_layout"] = sub_layout_s
self.session["theme"] = theme_s
self.session["style"] = style_s
self.session["libs"] = libs_s
self.session.permanent = True
return self.template(
"options.html.tpl",
section = "options",
labels = self._labels(),
errors = dict()
)
@appier.ensure(token = "admin.social", context = "admin")
def social(self):
socials = self.socials()
linked = self.linked()
return self.template(
"social.html.tpl",
section = "social",
socials = socials,
linked = linked
)
@appier.ensure(token = "admin.operations", context = "admin")
def operations(self):
return self.template(
"operations.html.tpl",
section = "operations"
)
@appier.ensure(token = "admin.status", context = "admin")
def status(self):
return self.template(
"status.html.tpl",
section = "status"
)
@appier.ensure(token = "admin.status", context = "admin")
def list_routes(self):
return self.template(
"routes.html.tpl",
section = "status",
routes = self._routes()
)
@appier.ensure(token = "admin.status", context = "admin")
def list_configs(self):
configs = appier.config.CONFIGS
configs = appier.legacy.items(configs)
configs.sort()
return self.template(
"configs.html.tpl",
section = "status",
configs = configs
)
@appier.ensure(token = "admin.status", context = "admin")
def list_parts(self):
parts = self.owner.get_parts()
return self.template(
"parts.html.tpl",
section = "status",
parts = parts
)
@appier.ensure(token = "admin.status", context = "admin")
def show_part(self, name):
part = self.owner.get_part(name)
info = part.info()
info_l = appier.legacy.keys(info)
info_l.sort()
return self.template(
"part.html.tpl",
section = "status",
part = part,
info = info,
info_l = info_l
)
@appier.ensure(token = "admin.status", context = "admin")
def load_part(self, name):
part = self.owner.get_part(name)
self.owner._load_part(part)
return self.redirect(
self.url_for(
"admin.show_part",
name = name,
message = "Part %s has been loaded" % name
)
)
@appier.ensure(token = "admin.status", context = "admin")
def unload_part(self, name):
part = self.owner.get_part(name)
self.owner._unload_part(part)
return self.redirect(
self.url_for(
"admin.show_part",
name = name,
message = "Part %s has been unloaded" % name
)
)
@appier.ensure(token = "admin.status", context = "admin")
def list_libraries(self):
libraries = self.owner.get_libraries()
return self.template(
"libraries.html.tpl",
section = "status",
libraries = libraries
)
@appier.ensure(context = "admin")
def oauth_authorize(self):
try:
# verifies if the OAuth system is allowed if that's not
# the case raises an exception indicating so
if not self.owner.admin_oauth: raise appier.SecurityError(
message = "OAuth not allowed"
)
# retrieves the complete set of fields that are going
# to be used on the initial authorize state of OAuth
client_id = self.field("client_id", mandatory = True)
redirect_uri = self.field("redirect_uri", mandatory = True)
scope = self.field("scope", mandatory = True)
response_type = self.field("response_type", "code")
state = self.field("state", None)
# verifies/ensures that the response type to be received
# is the code, as that's the only one supported
appier.verify("response_type", "code")
# normalizes the scope value to the list representation
# and then sorts it in the normal manner (normalization)
scope_l = scope.split(" ")
scope_l.sort()
# runs the mandatory retrieval of the OAuth client associated
# with the provided client id, notice that the redirect URI is
# used as part of the search filter (security measures)
oauth_client = models.OAuthClient.get_e(
client_id = client_id,
redirect_uri = redirect_uri
)
# asserts that the requested scope is valid for the associated
# OAuth client meaning that they overlap
oauth_client.assert_scope(scope_l)
# tries to reuse an already authorized token that is considered
# equivalent to the current one, if the re-usage operation is a
# success then redirects the user agent immediately
result, tokens, oauth_token = models.OAuthToken.reuse_s(
redirect_uri, scope_l, oauth_client
)
if result: return self.redirect(
redirect_uri,
params = dict(
code = oauth_token.authorization_code,
scope = " ".join(oauth_token.tokens),
state = state
)
)
# runs the template rendering for the OAuth authorize panel
# it should prompt the final user for permission agreement
return self.template(
"oauth/authorize.html.tpl",
client_id = client_id,
redirect_uri = redirect_uri,
scope = scope,
response_type = response_type,
state = state,
oauth_client = oauth_client,
tokens = tokens
)
except BaseException as exception:
redirect_uri = self.field("redirect_uri", None)
state = self.field("state", None)
if not redirect_uri: raise
code = exception.code if hasattr(exception, "code") else None
error_message = exception.message if hasattr(exception, "message") else None
error_code = OAUTH_ERROR_CODES.get(code, "server_error")
return self.redirect(
redirect_uri,
params = dict(
error = error_code,
error_description = error_message,
state = state
)
)
@appier.ensure(context = "admin")
def do_oauth_authorize(self):
if not self.owner.admin_oauth: raise appier.SecurityError(
message = "OAuth not allowed"
)
client_id = self.field("client_id", mandatory = True)
redirect_uri = self.field("redirect_uri", mandatory = True)
scope = self.field("scope", mandatory = True)
state = self.field("state", mandatory = True)
scope_l = scope.split(" ")
scope_l.sort()
account = self.account_c.from_session()
oauth_client = models.OAuthClient.get_e(
client_id = client_id,
redirect_uri = redirect_uri
)
oauth_token = oauth_client.build_token_s(
username = account.username,
scope = scope_l
)
return self.redirect(
redirect_uri,
params = dict(
code = oauth_token.authorization_code,
scope = " ".join(oauth_token.tokens),
state = state
)
)
@appier.ensure(context = "admin")
def oauth_deny(self):
if not self.owner.admin_oauth: raise appier.SecurityError(
message = "OAuth not allowed"
)
redirect_uri = self.field("redirect_uri", mandatory = True)
return self.redirect(
redirect_uri,
params = dict(
error = "access_denied",
error_description = "Permissions error"
)
)
def oauth_access_token(self):
# verifies if the OAuth system is allowed if that's not
# the case raises an exception indicating so
if not self.owner.admin_oauth: raise appier.SecurityError(
message = "OAuth not allowed"
)
# retrieve the multiple fields that are going to be used for the
# process of issuing the access token (only authorization code is
# going to be returned to the client)
client_id = self.field("client_id", mandatory = True)
client_secret = self.field("client_secret", mandatory = True)
redirect_uri = self.field("redirect_uri", mandatory = True)
code = self.field("code", None)
refresh_token = self.field("refresh_token", None)
grant_type = self.field("grant_type", "authorization_code")
# tries to retrieve the OAuth client associated with the
# provided client id and secret (client for authentication)
oauth_client = models.OAuthClient.get_e(
client_id = client_id,
client_secret = client_secret,
redirect_uri = redirect_uri
)
if grant_type == "authorization_code":
# uses the retrieved OAuth client together with the
# authorization code to try to retrieve the target token
oauth_token = models.OAuthToken.get_e(
authorization_code = code,
client = oauth_client.id,
rules = False
)
# verifies that the authorization code is the expected
# one and then unsets it from the OAuth token, so that
# it's no longer going to be used
oauth_token.verify_code(code, grant_type = grant_type)
oauth_token.unset_code_s()
elif grant_type == "refresh_token":
# uses the retrieved OAuth client together with the
# refresh token to try to retrieve the target token
oauth_token = models.OAuthToken.get_e(
refresh_token = refresh_token,
client = oauth_client.id,
rules = False
)
# verifies that the refresh token contains the expected
# value and then if that's the case re-generates a new
# access token value to be used
oauth_token.verify_refresh(refresh_token, grant_type = grant_type)
oauth_token.set_access_token_s()
else:
# raises a security error as no valid grant type was
# received (as expected)
raise appier.SecurityError(
message = "Invalid 'grant_type'"
)
# returns the final map based response containing the complete
# set of elements to the client to be used, notice that both
# the scope and the tokens are also returned so that the OAuth
# client is able to modify experience taking that into account
return dict(
access_token = oauth_token.access_token,
token_type = "bearer",
expires_in = oauth_token.expires_in,
refresh_token = oauth_token.refresh_token,
scope = oauth_token.scope,