Пример #1
0
def stored_oauth():
    consumer = oauth.Consumer(jiraappy.CONSUMER_KEY, jiraappy.CONSUMER_SECRET)
    accessToken = oauth.Token(jiraappy.JIRA_OAUTH_TOKEN, jiraappy.JIRA_OAUTH_SECRET)
    client = oauth.Client(consumer, accessToken)
    client.set_signature_method(SignatureMethod_RSA_SHA1())

    return consumer, client
Пример #2
0
def verified_oauth(oauth_token, oauth_token_secret):
    consumer = oauth.Consumer(jiraappy.CONSUMER_KEY, jiraappy.CONSUMER_SECRET)
    accessToken = oauth.Token(oauth_token, oauth_token_secret)
    client = oauth.Client(consumer, accessToken)
    client.set_signature_method(SignatureMethod_RSA_SHA1())

    return consumer, client
Пример #3
0
 def _get_credentials(self, key):
     request_token = {}
 
     request_token['oauth_token'] = sickbeard.TWITTER_USERNAME
     request_token['oauth_token_secret'] = sickbeard.TWITTER_PASSWORD
     request_token['oauth_callback_confirmed'] = 'true'
 
     token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
     token.set_verifier(key)
 
     logger.log('Generating and signing request for an access token using key '+key)
 
     signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable
     oauth_consumer             = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret)
     logger.log('oauth_consumer: '+str(oauth_consumer))
     oauth_client  = oauth.Client(oauth_consumer, token)
     logger.log('oauth_client: '+str(oauth_client))
     resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key)
     logger.log('resp, content: '+str(resp)+','+str(content))
 
     access_token  = dict(parse_qsl(content))
     logger.log('access_token: '+str(access_token))
 
     logger.log('resp[status] = '+str(resp['status']))
     if resp['status'] != '200':
         logger.log('The request for a token with did not succeed: '+str(resp['status']), logger.ERROR)
         return False
     else:
         logger.log('Your Twitter Access Token key: %s' % access_token['oauth_token'])
         logger.log('Access Token secret: %s' % access_token['oauth_token_secret'])
         sickbeard.TWITTER_USERNAME = access_token['oauth_token']
         sickbeard.TWITTER_PASSWORD = access_token['oauth_token_secret']
         return True
Пример #4
0
def redirect_oauth():

    consumer = oauth.Consumer(jiraappy.CONSUMER_KEY, jiraappy.CONSUMER_SECRET)
    client = oauth.Client(consumer)
    client.set_signature_method(SignatureMethod_RSA_SHA1())

    request_token_url = os.path.join(jiraappy.JIRA_BASE_URL, 'plugins/servlet/oauth/request-token')
    authorize_url = os.path.join(jiraappy.JIRA_BASE_URL, 'plugins/servlet/oauth/authorize')

    try:
        resp, content = client.request(request_token_url, "POST")
        if resp['status'] != '200':
            authorize_token_url = None
            status, status_msg = ajaxMSG('failure', 'Invalid Consumer Key, RSA Keys, or JIRA App Link - please check configuration')
        else:
            request_token = dict(urlparse.parse_qsl(content))
            request_token_info = {
                "oauth_token": request_token['oauth_token'],
                "oauth_token_secret": request_token['oauth_token_secret'],
                "authorize_token_url": "%s?oauth_token=%s" % (authorize_url, request_token['oauth_token'])
            }
            authorize_token_url = request_token_info['authorize_token_url']
            status, status_msg = ajaxMSG('success', 'JIRA Credentials recognized! Redirecting to JIRA login')
    except:
        authorize_token_url = "index"
        status, status_msg = ajaxMSG('failure', 'Invalid Consumer Key, RSA Keys, or JIRA App Link - please check configuration')

    return authorize_token_url, status, status_msg
Пример #5
0
def request_oauth(oauth_token):
    consumer = oauth.Consumer(jiraappy.CONSUMER_KEY, jiraappy.CONSUMER_SECRET)
    token = oauth.Token(oauth_token, oauth_token)
    client = oauth.Client(consumer, token)
    client.set_signature_method(SignatureMethod_RSA_SHA1())

    return consumer, client
