Skip to content

Ported to python3 #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added README.md
Empty file.
37 changes: 24 additions & 13 deletions oauthclient/credentialutil.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
"""
Copyright 2019 eBay Inc.

Licensed under the Apache License, Version 2.0 (the "License");
You may not use this file except in compliance with the License.
You may obtain a copy of the License at
Expand All @@ -15,9 +15,20 @@
See the License for the specific language governing permissions and
limitations under the License.
"""
import yaml, json
import yaml, json, os, sys
from .model.model import environment, credentials


import logging
from model.model import environment, credentials
logger = logging.getLogger(str(os.getpid()) +'."'+__file__+'"')
# check if there are parents handlers. If not then add console output
if len(logging.getLogger(str(os.getpid())).handlers) == 0:
logger.setLevel(logging.DEBUG)
fh = logging.StreamHandler(sys.stdout)
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
logger.debug('Loaded '+ __file__)


user_config_ids = ["sandbox-user", "production-user"]

Expand All @@ -26,11 +37,11 @@ class credentialutil(object):
credential_list: dictionary key=string, value=credentials
"""
_credential_list = {}


@classmethod
def load(cls, app_config_path):
logging.info("Loading credential configuration file at: %s", app_config_path)
logger.debug("Loading credential configuration file at: %s", app_config_path)
with open(app_config_path, 'r') as f:
if app_config_path.endswith('.yaml') or app_config_path.endswith('.yml'):
content = yaml.load(f)
Expand All @@ -43,9 +54,9 @@ def load(cls, app_config_path):
@classmethod
def _iterate(cls, content):
for key in content:
logging.debug("Environment attempted: %s", key)
if key in [environment.PRODUCTION.config_id, environment.SANDBOX.config_id]:
logger.debug("Environment attempted: %s", key)

if key in [environment.PRODUCTION.config_id, environment.SANDBOX.config_id]:
client_id = content[key]['appid']
dev_id = content[key]['devid']
client_secret = content[key]['certid']
Expand All @@ -54,18 +65,18 @@ def _iterate(cls, content):
app_info = credentials(client_id, client_secret, dev_id, ru_name)
cls._credential_list.update({key: app_info})



@classmethod
def get_credentials(cls, env_type):
"""
env_config_id: environment.PRODUCTION.config_id or environment.SANDBOX.config_id
"""
"""
if len(cls._credential_list) == 0:
msg = "No environment loaded from configuration file"
logging.error(msg)
logger.error(msg)
raise CredentialNotLoadedError(msg)
return cls._credential_list[env_type.config_id]

class CredentialNotLoadedError(Exception):
pass
10 changes: 5 additions & 5 deletions oauthclient/model/util.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
"""
Copyright 2019 eBay Inc.

Licensed under the Apache License, Version 2.0 (the "License");
You may not use this file except in compliance with the License.
You may obtain a copy of the License at
Expand All @@ -20,10 +20,10 @@

def _generate_request_headers(credential):

b64_encoded_credential = base64.b64encode(credential.client_id + ':' + credential.client_secret)
b64_encoded_credential = base64.b64encode((credential.client_id + ':' + credential.client_secret).encode())
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + b64_encoded_credential
'Authorization': 'Basic ' + b64_encoded_credential.decode()
}

return headers
Expand All @@ -37,14 +37,14 @@ def _generate_application_request_body(credential, scopes):
'redirect_uri': credential.ru_name,
'scope': scopes
}


return body

def _generate_refresh_request_body(scopes, refresh_token):
if refresh_token == None:
raise StandardError("credential object does not contain refresh_token and/or scopes")

body = {
'grant_type': 'refresh_token',
'refresh_token': refresh_token,
Expand Down
118 changes: 63 additions & 55 deletions oauthclient/oauth2api.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
"""
Copyright 2019 eBay Inc.

