Exemplo n.º 1
0
 def ESIMail(self, KilledCharID):
     security = EsiSecurity(
         app=self.app,
         redirect_uri='http://localhost/callback/',
         client_id=GlobalConsts.CLIENTID,
         secret_key=GlobalConsts.SECRETKEY,
     )
     print(security.get_auth_uri(scopes=GlobalConsts.REQUESTSCOPES))
     try:
         tokens = security.auth(GlobalConsts.CHARAUTHTOKEN)
     except:
         security.refresh_token = GlobalConsts.CHARREFRESHTOKEN
         tokens = security.refresh()
     accessToken = tokens[GlobalConsts.TOKENAUTHKEY]
     RefreshToken = tokens[GlobalConsts.TOKENREFRESHKEY]
     expire_date = datetime.fromtimestamp(
         time.time() + tokens[GlobalConsts.TOKENEXPIRESKEY], )
     api_info = security.verify()
     strCharacterID = api_info['CharacterID']
     Response = SendMail(strCharacterID, KilledCharID,
                         GlobalConsts.DEFAULTMESSAGE, accessToken)
     if Response.status_code == GlobalConsts.SUCCESSRESPONSECODE:
         print("Sent message to characterid {0}".format(KilledCharID))
     else:
         print("Failed to send message to characterid {0}".format(
             KilledCharID))
Exemplo n.º 2
0
def get_api(fn, scopes):
    esi_app = App.create(
        'https://esi.tech.ccp.is/latest/swagger.json?datasource=tranquility')
    esi_security = EsiSecurity(
        app=esi_app,
        redirect_uri='http://localhost:8080/callback',
        client_id='0b9ac4978a9a4feba20a7eba4f666a46',
        secret_key='odtDKZWZbwbFnBHNXnOhRX50YrU49owBw1qE3v7p',
    )
    esi_client = EsiClient(retry_requests=True, security=esi_security)

    def write_refresh_token(refresh_token, **kwargs):
        with open(fn, "w") as f:
            f.write(refresh_token)

    AFTER_TOKEN_REFRESH.add_receiver(write_refresh_token)

    if os.path.isfile(fn):
        with open(fn) as f:
            token = open(fn).read()
        esi_security.update_token({
            'access_token': '',
            'expires_in': -1,
            'refresh_token': token
        })
        tokens = esi_security.refresh()
    else:
        print(esi_security.get_auth_uri(scopes=scopes))
        tokens = esi_security.auth(input())
    write_refresh_token(**tokens)

    api_info = esi_security.verify()

    return api_info, esi_app, esi_client
Exemplo n.º 3
0
def authenticate():
    app = App.create(
        url="https://esi.tech.ccp.is/latest/swagger.json?datasource=tranquility"
    )
    security = EsiSecurity(
        app=app,
        redirect_uri='http://localhost:51350',
        client_id=secret['client_id'],
        secret_key=secret['secret_key'],
    )
    client = EsiClient(retry_requests=True,
                       header={'User-Agent': 'shipLocation'},
                       security=security)
    eve_sso_auth_url = security.get_auth_uri(
        scopes=['esi-location.read_ship_type.v1'])
    webbrowser.open(eve_sso_auth_url, new=2)  # open in a new browser tab
    auth_code = fetch_auth_code(
    )  # fetch authentication code using a temporary web server
    tokens = security.auth(auth_code)

    return (app, client, security, tokens)
Exemplo n.º 4
0
def do_security(tokens_file, scopes):
    esi_app = EsiApp(cache=cache, cache_time=0)
    app = esi_app.get_latest_swagger

    security = EsiSecurity(redirect_uri=redirect_uri,
                           client_id=client_id,
                           secret_key=secret_key,
                           headers=headers)

    client = EsiClient(retry_requests=True, headers=headers, security=security)

    print("Open link in browser and authorize")
    print(security.get_auth_uri(scopes=scopes))
    code = input("Enter in code:\n")
    tokens = security.auth(code)

    print(tokens)
    print("\n Writing tokens to " + str(tokens_file))
    with open(tokens_file, 'wb') as fp:
        pickle.dump(tokens, fp)
    fp.close()
Exemplo n.º 5
0
class ESIClient():
    """
    didn't use esiSecurity for callback handling as flask seems fine
    """
    def __init__(self, token, refresh=False):
        self.client_id = os.environ.get('EVE_SKILLS_CID')
        self.secret_id = os.environ.get('EVE_SKILLS_SECRET')
        self.redir_url = os.environ.get('EVE_SKILLS_REDIR')
        self.app = App.create(
            url=
            "https://esi.evetech.net/latest/swagger.json?datasource=tranquility"
        )
        self.security = EsiSecurity(
            app=self.app,
            redirect_uri=self.redir_url,
            client_id=self.client_id,
            secret_key=self.secret_id,
        )
        self.client = EsiClient(
            header={'User-Agent': 'EVE-SKILLS'},
            raw_body_only=
            False,  # parse json automatically, slow, bad performance
            security=self.security)
        self.token = None
        if not refresh:
            self.token = self.security.auth(
                token)  # use code from login redirect
        if refresh:
            print('[I] refreshing token')
            self.security.update_token({
                'access_token': '',
                'expires_in': -1,  # force refresh anyway
                'refresh_token': token
            })
            self.token = self.security.refresh()

        print(self.token)

    def get_info(self):
        return self.security.verify()  # verify token, get character info
Exemplo n.º 6
0
# with open ('scopes', 'rb') as fp:
#     scopeslist = pickle.load(fp)

sscp = app.root._Swagger__securityDefinitions['evesso']._SecurityScheme__scopes
scopeslist = list()
for i in sscp:
    scopeslist.append(i)

# this print a URL where we can log in
print(security.get_auth_uri(scopes=scopeslist))
print("please copy your code and paste here\n")
authcode = input()

# YOUR_CODE is the code you got from Step 3. (do not forget quotes around it)
tokens = security.auth(authcode)
print(tokens)

# use the verify endpoint to know who we are
api_info = security.verify()

