Exemplo n.º 1
0
    def make_request(self, url, data={}, method=None, **kwargs):
        """
        Builds and makes the OAuth2 Request, catches errors

        https://wiki.fitbit.com/display/API/API+Response+Format+And+Errors
        """
        if not method:
            method = 'POST' if data else 'GET'

        try:
            auth = OAuth2(client_id=self.client_id, token=self.token)
            response = self._request(method, url, data=data, auth=auth, **kwargs)
        except TokenExpiredError as e:
            self.refresh_token()
            auth = OAuth2(client_id=self.client_id, token=self.token)
            response = self._request(method, url, data=data, auth=auth, **kwargs)

        #yet another token expiration check
        #(the above try/except only applies if the expired token was obtained
        #using the current instance of the class this is a a general case)
        if response.status_code == 401:
            d = json.loads(response.content.decode('utf8'))
            try:
                if(d['errors'][0]['errorType']=='oauth' and
                    d['errors'][0]['fieldName']=='access_token' and
                    d['errors'][0]['message'].find('Access token invalid or expired:')==0):
                            self.refresh_token()
                            auth = OAuth2(client_id=self.client_id, token=self.token)
                            response = self._request(method, url, data=data, auth=auth, **kwargs)
            except:
                pass

        if response.status_code == 401:
            raise HTTPUnauthorized(response)
        elif response.status_code == 403:
            raise HTTPForbidden(response)
        elif response.status_code == 404:
            raise HTTPNotFound(response)
        elif response.status_code == 409:
            raise HTTPConflict(response)
        elif response.status_code == 429:
            exc = HTTPTooManyRequests(response)
            exc.retry_after_secs = int(response.headers['Retry-After'])
            raise exc

        elif response.status_code >= 500:
            raise HTTPServerError(response)
        elif response.status_code >= 400:
            raise HTTPBadRequest(response)
        return response
Exemplo n.º 2
0
def github_login_behavior():
    url = github_apis.auth_user()
    auth = OAuth2(client_id=client_id, token=session['oauth_user_token'])
    res = requests.get(url, auth=auth)
    if res.status_code != 200:
        msg = 'GitHub authorization failed'
        url = url_for('accounts.register')
        flash(msg, 'danger')
        return redirect(url)

    github_user = res.json()
    username = github_user.get('login')
    # email = github_user.get('email')
    # github_url = github_user.get('html_url')
    # github_avatar_url = github_user.get('avatar_url')

    try:
        user = models.User.objects.get(github_username=username)
    except models.User.DoesNotExist:
        msg = 'Please register first'
        flash(msg, 'danger')
        return redirect(url_for('accounts.register'))

    login_user(user)
    user.last_login = datetime.datetime.now
    user.save()

    url = url_for('main.index')
    return redirect(url)
Exemplo n.º 3
0
def github_link_account_behavior():
    url = github_apis.auth_user()
    auth = OAuth2(client_id=client_id, token=session['oauth_user_token'])
    res = requests.get(url, auth=auth)
    if res.status_code != 200:
        msg = 'GitHub authorization failed'
        flash(msg, 'danger')
        return redirect(url_for('main.index'))

    github_user = res.json()
    username = github_user.get('login')
    email = github_user.get('email')
    github_url = github_user.get('html_url')
    github_avatar_url = github_user.get('avatar_url')

    if len(models.User(github_username=username)) > 0:
        msg = 'This GitHub account({0}) has been binded to another user'.format(
            username)
        flash(msg, 'danger')
        return redirect(url_for('main.index'))

    if not current_user.avatar_url:
        avatar_name = 'github_avatar_{0}.jpeg'.format(username)
        avatar_url = qiniu_fetch_img(github_avatar_url, avatar_name)
        current_user.avatar_url = avatar_url

    current_user.github_username = username
    current_user.github = github_url

    current_user.save()

    return redirect(url_for('main.index'))
Exemplo n.º 4
0
    def get_activities(self,
                       before=None,
                       after=None,
                       activities=[],
                       per_page=30,
                       page=1):
        data = {'per_page': per_page, 'page': page}
        if before is not None:
            data['before'] = before

        if after is not None:
            data['after'] = after

        response = requests.get("https://www.strava.com/api/v3/activities",
                                auth=OAuth2(client_id=self.client_id,
                                            token={
                                                "access_token":
                                                self.access_token.token,
                                                "token_type": "Bearer"
                                            }),
                                data=data)

        json = response.json()

        activities = activities + json

        if len(json) < per_page:
            return activities

        return self.get_activities(before=before,
                                   after=after,
                                   activities=activities,
                                   per_page=per_page,
                                   page=page + 1)