Пример #6
0
    def create_shelf(self, shelf='lazylibrarian'):
        global consumer, client, token, user_id
        if not lazylibrarian.CONFIG['GR_API'] or not lazylibrarian.CONFIG['GR_SECRET'] or not \
                lazylibrarian.CONFIG['GR_OAUTH_TOKEN'] or not lazylibrarian.CONFIG['GR_OAUTH_SECRET']:
            logger.warn("Goodreads create shelf error: Please authorise first")
            return False, 'Unauthorised'

        consumer = oauth.Consumer(key=str(lazylibrarian.CONFIG['GR_API']),
                                  secret=str(
                                      lazylibrarian.CONFIG['GR_SECRET']))
        token = oauth.Token(lazylibrarian.CONFIG['GR_OAUTH_TOKEN'],
                            lazylibrarian.CONFIG['GR_OAUTH_SECRET'])
        client = oauth.Client(consumer, token)
        user_id = self.getUserId()

        # could also pass [featured] [exclusive_flag] [sortable_flag] all default to False
        body = urlencode({'user_shelf[name]': shelf.lower()})
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        gr_api_sleep()

        try:
            response, content = client.request(
                '%s/user_shelves.xml' % 'https://www.goodreads.com', 'POST',
                body, headers)
        except Exception as e:
            logger.error("Exception in client.request: %s %s" %
                         (type(e).__name__, traceback.format_exc()))
            return False, "Error in client.request: see error log"

        if not response['status'].startswith('2'):
            msg = 'Failure status: %s' % response['status']
            return False, msg
        return True, ''
Пример #7
0
    def get_credentials(self, key):
        request_token = dict(oauth_token=sickbeard.TWITTER_USERNAME, oauth_token_secret=sickbeard.TWITTER_PASSWORD,
                             oauth_callback_confirmed='true')

        token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
        token.set_verifier(key)

        self._log_debug('Generating and signing request for an access token using key ' + key)

        # noinspection PyUnusedLocal
        signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()
        oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret)
        self._log_debug('oauth_consumer: ' + str(oauth_consumer))
        oauth_client = oauth.Client(oauth_consumer, token)
        self._log_debug('oauth_client: ' + str(oauth_client))
        resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key)
        self._log_debug('resp, content: ' + str(resp) + ',' + str(content))

        access_token = dict(parse_qsl(content))
        self._log_debug('access_token: ' + str(access_token))

        self._log_debug('resp[status] = ' + str(resp['status']))
        if '200' != resp['status']:
            self._log_error('The request for a token with did not succeed: ' + str(resp['status']))
            result = False
        else:
            self._log_debug('Your Twitter Access Token key: %s' % access_token['oauth_token'])
            self._log_debug('Access Token secret: %s' % access_token['oauth_token_secret'])
            sickbeard.TWITTER_USERNAME = access_token['oauth_token']
            sickbeard.TWITTER_PASSWORD = access_token['oauth_token_secret']
            result = True

        message = ('Key verification successful', 'Unable to verify key')[not result]
        logger.log(u'%s result: %s' % (self.name, message))
        return self._choose(message, result)
Пример #8
0
    def goodreads_oauth1():
        global client, request_token, consumer
        if lazylibrarian.CONFIG['GR_API'] == 'ckvsiSDsuqh7omh74ZZ6Q':
            msg = "Please get your own personal GoodReads api key from https://www.goodreads.com/api/keys and try again"
            return msg
        if not lazylibrarian.CONFIG['GR_SECRET']:
            return "Invalid or missing GR_SECRET"

        if lazylibrarian.CONFIG['GR_OAUTH_TOKEN'] and lazylibrarian.CONFIG['GR_OAUTH_SECRET']:
            return "Already authorised"

        request_token_url = '%s/oauth/request_token' % 'https://www.goodreads.com'
        authorize_url = '%s/oauth/authorize' % 'https://www.goodreads.com'
        # access_token_url = '%s/oauth/access_token' % 'https://www.goodreads.com'

        consumer = oauth.Consumer(key=str(lazylibrarian.CONFIG['GR_API']),
                                  secret=str(lazylibrarian.CONFIG['GR_SECRET']))

        client = oauth.Client(consumer)

        try:
            response, content = client.request(request_token_url, 'GET')
        except Exception as e:
            return "Exception in client.request: %s %s" % (type(e).__name__, str(e))

        if response['status'] != '200':
            return 'Invalid response from: %s' % request_token_url

        request_token = dict(urlparse.parse_qsl(content))

        authorize_link = '%s?oauth_token=%s' % (authorize_url, request_token['oauth_token'])
        # print authorize_link
        return authorize_link
