68 lines
2.4 KiB
Python
68 lines
2.4 KiB
Python
# hobo - portal to configure and deploy applications
|
|
# Copyright (C) 2015-2022 Entr'ouvert
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify it
|
|
# under the terms of the GNU Affero General Public License as published
|
|
# by the Free Software Foundation, either version 3 of the License, or
|
|
# (at your option) any later version.
|
|
#
|
|
# This program 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
|
|
# GNU Affero General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU Affero General Public License
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
import urllib
|
|
|
|
import requests
|
|
from django.conf import settings
|
|
from django.utils.http import urlencode
|
|
from requests import Response
|
|
from requests import Session as RequestsSession
|
|
from requests.auth import AuthBase
|
|
|
|
from hobo.signature import sign_url
|
|
|
|
|
|
class PublikSignature(AuthBase):
|
|
def __init__(self, secret):
|
|
self.secret = secret
|
|
|
|
def __call__(self, request):
|
|
request.url = sign_url(request.url, self.secret)
|
|
return request
|
|
|
|
|
|
def get_known_service_for_url(url):
|
|
netloc = urllib.parse.urlparse(url).netloc
|
|
for services in settings.KNOWN_SERVICES.values():
|
|
for service in services.values():
|
|
remote_url = service.get('url')
|
|
if urllib.parse.urlparse(remote_url).netloc == netloc:
|
|
return service
|
|
return None
|
|
|
|
|
|
class Requests(RequestsSession):
|
|
def request(self, method, url, **kwargs):
|
|
remote_service = get_known_service_for_url(url)
|
|
kwargs['auth'] = PublikSignature(remote_service.get('secret'))
|
|
|
|
# only keeps the path (URI) in url parameter, scheme and netloc are
|
|
# in remote_service
|
|
scheme, netloc, path, params, query, fragment = urllib.parse.urlparse(url)
|
|
url = urllib.parse.urlunparse(('', '', path, params, query, fragment))
|
|
|
|
query_params = dict(urllib.parse.parse_qsl(query))
|
|
query_params['orig'] = remote_service.get('orig')
|
|
|
|
remote_service_base_url = remote_service.get('url')
|
|
scheme, netloc, dummy, params, old_query, fragment = urllib.parse.urlparse(remote_service_base_url)
|
|
|
|
query = urlencode(query_params)
|
|
url = urllib.parse.urlunparse((scheme, netloc, path, params, query, fragment))
|
|
|
|
return super().request(method, url, **kwargs)
|