Requests and stores the NOMIS API client token from mtp-api
4095
def get_client_token():
    
    if getattr(settings, 'NOMIS_API_CLIENT_TOKEN', ''):
        return settings.NOMIS_API_CLIENT_TOKEN
    global client_token
    if not client_token or client_token['expires'] and client_token['expires'] - now() < datetime.timedelta(days=1):
        session = None
        try:
            session = api_client.get_authenticated_api_session(settings.TOKEN_RETRIEVAL_USERNAME,
                                                               settings.TOKEN_RETRIEVAL_PASSWORD)
            client_token = session.get('/tokens/nomis/').json()
        except (requests.RequestException, HttpNotFoundError, ValueError, AttributeError):
            logger.exception('Cannot load NOMIS API client token')
            return None
        finally:
            if session and getattr(session, 'access_token', None):
                api_client.revoke_token(session.access_token)
        if client_token.get('expires'):
            client_token['expires'] = parse_datetime(client_token['expires'])
            if client_token['expires'] < now():
                logger.error('NOMIS API client token from mtp-api had expired')
                return None
    return client_token['token']
814857
def access_token(self):

        '''  '''

        title = '%s.access_token' % self.__class__.__name__
    
    # import dependencies
        from time import time
        import requests

    # construct request kwargs
        request_kwargs = {
            'url': self.token_endpoint,
            'data': {
                'client_id': self.client_id,
                'client_secret': self.client_secret,
                'grant_type': 'client_credentials'
            }
        }

    # send request
        try:
            current_time = time()
            response = requests.post(**request_kwargs)
        except Exception:
            if self.requests_handler:
                request_kwargs['method'] = 'POST'
                request_object = requests.Request(**request_kwargs)
                return self.requests_handler(request_object)
            else:
                raise

        response_details = self.response_handler.handle(response)

        if response_details['json']:
            self._access_token = response_details['json']['access_token']
            expires_in = response_details['json']['expires_in']
            self.expires_at = current_time + expires_in
            
        return self._access_token
925411
async def main():
    
    # Create Client from endpoint string in Duniter format
    client = Client(BMAS_ENDPOINT)
    tasks = []

    # Get the node summary infos by dedicated method (with json schema validation)
    print("\nCall bma.node.summary:")
    task = asyncio.ensure_future(client(bma.node.summary))
    tasks.append(task)

    # Get the money parameters located in the first block
    print("\nCall bma.blockchain.parameters:")
    task = asyncio.ensure_future(client(bma.blockchain.parameters))
    tasks.append(task)

    responses = await asyncio.gather(*tasks)
    # you now have all response bodies in this variable
    print("\nResponses:")
    print(responses)

    # Close client aiohttp session
    await client.close()
13508
def _api_post(path, data, server=None):
    '''
    
    '''
    server = _get_server(server)
    response = requests.post(
            url=_get_url(server['ssl'], server['url'], server['port'], path),
            auth=_get_auth(server['user'], server['password']),
            headers=_get_headers(),
            data=salt.utils.json.dumps(data),
            verify=False
    )
    return _api_response(response)
1104833
def _make_request(
            self, api_resource, method='GET', params=None, **kwargs):
        
        if kwargs.get('json'):
            headers = {
                'Authorization': 'Bearer {}'.format(self._token),
                'Content-Type': 'application/json'
            }
        else:
            headers = {
                'Authorization': 'Bearer {}'.format(self._token)
            }

        response = requests.request(
            method=method,
            url='{0}{1}'.format(self.BASE_API_URL, api_resource),
            headers=headers,
            params=params,
            **kwargs
        )

        if response.status_code >= 400:
            error_response = response.json()

            raise(ToshlException(
                status_code=response.status_code,
                error_id=error_response['error_id'],
                error_description=error_response['description'],
                extra_info=error_response.get('fields')))

        return response
416807
def encode_request(name, uuid, callable, partition_id):
    
    client_message = ClientMessage(payload_size=calculate_size(name, uuid, callable, partition_id))
    client_message.set_message_type(REQUEST_TYPE)
    client_message.set_retryable(RETRYABLE)
    client_message.append_str(name)
    client_message.append_str(uuid)
    client_message.append_data(callable)
    client_message.append_int(partition_id)
    client_message.update_frame_length()
    return client_message