Пример #9
0
    def _get_authorization(self):
        _ = oauth.SignatureMethod_HMAC_SHA1()
        oauth_consumer = oauth.Consumer(key=self.consumer_key,
                                        secret=self.consumer_secret)
        oauth_client = oauth.Client(oauth_consumer)

        logger.debug('Requesting temp token from Twitter')

        resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET')

        if resp['status'] != '200':
            logger.error(
                'Invalid respond from Twitter requesting temp token: %s' %
                resp['status'])
        else:
            # noinspection PyDeprecation
            request_token = dict(parse_qsl(content))
            lazylibrarian.CONFIG['TWITTER_USERNAME'] = request_token[
                'oauth_token']
            lazylibrarian.CONFIG['TWITTER_PASSWORD'] = request_token[
                'oauth_token_secret']
            logger.debug('Twitter oauth_token = %s oauth_secret = %s' %
                         (lazylibrarian.CONFIG['TWITTER_USERNAME'],
                          lazylibrarian.CONFIG['TWITTER_PASSWORD']))
            return self.AUTHORIZATION_URL + "?oauth_token=" + request_token[
                'oauth_token']
Пример #10
0
    def generateAuthorizationURL(self,
                                 consumer_key,
                                 consumer_secret,
                                 domain,
                                 callback_url=None):
        """ Fetch the OAuthToken and generate the authorization URL.
    Returns:
      the Authorization URL
    """

        consumer = oauth2.Consumer(consumer_key, consumer_secret)
        client = oauth2.Client(consumer)

        resp, content = client.request(
            "%s?scope=%s" %
            (OAUTH_SETTINGS['request_token_url'], OAUTH_SETTINGS['scope']),
            "GET")
        if resp['status'] != '200':
            raise Exception("Invalid response %s." % resp['status'])

        urlparts = content.split("&")
        oauth_token = urllib.unquote_plus(urlparts[0].split("=")[1])
        oauth_token_secret = urllib.unquote_plus(urlparts[1].split("=")[1])

        if callback_url:
            auth_url = "%s?oauth_token=%s&scope=%s&domain=%s&oauth_callback=%s" % (
                OAUTH_SETTINGS['authorize_url'], oauth_token,
                OAUTH_SETTINGS['scope'], domain, callback_url)
        else:
            auth_url = "%s?oauth_token=%s&scope=%s&domain=%s" % (
                OAUTH_SETTINGS['authorize_url'], oauth_token,
                OAUTH_SETTINGS['scope'], domain)

        return auth_url, oauth_token, oauth_token_secret
Пример #11
0
    def goodreads_oauth1(self):
        if self.key == 'ckvsiSDsuqh7omh74ZZ6Q':
            return "Please get your own personal GoodReads api key"
        if not self.secret:
            return "Invalid or missing GR_SECRET"

        #if self.oauth_token and self.oauth_secret:
        #    return "Already authorised"

        request_token_url = '%s/oauth/request_token' % self.url
        authorize_url = '%s/oauth/authorize' % self.url
        # access_token_url = '%s/oauth/access_token' % self.url

        consumer = oauth.Consumer(key=str(self.key), secret=str(self.secret))

        client = oauth.Client(consumer)

        try:
            response, content = client.request(request_token_url, 'GET')
        except Exception as e:
            return "Exception in client.request: %s" % str(e)

        if response['status'] != '200':
            return 'Invalid response from: %s' % request_token_url

        self.request_token = dict(urlparse.parse_qsl(content))

        authorize_link = '%s?oauth_token=%s' % (authorize_url, self.request_token['oauth_token'])
        return authorize_link