print(api_info)
# api_info contains data like this
# {
#   "Scopes": "esi-wallet.read_character_wallet.v1",
#   "ExpiresOn": "2017-07-14T21:09:20",
#   "TokenType": "Character",
#   "CharacterName": "SOME Char",
#   "IntellectualProperty": "EVE",
#   "CharacterOwnerHash": "4raef4rea8aferfa+E=",
#   "CharacterID": 123456789
Exemplo n.º 7
0
class TestEsiPy(unittest.TestCase):
    CALLBACK_URI = "https://foo.bar/baz/callback"
    LOGIN_EVE = "https://login.eveonline.com"
    OAUTH_VERIFY = "%s/oauth/verify" % LOGIN_EVE
    OAUTH_TOKEN = "%s/oauth/token" % LOGIN_EVE
    CLIENT_ID = 'foo'
    SECRET_KEY = 'bar'
    BASIC_TOKEN = six.u('Zm9vOmJhcg==')
    SECURITY_NAME = 'evesso'

    @mock.patch('six.moves.urllib.request.urlopen')
    def setUp(self, urlopen_mock):
        # I hate those mock... thx urlopen instead of requests...
        urlopen_mock.return_value = open('test/resources/swagger.json')

        self.app = App.create('https://esi.tech.ccp.is/latest/swagger.json')

        self.security = EsiSecurity(
            app=self.app,
            redirect_uri=TestEsiPy.CALLBACK_URI,
            client_id=TestEsiPy.CLIENT_ID,
            secret_key=TestEsiPy.SECRET_KEY,
        )

        self.cache = DictCache()
        self.client = EsiClient(self.security, cache=self.cache)
        self.client_no_auth = EsiClient(cache=self.cache, retry_requests=True)

    def tearDown(self):
        """ clear the cache so we don't have residual data """
        self.cache._dict = {}

    def test_esipy_client_no_args(self):
        client_no_args = EsiClient()
        self.assertIsNone(client_no_args.security)
        self.assertTrue(isinstance(client_no_args.cache, DictCache))
        self.assertEqual(client_no_args._session.headers['User-Agent'],
                         'EsiPy/Client - https://github.com/Kyria/EsiPy')
        self.assertEqual(client_no_args.raw_body_only, False)

    def test_esipy_client_with_headers(self):
        client_with_headers = EsiClient(headers={'User-Agent': 'foobar'})
        self.assertEqual(client_with_headers._session.headers['User-Agent'],
                         'foobar')

    def test_esipy_client_with_adapter(self):
        transport_adapter = HTTPAdapter()
        client_with_adapters = EsiClient(transport_adapter=transport_adapter)
        self.assertEqual(client_with_adapters._session.get_adapter('http://'),
                         transport_adapter)
        self.assertEqual(client_with_adapters._session.get_adapter('https://'),
                         transport_adapter)

    def test_esipy_client_without_cache(self):
        client_without_cache = EsiClient(cache=None)
        self.assertTrue(isinstance(client_without_cache.cache, DummyCache))

    def test_esipy_client_with_cache(self):
        cache = DictCache()
        client_with_cache = EsiClient(cache=cache)
        self.assertTrue(isinstance(client_with_cache.cache, BaseCache))
        self.assertEqual(client_with_cache.cache, cache)

    def test_esipy_client_wrong_cache(self):
        with self.assertRaises(ValueError):
            EsiClient(cache=DictCache)

    def test_esipy_request_public(self):
        with httmock.HTTMock(public_incursion):
            incursions = self.client_no_auth.request(
                self.app.op['get_incursions']())
            self.assertEqual(incursions.data[0].type, 'Incursion')
            self.assertEqual(incursions.data[0].faction_id, 500019)

    def test_esipy_request_authed(self):
        with httmock.HTTMock(*_all_auth_mock_):
            self.security.auth('let it bee')
            char_location = self.client.request(
                self.app.op['get_characters_character_id_location'](
                    character_id=123456789))
            self.assertEqual(char_location.data.station_id, 60004756)

            # force expire
            self.security.token_expiry = 0
            char_location_with_refresh = self.client.request(
                self.app.op['get_characters_character_id_location'](
                    character_id=123456789))
            self.assertEqual(char_location_with_refresh.data.station_id,
                             60004756)

    def test_client_cache_request(self):
        @httmock.all_requests
        def fail_if_request(url, request):
            self.fail('Cached data is not supposed to do requests')

        incursion_operation = self.app.op['get_incursions']

        with httmock.HTTMock(public_incursion_no_expires):
            incursions = self.client_no_auth.request(incursion_operation())
            self.assertEqual(incursions.data[0].state, 'mobilizing')

        with httmock.HTTMock(public_incursion_no_expires_second):
            incursions = self.client_no_auth.request(incursion_operation())
            self.assertEqual(incursions.data[0].state, 'established')

        with httmock.HTTMock(public_incursion):
            incursions = self.client_no_auth.request(incursion_operation())
            self.assertEqual(incursions.data[0].state, 'mobilizing')

        with httmock.HTTMock(fail_if_request):
            incursions = self.client_no_auth.request(incursion_operation())
            self.assertEqual(incursions.data[0].state, 'mobilizing')

    def test_client_warning_header(self):
        with httmock.HTTMock(public_incursion_warning):
            warnings.simplefilter('error')
            incursion_operation = self.app.op['get_incursions']

            with self.assertRaises(UserWarning):
                self.client_no_auth.request(incursion_operation())

    def test_client_raw_body_only(self):
        client = EsiClient(raw_body_only=True)
        self.assertEqual(client.raw_body_only, True)

        with httmock.HTTMock(public_incursion):
            incursions = client.request(self.app.op['get_incursions']())
            self.assertIsNone(incursions.data)
            self.assertTrue(len(incursions.raw) > 0)

            incursions = client.request(self.app.op['get_incursions'](),
                                        raw_body_only=False)
            self.assertIsNotNone(incursions.data)

    def test_esipy_reuse_operation(self):
        operation = self.app.op['get_incursions']()
        with httmock.HTTMock(public_incursion):
            incursions = self.client_no_auth.request(operation)
            self.assertEqual(incursions.data[0].faction_id, 500019)

            # this shouldn't create any errors
            incursions = self.client_no_auth.request(operation)
            self.assertEqual(incursions.data[0].faction_id, 500019)

    def test_esipy_multi_request(self):
        operation = self.app.op['get_incursions']()

        with httmock.HTTMock(public_incursion):
            count = 0
            for req, incursions in self.client_no_auth.multi_request(
                [operation, operation, operation], threads=2):
                self.assertEqual(incursions.data[0].faction_id, 500019)
                count += 1

            # Check we made 3 requests
            self.assertEqual(count, 3)

    def test_esipy_backoff(self):
        operation = self.app.op['get_incursions']()

        start_calls = time.time()

        with httmock.HTTMock(public_incursion_server_error):
            incursions = self.client_no_auth.request(operation)
            self.assertEqual(incursions.data.error, 'broke')

        end_calls = time.time()

        # Check we retried 5 times
        self.assertEqual(incursions.data.count, 5)

        # Check that backoff slept for a sum > 2 seconds
        self.assertTrue(end_calls - start_calls > 2)

    def test_esipy_timeout(self):
        def send_function(*args, **kwargs):
            """ manually create a ConnectionError to test the retry and be sure
            no exception is thrown """
            send_function.count += 1
            raise ConnectionError

        send_function.count = 0

        self.client_no_auth._session.send = mock.MagicMock(
            side_effect=send_function)

        operation = self.app.op['get_incursions']()
        with httmock.HTTMock(public_incursion):
            incursions = self.client_no_auth.request(operation)
            # there shouldn't be any exceptions

        self.assertEqual(incursions.status, 500)
        self.assertEqual(send_function.count, 5)
