Example #1
0
    def __init__(self, url, *auths):
        app = App._create_(url)
        auth = Security(app)
        for t, cred in auths:
            auth.update_with(t, cred)

        client = Client(auth)
        self.app, self.client = app, client

        self.client._Client__s.hooks['response'] = logHttp
Example #2
0
    def get_swagger(self):
        """Gets an authenticated Swagger Client."""

        swagger_url = self.get_url(
            'swagger', replacement_fields={'base_url': self.base_url})

        # load Swagger resource file into App object
        app = App._create_(swagger_url)

        auth = Security(app)
        # TODO: this isn't working...
        # ValueError: Unknown security name: [api_key]
        auth.update_with('api_key', self.api_token)

        # init swagger client
        client = Client(auth)

        return app, client
Example #3
0
    def request(self, operation, parameters):
        """Make a request against a certain operation on the API.

        :param operation: The operation to perform.
        :type operation: schema.Operation
        :param parameters: The parameters to use on the operation.
        :type parameters: dict

        :rtype: pyswagger.io.Response
        """
        security = Security(self._app)
        if self._auth_creds:
            security.update_with(*self._auth_creds)
        client = PyswaggerClient(security)

        result = client.request(operation._pyswagger_operation(**parameters))  # pylint: disable=protected-access

        return Response(result)
Example #4
0
    def __init__(
        self,
        schema_path,
        codec=None,
        username=None,
        password=None,
        token=None,
        security_name=None,
        extra_headers=None,
    ):
        if extra_headers is None:
            extra_headers = {}
        self.extra_headers = extra_headers

        self._schema_path = schema_path

        self._username = username
        self._password = password
        self._token = token

        self._auth_creds = None
        if username or password:
            security_name = security_name or "basic"
            self._auth_creds = (security_name, (username, password))
        elif token:
            security_name = security_name or "apiKey"
            self._auth_creds = (security_name, token)

        if codec is None:
            codec = CodecFactory()

        self._prim_factory = (codec._pyswagger_factory)  # pylint: disable=protected-access

        self._app = App.load(schema_path, prim=self._prim_factory)

        self._app.prepare()

        self._api = Api(self)

        security = Security(self._app)
        if self._auth_creds:
            security.update_with(*self._auth_creds)

        self.client = PyswaggerClient(security)
 def connect(self, token: str) -> None:
     """
     Establish connection for OpenSTF server
     :param token: stf access token
     :return: None
     """
     url = self.swagger_uri
     self.logger.debug(f"Fetch API spec from: {url}")
     # load Swagger resource file into App object
     try:
         self._app = App._create_(url)  # pylint: disable-line
     except (FileNotFoundError, urllib.error.URLError) as error:
         self.logger.error(error)
         raise
     auth = Security(self._app)
     auth.update_with('accessTokenAuth', f"Bearer {token}")  # token
     # init swagger client
     self._client = Client(auth)
     self.logger.info('StfClient library initiated')
Example #6
0
class BasicAuthAndApiKeyTestCase(unittest.TestCase):
    """ test cases for authorzation related """
    def setUp(self):
        self.s = Security(app)
        self.s.update_with('simple_key', '123456')
        self.s.update_with('simple_basic', ('mission', '123123'))
        self.s.update_with('simple_basic2', ('qoo', '456456'))
        self.s.update_with('simple_key2', '789789')

    def test_deleteUser(self):
        """ basic auth """
        req, _ = app.op['deleteUser'](username='******')
        self.s(req).prepare()

        self.assertTrue('Authorization' in req.header)
        self.assertEqual(req.header['Authorization'],
                         'Basic bWlzc2lvbjoxMjMxMjM=')

    def test_getUserByName(self):
        """ api key, passed by query """
        req, _ = app.op['getUserByName'](username='******')
        self.s(req).prepare()

        qk = [x for x in req.query if x[0] == 'simpleQK']
        self.assertTrue(len(qk) > 0)
        self.assertEqual(qk[0][1], '123456')

    def test_createUser(self):
        """ api key, passed by header """
        req, _ = app.op['createUser'](body=dict(
            id=0, username='******', firstName='liao', lastName='mission'))
        self.s(req).prepare()

        self.assertTrue('simpleHK' in req.header)
        self.assertEqual(req.header['simpleHK'], '789789')

    def test_getAllUsers(self):
        """ test global auth """
        req, _ = app.op['getAllUsers']()
        self.s(req).prepare()

        self.assertTrue('Authorization' in req.header)
        self.assertEqual(req.header['Authorization'], 'Basic cW9vOjQ1NjQ1Ng==')
Example #7
0
class BasicAuthAndApiKeyTestCase(unittest.TestCase):
    """ test cases for authorzation related """

    def setUp(self):
        self.s = Security(app)
        self.s.update_with('simple_key', '123456')
        self.s.update_with('simple_basic', ('mission', '123123'))
        self.s.update_with('simple_basic2', ('qoo', '456456'))
        self.s.update_with('simple_key2', '789789')

    def test_deleteUser(self):
        """ basic auth """
        req, _ = app.op['deleteUser'](username='******')
        self.s(req).prepare()

        self.assertTrue('Authorization' in req.header)
        self.assertEqual(req.header['Authorization'], 'Basic bWlzc2lvbjoxMjMxMjM=')

    def test_getUserByName(self):
        """ api key, passed by query """
        req, _ = app.op['getUserByName'](username='******')
        self.s(req).prepare()

        qk = [x for x in req.query if x[0] == 'simpleQK']
        self.assertTrue(len(qk) > 0)
        self.assertEqual(qk[0][1], '123456')

    def test_createUser(self):
        """ api key, passed by header """
        req, _ = app.op['createUser'](body=dict(id=0, username='******', firstName='liao', lastName='mission'))
        self.s(req).prepare()

        self.assertTrue('simpleHK' in req.header)
        self.assertEqual(req.header['simpleHK'], '789789')

    def test_getAllUsers(self):
        """ test global auth """
        req, _ = app.op['getAllUsers']()
        self.s(req).prepare()

        self.assertTrue('Authorization' in req.header)
        self.assertEqual(req.header['Authorization'], 'Basic cW9vOjQ1NjQ1Ng==')