Exemplo n.º 5
0
    def __delete(self, url, **kwargs):
        """
            Make DELETE request to the API using the URL with kwargs in query string

            The API DELETE request is used to delete objects of resources,
                kwargs are passed as query string in the URL

            Args:
                url (str): The URL to send the request to, this does not include
                    the base url which is automatically added from the stored auth
                    object.
                **kwargs (dictionary): A dictionary of keyword arguments which will
                    be passed in the query string

                Returns:
                    dict: A dictionary of the resource.
        """
        token = {"access_token": self.auth.token, "token_type": "Bearer"}
        auth = OAuth2(token=token)
        url = f"{self.auth.base_url}/{url}"
        data = kwargs.get("data", None)
        if data is None:
            return requests.delete(url, auth=auth, params=kwargs)
        else:
            del kwargs["data"]
            self.__get_json(data)
            return requests.delete(url, auth=auth, json=data, params=kwargs)
Exemplo n.º 6
0
    def SetCredentials(self,
                       consumer_key,
                       consumer_secret,
                       access_token_key=None,
                       access_token_secret=None,
                       application_only_auth=False):

        self._consumer_key = consumer_key
        self._consumer_secret = consumer_secret
        self._access_token_key = access_token_key
        self._access_token_secret = access_token_secret

        if application_only_auth:
            self._bearer_token = self.GetAppOnlyAuthToken(
                consumer_key, consumer_secret)
            self.__auth = OAuth2(token=self._bearer_token)
        else:
            auth_list = [
                consumer_key, consumer_secret, access_token_key,
                access_token_secret
            ]
            if all(auth_list):
                self.__auth = OAuth1(consumer_key, consumer_secret,
                                     access_token_key, access_token_secret)

        self._config = None
Exemplo n.º 7
0
    def obtain_user_context_token(self):
        """
        Collect a user context bearer token
        from client_key and client_secret and sets it as OAuth2 
        authentication method for further requests.
        """

        key = urllib.parse.quote_plus(self._credentials.consumer_key)
        secret = urllib.parse.quote_plus(self._credentials.consumer_secret)
        basic_token = base64.b64encode(
            '{0}:{1}'.format(key, secret).encode('utf8')).decode('utf8')
        
        res = self._session.post(
            url='{0}/oauth2/token'.format(self.API_ROOT_URI),
            headers={
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                'Authorization': 'Basic {0}'.format(basic_token),
            },
            data={
                'grant_type': 'client_credentials',
            })

        if res.status_code == 429:
            raise RateLimitException()
        if res.status_code != 200:
            raise Exception('request failed with status code {0}'.format(res.status_code))

        body = res.json()

        self._oauth = OAuth2(token=body)
Exemplo n.º 8
0
    def make_request(self, url, data={}, method=None, **kwargs):
        """
        Builds and makes the OAuth2 Request, catches errors

        https://wiki.fitbit.com/display/API/API+Response+Format+And+Errors
        """
        if not method:
            method = 'POST' if data else 'GET'

        auth = OAuth2(client_id=self.client_id, token=self.token)
        response = self._request(method, url, data=data, auth=auth, **kwargs)

        if response.status_code == 401:
            raise HTTPUnauthorized(response)
        elif response.status_code == 403:
            raise HTTPForbidden(response)
        elif response.status_code == 404:
            raise HTTPNotFound(response)
        elif response.status_code == 409:
            raise HTTPConflict(response)
        elif response.status_code == 429:
            exc = HTTPTooManyRequests(response)
            exc.retry_after_secs = int(response.headers['Retry-After'])
            raise exc

        elif response.status_code >= 500:
            raise HTTPServerError(response)
        elif response.status_code >= 400:
            raise HTTPBadRequest(response)
        return response