Exemplo n.º 8
0
class ESI:
    def __init__(self):
        self.db = Database()
        self.config = Config()
        self.scopes = self.config.getConfig()["settings"]["esiScopes"]
        self.esi_app = App.create(
            url=self.config.getConfig()["settings"]["esiURL"], )
        self.security = EsiSecurity(
            app=self.esi_app,
            redirect_uri=self.config.getConfig()["settings"]["esiCallback"],
            client_id=self.config.getConfig()["settings"]["esiClientID"],
            secret_key=self.config.getConfig()["settings"]["esiSecretKey"],
            headers={
                'User-Agent':
                self.config.getConfig()["settings"]["esiCustomHeader"]
            })
        self.client = EsiClient(
            security=self.security,
            retry_requests=True,
            headers={
                'User-Agent':
                self.config.getConfig()["settings"]["esiCustomHeader"]
            })

    def getAuthURI(self):
        return self.security.get_auth_uri(scopes=self.scopes)

    def getToken(self, code):
        return self.security.auth(code)

    def getESIChar(self, token):
        self.security.update_token(token)
        try:
            self.security.refresh()
        except APIException as e:
            if str(e) == "HTTP Error 400: invalid_token":
                session.pop('token', None)
                session.pop('char', None)
                return redirect(url_for('page_routes.logout'))

        return self.security.verify()

    def isVerified(self, token):
        try:
            self.security.update_token(token)
        except:
            return False

        try:
            self.security.refresh()
            character = self.security.verify()
        except:
            return False
        session["char"] = character
        return True

    def getESIInfo(self, endpoint, obj):
        info = self.esi_app.op[endpoint](**obj)
        res = self.client.request(info)
        result = res.data
        try:
            if "response" in result:
                result = result["response"]
        except:
            pass
        return result

    def getESIInfoMP(self, endpoint, obj):
        info = self.esi_app.op[endpoint](**obj)
        res = self.client.head(info)

        if res.status == 200:
            number_of_pages = res.header["X-Pages"][0]
            ops = []
            for page in range(1, number_of_pages + 1):
                obj["page"] = page
                ops.append(self.esi_app.op[endpoint](**obj))
            results = self.client.multi_request(ops)
            return results
        return {}

    def subToken(self, refresh_token):
        self.security.update_token({
            'access_token': '',
            'expires_in': -1,
            'refresh_token': refresh_token
        })

    def getForceRefresh(self):
        return self.security.refresh()