Пример #12
0
    def get_shelf_list(self):
        global consumer, client, token, user_id
        if not lazylibrarian.CONFIG['GR_API'] or not lazylibrarian.CONFIG['GR_SECRET'] or not \
                lazylibrarian.CONFIG['GR_OAUTH_TOKEN'] or not lazylibrarian.CONFIG['GR_OAUTH_SECRET']:
            logger.warn("Goodreads get shelf error: Please authorise first")
            return []
        else:
            #
            # loop over each page of shelves
            #     loop over each shelf
            #         add shelf to list
            #
            consumer = oauth.Consumer(key=str(lazylibrarian.CONFIG['GR_API']),
                                      secret=str(lazylibrarian.CONFIG['GR_SECRET']))
            token = oauth.Token(lazylibrarian.CONFIG['GR_OAUTH_TOKEN'], lazylibrarian.CONFIG['GR_OAUTH_SECRET'])
            client = oauth.Client(consumer, token)
            user_id = self.getUserId()

            current_page = 0
            shelves = []
            page_shelves = 1
            while page_shelves:
                current_page = current_page + 1
                page_shelves = 0
                shelf_template = Template('${base}/shelf/list.xml?user_id=${user_id}&key=${key}&page=${page}')
                body = urlencode({})
                headers = {'Content-Type': 'application/x-www-form-urlencoded'}
                request_url = shelf_template.substitute(base='https://www.goodreads.com', user_id=user_id,
                                                        page=current_page, key=lazylibrarian.CONFIG['GR_API'])
                gr_api_sleep()
                try:
                    response, content = client.request(request_url, 'GET', body, headers)
                except Exception as e:
                    logger.error("Exception in client.request: %s %s" % (type(e).__name__, traceback.format_exc()))
                    return shelves

                if not response['status'].startswith('2'):
                    logger.error('Failure status: %s for page %s' % (response['status'], current_page))
                    if lazylibrarian.LOGLEVEL & lazylibrarian.log_grsync:
                        logger.debug(request_url)
                else:
                    xmldoc = xml.dom.minidom.parseString(content)

                    shelf_list = xmldoc.getElementsByTagName('shelves')[0]
                    for item in shelf_list.getElementsByTagName('user_shelf'):
                        shelf_name = item.getElementsByTagName('name')[0].firstChild.nodeValue
                        shelf_count = item.getElementsByTagName('book_count')[0].firstChild.nodeValue
                        shelf_exclusive = item.getElementsByTagName('exclusive_flag')[0].firstChild.nodeValue
                        shelves.append({'name': shelf_name, 'books': shelf_count, 'exclusive': shelf_exclusive})
                        page_shelves += 1

                        if lazylibrarian.LOGLEVEL & lazylibrarian.log_grsync:
                            logger.debug('Shelf %s : %s: Exclusive %s' % (shelf_name, shelf_count, shelf_exclusive))

                    if lazylibrarian.LOGLEVEL & lazylibrarian.log_grsync:
                        logger.debug('Found %s shelves on page %s' % (page_shelves, current_page))

            logger.debug('Found %s shelves on %s page%s' % (len(shelves), current_page - 1, plural(current_page - 1)))
            # print shelves
            return shelves
Пример #13
0
    def create_shelf(self, shelf='lazylibrarian'):
        global consumer, client, token, user_id
        if not lazylibrarian.CONFIG['GR_API'] or not lazylibrarian.CONFIG['GR_SECRET'] or not \
                lazylibrarian.CONFIG['GR_OAUTH_TOKEN'] or not lazylibrarian.CONFIG['GR_OAUTH_SECRET']:
            logger.warn("Goodreads create shelf error: Please authorise first")
            return False, 'Unauthorised'

        consumer = oauth.Consumer(key=str(lazylibrarian.CONFIG['GR_API']),
                                  secret=str(
                                      lazylibrarian.CONFIG['GR_SECRET']))
        token = oauth.Token(lazylibrarian.CONFIG['GR_OAUTH_TOKEN'],
                            lazylibrarian.CONFIG['GR_OAUTH_SECRET'])
        client = oauth.Client(consumer, token)
        user_id = self.getUserId()

        # could also pass [featured] [exclusive_flag] [sortable_flag] all default to False
        body = urlencode({'user_shelf[name]': shelf.lower()})
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        time_now = int(time.time())
        if time_now <= lazylibrarian.LAST_GOODREADS:
            time.sleep(1)
            lazylibrarian.LAST_GOODREADS = time_now
        try:
            response, content = client.request(
                '%s/user_shelves.xml' % 'https://www.goodreads.com', 'POST',
                body, headers)
        except Exception as e:
            return False, "Exception in client.request: %s %s" % (
                type(e).__name__, str(e))

        if response['status'] != '200' and response['status'] != '201':
            msg = 'Failure status: %s' % response['status']
            return False, msg
        return True, ''