1195177
def _request(self, base_url, client_id, client_secret,
                 parameters, **kwargs):
        """"""
        logging.debug('Getting an OAuth token for client "%s" with scope "%s"',
                      client_id, parameters.get('scope'))
        headers = {'Content-Type': 'application/x-www-form-urlencoded',
                   'Accept': 'application/json'}

        api = API(base_url,
                  auth_username=client_id,
                  auth_password=client_secret,
                  **kwargs)
        endpoint = api.auth.token

        response = yield endpoint.post(body=urllib.urlencode(parameters),
                                       request_timeout=60,
                                       headers=headers)

        logging.debug('Received token: %s', response.get('access_token'))
        raise Return(response)
628410
def _post_parse_request(self, request, client_id='', **kwargs):
        

        request = RefreshAccessTokenRequest(**request.to_dict())

        try:
            keyjar = self.endpoint_context.keyjar
        except AttributeError:
            keyjar = ""

        request.verify(keyjar=keyjar, opponent_id=client_id)

        if "client_id" not in request:  # Optional for refresh access token request
            request["client_id"] = client_id

        logger.debug("%s: %s" % (request.__class__.__name__, sanitize(request)))

        return request
1117467
async def main():
    
    # Create Client from endpoint string in Duniter format
    client = Client(BMAS_ENDPOINT)

    # Get the node summary infos by dedicated method (with json schema validation)
    print("\nCall bma.node.summary:")
    response = await client(bma.node.summary)
    print(response)

    # Get the money parameters located in the first block
    print("\nCall bma.blockchain.parameters:")
    response = await client(bma.blockchain.parameters)
    print(response)

    # Get the current block
    print("\nCall bma.blockchain.current:")
    response = await client(bma.blockchain.current)
    print(response)

    # Get the block number 10
    print("\nCall bma.blockchain.block(10):")
    response = await client(bma.blockchain.block, 10)
    print(response)

    # jsonschema validator
    summary_schema = {
        "type": "object",
        "properties": {
            "duniter": {
                "type": "object",
                "properties": {
                    "software": {
                        "type": "string"
                    },
                    "version": {
                        "type": "string",
                    },
                    "forkWindowSize": {
                        "type": "number"
                    }
                },
                "required": ["software", "version"]
            },
        },
        "required": ["duniter"]
    }

    # Get the node summary infos (direct REST GET request)
    print("\nCall direct get on node/summary")
    response = await client.get('node/summary', rtype=RESPONSE_AIOHTTP, schema=summary_schema)
    print(response)

    # Close client aiohttp session
    await client.close()
242776
def on_post(self, req, resp):
        

        grant_type = req.get_param('grant_type')
        password = req.get_param('password')
        username = req.get_param('username')

        # errors or not, disable client caching along the way
        # per the spec
        resp.disable_caching()

        if not grant_type or not password or not username:
            resp.status = falcon.HTTP_400
            resp.serialize({
                'error': 'invalid_request',
                'error_description': 'A grant_type, username, & password '
                                     'parameters are all required when '
                                     'requesting an OAuth access_token',
                'error_uri': 'tools.ietf.org/html/rfc6749#section-4.3.2',
            })
        elif grant_type != 'password':
            resp.status = falcon.HTTP_400
            resp.serialize({
                'error': 'unsupported_grant_type',
                'error_description': 'The grant_type parameter MUST be set '
                                     'to "password" not "%s"' % grant_type,
                'error_uri': 'tools.ietf.org/html/rfc6749#section-4.3.2',
            })
        else:
            try:
                token = self.auth_creds(username, password)
                resp.serialize({
                    'access_token': token,
                    'token_type': 'Bearer',
                })
            except AuthRejected as exc:
                resp.status = falcon.HTTP_401
                resp.set_header('WWW-Authenticate', self._realm)
                resp.serialize({
                    'error': 'invalid_client',
                    'error_description': exc.detail,
                })