Exemplo n.º 9
0
class TestEsiSecurity(unittest.TestCase):
    CALLBACK_URI = "https://foo.bar/baz/callback"
    CLIENT_ID = 'foo'
    SECRET_KEY = 'bar'
    BASIC_TOKEN = six.u('Zm9vOmJhcg==')
    SECURITY_NAME = 'evesso'
    TOKEN_IDENTIFIER = 'ESIPY_TEST_TOKEN'
    CODE_VERIFIER = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
    CODE_CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"

    RSC_SSO_ENDPOINTS = "test/resources/oauth-authorization-server.json"
    RSC_JWKS = "test/resources/jwks.json"

    def setUp(self):
        warnings.simplefilter('ignore')
        self.custom_refresh_token_signal = Signal()

        with httmock.HTTMock(*_all_auth_mock_):
            self.security = EsiSecurity(
                redirect_uri=TestEsiSecurity.CALLBACK_URI,
                client_id=TestEsiSecurity.CLIENT_ID,
                secret_key=TestEsiSecurity.SECRET_KEY,
                signal_token_updated=self.custom_refresh_token_signal,
                token_identifier=TestEsiSecurity.TOKEN_IDENTIFIER)
            self.security_pkce = EsiSecurity(
                redirect_uri=TestEsiSecurity.CALLBACK_URI,
                client_id=TestEsiSecurity.CLIENT_ID,
                code_verifier=TestEsiSecurity.CODE_VERIFIER,
            )

        with open(TestEsiSecurity.RSC_SSO_ENDPOINTS, 'r') as sso_endpoints:
            self.sso_endpoints = json.load(sso_endpoints)

    def test_esisecurity_init(self):
        with httmock.HTTMock(*_all_auth_mock_):
            with self.assertRaises(AttributeError):
                EsiSecurity(redirect_uri=TestEsiSecurity.CALLBACK_URI,
                            client_id=TestEsiSecurity.CLIENT_ID,
                            secret_key=TestEsiSecurity.SECRET_KEY,
                            sso_endpoints_url="")

            with self.assertRaises(AttributeError):
                EsiSecurity(redirect_uri=TestEsiSecurity.CALLBACK_URI,
                            client_id=TestEsiSecurity.CLIENT_ID)

            with open(TestEsiSecurity.RSC_JWKS, 'r') as jwks:
                jwks = json.load(jwks)
                EsiSecurity(redirect_uri=TestEsiSecurity.CALLBACK_URI,
                            client_id=TestEsiSecurity.CLIENT_ID,
                            secret_key=TestEsiSecurity.SECRET_KEY,
                            jwks_key=jwks['keys'][0])

        self.assertEqual(self.security.security_name,
                         TestEsiSecurity.SECURITY_NAME)
        self.assertEqual(self.security.redirect_uri,
                         TestEsiSecurity.CALLBACK_URI)
        self.assertEqual(self.security.client_id, TestEsiSecurity.CLIENT_ID)
        self.assertEqual(self.security.secret_key, TestEsiSecurity.SECRET_KEY)
        self.assertEqual(self.security.token_identifier,
                         TestEsiSecurity.TOKEN_IDENTIFIER)
        self.assertEqual(self.security.oauth_issuer,
                         self.sso_endpoints['issuer'])
        self.assertEqual(self.security.oauth_authorize,
                         self.sso_endpoints['authorization_endpoint'])
        self.assertEqual(self.security.oauth_token,
                         self.sso_endpoints['token_endpoint'])
        self.assertEqual(self.security.oauth_revoke,
                         self.sso_endpoints['revocation_endpoint'])

    def test_esisecurity_update_token(self):
        self.security.update_token({
            'access_token': 'access_token',
            'refresh_token': 'refresh_token',
            'expires_in': 60
        })
        self.assertEqual(self.security.access_token, 'access_token')
        self.assertEqual(self.security.refresh_token, 'refresh_token')
        self.assertEqual(self.security.token_expiry, int(time.time() + 60))

    def test_esisecurity_get_auth_uri(self):
        with self.assertRaises(AttributeError):
            self.security.get_auth_uri(state="")

        self.assertEqual(self.security.get_auth_uri(state='teststate'),
                         ("%s?response_type=code"
                          "&redirect_uri=%s&client_id=%s&state=teststate") %
                         (self.sso_endpoints['authorization_endpoint'],
                          quote(TestEsiSecurity.CALLBACK_URI,
                                safe=''), TestEsiSecurity.CLIENT_ID))

        self.assertEqual(
            self.security.get_auth_uri(implicit=True, state='teststate'),
            ("%s?response_type=token"
             "&redirect_uri=%s&client_id=%s&state=teststate") %
            (self.sso_endpoints['authorization_endpoint'],
             quote(TestEsiSecurity.CALLBACK_URI,
                   safe=''), TestEsiSecurity.CLIENT_ID))

        scopes = ["Scope1", "Scope2"]
        self.assertEqual(
            self.security.get_auth_uri(scopes=scopes, state='teststate'),
            ("%s?response_type=code&redirect_uri=%s"
             "&client_id=%s&scope=Scope1+Scope2&state=teststate") %
            (self.sso_endpoints['authorization_endpoint'],
             quote(TestEsiSecurity.CALLBACK_URI,
                   safe=''), TestEsiSecurity.CLIENT_ID))

    def test_esisecurity_get_access_token_request_params(self):
        params = self.security.get_access_token_params('foo')
        self.assertEqual(
            params['headers'],
            {'Authorization': 'Basic %s' % TestEsiSecurity.BASIC_TOKEN})
        self.assertEqual(params['url'], self.sso_endpoints['token_endpoint'])
        self.assertEqual(params['data'], {
            'grant_type': 'authorization_code',
            'code': 'foo',
        })

    def test_esisecurity_get_refresh_token_request_params(self):
        with self.assertRaises(AttributeError):
            self.security.get_refresh_token_params()

        self.security.update_token({
            'access_token': 'access_token',
            'refresh_token': 'refresh_token',
            'expires_in': 60
        })

        # refresh all scopes
        params = self.security.get_refresh_token_params()
        self.assertEqual(
            params['headers'],
            {'Authorization': 'Basic %s' % TestEsiSecurity.BASIC_TOKEN})
        self.assertEqual(params['url'], self.sso_endpoints['token_endpoint'])
        self.assertEqual(params['data'], {
            'grant_type': 'refresh_token',
            'refresh_token': 'refresh_token',
        })

        # refresh specific scopes
        params = self.security.get_refresh_token_params(scope_list=['a', 'b'])
        self.assertEqual(
            params['data'], {
                'grant_type': 'refresh_token',
                'refresh_token': 'refresh_token',
                'scope': 'a+b'
            })

        # refresh specific scopes exception
        with self.assertRaises(AttributeError):
            self.security.get_refresh_token_params(scope_list='notalist')

    def test_esisecurity_token_expiry(self):
        self.security.token_expiry = None
        self.assertTrue(self.security.is_token_expired())

        self.security.token_expiry = time.time() - 10
        self.assertTrue(self.security.is_token_expired())

        self.security.token_expiry = time.time() + 60
        self.assertFalse(self.security.is_token_expired())
        self.assertTrue(self.security.is_token_expired(offset=70))

    def test_esisecurity_auth(self):
        with httmock.HTTMock(oauth_token):
            ret = self.security.auth('let it bee')
            self.assertEqual(ret['access_token'], 'access_token')
            self.assertEqual(ret['refresh_token'], 'refresh_token')
            self.assertEqual(ret['expires_in'], 1200)

            ret = self.security.auth('no_refresh')
            self.assertEqual(ret['access_token'], 'access_token')
            self.assertNotIn('refresh_token', ret)
            self.assertEqual(ret['expires_in'], 1200)

            with self.assertRaises(APIException):
                self.security.auth('fail_test')

    def test_esisecurity_refresh(self):
        with httmock.HTTMock(oauth_token):
            self.security.refresh_token = 'refresh_token'
            ret = self.security.refresh()
            self.assertEqual(ret['access_token'], 'access_token')
            self.assertEqual(ret['refresh_token'], 'refresh_token')
            self.assertEqual(ret['expires_in'], 1200)

            with self.assertRaises(APIException):
                self.security.refresh_token = 'fail_test_token'
                self.security.refresh()

    def test_esisecurity_revoke(self):
        with httmock.HTTMock(oauth_revoke):
            self.security.refresh_token = 'refresh_token'
            self.security.revoke()

            self.security.access_token = 'access_token'
            self.security.revoke()

            with self.assertRaises(AttributeError):
                self.security.revoke()

    def test_esisecurity_verify(self):
        # this is just for coverage purpose. This doesn't work without valid
        # jwt token
        with self.assertRaises(AttributeError):
            self.security.verify()

        self.security.update_token({
            'access_token': 'access_token',
            'refresh_token': 'refresh_token',
            'expires_in': 60
        })
        with self.assertRaises(JWTError):
            self.security.verify()
        with httmock.HTTMock(*_all_auth_mock_):
            with open(TestEsiSecurity.RSC_JWKS, 'r') as jwks:
                jwks = json.load(jwks)
                security_nojwks = EsiSecurity(
                    redirect_uri=TestEsiSecurity.CALLBACK_URI,
                    client_id=TestEsiSecurity.CLIENT_ID,
                    secret_key=TestEsiSecurity.SECRET_KEY,
                    jwks_key=jwks['keys'][0])

        security_nojwks.update_token({
            'access_token': 'access_token',
            'refresh_token': 'refresh_token',
            'expires_in': 60
        })
        with self.assertRaises(JWTError):
            security_nojwks.verify()

    def test_esisecurity_call(self):
        class RequestTest(object):
            def __init__(self):
                self._security = []
                self._p = {'header': {}}

        self.security.update_token({
            'access_token': 'access_token',
            'refresh_token': 'refresh_token',
            'expires_in': 60
        })

        req = RequestTest()
        self.security(req)
        self.assertNotIn('Authorization', req._p['header'])

        req._security.append({
            'unknown_security_name': {},
        })
        self.security(req)
        self.assertNotIn('Authorization', req._p['header'])

        req._security.append({
            'evesso': {},
        })
        self.security(req)
        self.assertIn('Authorization', req._p['header'])
        self.assertEqual('Bearer access_token',
                         req._p['header']['Authorization'])

    def test_esisecurity_callback_refresh(self):
        class RequestTest(object):
            """ pyswagger Request object over simplified for test purpose"""
            def __init__(self):
                self._security = ['evesso']
                self._p = {'header': {}}

        def callback_function(**kwargs):
            callback_function.count += 1

        callback_function.count = 0

        self.custom_refresh_token_signal.add_receiver(callback_function)

        self.security.update_token({
            'access_token': 'access_token',
            'refresh_token': 'refresh_token',
            'expires_in': -1
        })

        # test the auto refresh callback event customized
        with httmock.HTTMock(oauth_token):
            req = RequestTest()
            self.security(req)
            self.assertEqual(callback_function.count, 1)

    def test_esisecurity_non_json_response(self):
        self.security.update_token({
            'access_token': 'access_token',
            'refresh_token': 'refresh_token',
            'expires_in': -1
        })
        with httmock.HTTMock(non_json_error):
            try:
                self.security.auth('somecode')
            except APIException as exc:
                self.assertEqual(exc.status_code, 502)
                self.assertEqual(
                    exc.response,
                    six.b('<html><body>Some HTML Errors</body></html>'))

            try:
                self.security.refresh()
            except APIException as exc:
                self.assertEqual(exc.status_code, 502)
                self.assertEqual(
                    exc.response,
                    six.b('<html><body>Some HTML Errors</body></html>'))

    def test_esisecurity_pkce(self):
        uri = self.security_pkce.get_auth_uri('test')
        self.assertIn('code_challenge=%s' % TestEsiSecurity.CODE_CHALLENGE,
                      uri)

        params = self.security_pkce.get_access_token_params('test')
        self.assertEqual(params['data']['code_verifier'],
                         TestEsiSecurity.CODE_VERIFIER)
        self.assertEqual(params['data']['client_id'],
                         TestEsiSecurity.CLIENT_ID)
        self.assertNotIn('Authorization', params['headers'])