Пример #14
0
    def _get_authorization(self):

        signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1(
        )  # @UnusedVariable
        oauth_consumer = oauth.Consumer(key=self.consumer_key,
                                        secret=self.consumer_secret)
        oauth_client = oauth.Client(oauth_consumer)

        logger.info('Requesting temp token from Twitter')

        resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET')

        if resp['status'] != '200':
            logger.info(
                'Invalid respond from Twitter requesting temp token: %s' %
                resp['status'])
        else:
            request_token = dict(parse_qsl(content))

            lazylibrarian.TWITTER_USERNAME = request_token['oauth_token']
            lazylibrarian.TWITTER_PASSWORD = request_token[
                'oauth_token_secret']

            return self.AUTHORIZATION_URL + "?oauth_token=" + request_token[
                'oauth_token']
Пример #15
0
 def _post(self, query):
     consumer = oauth2.Consumer(self.consumer_key, self.consumer_secret)
     client = oauth2.Client(consumer, self.token)
     resp, content = client.request(uri=self.scope,
                                    method="POST",
                                    body=query)
     return content
Пример #16
0
    def _get_credentials(self, key):
        request_token = {'oauth_token': lazylibrarian.CONFIG['TWITTER_USERNAME'],
                         'oauth_token_secret': lazylibrarian.CONFIG['TWITTER_PASSWORD'],
                         'oauth_callback_confirmed': 'true'}

        token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
        token.set_verifier(key)

        logger.info('Generating and signing request for an access token using key ' + key)

        _ = oauth.SignatureMethod_HMAC_SHA1()
        oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret)
        logger.info('oauth_consumer: ' + str(oauth_consumer))
        oauth_client = oauth.Client(oauth_consumer, token)
        logger.info('oauth_client: ' + str(oauth_client))
        resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key)
        logger.info('resp, content: ' + str(resp) + ',' + str(content))

        access_token = dict(parse_qsl(content))
        logger.info('access_token: ' + str(access_token))

        logger.info('resp[status] = ' + str(resp['status']))
        if resp['status'] != '200':
            logger.error('The request for a token with did not succeed: ' + str(resp['status']))
            return False
        else:
            logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token'])
            logger.info('Access Token secret: %s' % access_token['oauth_token_secret'])
            lazylibrarian.CONFIG['TWITTER_USERNAME'] = access_token['oauth_token']
            lazylibrarian.CONFIG['TWITTER_PASSWORD'] = access_token['oauth_token_secret']
            return True
Пример #17
0
    def __init__(self, consumer_key, consumer_secret, token_key, token_secret):
        if not has_oauth:
            raise ImportError("No module named oauth2")
        super(OAuth2Method, self).__init__()

        consumer = oauth.Consumer(consumer_key, consumer_secret)
        token = oauth.Token(token_key, token_secret)
        self.authorized_client = oauth.Client(consumer, token)
Пример #18
0
    def get_gr_shelf(self, shelf='to-read'):

        if not self.key or not self.secret or not self.oauth_token or not self.oauth_secret:
            logger.debug("Goodreads sync error: Please authorise first")
            return []
        else:
            #
            # loop over each page of owned books
            #     loop over each book
            #         add book to list
            #
            if not self.consumer:
                self.consumer = oauth.Consumer(key=str(self.key), secret=str(self.secret))
            if not self.token:
                self.token = oauth.Token(self.oauth_token, self.oauth_secret)
            if not self.client:
                self.client = oauth.Client(self.consumer, self.token)

            self.user_id = self.getUserId()
            logger.debug('User id is: ' + self.user_id)

            current_page = 0
            total_books = 0
            gr_list = []

            while True:
                current_page = current_page + 1


                time_now = int(time.time())
                if time_now <= lazylibrarian.LAST_GOODREADS:
                    time.sleep(1)
                    lazylibrarian.LAST_GOODREADS = time_now
                content = self.getShelfBooks(current_page, shelf)
                xmldoc = xml.dom.minidom.parseString(content)

                page_books = 0
                for book in xmldoc.getElementsByTagName('book'):
                    book_id , book_title = self.getBookInfo(book)

                    if lazylibrarian.LOGLEVEL > 2:
                        try:
                            logger.debug('Book %10s : %s' % (str(book_id), book_title))
                        except UnicodeEncodeError:
                            logger.debug('Book %10s : %s' % (str(book_id), 'Title Messed Up By Unicode Error'))

                    gr_list.append(book_id)

                    page_books += 1
                    total_books += 1

                logger.debug('Found %s books on page %s (total = %s)' % (page_books, current_page, total_books))
                if page_books == 0:
                    break

            logger.debug('Found %s' % total_books)
            return gr_list