def bbof_get_patient(request, patient_id=None):
    context = {'name': 'Blue Button on FHIR'}
    urls = build_fhir_urls(patient_id)

    # first we get the token used to login
    token = request.user.social_auth.get(provider='oauth2io').access_token
    auth = OAuth2(settings.SOCIAL_AUTH_OAUTH2IO_KEY,
                  token={
                      'access_token': token,
                      'token_type': 'Bearer'
                  })
    # next we call the remote api
    url = urls['patient']

    logging.debug("calling FHIR Service with %s" % url)

    response = requests.get(url, auth=auth)

    if response.status_code in (200, 404):
        if response.json():
            content = json.dumps(response.json(), indent=4)
        else:
            content = {'error': 'problem reading content.'}
    elif response.status_code == 403:
        content = {'error': 'No read capability'}
        content = response.content
    else:
        content = response.content

    context['remote_status_code'] = response.status_code
    context['remote_content'] = content
    context['url'] = url
    context['pqtient'] = patient_id
    return render(request, 'bbof.html', context)
Exemplo n.º 10
0
    def get_auth(self, username, password):
        if not os.environ.get('API_KEY') or not os.environ.get('API_SECRET'):
            print('Set your API_KEY &API_SECRET in your environnement')
            sys.exit(2)

        client_id = os.environ.get('API_KEY')
        payload = {
            'grant_type':'password',
            'client_id': client_id,
            'client_secret':os.environ.get('API_SECRET'),
            'username':username,
            'password':password,
        }

        # token_url = "https://api.dailymotion.com/oauth/token"
        token_url = os.environ.get('AUTHORIZATION_URL')
        # r = requests.post(token_url, query_string=payload)
        r = requests.post(token_url, params=payload)
        if r.status_code != 200:
            print('oauth2DM: Invalid status code for token', r.status_code)

        res = r.json()
        if 'error' in res:
            print('oauth2:', res['error_description'])
            sys.exit(2)

        # if 'access_token' not in res or 'uid' not in res:
        if 'access_token' not in res:
            print('oauth2: Invalid token returned')
            sys.exit(2)
        
        from requests_oauthlib import OAuth2 
        # return OAuth2(client_id=res['uid'], token={'access_token':res['access_token'], 'token_type':'Bearer'})
        return OAuth2(client_id=client_id, token={'access_token':res['access_token'], 'token_type':'Bearer'})
Exemplo n.º 11
0
def rdio_oauth2_auth():
    social = get_rdio_social()
    access_token = social.extra_data['access_token']
    return OAuth2(token={
      'access_token': access_token,
      'token_type': 'bearer'
    })
def bbof_get_coverage(request):
    context = {'name': 'Blue Button on FHIR'}
    # first we get the token used to login
    token = request.user.social_auth.get(provider='oauth2io').access_token
    auth = OAuth2(settings.SOCIAL_AUTH_OAUTH2IO_KEY,
                  token={
                      'access_token': token,
                      'token_type': 'Bearer'
                  })

    # now we construct the url
    url = build_url('/Coverage/?_format=json')

    # next we call the remote api
    # patient = % s? request.user.username
    response = requests.get(url, auth=auth)

    if response.status_code in (200, 404):
        if response.json():
            content = json.dumps(response.json(), indent=4)
        else:
            content = {'error': 'problem reading content.'}

    elif response.status_code == 403:
        content = {'error': 'No read capability'}
        content = response.content
    else:
        content = response.json()

    # print(content)

    context['remote_status_code'] = response.status_code
    context['remote_content'] = content
    return render(request, 'bbof.html', context)
def bbof_get_userinfo(request):
    context = {'name': 'Get Userinfo'}
    url = getattr(settings, 'USER_INFO_ENDPOINT',
                  "https://sandbox.bluebutton.cms.gov/v1/connect/userinfo")
    token = request.user.social_auth.get(provider='oauth2io').access_token
    auth = OAuth2(settings.SOCIAL_AUTH_OAUTH2IO_KEY,
                  token={
                      'access_token': token,
                      'token_type': 'Bearer'
                  })
    response = requests.get(url, auth=auth)

    if response.status_code in (200, 404):
        if response.json():
            content = json.dumps(response.json(), indent=4)
        else:
            content = {'error': 'problem reading content.'}
    elif response.status_code == 403:
        content = {'error': 'No read capability'}
        content = response.content
    else:
        content = response.content

    context['remote_status_code'] = response.status_code
    context['remote_content'] = content
    context['url'] = url
    return render(request, 'bbof.html', context)