Exemplo n.º 10
0
class TestEsiPy(unittest.TestCase):
    CALLBACK_URI = "https://foo.bar/baz/callback"
    LOGIN_EVE = "https://login.eveonline.com"
    OAUTH_VERIFY = "%s/oauth/verify" % LOGIN_EVE
    OAUTH_TOKEN = "%s/oauth/token" % LOGIN_EVE
    CLIENT_ID = 'foo'
    SECRET_KEY = 'bar'
    BASIC_TOKEN = six.u('Zm9vOmJhcg==')
    SECURITY_NAME = 'evesso'

    RSC_SSO_ENDPOINTS = "test/resources/oauth-authorization-server.json"
    RSC_JWKS = "test/resources/jwks.json"

    @mock.patch('six.moves.urllib.request.urlopen')
    def setUp(self, urlopen_mock):
        # I hate those mock... thx urlopen instead of requests...
        urlopen_mock.return_value = open('test/resources/swagger.json')
        warnings.simplefilter('ignore')

        self.app = App.create('https://esi.evetech.net/latest/swagger.json')

        with open(TestEsiPy.RSC_SSO_ENDPOINTS, 'r') as sso_endpoints:
            with open(TestEsiPy.RSC_JWKS, "r") as jwks:
                self.security = EsiSecurity(
                    app=self.app,
                    redirect_uri=TestEsiPy.CALLBACK_URI,
                    client_id=TestEsiPy.CLIENT_ID,
                    secret_key=TestEsiPy.SECRET_KEY,
                    sso_endpoints=json.load(sso_endpoints),
                    jwks_key=json.load(jwks))

        self.cache = DictCache()
        self.client = EsiClient(self.security, cache=self.cache)
        self.client_no_auth = EsiClient(cache=self.cache, retry_requests=True)

    def tearDown(self):
        """ clear the cache so we don't have residual data """
        self.cache._dict = {}

    def test_esipy_client_no_args(self):
        client_no_args = EsiClient()
        self.assertIsNone(client_no_args.security)
        self.assertTrue(isinstance(client_no_args.cache, DictCache))
        self.assertEqual(client_no_args._session.headers['User-Agent'],
                         'EsiPy/Client - https://github.com/Kyria/EsiPy')
        self.assertEqual(client_no_args.raw_body_only, False)

    def test_esipy_client_with_headers(self):
        client_with_headers = EsiClient(headers={'User-Agent': 'foobar'})
        self.assertEqual(client_with_headers._session.headers['User-Agent'],
                         'foobar')

    def test_esipy_client_with_adapter(self):
        transport_adapter = HTTPAdapter()
        client_with_adapters = EsiClient(transport_adapter=transport_adapter)
        self.assertEqual(client_with_adapters._session.get_adapter('http://'),
                         transport_adapter)
        self.assertEqual(client_with_adapters._session.get_adapter('https://'),
                         transport_adapter)

    def test_esipy_client_without_cache(self):
        client_without_cache = EsiClient(cache=None)
        self.assertTrue(isinstance(client_without_cache.cache, DummyCache))

    def test_esipy_client_with_cache(self):
        cache = DictCache()
        client_with_cache = EsiClient(cache=cache)
        self.assertTrue(isinstance(client_with_cache.cache, BaseCache))
        self.assertEqual(client_with_cache.cache, cache)

    def test_esipy_client_wrong_cache(self):
        with self.assertRaises(ValueError):
            EsiClient(cache=DictCache)

    def test_esipy_request_public(self):
        with httmock.HTTMock(public_incursion):
            incursions = self.client_no_auth.request(
                self.app.op['get_incursions']())
            self.assertEqual(incursions.data[0].type, 'Incursion')
            self.assertEqual(incursions.data[0].faction_id, 500019)

    def test_esipy_request_authed(self):
        with httmock.HTTMock(*_all_auth_mock_):
            self.security.auth('let it bee')
            char_location = self.client.request(
                self.app.op['get_characters_character_id_location'](
                    character_id=123456789))
            self.assertEqual(char_location.data.station_id, 60004756)

            # force expire
            self.security.token_expiry = 0
            char_location_with_refresh = self.client.request(
                self.app.op['get_characters_character_id_location'](
                    character_id=123456789))
            self.assertEqual(char_location_with_refresh.data.station_id,
                             60004756)

    def test_client_cache_request(self):
        @httmock.all_requests
        def fail_if_request(url, request):
            self.fail('Cached data is not supposed to do requests')

        incursion_operation = self.app.op['get_incursions']

        with httmock.HTTMock(public_incursion_no_expires):
            incursions = self.client_no_auth.request(incursion_operation())
            self.assertEqual(incursions.data[0].state, 'mobilizing')

        with httmock.HTTMock(public_incursion_no_expires_second):
            incursions = self.client_no_auth.request(incursion_operation())
            self.assertEqual(incursions.data[0].state, 'established')

        with httmock.HTTMock(public_incursion):
            incursions = self.client_no_auth.request(incursion_operation())
            self.assertEqual(incursions.data[0].state, 'mobilizing')

        with httmock.HTTMock(fail_if_request):
            incursions = self.client_no_auth.request(incursion_operation())
            self.assertEqual(incursions.data[0].state, 'mobilizing')

    def test_client_warning_header(self):
        # deprecated warning
        warnings.simplefilter('error')
        with httmock.HTTMock(public_incursion_warning):
            incursion_operation = self.app.op['get_incursions']

            with self.assertRaises(UserWarning):
                self.client_no_auth.request(incursion_operation())

            with self.assertRaises(UserWarning):
                self.client_no_auth.head(incursion_operation())

    def test_client_raw_body_only(self):
        client = EsiClient(raw_body_only=True)
        self.assertEqual(client.raw_body_only, True)

        with httmock.HTTMock(public_incursion):
            incursions = client.request(self.app.op['get_incursions']())
            self.assertIsNone(incursions.data)
            self.assertTrue(len(incursions.raw) > 0)

            incursions = client.request(self.app.op['get_incursions'](),
                                        raw_body_only=False)
            self.assertIsNotNone(incursions.data)

    def test_esipy_reuse_operation(self):
        operation = self.app.op['get_incursions']()
        with httmock.HTTMock(public_incursion):
            incursions = self.client_no_auth.request(operation)
            self.assertEqual(incursions.data[0].faction_id, 500019)

            # this shouldn't create any errors
            incursions = self.client_no_auth.request(operation)
            self.assertEqual(incursions.data[0].faction_id, 500019)

    def test_esipy_multi_request(self):
        operation = self.app.op['get_incursions']()

        with httmock.HTTMock(public_incursion):
            count = 0
            for req, incursions in self.client_no_auth.multi_request(
                [operation, operation, operation], threads=2):
                self.assertEqual(incursions.data[0].faction_id, 500019)
                count += 1

            # Check we made 3 requests
            self.assertEqual(count, 3)

    def test_esipy_backoff(self):
        operation = self.app.op['get_incursions']()

        start_calls = time.time()

        with httmock.HTTMock(public_incursion_server_error):
            incursions = self.client_no_auth.request(operation)
            self.assertEqual(incursions.data.error, 'broke')

        end_calls = time.time()

        # Check we retried 5 times
        self.assertEqual(incursions.data.count, 5)

        # Check that backoff slept for a sum > 2 seconds
        self.assertTrue(end_calls - start_calls > 2)

    def test_esipy_timeout(self):
        def send_function(*args, **kwargs):
            """ manually create a ConnectionError to test the retry and be sure
            no exception is thrown """
            send_function.count += 1
            raise ConnectionError

        send_function.count = 0

        self.client_no_auth._session.send = mock.MagicMock(
            side_effect=send_function)

        operation = self.app.op['get_incursions']()
        with httmock.HTTMock(public_incursion):
            incursions = self.client_no_auth.request(operation)
            # there shouldn't be any exceptions

        self.assertEqual(incursions.status, 500)
        self.assertEqual(send_function.count, 5)

    def test_esipy_raise_on_error(self):
        operation = self.app.op['get_incursions']()

        with httmock.HTTMock(public_incursion_server_error):
            # try with retries
            with self.assertRaises(APIException):
                self.client_no_auth.request(operation, raise_on_error=True)

            # try without retries
            with self.assertRaises(APIException):
                self.client.request(operation, raise_on_error=True)

            # try with head
            with self.assertRaises(APIException):
                self.client_no_auth.head(operation, raise_on_error=True)

    def test_esipy_expired_response(self):
        operation = self.app.op['get_incursions']

        with httmock.HTTMock(public_incursion_expired):
            warnings.filterwarnings('error', '.*returned expired result')

            with self.assertRaises(UserWarning):
                self.client_no_auth.request(operation())

            warnings.resetwarnings()
            warnings.simplefilter('ignore')
            incursions = self.client_no_auth.request(operation())
            self.assertEquals(incursions.status, 200)

    def test_esipy_uncached_method(self):
        operation = self.app.op['post_universe_ids'](names=['Foo'])

        self.assertEqual(self.cache._dict, {})
        with httmock.HTTMock(post_universe_id):
            res = self.client.request(operation)
            self.assertEqual(res.data.characters[0].id, 123456789)

        self.assertEqual(self.cache._dict, {})

    def test_esipy_head_request(self):
        operation = self.app.op['get_incursions']()

        with httmock.HTTMock(public_incursion):
            res = self.client.head(operation)
            self.assertIsNone(res.data)
            self.assertIn('Expires', res.header)

    def test_esipy_expired_header_etag(self):
        @httmock.all_requests
        def check_etag(url, request):
            self.assertEqual(request.headers.get('If-None-Match'),
                             '"esipy_test_etag_status"')
            return httmock.response(headers={
                'Etag': '"esipy_test_etag_status"',
                'expires': make_expire_time_str(),
                'date': make_expire_time_str()
            },
                                    status_code=304)

        operation = self.app.op['get_status']()

        with httmock.HTTMock(eve_status):
            self.assertEqual(self.cache._dict, {})
            res = self.client.request(operation)
            self.assertNotEqual(self.cache._dict, {})
            self.assertEqual(res.data.server_version, "1313143")

        time.sleep(2)

        with httmock.HTTMock(check_etag):
            res = self.client.request(operation)
            self.assertEqual(res.data.server_version, "1313143")

    def test_esipy_expired_header_noetag(self):
        def check_etag(url, request):
            self.assertNotIn('If-None-Match', request.headers)
            return httmock.response(status_code=200,
                                    content={
                                        "players": 29597,
                                        "server_version": "1313143",
                                        "start_time": "2018-05-20T11:04:30Z"
                                    })

        operation = self.app.op['get_status']()

        with httmock.HTTMock(eve_status_noetag):
            res = self.client.request(operation)
            self.assertEqual(res.data.server_version, "1313143")

        time.sleep(2)

        with httmock.HTTMock(check_etag):
            res = self.client.request(operation)
            self.assertEqual(res.data.server_version, "1313143")

    def test_esipy_non_json_response(self):
        operation = self.app.op['get_status']()
        with httmock.HTTMock(non_json_error):
            try:
                self.client.request(operation)
            except APIException as exc:
                self.assertEqual(exc.status_code, 502)
                self.assertEqual(
                    exc.response,
                    six.b('<html><body>Some HTML Errors</body></html>'))

            try:
                self.client_no_auth.request(operation)
            except APIException as exc:
                self.assertEqual(exc.status_code, 502)
                self.assertEqual(
                    exc.response,
                    six.b('<html><body>Some HTML Errors</body></html>'))
