Example #1
0
 def urlopen(self, url, **kwargs):
   """Wraps urllib2.urlopen() and adds OAuth credentials to the request.
   """
   headers = {'Authorization': 'Bearer %s' % self.access_token_str}
   try:
     return util.urlopen(urllib2.Request(url, headers=headers), **kwargs)
   except BaseException, e:
     util.interpret_http_exception(e)
     raise
Example #2
0
 def urlopen(self, url, **kwargs):
     """Wraps urllib2.urlopen() and adds OAuth credentials to the request.
 """
     kwargs.setdefault('headers', {})['authorization'] = \
         'Bearer ' + self.access_token_str
     try:
         return util.urlopen(urllib2.Request(url, **kwargs))
     except BaseException, e:
         util.interpret_http_exception(e)
         raise
Example #3
0
  def urlopen_access_token(url, access_token, api_key=None, **kwargs):
    """Wraps urllib2.urlopen() and adds an access_token query parameter.

    Kwargs are passed through to urlopen().
    """
    params = [('access_token', access_token)]
    if api_key:
      params.append(('api_key', api_key))
    url = util.add_query_params(url, params)

    try:
      return util.urlopen(url, **kwargs)
    except BaseException, e:
      util.interpret_http_exception(e)
      raise
Example #4
0
  def get(self):
    if CallbackHandler.handle_error(self):
      return

    auth_code = util.get_required_param(self, 'code')
    url = GET_ACCESS_TOKEN_URL % {
      'auth_code': auth_code,
      'client_id': appengine_config.FACEBOOK_APP_ID,
      'client_secret': appengine_config.FACEBOOK_APP_SECRET,
      'redirect_uri': urllib.quote_plus(self.request.path_url),
      }
    try:
      resp = json.loads(util.urlopen(url).read())
    except urllib2.HTTPError, e:
      logging.error(e.read())
      raise
Example #5
0
    def get(self):
        # handle errors
        error = self.request.get('error')
        if error:
            error_description = urllib.unquote_plus(
                self.request.get('error_description', ''))
            if error == 'access_denied':
                logging.info('User declined: %s', error_description)
                self.finish(None, state=self.request.get('state'))
                return
            else:
                raise exc.HTTPBadRequest('Error: %s %s ' %
                                         (error, error_description))

        # extract auth code and request access token
        auth_code = util.get_required_param(self, 'code')
        data = {
            'code': auth_code,
            'client_id': appengine_config.WORDPRESS_CLIENT_ID,
            'client_secret': appengine_config.WORDPRESS_CLIENT_SECRET,
            # redirect_uri here must be the same in the oauth code request!
            # (the value here doesn't actually matter since it's requested server side.)
            'redirect_uri': self.request.path_url,
            'grant_type': 'authorization_code',
        }
        resp = util.urlopen(GET_ACCESS_TOKEN_URL,
                            data=urllib.urlencode(data)).read()
        logging.debug('Access token response: %s', resp)

        try:
            resp = json.loads(resp)
            blog_id = resp['blog_id']
            blog_url = resp['blog_url']
            blog_domain = util.domain_from_link(resp['blog_url'])
            access_token = resp['access_token']
        except:
            logging.exception('Could not decode JSON')
            raise

        auth = WordPressAuth(id=blog_domain,
                             blog_id=blog_id,
                             blog_url=blog_url,
                             access_token_str=access_token)
        auth.user_json = auth.urlopen(API_USER_URL).read()
        auth.put()

        self.finish(auth, state=self.request.get('state'))
Example #6
0
  def get(self):
    oauth_token = self.request.get('oauth_token')
    oauth_verifier = self.request.get('oauth_verifier')
    request_token = models.OAuthRequestToken.get_by_id(oauth_token)

    client = oauthlib.oauth1.Client(
      appengine_config.FLICKR_APP_KEY,
      client_secret=appengine_config.FLICKR_APP_SECRET,
      resource_owner_key=oauth_token,
      resource_owner_secret=request_token.token_secret,
      verifier=oauth_verifier)

    uri, headers, body = client.sign(ACCESS_TOKEN_URL)
    try:
      resp = util.urlopen(urllib2.Request(uri, body, headers))
    except BaseException, e:
      util.interpret_http_exception(e)
      raise
Example #7
0
    def get(self):
        oauth_token = self.request.get('oauth_token')
        oauth_verifier = self.request.get('oauth_verifier')
        request_token = models.OAuthRequestToken.get_by_id(oauth_token)

        client = oauthlib.oauth1.Client(
            appengine_config.FLICKR_APP_KEY,
            client_secret=appengine_config.FLICKR_APP_SECRET,
            resource_owner_key=oauth_token,
            resource_owner_secret=request_token.token_secret,
            verifier=oauth_verifier)

        uri, headers, body = client.sign(ACCESS_TOKEN_URL)
        try:
            resp = util.urlopen(urllib2.Request(uri, body, headers))
        except BaseException, e:
            util.interpret_http_exception(e)
            raise
