comparison libervia/pages/_bridge/page_meta.py @ 1288:7cec74557aa3

pages: `_bridge` page: this page is an endpoint to do bridge calls from browser scripts.
author Goffi <goffi@goffi.org>
date Fri, 19 Jun 2020 16:47:51 +0200
parents
children b1215347b5c3
comparison
equal deleted inserted replaced
1287:1f26d8c2afc1 1288:7cec74557aa3
1 #!/usr/bin/env python3
2
3 import tempfile
4 import os
5 import os.path
6 import json
7 from twisted.internet import defer
8 from twisted.web import static
9 from sat.core.i18n import _
10 from sat.core.log import getLogger
11 from libervia.server.constants import Const as C
12 from libervia.server.utils import ProgressHandler
13
14
15 log = getLogger(__name__)
16 """access to restricted bridge"""
17
18 name = "bridge"
19 on_data_post = "continue"
20
21
22 def parse_url(self, request):
23 self.getPathArgs(request, ["method_name"], min_args=1)
24
25
26 async def render(self, request):
27 if request.method != b'POST':
28 log.warning(f"Bad method used with _bridge endpoint: {request.method.decode()}")
29 return self.pageError(request, C.HTTP_BAD_REQUEST)
30 data = self.getRData(request)
31 profile = self.getProfile(request)
32 if profile is None:
33 log.warning("_bridge endpoint accessed without authorisation")
34 return self.pageError(request, C.HTTP_UNAUTHORIZED)
35 self.checkCSRF(request)
36 method_name = data["method_name"]
37 method_data = json.load(request.content)
38 try:
39 bridge_method = getattr(self.host.restricted_bridge, method_name)
40 except AttributeError:
41 log.warning(_(
42 "{profile!r} is trying to access a bridge method not implemented in "
43 "RestrictedBridge: {method_name}").format(
44 profile=profile, method_name=method_name))
45 return self.pageError(request, C.HTTP_BAD_REQUEST)
46
47 try:
48 args, kwargs = method_data['args'], method_data['kwargs']
49 except KeyError:
50 log.warning(_(
51 "{profile!r} has sent a badly formatted method call: {method_data}"
52 ).format(profile=profile, method_data=method_data))
53 return self.pageError(request, C.HTTP_BAD_REQUEST)
54
55 if "profile" in kwargs:
56 log.warning(_(
57 '"profile" key should not be in method kwargs, hack attempt? '
58 "profile={profile}, method_data={method_data}"
59 ).format(profile=profile, method_data=method_data))
60 return self.pageError(request, C.HTTP_BAD_REQUEST)
61
62 ret = await bridge_method(*args, **kwargs, profile=profile)
63 return json.dumps(ret)