def djmongo_read(request):
    context = {'name': 'Djmongo OAuth2 Read Test'}
    # first we get the token used to login
    token = request.user.social_auth.get(provider='oauth2io').access_token
    auth = OAuth2(settings.SOCIAL_AUTH_OAUTH2IO_KEY,
                  token={
                      'access_token': token,
                      'token_type': 'Bearer'
                  })
    # next we call the remote api
    url = urljoin(settings.HHS_OAUTH_URL,
                  '/djm/search/api/oauth2/nppes/pjson/pjson2.json')
    response = requests.get(url, auth=auth)
    if response.status_code in (200, 404):
        if response.json():
            content = json.dumps(response.json(), indent=4)
        else:
            content = {'error': 'problem reading content.'}

    elif response.status_code == 403:
        content = {'error': 'No read capability'}
    else:
        content = response.json()

    context['remote_status_code'] = response.status_code
    context['remote_content'] = content
    return render(request, 'bbof.html', context)
Exemplo n.º 15
0
 def _create_oauth2_session(self, oauth_dict):
     # print("in oauth 2 method")
     token_dict = dict()
     token_dict['access_token'] = oauth_dict['access_token']
     token_dict['token_type'] = 'bearer'
     oauth2 = OAuth2(client_id=oauth_dict['client_id'], token=token_dict)
     self._session.auth = oauth2
Exemplo n.º 16
0
 def get_request_kwargs(self, api_params, *args, **kwargs):
     arguments = super(GithubClientAdapter, self).get_request_kwargs(
         api_params, *args, **kwargs)
     client_id = api_params.get('client_id')
     arguments['auth'] = OAuth2(
         client_id, token={'access_token': api_params.get('access_token')})
     return arguments
def bbof_get_coverage(request, patient_id=None):
    context = {'name': 'Blue Button on FHIR'}
    # first we get the token used to login
    token = request.user.social_auth.get(provider='oauth2io').access_token
    auth = OAuth2(settings.SOCIAL_AUTH_OAUTH2IO_KEY,
                  token={
                      'access_token': token,
                      'token_type': 'Bearer'
                  })
    urls = build_fhir_urls(patient_id)
    response = requests.get(urls['coverage'], auth=auth)

    if response.status_code in (200, 404):
        if response.json():
            content = json.dumps(response.json(), indent=4)
        else:
            content = {'error': 'problem reading content.'}

    elif response.status_code == 403:
        content = {'error': 'No read capability'}
        content = response.content
    else:
        content = response.json()
    context['remote_status_code'] = response.status_code
    context['remote_content'] = content
    return render(request, 'bbof.html', context)
Exemplo n.º 18
0
 def __init__(self, client_id, client_secret, access_token, user_id=None):
     auth = OAuth2(client_id, Client(client_id),
                   {'access_token': access_token})
     user = user_id if user_id else 'me'
     s = Serializer(default="json", serializers=[MisfitSerializer()])
     self.api = slumber.API('%smove/resource/v1/user/%s/' % (API_URL, user),
                            auth=auth,
                            serializer=s)
Exemplo n.º 19
0
 def test_add_token_to_body(self):
     body = "foo=bar"
     new_body = body + "&access_token=" + self.token["access_token"]
     for client in self.clients:
         client.default_token_placement = "body"
         auth = OAuth2(client=client, token=self.token)
         r = Request("GET", "https://i.b", data=body, auth=auth).prepare()
         self.assertEqual(r.body, new_body)
Exemplo n.º 20
0
 def test_add_token_to_url(self):
     url = 'https://example.com/resource?foo=bar'
     new_url = url + '&access_token=' + self.token['access_token']
     for client in self.clients:
         client.default_token_placement = 'query'
         auth = OAuth2(client=client, token=self.token)
         r = Request('GET', url, auth=auth).prepare()
         self.assertEqual(r.url, new_url)
Exemplo n.º 21
0
 def test_add_token_to_body(self):
     body = 'foo=bar'
     new_body = body + '&access_token=' + self.token['access_token']
     for client in self.clients:
         client.default_token_placement = 'body'
         auth = OAuth2(client=client, token=self.token)
         r = Request('GET', 'https://i.b', data=body, auth=auth).prepare()
         self.assertEqual(r.body, new_body)
Exemplo n.º 22
0
 def test_add_token_to_url(self):
     url = "https://example.com/resource?foo=bar"
     new_url = url + "&access_token=" + self.token["access_token"]
     for client in self.clients:
         client.default_token_placement = "query"
         auth = OAuth2(client=client, token=self.token)
         r = Request("GET", url, auth=auth).prepare()
         self.assertEqual(r.url, new_url)