Example #8
0
    def get(self):
        if self.handle_error():
            return

        # https://disqus.com/api/docs/auth/
        auth_code = util.get_required_param(self, 'code')
        data = {
            'grant_type': 'authorization_code',
            'client_id': appengine_config.DISQUS_CLIENT_ID,
            'client_secret': appengine_config.DISQUS_CLIENT_SECRET,
            'redirect_uri': self.request_url_with_state(),
            'code': auth_code,
        }

        resp = util.urlopen(GET_ACCESS_TOKEN_URL,
                            data=urllib.urlencode(data)).read()
        try:
            data = json.loads(resp)
        except (ValueError, TypeError):
            logging.exception('Bad response:\n%s', resp)
            raise exc.HttpBadRequest(
                'Bad Disqus response to access token request')

        access_token = data['access_token']
        user_id = data['user_id']
        # TODO is a username key preferred?
        # username = data['username']

        auth = DisqusAuth(id=str(user_id),
                          auth_code=auth_code,
                          access_token_str=access_token)

        resp = auth.urlopen(USER_DETAILS_URL % user_id).read()
        try:
            user_data = json.loads(resp)['response']
        except (ValueError, TypeError):
            logging.exception('Bad response:\n%s', resp)
            raise exc.HttpBadRequest(
                'Bad Disqus response to user details request')

        auth.user_json = json.dumps(user_data)
        logging.info('created disqus auth %s', auth)
        auth.put()
        self.finish(auth, state=self.request.get('state'))
Example #9
0
  def get(self):
    if facebook.CallbackHandler.handle_error(self):
      return

    # http://instagram.com/developer/authentication/
    auth_code = util.get_required_param(self, 'code')
    data = {
      'client_id': appengine_config.INSTAGRAM_CLIENT_ID,
      'client_secret': appengine_config.INSTAGRAM_CLIENT_SECRET,
      'code': auth_code,
      'redirect_uri': self.request_url_with_state(),
      'grant_type': 'authorization_code',
    }

    try:
      resp = util.urlopen(GET_ACCESS_TOKEN_URL, data=urllib.urlencode(data)).read()
    except BaseException, e:
      util.interpret_http_exception(e)
      raise
Example #10
0
  def redirect_url(self, state=None):
    assert (appengine_config.FLICKR_APP_KEY and
            appengine_config.FLICKR_APP_SECRET), (
      "Please fill in the flickr_app_key and flickr_app_secret files in "
      "your app's root directory.")

    client = oauthlib.oauth1.Client(
      appengine_config.FLICKR_APP_KEY,
      client_secret=appengine_config.FLICKR_APP_SECRET,
      # double-URL-encode state because Flickr URL-decodes the redirect URL
      # before redirecting to it, and JSON values may have ?s and &s. e.g. the
      # Bridgy WordPress plugin's redirect URL when using Bridgy's registration
      # API (https://brid.gy/about#registration-api) looks like:
      # /wp-admin/admin.php?page=bridgy_options&service=flickr
      callback_uri=native_str(self.to_url(state=urllib.quote(state))))

    uri, headers, body = client.sign(REQUEST_TOKEN_URL)
    resp = util.urlopen(urllib2.Request(uri, body, headers))
    parsed = dict(urlparse.parse_qs(resp.read()))

    resource_owner_key = parsed.get('oauth_token')[0]
    resource_owner_secret = parsed.get('oauth_token_secret')[0]

    models.OAuthRequestToken(
      id=resource_owner_key,
      token_secret=resource_owner_secret,
      state=state).put()

    if self.scope:
      auth_url = AUTHORIZE_URL + '?' + urllib.urlencode({
        'perms': self.scope or 'read',
        'oauth_token': resource_owner_key
      })
    else:
      auth_url = AUTHENTICATE_URL + '?' + urllib.urlencode({
        'oauth_token': resource_owner_key
      })

    logging.info(
      'Generated request token, redirect to Flickr authorization url: %s',
      auth_url)
    return auth_url