Example #8
0
def generate_client(URL, KEY=None):
    app = App._create_(URL)
    auth = Security(app)
    auth.update_with('apiKeyHeader', KEY)  # api key
    client = Client(auth)
    return app, client
 def connect_to_stf(self, host, token):
     self.app = App._create_('http://%s/api/v1/swagger.json' % host)
     auth = Security(self.app)
     auth.update_with('accessTokenAuth', 'Bearer ' + token)
     self.client = Client(auth)
Example #10
0
#!/usr/bin/env python3

from pyswagger import App, Security
from pyswagger.contrib.client.requests import Client as SwagClient

from shared.config import config

import startup

oauth_credentials = startup.run_flow()

# Autheticates against the Bikebuds API using google-based oauth identity.
# I can't figure out how to do this with firebase identity
swag_app = App._create_(config.api_url + '/bikebudsv1openapi.json')
swag_auth = Security(swag_app)
swag_auth.update_with('api_key', config.python_client_testing_api_key)

api_client = SwagClient(swag_auth)
api_client._Client__s.headers[
    'Authorization'] = 'Bearer ' + oauth_credentials.id_token
# This is a hack for my server, auth_util.verify_claims by default tries to
# validate via firebase.
api_client._Client__s.headers['UseAltAuth'] = '1'

req, resp = swag_app.op['getProfile'](body=None)
req.produce('application/json')
api_client.request((req, resp))
print(resp.status)
print(resp.data)
Example #11
0
class Riot:
    def __init__(
        self,
        api_key: str,
        swagger_file:
        str = "http://www.mingweisamuel.com/riotapi-schema/swaggerspec-2.0.yml"
    ):

        self.api_key = api_key
        self.swagger_file = swagger_file
        self.app = App.create(swagger_file)
        self.auth = Security(self.app)
        self.auth.update_with("api_key", api_key)
        self.client = Client(self.auth)

    @staticmethod
    def badStatus(response: SwaggerResponse) -> bool:
        status_code = response.status
        good_statuses = [200]
        if status_code in good_statuses:
            return True
        elif status_code == 429:  # Rate Limit
            # raise RateLimitException("rate limit hit ")
            return True
        elif status_code == 403:
            raise Exception('YOUR AUTH TOKEN EXPIRED! Response 403: ' +
                            response.text)
        return False

    def get_opp(self, operation_id: str, **kwargs) -> SwaggerResponse:
        print(kwargs)
        req, resp = self.app.op[operation_id](**kwargs)
        req.produce('application/json')
        response: SwaggerResponse = self.client.request((req, resp))
        if response.status == 429:
            logger.warning("rate limit hit")
            sleep(60)
            return self.client.request((req, resp))
        return response

    def getMatchList(self, account_id: Union[str, int]) -> json:
        operation_id = 'getMatchlist'
        response = self.get_opp(operation_id, accountId=account_id)
        return response.data

    def getSummonerByName(self, name: str) -> json:
        operation_id = 'getBySummonerName'
        response = self.get_opp(operation_id, summonerName=name)
        return response.data

    def getMatch(self, matchId: Union[int, str]) -> json:
        op_id = 'getMatch'
        response = self.get_opp(op_id, matchId=matchId)
        return response.data

    def getFeaturedGames(self) -> json:
        op_id = 'getFeaturedGames'
        response = self.get_opp(op_id)
        return response.data

    def getMatchTimeline(self, match_id: int) -> json:
        op_id = 'getMatchTimeline'
        response = self.get_opp(op_id, matchId=match_id)
        return response.data
Example #12
0
from pyswagger import App, Security
from pyswagger.contrib.client.requests import Client
from pyswagger.utils import jp_compose
from typing import Dict

# load Swagger resource file into App object

app = App.create("lolcrawler/swaggerspec-2.0.yml")

definitions: Dict = app.root.resolve("definitions")
for k, v in definitions.items():
    print(k, v)

auth = Security(app)
auth.update_with('api_key', 'RGAPI-8dc9be1b-5b2a-4db5-8cb6-66ec939033e8')

# init swagger client
client = Client(auth)

foo = app.resolve('#/definitions/match-v3.MatchDto')
print(foo)

for i in range(60):
    # - access an Operation object via App.op when operationId is defined
    req, resp = app.op['getBySummonerName'](summonerName="Faker")
    # prefer json as response
    req.produce('application/json')
    faker = client.request((req, resp))

    print(faker.header)
    print(faker.data)
def connect_to_stf(host, token):
    global app, client
    app = App._create_('http://%s/api/v1/swagger.json' % host)
    auth = Security(app)
    auth.update_with('accessTokenAuth', 'Bearer ' + token)
    client = Client(auth)
Example #14
0
def client_apptoken(app):
    auth = Security(app)
    apptoken = AppToken.objects.first()
    auth.update_with("AppTokenHeader", f"AppToken {apptoken.key}")
    client = Client(auth)
    return client
Example #15
0
def client_usertoken(app):
    auth = Security(app)
    usertoken = UserToken.objects.first()
    auth.update_with("UserTokenHeader", f"UserToken {usertoken.key}")
    client = Client(auth)
    return client