Exemplo n.º 1
0
 def run_action_webhook_multi(self, action, eval_context={}):
     user = eval_context.get('user')
     fields = action.webhook_fields.mapped('name')
     records = eval_context.get('records') or self.env[action.model_name]
     payload = {
         'name': action.name,
         'uid': eval_context.get('uid'),
         'user': user and user.name,
         'model': action.model_name,
         'records': json.dumps(records.read(fields=fields), cls=RecordEncoder)
     }
     auth = None
     session = Session()
     if action.webhook_authentication == 'base':
         auth = HTTPBasicAuth(action.webhook_user, action.webhook_password)
     elif action.webhook_authentication == 'digest':
         auth = HTTPDigestAuth(action.webhook_user, action.webhook_password)
     elif action.webhook_authentication == 'oauth1':
         auth = OAuth1(action.webhook_client_key, client_secret=action.webhook_client_secret,
                resource_owner_key=action.webhook_resource_owner_key,
                resource_owner_secret=action.webhook_resource_owner_secret)
     elif action.webhook_authentication == 'oauth2' and action.webhook_grant == 'password':
         session = OAuth2Session(client=LegacyApplicationClient(client_id=action.webhook_client_key))
         session.fetch_token(token_url=action.webhook_token_url, username=action.webhook_user,
             password=action.webhook_password, client_id=action.webhook_client_key, 
             client_secret=action.webhook_client_secret)
     elif action.webhook_authentication == 'oauth2' and action.webhook_grant == 'client_credentials':
         session = OAuth2Session(client=BackendApplicationClient(client_id=client_id))
         session.fetch_token(token_url=action.webhook_token_url, client_id=action.webhook_client_key, 
             client_secret=action.webhook_client_secret)
     elif action.webhook_authentication == 'token':
         payload.update({'access_token': action.webhook_token})
     if action.webhook_payload:
         safe_eval(action.webhook_payload.strip(), eval_context, mode="exec", nocopy=True)
         if 'content' in eval_context:
             payload.update({'content': eval_context['content']})
     request = Request(action.webhook_method,  action.webhook_address, data=payload, auth=auth)
     prepared_request = session.prepare_request(request)
     logger_message = "Webhook: [%s] %s" % (action.webhook_method, action.webhook_address)
     try:
         webhook_path = action.webhook_path
         webhook_verify = action.webhook_verify
         verify = webhook_path if webhook_verify and webhook_path else webhook_verify
         response = session.send(prepared_request, timeout=action.webhook_timeout, verify=verify)
         _logger.info("%s - %s" % (logger_message, response.status_code))
         if action.webhook_process:
             eval_context.update({'request': prepared_request, 'response': response})
             safe_eval(action.webhook_process.strip(), eval_context, mode="exec")
     except RequestException:
         _logger.exception(logger_message)
     finally:
         session.close()
Exemplo n.º 2
0
 def get_app_session(self, domain):
     if self.can_auth_with_client_credentials:
         sess = self.app_sessions.get(domain)
         if not sess:
             client_id = self.get_credentials(domain)[0]
             if self.use_basic_auth_for_app_session:
                 sess = Session()
                 sess.auth = self.get_credentials(domain)
             else:
                 sess = self.session_class(client=BackendApplicationClient(client_id))
             self.app_sessions[domain] = sess
         if not sess.auth and not sess.token:
             access_token_url = self.access_token_url.format(domain=domain)
             client_id, client_secret = self.get_credentials(domain)
             sess.fetch_token(access_token_url, client_id=client_id,
                              client_secret=client_secret)
         return sess
     else:
         return self.get_auth_session(domain)
