Beispiel #1
0
def not_authenticated(response):
    response_content = decoded_response(response)
    try:
        if response.status_code == 401 or json.loads(
                response_content)["responseCode"] == 402:
            # need to put 'OR' because the HS responseCode is not always received!
            return True
    except ValueError as e:  # If there is no JSON response.
        pass
    return False
    def check_if_username_exists(self, username):
        '''
        Check if the username handles exists.

        :param username: The username, in the form index:prefix/suffix
        :raises: :exc:`~pyhandle.handleexceptions.HandleNotFoundException`
        :raises: :exc:`~pyhandle.handleexceptions.GenericHandleError`
        :return: True. If it does not exist, an exception is raised.

        *Note:* Only the existence of the handle is verified. The existence or
        validity of the index is not checked, because entries containing
        a key are hidden anyway.
        '''
        LOGGER.debug('check_if_username_exists...')

        _, handle = pyhandle.utilhandle.remove_index_from_handle(username)

        resp = self.send_handle_get_request(handle)
        resp_content = decoded_response(resp)
        if pyhandle.hsresponses.does_handle_exist(resp):
            handlerecord_json = json.loads(resp_content)
            if not handlerecord_json['handle'] == handle:
                raise GenericHandleError(
                    operation='Checking if username exists',
                    handle=handle,
                    reponse=resp,
                    msg=
                    'The check returned a different handle than was asked for.'
                )
            return True
        elif pyhandle.hsresponses.handle_not_found(resp):
            msg = 'The username handle does not exist'
            raise HandleNotFoundException(handle=handle,
                                          msg=msg,
                                          response=resp)
        else:
            op = 'checking if handle exists'
            msg = 'Checking if username exists went wrong'
            raise GenericHandleError(operation=op,
                                     handle=handle,
                                     response=resp,
                                     msg=msg)
Beispiel #3
0
    def retrieve_handle_record_json(self, handle):
        '''
        Retrieve a handle record from the Handle server as a complete nested
        dict (including index, ttl, timestamp, ...) for later use.

        Note: For retrieving a simple dict with only the keys and values,
        please use :meth:`~pyhandle.handleclient.RESTHandleClient.retrieve_handle_record`.

        :param handle: The Handle whose record to retrieve.
        :raises: :exc:`~pyhandle.handleexceptions.HandleSyntaxError`
        :return: The handle record as a nested dict. If the handle does not
            exist, returns None.
        '''
        LOGGER.debug('retrieve_handle_record_json...')

        utilhandle.check_handle_syntax(handle)
        response = self.__send_handle_get_request(handle)
        response_content = decoded_response(response)

        if hsresponses.handle_not_found(response):
            return None
        elif hsresponses.does_handle_exist(response):

            handlerecord_json = json.loads(response_content)
            if not handlerecord_json['handle'] == handle:
                raise GenericHandleError(
                    operation='retrieving handle record',
                    handle=handle,
                    response=response,
                    custom_message=
                    'The retrieve returned a different handle than was asked for.'
                )
            return handlerecord_json
        elif hsresponses.is_handle_empty(response):
            handlerecord_json = json.loads(response_content)
            return handlerecord_json
        else:
            raise GenericHandleError(operation='retrieving',
                                     handle=handle,
                                     response=response)
