예제 #1
0
def sendPutRequestToOCLC(url, bodyData):
    """ Function builds a put request to OCLC's API and send data
    """

    configData = parseConfigFile("config.json")

    #Assign variables
    key = configData["client_id"]
    secret = configData["client_secret"]
    principal_id = configData["principalID"]
    principal_idns = configData["principalIDNS"]
    institution_id = configData["institutionId"]

    my_wskey = wskey.Wskey(key=key, secret=secret, options=None)

    my_user = user.User(authenticating_institution_id=institution_id,
                        principal_id=principal_id,
                        principal_idns=principal_idns)

    authorization_header = my_wskey.get_hmac_signature(method='PUT',
                                                       request_url=url,
                                                       options={
                                                           'user': my_user,
                                                           'auth_params': None
                                                       })

    my_request = requests.put(url=url,
                              data=bodyData,
                              headers={
                                  'Authorization': authorization_header,
                                  "accept": "application/atom+json",
                                  "Content-Type": "application/atom+json"
                              })

    return my_request
예제 #2
0
def authenticate():
    """
    Retrieves a token from OCLC with Client Credentials grant and
    returns the token.
    """
    key = settings.KEY
    secret = settings.SECRET
    authenticating_institution_id = settings.AUTHENTICATING_INSTITUTION_ID
    context_institution_id = settings.CONTEXT_INSTITUTION_ID

    # Configure the wskey library object
    my_wskey = wskey.Wskey(key=key,
                           secret=secret,
                           options={'services': ['WorldCatDiscoveryAPI']})

    # Get an access token
    access_token = my_wskey.get_access_token_with_client_credentials(
        authenticating_institution_id=authenticating_institution_id,
        context_institution_id=context_institution_id)

    if (access_token.access_token_string == None):
        raise AuthenticationError(code=access_token.error_code,
                                  msg=access_token.error_message,
                                  url=access_token.url)

    return access_token
예제 #3
0
 def setUp(self):
     self._my_wskey = wskey.Wskey(
         **{
             'key':
             'CancdeDMjFO9vnzkDrB6WJg1UnyTnkn8lLupLKygr0U1KJLiaAittuVjGRywCDdrsxahv2sbjgKq6hLM',
             'secret': 'YeZfIJdGYUeatxQOjekRZw==',
             'options': {
                 'redirect_uri': 'http://www.oclc.org/test',
                 'services': ['WMS_NCIP', 'WMS_ACQ']
             }
         })
예제 #4
0
 def testCreateWskeyExceptions(self):
     with self.assertRaises(wskey.InvalidObject):
         wskey.Wskey('123ABC', '987', '')
     with self.assertRaises(wskey.InvalidParameter):
         wskey.Wskey('123ABC', '987', {
             'redirect_uri': '',
             'services': ['one', 'two']
         })
     with self.assertRaises(wskey.InvalidParameter):
         wskey.Wskey(
             '123ABC', '987', {
                 'redirect_uri': 'www.mylibrary123.org/myapp',
                 'services': ['one', 'two']
             })
     with self.assertRaises(wskey.InvalidParameter):
         wskey.Wskey(
             '123ABC', '987', {
                 'redirect_uri': 'http://www.mylibrary123.org/myapp',
                 'services': None
             })
     with self.assertRaises(wskey.InvalidParameter):
         wskey.Wskey(
             '123ABC', '987', {
                 'redirect_uri': 'http://www.mylibrary123.org/myapp',
                 'services': ''
             })
     with self.assertRaises(wskey.InvalidParameter):
         wskey.Wskey(
             '123ABC', '987', {
                 'redirect_uri': 'http://www.mylibrary123.org/myapp',
                 'services': []
             })