Exemplo n.º 3
0
class Client:
    __secrets = {"username": None,
                 "password": None,
                 "client_id": None,
                 "client_secret": None}

    def __init__(self, config_file=None, **kwargs):
        auth_types = {'basicauth': self.__http_basic_auth,
                      'digestauth': self.__http_digest_auth,
                      'oauth2': self.__oauth2}

        self.config = Config(path=config_file)

        #self.config['auth'] = auth

        if self.config.auth:
            assert self.config['auth']['type'].lower() in auth_types.keys()
            self.__get_secrets_file(path=self.config['auth']['secret'])
            auth_types[self.config['auth']['type']]()
        else:
            self.session = Session()
        self.iota = Agent(config=self.config, session=self.session)
        self.ocb = Orion(config=self.config, session=self.session)
        self.timeseries = QuantumLeap(config=self.config, session=self.session)

    @property
    def headers(self):
        return self.session.headers

    @property
    def cert(self):
        return self.session.cert

    @property
    def secrets(self):
        return self.__secrets

    @secrets.setter
    def secrets(self, data: dict):
        self.__secrets.update(data)

    @secrets.deleter
    def secrets(self):
        self.__secrets = {}

    def __get_secrets_file(self, path=None):
        """
        Reads credentials form secret file the path variable is pointing to.
        :param path: location of secrets-file
        :return: None
        """

        try:
            with open(path, 'r') as filename:
                logger.info(f"Reading credentials from: {path}")
                self.__secrets.update(json.load(filename))

        except IOError as err:
            if err.errno == errno.ENOENT:
                logger.error(f"{path} - does not exist")
            elif err.errno == errno.EACCES:
                logger.error(f"{path} - cannot be read")
            else:
                logger.error(f"{path} - some other error")

    def __http_basic_auth(self):
        """
        Initiates a client using the basic authorization mechanism provided by
        the requests package. The documentation of the package is located here:
        https://requests.readthedocs.io/en/master/user/authentication/
        The credentials must be provided via secret-file.
        """
        try:
            self.session = Session()
            self.session.auth = HTTPBasicAuth(self.__secrets['username'],
                                              self.__secrets['password'])
        except KeyError:
            pass

    def __http_digest_auth(self):
        """
        Initiates a client using the digest authorization mechanism provided by
        the requests package. The documentation of the package is located here:
        https://requests.readthedocs.io/en/master/user/authentication/
        The credentials must be provided via secret-file.
        """
        try:
            self.session = Session()
            self.session.auth = HTTPDigestAuth(self.__secrets['username'],
                                               self.__secrets['password'])
        except KeyError:
            pass

    def __oauth2(self):
        """
        Initiates a oauthclient according to the workflows defined by OAuth2.0.
        We use requests-oauthlib for this implementation. The documentation
        of the package is located here:
        https://requests-oauthlib.readthedocs.io/en/latest/index.html
        The information for workflow selection must be provided via
        filip-config. The credentials must be provided via secrets-file.
        :return: None
        """
        oauth2clients = {'authorization_code': None,
                         'implicit': MobileApplicationClient,
                         'resource_owner_password_credentials':
                             LegacyApplicationClient,
                         'client_credentials': BackendApplicationClient, }
        try:
            workflow = self.config['auth']['workflow']
        except KeyError:
            logger.warning(f"No workflow for OAuth2 defined! Default "
                           f"workflow will used: Authorization Code Grant."
                           f"Other oauth2-workflows available are: "
                           f"{oauth2clients.keys()}")
            workflow = 'authorization_code_grant'

        oauthclient = oauth2clients[workflow](client_id=self.__secrets[
            'client_id'])
        self.session = OAuth2Session(client_id=None,
                                     client=oauthclient,
                                     auto_refresh_url=self.__secrets[
                                         'token_url'],
                                     auto_refresh_kwargs={
                                         self.__secrets['client_id'],
                                         self.__secrets['client_secret']})

        self.__token = self.session.fetch_token(
            token_url=self.__secrets['token_url'],
            username=self.__secrets['username'],
            password=self.__secrets['password'],
            client_id=self.__secrets['client_id'],
            client_secret=self.__secrets['client_secret'])

    def __token_saver(self, token):
        self.__token = token