1100169
def process_request(self, request=None, cookie=None, **kwargs):
        
        _cntx = self.endpoint_context
        _sdb = _cntx.sdb

        if 'post_logout_redirect_uri' in request:
            if 'id_token_hint' not in request:
                raise InvalidRequest(
                    "If post_logout_redirect_uri then id_token_hint is a MUST")
        _cookie_name = self.endpoint_context.cookie_name['session']
        try:
            part = self.endpoint_context.cookie_dealer.get_cookie_value(
                cookie, cookie_name=_cookie_name)
        except IndexError:
            raise InvalidRequest('Cookie error')
        except KeyError:
            part = None

        if part:
            # value is a base64 encoded JSON document
            _cookie_info = json.loads(as_unicode(b64d(as_bytes(part[0]))))
            logger.debug('Cookie info: {}'.format(_cookie_info))
            _sid = _cookie_info['sid']
        else:
            logger.debug('No relevant cookie')
            _sid = ''
            _cookie_info = {}

        if 'id_token_hint' in request:
            logger.debug(
                'ID token hint: {}'.format(
                    request[verified_claim_name("id_token_hint")]))

            auds = request[verified_claim_name("id_token_hint")]['aud']
            _ith_sid = ''
            _sids = _sdb.sso_db.get_sids_by_sub(
                request[verified_claim_name("id_token_hint")]['sub'])

            if _sids is None:
                raise ValueError('Unknown subject identifier')

            for _isid in _sids:
                if _sdb[_isid]['authn_req']['client_id'] in auds:
                    _ith_sid = _isid
                    break

            if not _ith_sid:
                raise ValueError('Unknown subject')

            if _sid:
                if _ith_sid != _sid:  # someone's messing with me
                    raise ValueError('Wrong ID Token hint')
            else:
                _sid = _ith_sid
        else:
            auds = []

        try:
            session = _sdb[_sid]
        except KeyError:
            raise ValueError("Can't find any corresponding session")

        client_id = session['authn_req']['client_id']
        # Does this match what's in the cookie ?
        if _cookie_info:
            if client_id != _cookie_info['client_id']:
                logger.warning(
                    'Client ID in authz request and in cookie does not match')
                raise ValueError("Wrong Client")

        if auds:
            if client_id not in auds:
                raise ValueError('Incorrect ID Token hint')

        _cinfo = _cntx.cdb[client_id]

        # verify that the post_logout_redirect_uri if present are among the ones
        # registered

        try:
            _uri = request['post_logout_redirect_uri']
        except KeyError:
            if _cntx.issuer.endswith('/'):
                _uri = "{}{}".format(_cntx.issuer,
                                     self.kwargs['post_logout_uri_path'])
            else:
                _uri = "{}/{}".format(_cntx.issuer,
                                      self.kwargs['post_logout_uri_path'])
            plur = False
        else:
            plur = True
            verify_uri(_cntx, request, 'post_logout_redirect_uri',
                       client_id=client_id)

        payload = {
            'sid': _sid, 'client_id': client_id,
            'user': session['authn_event']['uid']
        }

        # redirect user to OP logout verification page
        if plur and 'state' in request:
            _uri = '{}?{}'.format(_uri, urlencode({'state': request['state']}))
            payload['state'] = request['state']

        payload['redirect_uri'] = _uri

        logger.debug('JWS payload: {}'.format(payload))
        # From me to me
        _jws = JWT(_cntx.keyjar, iss=_cntx.issuer, lifetime=86400,
                   sign_alg=self.kwargs['signing_alg'])
        sjwt = _jws.pack(payload=payload, recv=_cntx.issuer)

        location = '{}?{}'.format(self.kwargs['logout_verify_url'],
                                  urlencode({'sjwt': sjwt}))
        return {'redirect_location': location}
990838
def authorize(client_key, client_secret, credfile=CONFIG_FILE, app='trlo.py',
              expiration='never', scope='read,write'):
    
    # 1. Obtain the request token.
    oauth = OAuth1Session(client_key, client_secret=client_secret)
    request_token = oauth.fetch_request_token(OAUTH_REQUEST_TOKEN_URL)

    # 2. Authorize the user (in the browser).
    authorization_url = oauth.authorization_url(OAUTH_BASE_AUTHORIZE_URL,
        name=app, expiration=expiration, scope=scope)
    print("Please visit the following URL to authorize this app:")
    print(authorization_url)
    print('')
    print("Once you've authorized, copy and paste the token Trello gives you below.")
    # Py3K backwards-compatibility shim
    global input
    try:
        input = raw_input
    except NameError:
        pass
    verifier = input("Trello's token: ").strip()

    # 3. Obtain the access token
    oauth = OAuth1Session(client_key, client_secret=client_secret,
        resource_owner_key=request_token['oauth_token'],
        resource_owner_secret=request_token['oauth_token_secret'],
        verifier=verifier)
    access_token = oauth.fetch_access_token(OAUTH_ACCESS_TOKEN_URL)

    # Save all our creds to ~/.trlo so we can get at 'em later.
    # The names are specially chosen so we can do OAuth1Session(**creds)
    creds = {
        'client_key': client_key,
        'client_secret': client_secret,
        'resource_owner_key': access_token['oauth_token'],
        'resource_owner_secret': access_token['oauth_token_secret'],
    }
    with open(credfile, 'w') as fp:
        json.dump(creds, fp)