예제 #5
0
    def __init__(self, params, options=None):
        self.key = params.get('key')
        self.secret = params.get('secret')
        self.principleId = params.get('principleId')
        self.principleIDNS = params.get('principleIDNS')
        self.institutionId = params.get('institutionId')
        self.options = options
        self.etag = None

        self.user = user.User(authenticating_institution_id=self.institutionId,
                              principal_id=self.principleId,
                              principal_idns=self.principleIDNS)

        self.wsKey = wskey.Wskey(key=self.key,
                                 secret=self.secret,
                                 options=self.options)
예제 #6
0
    def comprobarDisponibilidad(self, codigosOCLC):
        """ Dado un codigo OCLC de un libro comprueba la disponibilidad de dicho libro """
        URL = self.__URLavailability + "query=no%3Aocm" + codigosOCLC + "&x-registryId=" +\
              self.__wskeydata['registry_id']

        APIkey = self.__wskeydata['key']
        secret = self.__wskeydata['secret']

        my_wskey = wskey.Wskey(key=APIkey, secret=secret, options=None)

        authorization_header = my_wskey.get_hmac_signature(method='GET',
                                                           request_url=URL,
                                                           options=None)

        r = urllib.request.Request(
            url=URL, headers={'Authorization': authorization_header})
        response = urllib.request.urlopen(r)

        content = response.read()

        xmlns = {'sRR': 'http://www.loc.gov/zing/srw/'}

        tree = ET.parse(io.BytesIO(content))
        root = tree.getroot()

        resultado = []
        biblioteca = {}

        for holdings in root.findall(
                './/sRR:records/sRR:record/sRR:recordData/opacRecord/holdings',
                xmlns):
            for items in holdings.iterdescendants('holding'):
                for item in items.findall('.//circulation'):
                    if int(item.find('availableNow').get('value')) > 0:
                        if self.__equivalencias[items.find(
                                'localLocation').text] not in biblioteca:
                            biblioteca[self.__equivalencias[items.find('localLocation').text]] = \
                                int(item.find('availableNow').get('value'))
                        else:
                            biblioteca[self.__equivalencias[items.find('localLocation').text]] += \
                                int(item.find('availableNow').get('value'))

        resultado.append(biblioteca)
        return resultado
import urllib2
from authliboclc import wskey

#
# Authentication Parameters
#

key = '{clientID}'
secret = '{secret}'
authenticating_institution_id = '{institutionId}'
context_institution_id = '{institutionId}'

# Configure the wskey library object
my_wskey = wskey.Wskey(key=key,
                       secret=secret,
                       options={'services': ['WorldCatDiscoveryAPI']})

# Get an access token
access_token = my_wskey.get_access_token_with_client_credentials(
    authenticating_institution_id=authenticating_institution_id,
    context_institution_id=context_institution_id)

# Describe the token received, or the error produced
print("")
if (access_token.access_token_string == None):
    if (key == '{clientID}'):
        print(
            "**** You must configure the key, secret, authenticating_institution_id and context_institution_id ****"
        )
        print("")
예제 #8
0
def perpetualAccessCheck(collUid):
	global perAccess
	global archivalCopy
	perAccess = ''
	archivalCopy = ''