Exemplo n.º 23
0
def query_GitHub(url,
                 username=None,
                 password=None,
                 token=None,
                 data=None,
                 OTP=None,
                 headers=None,
                 params=None,
                 files=None):
    """
    Query GitHub API.

    In case of a multipage result, DOES NOT query the next page.

    """
    headers = headers or {}

    if OTP:
        headers['X-GitHub-OTP'] = OTP

    if token:
        auth = OAuth2(client_id=username,
                      token=dict(access_token=token, token_type='bearer'))
    else:
        auth = HTTPBasicAuth(username, password)
    if data:
        r = requests.post(url,
                          auth=auth,
                          data=data,
                          headers=headers,
                          params=params,
                          files=files)
    else:
        r = requests.get(url,
                         auth=auth,
                         headers=headers,
                         params=params,
                         stream=True)

    if r.status_code == 401:
        two_factor = r.headers.get('X-GitHub-OTP')
        if two_factor:
            print("A two-factor authentication code is required:",
                  two_factor.split(';')[1].strip())
            OTP = raw_input("Authentication code: ")
            return query_GitHub(url,
                                username=username,
                                password=password,
                                token=token,
                                data=data,
                                OTP=OTP)

        raise AuthenticationFailed("invalid username or password")

    r.raise_for_status()
    return r
Exemplo n.º 24
0
 def get_request_kwargs(self, api_params):
     client_id = api_params.get('client_id')
     return {
         'auth':
         OAuth2(client_id,
                token={
                    'access_token': api_params.get('access_token'),
                    'token_type': 'Bearer'
                })
     }
Exemplo n.º 25
0
    def get_athlete(self):
        response = requests.get("https://www.strava.com/api/v3/athlete",
                                auth=OAuth2(client_id=self.client_id,
                                            token={
                                                "access_token":
                                                self.access_token.token,
                                                "token_type": "Bearer"
                                            }))

        print(response)
Exemplo n.º 26
0
def github_auth_user_behavior():
    url = github_apis.auth_user()
    auth = OAuth2(client_id=client_id, token=session['oauth_user_token'])
    res = requests.get(url, auth=auth)
    if res.status_code != 200:
        msg = 'GitHub authorization failed'
        url = url_for('accounts.register')
        flash(msg, 'danger')
        return False

    return True
 def get_request_kwargs(self, api_params, *args, **kwargs):
     params = super(BookingSyncClientAdapter, self).get_request_kwargs(
         api_params, *args, **kwargs
     )
     params['auth'] = OAuth2(
         api_params.get('client_id', ''),
         token={
             'access_token': api_params.get('access_token'),
             'token_type': 'Bearer'
         }
     )
     return params
Exemplo n.º 28
0
 def _create_oauth2_session(self, oauth_dict):
     """
     Use OAuth 2.0 Authentication
     :param oauth_dict: Dictionary containing access information. Must at
         least contain "client_id" and "token". "token" is a dictionary and
         must at least contain "access_token" and "token_type".
     :return:
     """
     if "client" not in oauth_dict:
         oauth_dict["client"] = None
     oauth = OAuth2(oauth_dict["client_id"], oauth_dict["client"], oauth_dict["token"])
     self._session.auth = oauth
Exemplo n.º 29
0
 def GetRequestAuthObject(self, authRequired):
     """Get HTTP header value with authorization string.
     param authRequired - if False force basic auth
     return string Authorization string
     """
     if authRequired == False: # or self._root.Config.AuthenticationType == enums.AuthenticationType.Basic:
         return HTTPBasicAuth(self._root.Config.ClientID, self._root.Config.ClientPassword)
     else:
         oauth = self._root.OAuthTokenManager.GetToken()
         if not oauth or not oauth.access_token or not oauth.token_type:
             raise Exception('OAuthToken is not created (or is invalid) for strong authentication')
         token = {'access_token' : oauth.access_token, 'token_type' : oauth.token_type}
         return OAuth2(token = token, client_id = self._root.Config.ClientID)
Exemplo n.º 30
0
    def _build_auth_object(self):
        client = BackendApplicationClient(client_id=self.client_id)
        oauth_session = OAuth2Session(client=client)
        token = oauth_session.fetch_token(
            token_url=f"{self.host}/oauth/token",
            client_id=self.client_id,
            client_secret=self.client_secret,
        )

        return (
            oauth_session,
            OAuth2(client_id=self.client_id, client=client, token=token),
        )