Esempio n. 1
0
class SlrStatus(Resource):
    def __init__(self):
        """
        
        """
        super(SlrStatus, self).__init__()
        self.service_registry_handler = ServiceRegistryHandler(
            current_app.config["SERVICE_REGISTRY_SEARCH_DOMAIN"],
            current_app.config["SERVICE_REGISTRY_SEARCH_ENDPOINT"])
        self.request_timeout = current_app.config["TIMEOUT"]
        self.uid = current_app.config["UID"]
        self.helper = Helpers(current_app.config)
        self.store_session = self.helper.store_session

    @error_handler
    @api_logging
    def post(self, account_id, service_id, slr_id):
        """
        
        :param slr_id:      Id of SLR we want to change
        :param account_id:  Account Manager user id
        :param service_id:  Service id as in Service Registry
        """
        service_url = self.service_registry_handler.getService_url(service_id)

        try:
            am = get_am(current_app, request.headers)
            # Verify Api-Key-User
            key_check = am.verify_user_key(account_id)
            debug_log.info("Verifying User Key resulted: {}".format(key_check))
            try:
                # Get SLR
                slr = am.get_slr(slr_id, account_id)
                decoded_slr = base_token_tool.decode_payload(
                    slr["data"]["attributes"]["payload"])
                surrogate_id = decoded_slr["surrogate_id"]
                last_ssr = am.get_last_slr_status(slr_id)
                last_ssr_payload = base_token_tool.decode_payload(
                    last_ssr["data"]["attributes"]["payload"])
                if last_ssr_payload["sl_status"] != "Active":
                    raise TypeError("This SLR isn't Active to begin with.")
                prev_record_id = last_ssr_payload["record_id"]
                debug_log.info(
                    "Got Decoded SLR Payload:\n {}".format(decoded_slr))
                consents = am.get_crs(slr_id, account_id, pairs=True)["data"]

                # Loop trough the consents and fetch pairs.
                # Step redundant since endpoint at Account gives us paired consent as well.
            except Exception as e:
                raise e

            self.helper.change_cr_pair_status(slr_id, account_id, am,
                                              self.service_registry_handler,
                                              "Withdrawn")

            try:
                # Create new SLR status

                created_ssr = am.create_ssr(
                    surrogate_id=surrogate_id,
                    slr_id=slr_id,
                    sl_status="Removed",
                    prev_record_id=prev_record_id,
                )

            except Exception as e:
                raise e

            try:
                # Notify Service of SLR status chanege

                endpoint = "/api/1.3/slr/status"
                req = post(service_url + endpoint, json=created_ssr)
                debug_log.debug(
                    "Posted SSR to service:\n{}  {}  {}  {}".format(
                        req.status_code, req.reason, req.text, req.content))

                return created_ssr, 201

            except Exception as e:
                raise e

        except DetailedHTTPException as e:
            raise e
        except Exception as e:
            raise DetailedHTTPException(
                status=500,
                title="Something went really wrong during SLR Status Change.",
                detail="Error: {}".format(repr(e)),
                exception=e,
                trace=traceback.format_exc(limit=100).splitlines())
Esempio n. 2
0
class StatusChange(Resource):
    def __init__(self):
        super(StatusChange, self).__init__()
        self.am_url = current_app.config["ACCOUNT_MANAGEMENT_URL"]
        self.am_user = current_app.config["ACCOUNT_MANAGEMENT_USER"]
        self.am_password = current_app.config["ACCOUNT_MANAGEMENT_PASSWORD"]
        self.timeout = current_app.config["TIMEOUT"]
        self.helper_object = Helpers(current_app.config)
        self.service_registry_handler = ServiceRegistryHandler(
            current_app.config["SERVICE_REGISTRY_SEARCH_DOMAIN"],
            current_app.config["SERVICE_REGISTRY_SEARCH_ENDPOINT"])

    @error_handler
    @api_logging
    def post(self, acc_id, srv_id, cr_id, new_status):
        '''post

        :return: Change status of CR
        '''
        sq.opt("Start CR status change.")
        sq.message_from("OpUi", "POST: Change CR status")
        sq.activate()
        sq.task("Verify new state is supported one.")
        try:
            allowed_states = ["Active", "Disabled", "Withdrawn"]
            if new_status in allowed_states:
                debug_log.info(
                    "We received status change request for cr_id ({}) for srv_id ({}) on account ({})"
                    .format(cr_id, srv_id, acc_id))
                # How do we authorize this request? Who is allowed to make it?
                # Now only those who have Account User Key can successfully make this.
                # Get previous_csr_id

                am = get_am(current_app, request.headers)
                key_check = am.verify_user_key(acc_id)
                debug_log.info(
                    "Verifying User Key resulted: {}".format(key_check))

                link_id, surrogate_id = am.get_surrogate_and_slr_id(
                    acc_id, srv_id)

                previous_csr = am.get_last_csr(cr_id, link_id)
                previous_csr_id = previous_csr["record_id"]
                previous_status = previous_csr["consent_status"]
                if previous_status == new_status:
                    raise DetailedHTTPException(
                        title="Unable to change consent status from {} to {}.".
                        format(previous_csr["consent_status"], new_status),
                        detail={
                            "msg":
                            "Status change must happen from one state to another."
                        },
                        status=409)
                elif previous_status == "Withdrawn":
                    raise DetailedHTTPException(
                        title="Unable to change consent status from {} to {}.".
                        format(previous_csr["consent_status"], new_status),
                        detail={"msg": "Status change to Withdrawn is final."},
                        status=409)

                csr = self.helper_object.change_cr_pair_status(
                    link_id, acc_id, am, self.service_registry_handler,
                    new_status)

            else:
                raise DetailedHTTPException(
                    title="Unable to change consent status to {}.".format(
                        new_status),
                    detail={"msg": "Unsupported Status Change"},
                    status=409)
        except Exception as e:
            raise DetailedHTTPException(
                status=500,
                title="Consent Status Change Failed.",
                detail=
                "Server encountered unexpected error while trying consent status change,"
                " please try again.",
                trace=traceback.format_exc(limit=100).splitlines())
        return csr, 201