Exemplo n.º 11
0

        # Create response header to load afterwards back

        header_re = {
             "access_token": '%s' % file.acc,
             "token_type":"Bearer",
             "expires_in": int(file.exp_t_s),
             "refresh_token":"***static***"
            }

        #This was for authentication to generate auth-code to get access token

        print uri
        x=raw_input("Paste Code :")
        esi_security.auth(x)
        verify=esi_security.verify()


        #Important stuff, load response header to upload "token" and refresh to get new access token, last verify to get your needed inquiry response

        esi_security.update_token(header_re)
        esi_security.refresh()
        verify=esi_security.verify()


        #Get access token and time token from esipy code after successful refresh (expiry method is custom changed)
        accesscode = esi_security._EsiSecurity__get_token_auth_header()
        accesscode = accesscode['Authorization'][8:]
        timestp = esi_security.is_token_expired2() #custom changed
Exemplo n.º 12
0
class TestEsiSecurity(unittest.TestCase):
    CALLBACK_URI = "https://foo.bar/baz/callback"
    LOGIN_EVE = "https://login.eveonline.com"
    OAUTH_VERIFY = "https://esi.tech.ccp.is/verify/"
    OAUTH_TOKEN = "%s/oauth/token" % LOGIN_EVE
    OAUTH_AUTHORIZE = "%s/oauth/authorize" % LOGIN_EVE
    CLIENT_ID = 'foo'
    SECRET_KEY = 'bar'
    BASIC_TOKEN = six.u('Zm9vOmJhcg==')
    SECURITY_NAME = 'evesso'

    @mock.patch('six.moves.urllib.request.urlopen')
    def setUp(self, urlopen_mock):
        # I hate those mock... thx urlopen instead of requests...
        urlopen_mock.return_value = open('test/resources/swagger.json')

        self.app = App.create('https://esi.tech.ccp.is/latest/swagger.json')

        self.security = EsiSecurity(
            app=self.app,
            redirect_uri=TestEsiSecurity.CALLBACK_URI,
            client_id=TestEsiSecurity.CLIENT_ID,
            secret_key=TestEsiSecurity.SECRET_KEY,
        )

    def test_esisecurity_init_with_app(self):
        """ test security init with app and URL"""
        with self.assertRaises(NameError):
            EsiSecurity(app=self.app,
                        redirect_uri=TestEsiSecurity.CALLBACK_URI,
                        client_id=TestEsiSecurity.CLIENT_ID,
                        secret_key=TestEsiSecurity.SECRET_KEY,
                        security_name="security_name_that_does_not_exist")

        with self.assertRaises(AttributeError):
            EsiSecurity(app=self.app,
                        redirect_uri=TestEsiSecurity.CALLBACK_URI,
                        client_id=TestEsiSecurity.CLIENT_ID,
                        secret_key=TestEsiSecurity.SECRET_KEY,
                        esi_url="")

        self.assertEqual(self.security.security_name,
                         TestEsiSecurity.SECURITY_NAME)
        self.assertEqual(self.security.redirect_uri,
                         TestEsiSecurity.CALLBACK_URI)
        self.assertEqual(self.security.client_id, TestEsiSecurity.CLIENT_ID)
        self.assertEqual(self.security.secret_key, TestEsiSecurity.SECRET_KEY)
        self.assertEqual(self.security.oauth_verify,
                         TestEsiSecurity.OAUTH_VERIFY)
        self.assertEqual(self.security.oauth_token,
                         TestEsiSecurity.OAUTH_TOKEN)
        self.assertEqual(self.security.oauth_authorize,
                         TestEsiSecurity.OAUTH_AUTHORIZE)

    def test_esisecurity_other_init(self):
        """ test security init without app and with urls """
        with self.assertRaises(AttributeError):
            EsiSecurity(redirect_uri=TestEsiSecurity.CALLBACK_URI,
                        client_id=TestEsiSecurity.CLIENT_ID,
                        secret_key=TestEsiSecurity.SECRET_KEY,
                        sso_url="")

        security = EsiSecurity(redirect_uri=TestEsiSecurity.CALLBACK_URI,
                               client_id=TestEsiSecurity.CLIENT_ID,
                               secret_key=TestEsiSecurity.SECRET_KEY,
                               sso_url='foo.com',
                               esi_url='bar.baz')

        self.assertEqual(security.oauth_verify, "bar.baz/verify/")
        self.assertEqual(security.oauth_token, "foo.com/oauth/token")
        self.assertEqual(security.oauth_authorize, "foo.com/oauth/authorize")

    def test_esisecurity_update_token(self):
        self.security.update_token({
            'access_token': 'access_token',
            'refresh_token': 'refresh_token',
            'expires_in': 60
        })
        self.assertEqual(self.security.access_token, 'access_token')
        self.assertEqual(self.security.refresh_token, 'refresh_token')
        self.assertEqual(self.security.token_expiry, int(time.time() + 60))

    def test_esisecurity_get_auth_uri(self):
        self.assertEqual(self.security.get_auth_uri(),
                         ("%s/oauth/authorize?response_type=code"
                          "&redirect_uri=%s&client_id=%s") %
                         (TestEsiSecurity.LOGIN_EVE,
                          quote(TestEsiSecurity.CALLBACK_URI,
                                safe=''), TestEsiSecurity.CLIENT_ID))

        self.assertEqual(self.security.get_auth_uri(implicit=True),
                         ("%s/oauth/authorize?response_type=token"
                          "&redirect_uri=%s&client_id=%s") %
                         (TestEsiSecurity.LOGIN_EVE,
                          quote(TestEsiSecurity.CALLBACK_URI,
                                safe=''), TestEsiSecurity.CLIENT_ID))

        scopes = ["Scope1", "Scope2"]
        state = "foo"
        self.assertEqual(self.security.get_auth_uri(
            scopes,
            state), ("%s/oauth/authorize?response_type=code&redirect_uri=%s"
                     "&client_id=%s&scope=Scope1+Scope2&state=foo") %
                         (TestEsiSecurity.LOGIN_EVE,
                          quote(TestEsiSecurity.CALLBACK_URI,
                                safe=''), TestEsiSecurity.CLIENT_ID))

    def test_esisecurity_get_access_token_request_params(self):
        params = self.security.get_access_token_request_params('foo')
        self.assertEqual(
            params['headers'],
            {'Authorization': 'Basic %s' % TestEsiSecurity.BASIC_TOKEN})
        self.assertEqual(params['url'], TestEsiSecurity.OAUTH_TOKEN)
        self.assertEqual(params['data'], {
            'grant_type': 'authorization_code',
            'code': 'foo',
        })

    def test_esisecurity_get_refresh_token_request_params(self):
        with self.assertRaises(AttributeError):
            self.security.get_refresh_token_request_params()

        self.security.update_token({
            'access_token': 'access_token',
            'refresh_token': 'refresh_token',
            'expires_in': 60
        })

        params = self.security.get_refresh_token_request_params()

        self.assertEqual(
            params['headers'],
            {'Authorization': 'Basic %s' % TestEsiSecurity.BASIC_TOKEN})
        self.assertEqual(params['url'], TestEsiSecurity.OAUTH_TOKEN)
        self.assertEqual(params['data'], {
            'grant_type': 'refresh_token',
            'refresh_token': 'refresh_token',
        })

    def test_esisecurity_token_expiry(self):
        self.security.token_expiry = None
        self.assertTrue(self.security.is_token_expired())

        self.security.token_expiry = time.time() - 10
        self.assertTrue(self.security.is_token_expired())

        self.security.token_expiry = time.time() + 60
        self.assertFalse(self.security.is_token_expired())
        self.assertTrue(self.security.is_token_expired(offset=70))

    def test_esisecurity_auth(self):
        with httmock.HTTMock(oauth_token):
            ret = self.security.auth('let it bee')
            self.assertEqual(ret['access_token'], 'access_token')
            self.assertEqual(ret['refresh_token'], 'refresh_token')
            self.assertEqual(ret['expires_in'], 1200)

            ret = self.security.auth('no_refresh')
            self.assertEqual(ret['access_token'], 'access_token')
            self.assertNotIn('refresh_token', ret)
            self.assertEqual(ret['expires_in'], 1200)

            with self.assertRaises(APIException):
                self.security.auth('fail_test')

    def test_esisecurity_refresh(self):
        with httmock.HTTMock(oauth_token):
            self.security.refresh_token = 'refresh_token'
            ret = self.security.refresh()
            self.assertEqual(ret['access_token'], 'access_token')
            self.assertEqual(ret['refresh_token'], 'refresh_token')
            self.assertEqual(ret['expires_in'], 1200)

            with self.assertRaises(APIException):
                self.security.refresh_token = 'fail_test_token'
                self.security.refresh()

    def test_esisecurity_verify(self):
        self.security.update_token({
            'access_token': 'access_token',
            'refresh_token': 'refresh_token',
            'expires_in': 60
        })

        with httmock.HTTMock(oauth_verify):
            char_data = self.security.verify()
            self.assertEqual(char_data['CharacterID'], 123456789)
            self.assertEqual(char_data['CharacterName'], 'EsiPy Tester')
            self.assertEqual(char_data['CharacterOwnerHash'], 'YetAnotherHash')

        with httmock.HTTMock(oauth_verify_fail):
            with self.assertRaises(APIException):
                self.security.verify()

    def test_esisecurity_call(self):
        class RequestTest(object):
            def __init__(self):
                self._security = []
                self._p = {'header': {}}

        self.security.update_token({
            'access_token': 'access_token',
            'refresh_token': 'refresh_token',
            'expires_in': 60
        })

        req = RequestTest()
        self.security(req)
        self.assertNotIn('Authorization', req._p['header'])

        req._security.append({
            'unknown_security_name': {},
        })
        self.security(req)
        self.assertNotIn('Authorization', req._p['header'])

        req._security.append({
            'evesso': {},
        })
        self.security(req)
        self.assertIn('Authorization', req._p['header'])
        self.assertEqual('Bearer access_token',
                         req._p['header']['Authorization'])
