comparison libervia/web/pages/_bridge/page_meta.py @ 1518:eb00d593801d

refactoring: rename `libervia` to `libervia.web` + update imports following backend changes
author Goffi <goffi@goffi.org>
date Fri, 02 Jun 2023 16:49:28 +0200
parents libervia/pages/_bridge/page_meta.py@106bae41f5c8
children
comparison
equal deleted inserted replaced
1517:b8ed9726525b 1518:eb00d593801d
1 #!/usr/bin/env python3
2
3 import json
4 from libervia.backend.core.i18n import _
5 from libervia.backend.core.log import getLogger
6 from libervia.frontends.bridge.bridge_frontend import BridgeException
7 from libervia.web.server.constants import Const as C
8
9
10 log = getLogger(__name__)
11 """access to restricted bridge"""
12
13 name = "bridge"
14 on_data_post = "continue"
15
16 # bridge method allowed when no profile is connected
17 NO_SESSION_ALLOWED = ("contacts_get", "identities_base_get", "identities_get")
18
19
20 def parse_url(self, request):
21 self.get_path_args(request, ["method_name"], min_args=1)
22
23
24 async def render(self, request):
25 if request.method != b'POST':
26 log.warning(f"Bad method used with _bridge endpoint: {request.method.decode()}")
27 return self.page_error(request, C.HTTP_BAD_REQUEST)
28 data = self.get_r_data(request)
29 profile = self.get_profile(request)
30 self.check_csrf(request)
31 method_name = data["method_name"]
32 if profile is None:
33 if method_name in NO_SESSION_ALLOWED:
34 # this method is allowed, we use the service profile
35 profile = C.SERVICE_PROFILE
36 else:
37 log.warning("_bridge endpoint accessed without authorisation")
38 return self.page_error(request, C.HTTP_UNAUTHORIZED)
39 method_data = json.load(request.content)
40 try:
41 bridge_method = getattr(self.host.restricted_bridge, method_name)
42 except AttributeError:
43 log.warning(_(
44 "{profile!r} is trying to access a bridge method not implemented in "
45 "RestrictedBridge: {method_name}").format(
46 profile=profile, method_name=method_name))
47 return self.page_error(request, C.HTTP_BAD_REQUEST)
48
49 try:
50 args, kwargs = method_data['args'], method_data['kwargs']
51 except KeyError:
52 log.warning(_(
53 "{profile!r} has sent a badly formatted method call: {method_data}"
54 ).format(profile=profile, method_data=method_data))
55 return self.page_error(request, C.HTTP_BAD_REQUEST)
56
57 if "profile" in kwargs or "profile_key" in kwargs:
58 log.warning(_(
59 '"profile" key should not be in method kwargs, hack attempt? '
60 "profile={profile}, method_data={method_data}"
61 ).format(profile=profile, method_data=method_data))
62 return self.page_error(request, C.HTTP_BAD_REQUEST)
63
64 try:
65 ret = await bridge_method(*args, **kwargs, profile=profile)
66 except BridgeException as e:
67 request.setResponseCode(C.HTTP_PROXY_ERROR)
68 ret = {
69 "fullname": e.fullname,
70 "message": e.message,
71 "condition": e.condition,
72 "module": e.module,
73 "classname": e.classname,
74 }
75 return json.dumps(ret)