Beispiel #4
0
    def register_handle(self,
                        handle,
                        location,
                        checksum=None,
                        additional_URLs=None,
                        overwrite=False,
                        **extratypes):
        '''
        Registers a new Handle with given name. If the handle already exists
        and overwrite is not set to True, the method will throw an
        exception.

        :param handle: The full name of the handle to be registered (prefix
            and suffix)
        :param location: The URL of the data entity to be referenced
        :param checksum: Optional. The checksum string.
        :param extratypes: Optional. Additional key value pairs.
        :param additional_URLs: Optional. A list of URLs (as strings) to be
            added to the handle record as 10320/LOC entry.
        :param overwrite: Optional. If set to True, an existing handle record
            will be overwritten. Defaults to False.
        :raises: :exc:`~pyhandle.handleexceptions.HandleAlreadyExistsException` Only if overwrite is not set or
            set to False.
        :raises: :exc:`~pyhandle.handleexceptions.HandleAuthenticationError`
        :raises: :exc:`~pyhandle.handleexceptions.HandleSyntaxError`
        :return: The handle name.
        '''
        LOGGER.debug('register_handle...')

        # If already exists and can't be overwritten:
        if overwrite == False:
            handlerecord_json = self.retrieve_handle_record_json(handle)
            if handlerecord_json is not None:
                msg = 'Could not register handle'
                LOGGER.error(msg + ', as it already exists.')
                raise HandleAlreadyExistsException(handle=handle, msg=msg)

        # Create admin entry
        list_of_entries = []
        adminentry = self.__create_admin_entry(
            self.__handleowner, self.__HS_ADMIN_permissions,
            self.__make_another_index(list_of_entries, hs_admin=True), handle)
        list_of_entries.append(adminentry)

        # Create other entries
        entry_URL = self.__create_entry(
            'URL', location,
            self.__make_another_index(list_of_entries, url=True))
        list_of_entries.append(entry_URL)
        if checksum is not None:
            entryChecksum = self.__create_entry(
                'CHECKSUM', checksum,
                self.__make_another_index(list_of_entries))
            list_of_entries.append(entryChecksum)
        if extratypes is not None:
            for key, value in extratypes.items():
                entry = self.__create_entry(
                    key, value, self.__make_another_index(list_of_entries))
                list_of_entries.append(entry)

        # Create record itself and put to server
        op = 'registering handle'
        resp, put_payload = self.__send_handle_put_request(handle,
                                                           list_of_entries,
                                                           overwrite=overwrite,
                                                           op=op)
        resp_content = decoded_response(resp)
        if hsresponses.was_handle_created(resp) or hsresponses.handle_success(
                resp):
            LOGGER.info("Handle registered: " + handle)
            return json.loads(resp_content)['handle']
        elif hsresponses.is_temporary_redirect(resp):
            oldurl = resp.url
            newurl = resp.headers['location']
            raise GenericHandleError(operation=op,
                                     handle=handle,
                                     response=resp,
                                     payload=put_payload,
                                     msg='Temporary redirect from ' + oldurl +
                                     ' to ' + newurl + '.')
        elif hsresponses.handle_not_found(resp):
            raise GenericHandleError(
                operation=op,
                handle=handle,
                response=resp,
                payload=put_payload,
                msg=
                'Could not create handle. Possibly you used HTTP instead of HTTPS?'
            )
        else:
            raise GenericHandleError(operation=op,
                                     handle=handle,
                                     reponse=resp,
                                     payload=put_payload)
Beispiel #5
0
def handle_already_exists(response):
    response_content = decoded_response(response)
    if response.status_code == 409 & json.loads(
            response_content)["responseCode"] == 101:
        return True
    return False
Beispiel #6
0
def values_not_found(response):
    response_content = decoded_response(response)
    if response.status_code == 400 and json.loads(
            response_content)["responseCode"] == 200:
        return True
    return False
Beispiel #7
0
def handle_not_found(response):
    response_content = decoded_response(response)
    if response.status_code == 404 and json.loads(
            response_content)["responseCode"] == 100:
        return True
    return False
Beispiel #8
0
def was_handle_created(response):
    response_content = decoded_response(response)
    if response.status_code == 201 and json.loads(
            response_content)["responseCode"] == 1:
        return True
    return False
Beispiel #9
0
def is_handle_empty(response):
    response_content = decoded_response(response)
    if response.status_code == 200 and json.loads(
            response_content)["responseCode"] == 200:
        return True
    return False
Beispiel #10
0
def handle_success(response):
    response_content = decoded_response(response)
    if (response.status_code == 200 or response.status_code
            == 201) and json.loads(response_content)["responseCode"] == 1:
        return True
    return False