60597
def get_token(self, client_id, target, api_type, grant_type,
                  id_token=None, refresh_token=None, scope='openid'):

        

        if id_token and refresh_token:
            raise ValueError('Only one of id_token or refresh_token '
                             'can be None')

        data = {
            'client_id': client_id,
            'grant_type': grant_type,
            'target': target,
            'scope': scope,
            'api_type': api_type,
        }

        if id_token:
            data.update({'id_token': id_token})
        elif refresh_token:
            data.update({'refresh_token': refresh_token})
        else:
            raise ValueError('Either id_token or refresh_token must '
                             'have a value')

        return self.post(
            'https://{}/delegation'.format(self.domain),
            headers={'Content-Type': 'application/json'},
            data=data
        )
113057
async def _request(
            self,
            method: str,
            url: str,
            *,
            access_token: str = None,
            access_token_expiration: datetime = None,
            headers: dict = None,
            params: dict = None,
            json: dict = None,
            ssl: bool = True) -> dict:
        """"""
        if (access_token_expiration
                and datetime.now() >= access_token_expiration):
            raise TokenExpiredError('Long-lived access token has expired')

        if not headers:
            headers = {}
        headers.update({'Content-Type': 'application/json'})

        if not params:
            params = {}
        if access_token:
            params.update({'access_token': access_token})

        try:
            async with async_timeout.timeout(self.request_timeout):
                async with self._websession.request(
                        method, url, headers=headers, params=params, json=json,
                        ssl=ssl) as resp:
                    resp.raise_for_status()
                    data = await resp.json(content_type=None)
                    _raise_for_remote_status(url, data)
        except ClientError as err:
            raise RequestError(
                'Error requesting data from {0}: {1}'.format(url, err))
        except asyncio.TimeoutError:
            raise RequestError('Timeout during request: {0}'.format(url))

        return data
1344090
def setup_client(token)
      client = Octokit::Client.new(access_token: token)
      client.auto_paginate = true
      client
    end
502540
def __perform_request(self, url, type=GET, params=None):
        
        if params is None:
            params = {}

        # check we have a token
        if not self.token:
            raise SetupError("No token provided.")

        # check we have an endpoint
        if not self.endpoint:
            raise SetupError("No endpoint provided.")

        # don't show warning about self-signed certificate in dev mode
        if self.dev:
            requests.packages.urllib3.disable_warnings()

        url = urljoin(self.endpoint, url)

        # lookup table to find out the apropriate requests method,
        # headers and payload type (json or query parameters)
        identity = lambda x: x
        json_dumps = lambda x: json.dumps(x)
        lookup = {
            GET: (requests.get, {}, 'params', identity),
            POST: (requests.post, {'Content-type': 'application/json'}, 'data',
                   json_dumps),
            PUT: (requests.put, {'Content-type': 'application/json'}, 'data',
                  json_dumps),
            DELETE: (requests.delete,
                     {'content-type': 'application/json'},
                     'data', json_dumps),
        }

        requests_method, headers, payload, transform = lookup[type]
        headers.update({'Authorization': self.token})
        kwargs = {'headers': headers, payload: transform(params)}

        # remove token from log
        headers_str = str(headers).replace(self.token.strip(), 'TOKEN')
        self._log.debug('%s %s %s:%s %s' %
                        (type, url, payload, params, headers_str))

        return requests_method(url, verify=False, **kwargs)
247297
def request_token(self):
        
        client_key = request.oauth.client_key
        realm = request.oauth.realm
        # TODO: fallback on default realm?
        callback = request.oauth.callback_uri
        request_token = generate_token(length=self.request_token_length[1])
        token_secret = generate_token(length=self.secret_length)
        self.save_request_token(client_key, request_token, callback,
            realm=realm, secret=token_secret)
        return urlencode([(u'oauth_token', request_token),
                          (u'oauth_token_secret', token_secret),
                          (u'oauth_callback_confirmed', u'true')])