예제 #1
0
    def __init__(self,
                 creds=elicit_creds.ElicitCreds(),
                 api_url=PRODUCTION_URL,
                 send_opt=dict(verify=True)):
        print("Initialize Elicit client library for %s options:" % api_url)
        print(send_opt)

        if ((not send_opt['verify']) and api_url.startswith("https")):
            print('WARNING: not checking SSL')
            dont_check_ssl()

        self.api_url = api_url
        self.swagger_url = self.api_url + '/apidocs/v1/swagger.json'
        self.app = App._create_(self.swagger_url)
        self.auth = Security(self.app)
        self.creds = creds

        # init swagger client
        self.client = Client(
            self.auth, send_opt=send_opt
        )  # HACK to work around self-signed SSL certs used in development
        if (self.app.root.host != self.api_url):
            print(
                'WARNING: API URL from swagger doesn\'t match this configuration: [%s] vs [%s]'
                % (self.api_url, self.app.root.host))
예제 #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
예제 #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)
예제 #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)
예제 #5
0
 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')
예제 #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==')
예제 #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==')
def characterid_from_name(char_name: str) -> Tuple[Optional[int], Optional[str]]:
    """
    @return: charid, name
    """

    api = get_api()
    security = Security(
        api,
    )

    client = EsiClient(security, timeout=10)

    search_answer = client.request(api.op['get_search'](search=char_name, categories=['character'], strict=True))
    # this character name doesn't exist
    if not ('character' in search_answer.data):
        return None, None
    char_id: int = int(search_answer.data['character'][0])
    
    char_answer = client.request(api.op['get_characters_character_id'](character_id=char_id))
    char_name: str = char_answer.data['name']
    
    return char_id, char_name
예제 #9
0
 def setUp(self):
     self.s = Security(app)
예제 #10
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
예제 #11
0
from pyswagger import App, Security
from pyswagger.contrib.client.requests import Client
from pyswagger.utils import jp_compose

# load Swagger resource file into App object
app = App._create_('https://canvas.instructure.com/doc/api/courses.json')

auth = Security(app)
# auth.update_with('api_key', '9371~SNSl0krgbvfe8JYXS5NSKh7FJLcqO8yNmwZOb9ku79YGDmIXLNCjzjiOBGvfFya9') # api key
# auth.update_with('petstore_auth', '12334546556521123fsfss') # oauth2

# init swagger client
client = Client(auth)

 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)
예제 #13
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
예제 #14
0
 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')
예제 #15
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
예제 #16
0
 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')
예제 #17
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)
예제 #18
0
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)
예제 #19
0
파일: bbapi.py 프로젝트: jlapenna/bikebuds
#!/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)
예제 #20
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