Пример #19
0
    def get_gr_shelf_contents(self, shelf='to-read'):
        global consumer, client, token, user_id
        if not lazylibrarian.CONFIG['GR_API'] or not lazylibrarian.CONFIG['GR_SECRET'] or not \
                lazylibrarian.CONFIG['GR_OAUTH_TOKEN'] or not lazylibrarian.CONFIG['GR_OAUTH_SECRET']:
            logger.warn(
                "Goodreads shelf contents error: Please authorise first")
            return []
        else:
            #
            # loop over each page of owned books
            #     loop over each book
            #         add book to list
            #
            consumer = oauth.Consumer(key=str(lazylibrarian.CONFIG['GR_API']),
                                      secret=str(
                                          lazylibrarian.CONFIG['GR_SECRET']))
            token = oauth.Token(lazylibrarian.CONFIG['GR_OAUTH_TOKEN'],
                                lazylibrarian.CONFIG['GR_OAUTH_SECRET'])
            client = oauth.Client(consumer, token)
            user_id = self.getUserId()
            logger.debug('User id is: ' + user_id)

            current_page = 0
            total_books = 0
            gr_list = []

            while True:
                current_page = current_page + 1
                content = self.getShelfBooks(current_page, shelf)
                xmldoc = xml.dom.minidom.parseString(content)

                page_books = 0
                for book in xmldoc.getElementsByTagName('book'):
                    book_id, book_title = self.getBookInfo(book)

                    if lazylibrarian.LOGLEVEL > 2:
                        try:
                            logger.debug('Book %10s : %s' %
                                         (str(book_id), book_title))
                        except UnicodeEncodeError:
                            logger.debug('Book %10s : %s' %
                                         (str(book_id),
                                          'Title Messed Up By Unicode Error'))

                    gr_list.append(book_id)

                    page_books += 1
                    total_books += 1

                if lazylibrarian.LOGLEVEL > 2:
                    logger.debug('Found %s books on page %s (total = %s)' %
                                 (page_books, current_page, total_books))
                if page_books == 0:
                    break

            logger.debug('Found %s' % total_books)
            return gr_list
Пример #20
0
    def _oauth1_client(self,
                       token=None,
                       consumer_key=None,
                       consumer_secret=None):
        """Returns OAuth 1.0 client that is capable of signing requests."""
        args = [oauth1.Consumer(key=consumer_key, secret=consumer_secret)]
        if token:
            args.append(token)

        return oauth1.Client(*args)
Пример #21
0
    def follow_author(self, authorid=None, follow=True):
        global consumer, client, token, user_id
        if not lazylibrarian.CONFIG['GR_API'] or not lazylibrarian.CONFIG['GR_SECRET'] or not \
                lazylibrarian.CONFIG['GR_OAUTH_TOKEN'] or not lazylibrarian.CONFIG['GR_OAUTH_SECRET']:
            logger.warn(
                "Goodreads follow author error: Please authorise first")
            return False, 'Unauthorised'

        consumer = oauth.Consumer(key=str(lazylibrarian.CONFIG['GR_API']),
                                  secret=str(
                                      lazylibrarian.CONFIG['GR_SECRET']))
        token = oauth.Token(lazylibrarian.CONFIG['GR_OAUTH_TOKEN'],
                            lazylibrarian.CONFIG['GR_OAUTH_SECRET'])
        client = oauth.Client(consumer, token)
        user_id = self.getUserId()

        # follow https://www.goodreads.com/author_followings?id=AUTHOR_ID&format=xml
        # unfollow https://www.goodreads.com/author_followings/AUTHOR_FOLLOWING_ID?format=xml
        time_now = int(time.time())
        if time_now <= lazylibrarian.LAST_GOODREADS:
            time.sleep(1)
            lazylibrarian.LAST_GOODREADS = time_now

        if follow:
            body = urlencode({'id': authorid, 'format': 'xml'})
            headers = {'Content-Type': 'application/x-www-form-urlencoded'}
            try:
                response, content = client.request(
                    '%s/author_followings' % 'https://www.goodreads.com',
                    'POST', body, headers)
            except Exception as e:
                logger.error("Exception in client.request: %s %s" %
                             (type(e).__name__, traceback.format_exc()))
                return False, "Error in client.request: see error log"
        else:
            body = urlencode({'format': 'xml'})
            headers = {'Content-Type': 'application/x-www-form-urlencoded'}
            try:
                response, content = client.request(
                    '%s/author_followings/%s' %
                    ('https://www.goodreads.com', authorid), 'DELETE', body,
                    headers)
            except Exception as e:
                logger.error("Exception in client.request: %s %s" %
                             (type(e).__name__, traceback.format_exc()))
                return False, "Error in client.request: see error log"

        if follow and response['status'] == '422':
            return True, 'Already following'

        if response['status'].startswith('2'):
            if follow:
                return True, content.split('<id>')[1].split('</id>')[0]
            return True, ''
        return False, 'Failure status: %s' % response['status']
