示例#1
0
    def start_deposit_rsc(self, request):
        """
        Ping the async-service to start the process of depositing RSC
        """

        url = ASYNC_SERVICE_HOST + "/ethereum/deposit"
        deposit = Deposit.objects.create(
            user=request.user,
            amount=request.data.get("amount"),
            from_address=request.data.get("from_address"),
            transaction_hash=request.data.get("transaction_hash"),
        )
        message_raw = {
            "deposit_id": deposit.id,
            "tx_hash": deposit.transaction_hash,
            "amount": deposit.amount,
            "from_address": deposit.from_address,
            "user_id": deposit.user.id,
        }
        signature, message, public_key = ethereum.utils.sign_message(
            message_raw, WEB3_SHARED_SECRET)
        data = {
            "signature": signature,
            "message": message.hex(),
            "public_key": public_key,
        }
        response = http_request(POST, url, data=json.dumps(data), timeout=10)
        response.raise_for_status()
        logging.info(response.content)
        return Response(status=response.status_code)
    def _send_put_request(self, url, data, headers, error_message):
        """Returns the response of a put request to Elasticsearch.

        Raises ElasticsearchPluginError on error.
        """
        try:
            response = http_request(
                methods.PUT,
                url,
                json.dumps(data),
                timeout=8,
                headers=headers
            )
            if not response.ok:
                message = (
                    f'Request to Elasticsearch failed with'
                    f'{response.status_code}'
                )
                sentry.log_error(
                    response.text,
                    message
                )
            return response
        except Exception as e:
            raise ElasticsearchPluginError(e, error_message)
示例#3
0
def orcid_connect(request):
    success = False
    status = 400

    try:
        orcid = request.data.get('orcid')
        access_token = request.data.get('access_token')
        url = f'https://pub.orcid.org/v3.0/{orcid}/record'
        headers = {
            'Accept': 'application/json',
            'Authorization': f'Bearer {access_token}'
        }
        # Raise for status because we need to make sure we can authenticate
        # correctly with orcid. Without this check, anyone could make a post
        # request to connect any other orcid account to their own.
        response = http_request(RequestMethods.GET, url=url, headers=headers)
        response.raise_for_status()
        user = request.user

        save_orcid_author(user, orcid, response.json())
        events_api.track_account(user, request, update=True)

        success = True
        status = 201
        data = {
            'success': success,
            'orcid_profile': f'https://orcid.org/{orcid}'
        }
    except Exception as e:
        data = str(e)
        sentry.log_error(e)
        print(e)

    return Response(data, status=status)
    def _get_response(self, url):
        response = http_request(GET, url)
        time.sleep(.1)

        if response.status_code == 429:
            logging.warning(
                'Semantic Scholar responded with 429. Sleeping for 4 seconds')
            time.sleep(4)
            response = http_request(GET, url)

        if response.status_code == 403:
            logging.warning(
                'Semantic Scholar responded with 403. Sleeping for 5 minutes')
            time.sleep(300)
            response = http_request(GET, url)

        return response
示例#5
0
 def track_paid_status(self, purchase_id, transaction_hash):
     url = ASYNC_SERVICE_HOST + '/ethereum/track_purchase'
     data = {'purchase': purchase_id, 'transaction_hash': transaction_hash}
     response = http_request(RequestMethods.POST,
                             url,
                             data=json.dumps(data),
                             timeout=3)
     response.raise_for_status()
     return response
 def _check_pipeline_exists(self):
     response = http_request(methods.GET, self.url)
     if response.status_code == 200:
         return True
     if response.status_code == 404:
         return False
     raise ElasticsearchPluginError(
         None,
         f'Check pipeline failed with status code {response.status_code}'
     )
示例#7
0
 def refetch_api_tokens(self, scope='/read-public'):
     data = {
         'client_id': orcid['CLIENT_ID'],
         'client_secret': orcid['CLIENT_SECRET'],
         'grant_type': 'client_credentials',
         'scope': scope,
     }
     response = http_request(POST, data)
     self.access_token = response.data['access_token']
     self.refresh_token = response.data['refresh_token']
     self._build_default_headers()
示例#8
0
 def search_by_paper_id(self, doi=None, arxiv=None):
     key = ''
     uid = ''
     if doi is not None:
         key = 'doi-self'
         uid = doi
     elif arxiv is not None:
         key = 'arxiv'
         uid = arxiv
     url = self.search_url + f'/?q={key}:{uid}'
     response = http_request(GET, url, headers=self.headers, timeout=5)
     return response, uid
示例#9
0
def get_redirect_url(url):
    response = http_request(methods.GET, url, allow_redirects=False)
    status_code = response.status_code
    if status_code == 301 or status_code == 302 or status_code == 303:
        headers = response.headers
        location = headers.get("Location")
        if location:
            return location
        else:
            return None
    elif status_code == 200:
        return url
    return None
示例#10
0
def _get_orcid_email(sociallogin):
    from utils.http import http_request, GET
    from oauth.exceptions import LoginError

    url = f'https://pub.orcid.org/v3.0/{sociallogin.account.uid}/email'
    headers = {
        'authorization': f'Bearer {sociallogin.token.token}',
        'accept': f'application/json'
    }

    response = http_request(GET, url, headers=headers)

    email = _parse_email_from_orcid_response(response)
    if email is None:
        raise LoginError(None, 'Failed to retrieve orcid email')
    return email
示例#11
0
def email_notifications(request):
    """Handles AWS SNS email notifications."""

    data = request.data
    if type(request.data) is not dict:
        data = json.loads(request.data)

    data_type = None
    try:
        data_type = data['Type']
    except KeyError:
        raise ParseError(f'Did not find key `Type` in {data}')

    if data_type == 'SubscriptionConfirmation':
        url = data['SubscribeURL']
        resp = http_request('GET', url)
        if resp.status_code != 200:
            message = 'Failed to subscribe to SNS'
            log_request_error(resp, message)

    elif data_type == 'Notification':
        data_message = json.loads(data['Message'])
        if data_message['notificationType'] == 'Bounce':
            bounced_recipients = data_message['bounce']['bouncedRecipients']

            for b_r in bounced_recipients:
                email_address = b_r['emailAddress']
                # TODO: Sanitize email address before putting it in the db
                try:
                    recipient, created = EmailRecipient.objects.get_or_create(
                        email=email_address)
                    recipient.bounced()
                except Exception as e:
                    message = (
                        f'Failed handling bounced recipient: {email_address}')
                    error = EmailNotificationError(e, message)
                    print(error)
                    log_error(error, base_error=e)
    elif data_type == 'Complaint':
        message = (f'`email_notifications` received {data_type}')
        log_info(message)
    else:
        message = (
            f'`email_notifications` received unsupported type {data_type}')
        print(message)

    return Response({})
示例#12
0
 def delete(self):
     """Deletes the pipeline from Elasticsearch"""
     return http_request(methods.DELETE, self.url)
示例#13
0
 def search_by_id(self, uid):
     url = self.base_url + f'/{uid}/record'
     response = http_request(GET, url, headers=self.headers, timeout=5)
     return response
示例#14
0
 def search_by_name(self, given_names, family_name):
     url = self.search_url + f'/?q="{given_names}%20{family_name}"'
     response = http_request(GET, url, headers=self.headers, timeout=2)
     return response
示例#15
0
def get_pdf_from_url(url):
    response = http_request(methods.GET, url, timeout=3)
    pdf = ContentFile(response.content)
    return pdf