Licensed under the Apache License, Version 2.0 (the "License");
You may not use this file except in compliance with the License.
You may obtain a copy of the License at
Expand All @@ -16,30 +16,38 @@
limitations under the License.
"""

import json
import urllib
import json, os, sys
from urllib.parse import urlencode
import requests
import logging
import model.util
from .model import util
from datetime import datetime, timedelta
from credentialutil import credentialutil
from model.model import oAuth_token
from .credentialutil import credentialutil
from .model.model import oAuth_token

LOGFILE = 'eBay_Oauth_log.txt'
logging.basicConfig(level=logging.DEBUG, filename=LOGFILE, format="%(asctime)s: %(levelname)s - %(funcName)s: %(message)s", filemode='w')


import logging
logger = logging.getLogger(str(os.getpid()) +'."'+__file__+'"')
# check if there are parents handlers. If not then add console output
if len(logging.getLogger(str(os.getpid())).handlers) == 0:
logger.setLevel(logging.DEBUG)
fh = logging.StreamHandler(sys.stdout)
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
logger.debug('Loaded '+ __file__)


class oauth2api(object):


def generate_user_authorization_url(self, env_type, scopes, state=None):
'''
env_type = environment.SANDBOX or environment.PRODUCTION
scopes = list of strings
'''

credential = credentialutil.get_credentials(env_type)
credential = credentialutil.get_credentials(env_type)

scopes = ' '.join(scopes)
param = {
'client_id':credential.client_id,
Expand All @@ -48,86 +56,86 @@ def generate_user_authorization_url(self, env_type, scopes, state=None):
'prompt':'login',
'scope':scopes
}

if state != None:
param.update({'state':state})
query = urllib.urlencode(param)


query = urlencode(param)
return env_type.web_endpoint + '?' + query


def get_application_token(self, env_type, scopes):
"""
makes call for application token and stores result in credential object
returns credential object
"""
logging.info("Trying to get a new application access token ... ")
credential = credentialutil.get_credentials(env_type)
headers = model.util._generate_request_headers(credential)
body = model.util._generate_application_request_body(credential, ' '.join(scopes))

logging.info("Trying to get a new application access token ... ")
credential = credentialutil.get_credentials(env_type)
headers = util._generate_request_headers(credential)
body = util._generate_application_request_body(credential, ' '.join(scopes))

resp = requests.post(env_type.api_endpoint, data=body, headers=headers)
content = json.loads(resp.content)
token = oAuth_token()
token = oAuth_token()

if resp.status_code == requests.codes.ok:
token.access_token = content['access_token']
# set token expiration time 5 minutes before actual expire time
token.token_expiry = datetime.utcnow()+timedelta(seconds=int(content['expires_in']))-timedelta(minutes=5)

else:
token.error = str(resp.status_code) + ': ' + content['error_description']
logging.error("Unable to retrieve token. Status code: %s - %s", resp.status_code, requests.status_codes._codes[resp.status_code])
logging.error("Error: %s - %s", content['error'], content['error_description'])
return token

def exchange_code_for_access_token(self, env_type, code):
logging.info("Trying to get a new user access token ... ")
credential = credentialutil.get_credentials(env_type)
headers = model.util._generate_request_headers(credential)
body = model.util._generate_oauth_request_body(credential, code)
logger.error("Unable to retrieve token. Status code: %s - %s", resp.status_code, requests.status_codes._codes[resp.status_code])
logger.error("Error: %s - %s", content['error'], content['error_description'])
return token


def exchange_code_for_access_token(self, env_type, code):
logger.info("Trying to get a new user access token ... ")
credential = credentialutil.get_credentials(env_type)

headers = util._generate_request_headers(credential)
body = util._generate_oauth_request_body(credential, code)
resp = requests.post(env_type.api_endpoint, data=body, headers=headers)

content = json.loads(resp.content)
token = oAuth_token()
token = oAuth_token()

if resp.status_code == requests.codes.ok:
token.access_token = content['access_token']
token.token_expiry = datetime.utcnow()+timedelta(seconds=int(content['expires_in']))-timedelta(minutes=5)
token.refresh_token = content['refresh_token']
token.refresh_token_expiry = datetime.utcnow()+timedelta(seconds=int(content['refresh_token_expires_in']))-timedelta(minutes=5)
else:
token.error = str(resp.status_code) + ': ' + content['error_description']
logging.error("Unable to retrieve token. Status code: %s - %s", resp.status_code, requests.status_codes._codes[resp.status_code])
logging.error("Error: %s - %s", content['error'], content['error_description'])
logger.error("Unable to retrieve token. Status code: %s - %s", resp.status_code, requests.status_codes._codes[resp.status_code])
logger.error("Error: %s - %s", content['error'], content['error_description'])
return token


def get_access_token(self, env_type, refresh_token, scopes):
"""
refresh token call
"""

logging.info("Trying to get a new user access token ... ")

credential = credentialutil.get_credentials(env_type)

headers = model.util._generate_request_headers(credential)
body = model.util._generate_refresh_request_body(' '.join(scopes), refresh_token)
logger.debug("Trying to get a new user access token ... ")

credential = credentialutil.get_credentials(env_type)

headers = util._generate_request_headers(credential)
body = util._generate_refresh_request_body(' '.join(scopes), refresh_token)
resp = requests.post(env_type.api_endpoint, data=body, headers=headers)
content = json.loads(resp.content)
token = oAuth_token()
token.token_response = content
token = oAuth_token()
token.token_response = content

if resp.status_code == requests.codes.ok:
token.access_token = content['access_token']
token.token_expiry = datetime.utcnow()+timedelta(seconds=int(content['expires_in']))-timedelta(minutes=5)
else:
token.error = str(resp.status_code) + ': ' + content['error_description']
logging.error("Unable to retrieve token. Status code: %s - %s", resp.status_code, requests.status_codes._codes[resp.status_code])
logging.error("Error: %s - %s", content['error'], content['error_description'])
logger.error("Unable to retrieve token. Status code: %s - %s", resp.status_code, requests.status_codes._codes[resp.status_code])
logger.error("Error: %s - %s", content['error'], content['error_description'])
return token
Loading