Пример #22
0
    def __init__(self, consumer_key, consumer_secret, server_url, request_token_url, access_token_url, authorization_url):
        self.consumer_secret = consumer_secret
        self.consumer_key = consumer_key

        self.consumer = oauth2.Consumer(consumer_key, consumer_secret)
        self.signature_method = oauth2.SignatureMethod_HMAC_SHA1()

        self.server_url = server_url
        self.request_token_url = request_token_url
        self.access_token_url = access_token_url
        self.authorization_url = authorization_url
Пример #23
0
 def __init__(self, consumer_key, consumer_secret):
     if not has_oauth:
         raise ImportError("No module named oauth2")
     super(OAuthMethod, self).__init__()
     self.oauth_key = consumer_key
     self.oauth_secret = consumer_secret
     self.consumer = oauth.Consumer(self.oauth_key, self.oauth_secret)
     self.authorized_client = None
     self.token_key = None
     self.token_secret = None
     self.callback = None
Пример #24
0
    def auth(self):
        consumer = oauth.Consumer(config.TWITTER_CONSUMER_KEY,
                                  config.TWITTER_CONSUMER_SECRET)
        client = oauth.Client(consumer)

        resp, content = client.request(config.TWITTER_REQUEST_TOKEN_URL, "GET")
        if resp['status'] != '200':
            raise Exception("Invalid response %s." % resp['status'])
        request_token = dict(urlparse.parse_qsl(content))

        self.session['req_token'] = request_token

        self.redirect(
            '%s?oauth_token=%s' %
            (config.TWITTER_AUTHORIZE_URL, request_token['oauth_token']))
Пример #25
0
    def goodreads_oauth1():
        global client, request_token, consumer
        if lazylibrarian.CONFIG['GR_API'] == 'ckvsiSDsuqh7omh74ZZ6Q':
            msg = "Please get your own personal GoodReads api key from https://www.goodreads.com/api/keys and try again"
            return msg
        if not lazylibrarian.CONFIG['GR_SECRET']:
            return "Invalid or missing GR_SECRET"

        if lazylibrarian.CONFIG['GR_OAUTH_TOKEN'] and lazylibrarian.CONFIG[
                'GR_OAUTH_SECRET']:
            return "Already authorised"

        request_token_url = '%s/oauth/request_token' % 'https://www.goodreads.com'
        authorize_url = '%s/oauth/authorize' % 'https://www.goodreads.com'
        # access_token_url = '%s/oauth/access_token' % 'https://www.goodreads.com'

        consumer = oauth.Consumer(key=str(lazylibrarian.CONFIG['GR_API']),
                                  secret=str(
                                      lazylibrarian.CONFIG['GR_SECRET']))

        client = oauth.Client(consumer)

        try:
            response, content = client.request(request_token_url, 'GET')

        except Exception as e:
            logger.error("Exception in client.request: %s %s" %
                         (type(e).__name__, traceback.format_exc()))
            return "Exception in client.request: see debug log"

        if not response['status'].startswith('2'):
            return 'Invalid response [%s] from: %s' % (response['status'],
                                                       request_token_url)

        request_token = dict(parse_qsl(content))
        if not PY2:
            request_token = {
                key.decode("utf-8"): request_token[key].decode("utf-8")
                for key in request_token
            }
        if 'oauth_token' in request_token:
            authorize_link = '%s?oauth_token=%s' % (
                authorize_url, request_token['oauth_token'])
            # print authorize_link
            return authorize_link
        else:
            return "No oauth_token, got %s" % content