Exemplo n.º 13
0
security = EsiSecurity(
    app=app,
    redirect_uri='http://*****:*****@gmail.com'},
                   security=security)

# this print a URL where we can log in
print security.get_auth_uri(scopes=['esi-markets.structure_markets.v1'])

tokens = security.auth(
    'drsYPDYBwgMwNKkLOS2egrb-vlpxzITrrDJFiE-lO_4HKjVbLuXOfoGySZlR3hsw0')

print tokens

{
    "access_token": "frenafeifafrbaefluerbfeainb",
    "token_type": "Bearer",
    "expires_in": 1200,
    "refresh_token": "fera48ftea4at64fr684fae"
}

# use the verify endpoint to know who we are
api_info = security.verify()

# api_info contains data like this
# {
Exemplo n.º 14
0
    secret_key=config.ESI_SECRET_KEY,
    # code_verifier=generate_code_verifier()
    headers={'User-Agent': config.ESI_USER_AGENT})

# init the client
client = EsiClient(
    cache=cache,
    security=security,
    headers={'User-Agent': config.ESI_USER_AGENT},
    retry_requests=True,
)

### Authenticate
eve_sso_auth_url = security.get_auth_uri(
    state=helpers.generate_state_token(),
    # scopes=config.ESI_SCOPES  # or None (default) if you don't need any scope
    scopes=['publicData'])

webbrowser.open_new_tab(eve_sso_auth_url)

code = input('Code: ')

tokens = security.auth(code)
security.verify()

m = trade.Markets(app, client)
# m.get_space_rich_jita()
m.get_space_rich_amarr()

print('debug')