Example #11
0
    def redirect_url(self, state=None):
        assert (
            appengine_config.FLICKR_APP_KEY
            and appengine_config.FLICKR_APP_SECRET
        ), ("Please fill in the flickr_app_key and flickr_app_secret files in "
            "your app's root directory.")

        client = oauthlib.oauth1.Client(
            appengine_config.FLICKR_APP_KEY,
            client_secret=appengine_config.FLICKR_APP_SECRET,
            # double-URL-encode state because Flickr URL-decodes the redirect URL
            # before redirecting to it, and JSON values may have ?s and &s. e.g. the
            # Bridgy WordPress plugin's redirect URL when using Bridgy's registration
            # API (https://brid.gy/about#registration-api) looks like:
            # /wp-admin/admin.php?page=bridgy_options&service=flickr
            callback_uri=native_str(self.to_url(state=urllib.quote(state))))

        uri, headers, body = client.sign(REQUEST_TOKEN_URL)
        resp = util.urlopen(urllib2.Request(uri, body, headers))
        parsed = dict(urlparse.parse_qs(resp.read()))

        resource_owner_key = parsed.get('oauth_token')[0]
        resource_owner_secret = parsed.get('oauth_token_secret')[0]

        models.OAuthRequestToken(id=resource_owner_key,
                                 token_secret=resource_owner_secret,
                                 state=state).put()

        if self.scope:
            auth_url = AUTHORIZE_URL + '?' + urllib.urlencode(
                {
                    'perms': self.scope or 'read',
                    'oauth_token': resource_owner_key
                })
        else:
            auth_url = AUTHENTICATE_URL + '?' + urllib.urlencode(
                {'oauth_token': resource_owner_key})

        logging.info(
            'Generated request token, redirect to Flickr authorization url: %s',
            auth_url)
        return auth_url
Example #12
0
    def get(self):
        if facebook.CallbackHandler.handle_error(self):
            return

        # http://instagram.com/developer/authentication/
        auth_code = util.get_required_param(self, 'code')
        data = {
            'client_id': appengine_config.INSTAGRAM_CLIENT_ID,
            'client_secret': appengine_config.INSTAGRAM_CLIENT_SECRET,
            'code': auth_code,
            'redirect_uri': self.request_url_with_state(),
            'grant_type': 'authorization_code',
        }

        try:
            resp = util.urlopen(GET_ACCESS_TOKEN_URL,
                                data=urllib.urlencode(data)).read()
        except BaseException, e:
            util.interpret_http_exception(e)
            raise
Example #13
0
  def get(self):
    if self.handle_error():
      return

    # https://disqus.com/api/docs/auth/
    auth_code = util.get_required_param(self, 'code')
    data = {
        'grant_type': 'authorization_code',
        'client_id': appengine_config.DISQUS_CLIENT_ID,
        'client_secret': appengine_config.DISQUS_CLIENT_SECRET,
        'redirect_uri': self.request_url_with_state(),
        'code': auth_code,
    }

    resp = util.urlopen(GET_ACCESS_TOKEN_URL, data=urllib.urlencode(data)).read()
    try:
      data = json.loads(resp)
    except (ValueError, TypeError):
      logging.exception('Bad response:\n%s', resp)
      raise exc.HttpBadRequest('Bad Disqus response to access token request')

    access_token = data['access_token']
    user_id = data['user_id']
    # TODO is a username key preferred?
    # username = data['username']

    auth = DisqusAuth(id=str(user_id),
                      auth_code=auth_code,
                      access_token_str=access_token)

    resp = auth.urlopen(USER_DETAILS_URL % user_id).read()
    try:
      user_data = json.loads(resp)['response']
    except (ValueError, TypeError):
      logging.exception('Bad response:\n%s', resp)
      raise exc.HttpBadRequest('Bad Disqus response to user details request')

    auth.user_json = json.dumps(user_data)
    logging.info('created disqus auth %s', auth)
    auth.put()
    self.finish(auth, state=self.request.get('state'))
Example #14
0
  def get(self):
    state = util.get_required_param(self, 'state')

    # handle errors
    error = self.request.get('error')
    error_reason = urllib.unquote_plus(self.request.get('error_reason', ''))

    if error or error_reason:
      if error == 'access_denied':
        logging.info('User declined: %s', error_reason)
        self.finish(None, state=state)
        return
      else:
        raise exc.HTTPBadRequest(' '.join((error, error_reason)))

    # lookup the CSRF token
    try:
      csrf_id = int(urllib.unquote_plus(state).split('|')[-1])
    except (ValueError, TypeError):
      raise exc.HTTPBadRequest('Invalid state value %r' % state)

    csrf = DropboxCsrf.get_by_id(csrf_id)
    if not csrf:
      raise exc.HTTPBadRequest('No CSRF token for id %s' % csrf_id)

    # request an access token
    data = {
      'client_id': appengine_config.DROPBOX_APP_KEY,
      'client_secret': appengine_config.DROPBOX_APP_SECRET,
      'code': util.get_required_param(self, 'code'),
      'redirect_uri': self.request.path_url,
    }
    try:
      resp = util.urlopen(GET_ACCESS_TOKEN_URL % data, data='').read()
    except BaseException, e:
      util.interpret_http_exception(e)
      raise