#authentication code for License Manager API taken from OCLC documentation: https://github.com/OCLC-Developer-Network/oclc-auth-python
	request_url = 'https://1284.share.worldcat.org/license-manager/license/search?q=collectionId:' + collUid
	my_wskey = wskey.Wskey(
		key=lmKey,
		secret=secret,
		options=None
		)

	my_user = user.User(
		authenticating_institution_id=authenticating_institution_id,
		principal_id=principal_id,
		principal_idns=principal_idns
		)

	authorization_header = my_wskey.get_hmac_signature(
		method='GET',
		request_url=request_url,
		options={
		'user': my_user,
		'auth_params': None}
		)
	print (request_url)
	myRequest = urllib2.Request(
		url=request_url,
		data=None,
		headers={'Authorization': authorization_header}
		)
	time.sleep(1)
	r = urllib2.urlopen(myRequest).read()
	root = ET.fromstring(r)
	resultCheck = root.find('os:totalResults', ns)
	emptyCheck = resultCheck.text
	print('Results: ' + emptyCheck)
	if emptyCheck == "0":
		print('no license found')
		perAccess = 'no license found'
		archivalCopy = 'no license found'
		
	else:
		customTermPath = root.findall("atom:entry/atom:content/df:license/df:terms/df:term/[df:type='Custom Term']", ns)
		for match in customTermPath:
			namePath = match.findall("./df:name", ns)
			termValuePath = match.findall("./df:termValue", ns)
			for name in namePath:
				for termValue in termValuePath:
					if name.text == 'Perpetual Access Rights':
						if termValue.text == 'yes':
							perAccess = 'yes'
					else:
						perAccess = 'no or silent'
						#elif termValue.text == 'no':
						#	perAccess = 'no'
						#elif termValue.text == 'silent':
						#	perAccess = 'silent'
					#	elif termValue.txt is None:
						#	perAccess = 'silent'
		archivalCopyValue = root.find("atom:entry/atom:content/df:license/df:terms/df:term/[df:type='Archival_Copy_Provided']/df:termValue", ns)
		if archivalCopyValue is None:
			archivalCopy = 'silent'
		elif archivalCopyValue.text == 'yes':
			archivalCopy = 'yes'
		elif archivalCopyValue.text == 'no':
			archivalCopy = 'no'
		else:
			archivalCopy = 'silent'
예제 #9
0
    def do_GET(self):

        if KEY == '{clientID}':
            """The developer forgot to insert authentication parameters into the example."""
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.end_headers()
            self.wfile.write('<h2>Please set the authentication parameters in ' +
                             '<span style="color:red">examples/authentication_token/server.py</span>, ' +
                             'lines 29 & 30.</h2>')
            return

        if (self.path[:6] != '/auth/'):
            """Handle other, non authentication requests here. For example, loading the favicon.ico"""
            return

        print "\n-- Handling a Request --"

        html = ("""<!doctype html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="https://static1.worldcat.org/yui/combo?pure/0.4.2/pure-min.css">
        <style>
            body {width:800px; margin:auto}
            h1 {font-size: 150%}
            td {vertical-align:top}
            .error {line-height: 140%; background-color: lightcoral; padding: 3px 20px; border-radius: 12px}
            pre {font-size: 83%; margin-top:0}
        </style>
    </head>
    <body>
        <h1>Authentication Token & Bibliographic Record</h1>
            """)

        """Populate the WSKey object's parameters"""
        my_wskey = wskey.Wskey(key=KEY, secret=SECRET, options={'services': SERVICES, 'redirect_uri': REDIRECT_URI})

        session_handler = SessionHandler(headers=self.headers)
        access_token = session_handler.get_access_token()

        """If there is a code parameter on the current URL, load it."""
        code = None
        if (self.path is not None):
            params = parse_qs(urlparse(self.path).query)
            if 'code' in params:
                code = params['code'][0]

        """If there are error parameters on the current URL, load them."""
        error = self.headers.get('error', None)
        error_description = self.headers.get('error_description', None)

        if access_token is None and code is None:
            """There is no access token and no authentication code. Initiate user authentication."""

            """Get the user authentication url"""
            login_url = my_wskey.get_login_url(
                authenticating_institution_id=AUTHENTICATING_INSTITUTION_ID,
                context_institution_id=CONTEXT_INSTITUTION_ID
            )

            """Redirect the browser to the login_url"""
            self.send_response(303)
            self.send_header('Location', login_url)
            self.end_headers()

            print "Requiring user to authenticate."

        else:

            if error is not None:
                """If an error was returned, display it."""
                html = ''.join([html, '<p class="error">Error: ', error, '<br>', error_description, '</p>'])

            if access_token is None and code is not None:
                """Request an access token using the user authentication code returned after the user authenticated"""
                """Then request a bibliographic record"""

                print "I now have an authentication code. I will request an access token."
                access_token = my_wskey.get_access_token_with_auth_code(
                    code=code,
                    authenticating_institution_id=AUTHENTICATING_INSTITUTION_ID,
                    context_institution_id=CONTEXT_INSTITUTION_ID
                )

                if access_token.error_code is None:
                    session_handler.save_access_token(access_token)
                    html = ''.join([html, '<p><strong>Access Token</strong> saved to session database.</p>'])

            if access_token is not None:
                """Display the token and request a Bibliographic Record"""
                print "Displaying access token parameters."
                if access_token.error_code is None and code is None:
                    html = ''.join([html, '<p><strong>Access Token</strong> retrieved from session database.</p>'])

                access_token_formatter = AccessTokenFormatter(access_token=access_token)
                html = ''.join([html, access_token_formatter.format()])

                if access_token.error_code is None:
                    print "Using Access Token to request a Bibliographic Record."
                    bib_record = BibRecord(access_token=access_token, wskey=my_wskey)
                    html = ''.join([html, bib_record.read()])

            html = ''.join([html, '</body></html>'])

            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.wfile.write(''.join([session_handler.cookie_header_output(), '\n']))
            self.end_headers()
            self.wfile.write(html)

        return