Пример #26
0
 def get_user_id(self):
     global consumer, client, token, user_id
     if not lazylibrarian.CONFIG['GR_API'] or not lazylibrarian.CONFIG['GR_SECRET'] or not \
             lazylibrarian.CONFIG['GR_OAUTH_TOKEN'] or not lazylibrarian.CONFIG['GR_OAUTH_SECRET']:
         logger.warn("Goodreads user id error: Please authorise first")
         return ""
     else:
         try:
             consumer = oauth.Consumer(key=str(lazylibrarian.CONFIG['GR_API']),
                                       secret=str(lazylibrarian.CONFIG['GR_SECRET']))
             token = oauth.Token(lazylibrarian.CONFIG['GR_OAUTH_TOKEN'], lazylibrarian.CONFIG['GR_OAUTH_SECRET'])
             client = oauth.Client(consumer, token)
             user_id = self.getUserId()
             return user_id
         except Exception as e:
             logger.error("Unable to get UserID: %s %s" % (type(e).__name__, str(e)))
             return ""
Пример #27
0
def check_oauth():
    consumer = oauth.Consumer(jiraappy.CONSUMER_KEY, jiraappy.CONSUMER_SECRET)
    accessToken = oauth.Token(jiraappy.JIRA_OAUTH_TOKEN, jiraappy.JIRA_OAUTH_SECRET)
    client = oauth.Client(consumer, accessToken)
    client.set_signature_method(SignatureMethod_RSA_SHA1())

    data_url = os.path.join(jiraappy.JIRA_BASE_URL, 'rest/api/2/myself')

    resp, content = client.request(data_url, "GET")
    if resp['status'] != '200':
        jiraappy.JIRA_LOGIN_STATUS = None
        jiraappy.JIRA_LOGIN_USER = None
        logger.warn("OAuth credentials missing or invalid")
    else:
        resp_dict = json.loads(content)
        jiraappy.JIRA_LOGIN_STATUS = True
        jiraappy.JIRA_LOGIN_USER = resp_dict['name']
        logger.info("JIRA user %s verified login" % resp_dict['name'])
Пример #28
0
    def get_user_id(self):

        if not self.key or not self.secret or not self.oauth_token or not self.oauth_secret:
            logger.debug("Goodreads sync error: Please authorise first")
            return ""
        else:
            try:
                if not self.consumer:
                    self.consumer = oauth.Consumer(key=str(self.key), secret=str(self.secret))
                if not self.token:
                    self.token = oauth.Token(self.oauth_token, self.oauth_secret)
                if not self.client:
                    self.client = oauth.Client(self.consumer, self.token)

                self.user_id = self.getUserId()
                return self.user_id
            except Exception as e:
                logger.debug("Unable to get UserID: %s" % str(e))
                return ""
Пример #29
0
    def get_authorization(self):

        # noinspection PyUnusedLocal
        signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()
        oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret)
        oauth_client = oauth.Client(oauth_consumer)

        self._log_debug('Requesting temp token from Twitter')

        resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET')

        if '200' != resp['status']:
            self._log_error('Invalid response from Twitter requesting temp token: %s' % resp['status'])
        else:
            request_token = dict(parse_qsl(content))

            sickbeard.TWITTER_USERNAME = request_token['oauth_token']
            sickbeard.TWITTER_PASSWORD = request_token['oauth_token_secret']

            return self.AUTHORIZATION_URL + '?oauth_token=' + request_token['oauth_token']
Пример #30
0
    def callback(self):
        verifier = self.request.get('oauth_verifier')
        request_token = self.session.pop('req_token', None)
        token = oauth.Token(request_token['oauth_token'],
                            request_token['oauth_token_secret'])
        token.set_verifier(verifier)
        consumer = oauth.Consumer(config.TWITTER_CONSUMER_KEY,
                                  config.TWITTER_CONSUMER_SECRET)
        client = oauth.Client(consumer, token)

        resp, content = client.request(config.TWITTER_ACCESS_TOKEN_URL, "POST")
        access_token = dict(urlparse.parse_qsl(content))

        user = users.get_current_user()
        clients = db.GqlQuery("SELECT * FROM Client", email=user.email())
        client = clients.get()
        client.twitter_actoken_key = access_token['oauth_token']
        client.twitter_actoken_secret = access_token['oauth_token_secret']
        client.put()

        self.redirect('/')