예제 #10
0
    except URLError as e:
        response_body = e.read()
        print "Response Code = %i" % e.code
        print response_body
        if config.key == '{clientID}':
            print('\n** Note: Edit the script and supply \
                  valid authentication parameters. **\n')

    return bibresult


if __name__ == "__main__":
    import config

    my_wskey = wskey.Wskey(key=config.key, secret=config.secret, options=None)

    my_user = user.User(
        authenticating_institution_id=config.authenticating_institution_id,
        principal_id=config.principal_id,
        principal_idns=config.principal_idns)

    idfile = open(config.idfile, 'r')
    outfile = codecs.open(config.outfile, 'w', 'utf-8')
    outfile.write('OCLC ID,SUDOC,TITLE,YEAR,FORMAT\n')
    lastid = "0"
    lastbibinfo = {}
    for line in idfile.readlines():
        if len(line.strip()) == 0:
            outfile.write(",,,,\n")
        else:
예제 #11
0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################

# Sample HMAC Hashing for any sandbox OCLC record retrieval

from authliboclc import wskey, user

#
# You must supply these parameters to authenticate
# Note - a WSKey consists of two parts, a public clientID and a private secret
#

key = {key}
secret = {secret}
principal_id = {id}
principal_idns = {idns}
authenticating_institution_id = {inst_id}

my_wskey = wskey.Wskey(key=key, secret=secret, options=None)

my_user = user.User(
    authenticating_institution_id=authenticating_institution_id,
    principal_id=principal_id,
    principal_idns=principal_idns)
예제 #12
0
#
# Also requires principleID and principleIDNS as per
#   https://www.oclc.org/developer/develop/authentication/user-level-authentication-and-authorization.en.html
#

key = '{wskey}'
secret = '{secret}'
principal_id = '{principleID}'
principal_idns = '{principleIDNS}'
authenticating_institution_id = '{registryID}'
context_institution_id = '{registryID}'

# Configure the wskey library object

my_wskey = wskey.Wskey(key=key,
                       secret=secret,
                       options={'services': ['WorldCatMetadataAPI']})

my_user = user.User(
    authenticating_institution_id=authenticating_institution_id,
    principal_id=principal_id,
    principal_idns=principal_idns)

# Get an access token
access_token = my_wskey.get_access_token_with_client_credentials(
    authenticating_institution_id=authenticating_institution_id,
    context_institution_id=context_institution_id,
    user=my_user)

# Describe the token received, or the error produced
print("")
예제 #13
0
def setWSKey():
    my_wskey = wskey.Wskey(key=key, secret=secret, options=None)
    return my_wskey