Example #1
0
 def __init__(self, key, secret, api_url=None):
     self.client = oauth2.Client(oauth2.Consumer(key, secret))
     self.client.ca_certs = os.path.join(
         os.path.dirname(os.path.abspath(__file__)), "toopher.pem")
     base_url = api_url if api_url else DEFAULT_BASE_URL
     self.base_url = base_url.rstrip('/')
Example #2
0
import oauth2 as oauth
import urllib2 as urllib

# See assignment1.html instructions or README for how to get these credentials

api_key = "SB68AxPKAUXUxngf1sJyKmFNP"
api_secret = "OJs4AWigxzuDOzIjcMr4kBfaHofV9mNTDoeb0xgS58GFqb2083"
access_token_key = "712755769611956224-0tgMPSClgEYX5JfqOYvggMsLFrcq8Ca"
access_token_secret = "Q0SrbkMIc2475swI7PMHZsRRJpC4L9fNtYgKLlewcWtw8"

_debug = 0

oauth_token = oauth.Token(key=access_token_key, secret=access_token_secret)
oauth_consumer = oauth.Consumer(key=api_key, secret=api_secret)

signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()

http_method = "GET"

http_handler = urllib.HTTPHandler(debuglevel=_debug)
https_handler = urllib.HTTPSHandler(debuglevel=_debug)
'''
Construct, sign, and open a twitter request
using the hard-coded credentials above.
'''


def twitterreq(url, method, parameters):
    req = oauth.Request.from_consumer_and_token(oauth_consumer,
                                                token=oauth_token,
                                                http_method=http_method,
Example #3
0
from django.template import loader
from django.views.generic.edit import FormView
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode

from accounts.tokens import password_reset_token
from django.contrib import messages

from client.models import Client
from subscribers.models import Subscriber
from volunteer.models import Volunteer

from app_utility.email_utils import SendEmail
from celery_stuff.tasks import task_twitter_mentions, task_initial_twitter_timeline

consumer = oauth.Consumer(settings.TWITTER_TOKEN, settings.TWITTER_SECRET)
client = oauth.Client(consumer)

request_token_url = 'https://api.twitter.com/oauth/request_token'
access_token_url = 'https://api.twitter.com/oauth/access_token'
authenticate_url = 'https://api.twitter.com/oauth/authenticate'


def index(request):
    template = 'accounts/login_page.html'
    return render(request, template, {})


def login_page(request):
    template = 'accounts/login_page.html'
    return render(request, template, {})
Example #4
0
 def get_consumer(self):
     return oauth.Consumer(self.data['consumer_key'],
                           self.data['consumer_secret'])
Example #5
0
# -*- coding: utf-8 -*-

import oauth2 as oauth
import json
import time
import pymongo

CONSUMER_KEY = ""
CONSUMER_SECRET = ""
ACCESS_KEY = ""
ACCESS_SECRET = ""

consumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)
access_token = oauth.Token(key=ACCESS_KEY, secret=ACCESS_SECRET)
client = oauth.Client(consumer, access_token)

clientMongo = pymongo.MongoClient("localhost", 27017)
db = clientMongo.db_cores_observatory

#since_id = '' #pode usar since_id ou nao, se usar, colocar na url

#Geolocalização da Central do Brasil
#Latitude, Longitude, Raio Radius ao redor da posição.
#Com este radius de 70km, a área abrange toda Região Metropolitana do RJ.
#geo='-22.903426,-43.191478,70km'

#Desde. Formato YYYY-MM-DD.
since = '2018-04-24'

#Até o dia anterior de. Formato YYYY-MM-DD.
until = '2018-05-02'
Example #6
0
import urllib2 as urllib
import oauth2 as oauth
import json
import os

# urlib2 stuff
_debug = 0
http_handler = urllib.HTTPHandler(debuglevel=_debug)
https_handler = urllib.HTTPSHandler(debuglevel=_debug)

# oauth2 stuff
with open(os.path.dirname(__file__) + "/twitter_credentials.json") as f:
    tc = json.load(f)
oauth_token = oauth.Token(key=tc["access_token_key"],
                          secret=tc["access_token_secret"])
oauth_consumer = oauth.Consumer(key=tc["api_key"], secret=tc["api_secret"])
signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()


def twitter_request(url, http_method, parameters):
    req = oauth.Request.from_consumer_and_token(oauth_consumer,
                                                token=oauth_token,
                                                http_method=http_method,
                                                http_url=url,
                                                parameters=parameters)
    req.sign_request(signature_method_hmac_sha1, oauth_consumer, oauth_token)

    if http_method == "POST":
        encoded_post_data = req.to_postdata()
    else:
        encoded_post_data = None
Example #7
0
def main():
    if len(sys.argv) < 2:
        print >> sys.stderr, 'Usage: python upload2ourbricks.py file1 [file2 [file3 ..]]'
        sys.exit(1)

    opts, args = getopt.getopt(sys.argv[1:], ':')
    upload_files = args
    for f in upload_files:
        if not os.path.isfile(f):
            print >> sys.stderr, 'File not found: %s' % (f, )
            sys.exit(1)

    consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET)
    client = oauth2.Client(consumer)

    # Step 1: Get a request token. This is a temporary token that is used for
    # having the user authorize an access token and to sign the request to obtain
    # said access token.

    resp, content = client.request(REQUEST_TOKEN_URL, "GET")
    if resp['status'] != '200':
        exitprint(resp, content)

    request_token = dict(urlparse.parse_qsl(content))

    print "Request Token:"
    print "    - oauth_token        = %s" % request_token['oauth_token']
    print "    - oauth_token_secret = %s" % request_token['oauth_token_secret']
    print

    # Step 2: Redirect to the provider. Since this is a CLI script we do not
    # redirect. In a web application you would redirect the user to the URL
    # below.

    print "Go to the following link in your browser:"
    print "%s?oauth_token=%s" % (AUTHORIZATION_URL,
                                 request_token['oauth_token'])
    print

    # After the user has granted access to you, the consumer, the provider will
    # redirect you to whatever URL you have told them to redirect to. You can
    # usually define this in the oauth_callback argument as well.
    accepted = raw_input('Have you authorized me? (y/n) ')
    if accepted != 'y':
        print "Well, then nothing to do here. Exiting"
        sys.exit(0)
    oauth_verifier = raw_input('What is the PIN? ')

    # Step 3: Once the consumer has redirected the user back to the oauth_callback
    # URL you can request the access token the user has approved. You use the
    # request token to sign this request. After this is done you throw away the
    # request token and use the access token returned. You should store this
    # access token somewhere safe, like a database, for future use.
    token = oauth2.Token(request_token['oauth_token'],
                         request_token['oauth_token_secret'])
    token.set_verifier(oauth_verifier)
    client = oauth2.Client(consumer, token)

    resp, content = client.request(ACCESS_TOKEN_URL, "POST")
    access_token = dict(urlparse.parse_qsl(content))
    if resp['status'] != '200':
        exitprint(resp, content)

    print "Access Token:"
    print "    - oauth_token        = %s" % access_token['oauth_token']
    print "    - oauth_token_secret = %s" % access_token['oauth_token_secret']
    print

    # Step 4: We have an access token, so we can issue
    # an upload request on behalf of the user

    token = oauth2.Token(access_token['oauth_token'],
                         access_token['oauth_token_secret'])

    upload_params = dict(title=raw_input('Title: '),
                         description=raw_input('Description: '),
                         tags=raw_input('Tags: '),
                         author=raw_input('Author: '))
    license = get_choice('Choose A License: ', LICENSE_CHOICES)
    upload_params['license'] = license
    if license == 'For Sale':
        price = -1.0
        while price < 0:
            price = raw_input('Price: ')
            try:
                price = float(price)
            except ValueError:
                price = -1
            if price < 0:
                print 'Invalid input.'
                print
    else:
        price = ''
    upload_params['price'] = str(price)

    req = oauth2.Request.from_consumer_and_token(consumer,
                                                 token=token,
                                                 http_method="POST",
                                                 http_url=UPLOAD_URL,
                                                 parameters=upload_params)

    req.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token)
    compiled_postdata = req.to_postdata()
    all_upload_params = urlparse.parse_qs(compiled_postdata,
                                          keep_blank_values=True)

    #parse_qs returns values as arrays, so convert back to strings
    for key, val in all_upload_params.iteritems():
        all_upload_params[key] = val[0]

    for i, fpath in enumerate(upload_files):
        all_upload_params['file' + str(i)] = open(fpath, 'rb')
    datagen, headers = multipart_encode(all_upload_params)
    request = urllib2.Request(UPLOAD_URL, datagen, headers)

    try:
        respdata = urllib2.urlopen(request).read()
    except urllib2.HTTPError, ex:
        print >> sys.stderr, 'Received error code: ', ex.code
        print >> sys.stderr
        print >> sys.stderr, ex
        sys.exit(1)
Example #8
0
 def __init__(self, oauth_key, oauth_secret):
     self.consumer = oauth.Consumer(oauth_key, oauth_secret)
     self.oauth_client = oauth.Client(self.consumer)
     self.token = None
import time
import urllib2
import json
import oauth2

url1 = "https://api.twitter.com/1.1/search/tweets.json"  # FIXED AUTHENCATION PARAMETERS

params = {
    "oauth_version": "1.0",
    "oauth_nonce": oauth2.generate_nonce(),
    "oauth_timestamp": int(time.time())
}

consumer = oauth2.Consumer(
    key="TBUe0iD3p2tLJWOWk5E8bbURc",
    secret="tLYGKX6hqGNSAAnLFU9crk2f6uMrooWRCDfaTcDihLUL5uA2mp")

token = oauth2.Token(key="771617182690086913-93nqBNjamtUnGB51LIvDLJBRE9ohvZx",
                     secret="szHwhzlifubfeUHEK7pdkJJAMwj95sRRh0hVU0dacEROZ")

params["oauth_consumer_key"] = consumer.key  # VARIABLE AUTHENCATION PARAMETERS

params["oauth_token"] = token.key

params["q"] = "jaipur"

req = oauth2.Request(method="GET", url=url1, parameters=params)
signature_method = oauth2.SignatureMethod_HMAC_SHA1()
req.sign_request(signature_method, consumer, token)
url = req.to_url()
response = urllib2.Request(url)
Example #10
0
from BeautifulSoup import BeautifulSoup

# See http://code.google.com/p/google-mail-xoauth-tools/wiki/
#     XoauthDotPyRunThrough for details on xoauth.py

OAUTH_TOKEN = sys.argv[1]  # obtained with xoauth.py
OAUTH_TOKEN_SECRET = sys.argv[2]  # obtained with xoauth.py
GMAIL_ACCOUNT = sys.argv[3]  # [email protected]
Q = sys.argv[4]

url = 'https://mail.google.com/mail/b/%s/imap/' % (GMAIL_ACCOUNT, )

# Authenticate with OAuth

# Standard values for GMail's xoauth implementation
consumer = oauth.Consumer('anonymous', 'anonymous')
token = oauth.Token(OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
conn = imaplib.IMAP4_SSL('imap.googlemail.com')
conn.debug = 4
conn.authenticate(url, consumer, token)

# Select a folder of interest

conn.select('INBOX')

# Repurpose scripts from "Mailboxes: Oldies but Goodies"


def cleanContent(msg):

    # Decode message from "quoted printable" format
Example #11
0
import oauth2 as oauth
import httplib2
import time, os, sys
import simplejson as json

# Fill the keys and secrets you retrieved after registering your app
api_key = sys.argv[1]
secret_key = sys.argv[2]
user_token = sys.argv[3]
user_secret = sys.argv[4]

# Use your API key and secret to instantiate consumer object
consumer = oauth.Consumer(api_key, secret_key)

# Use your developer token and secret to instantiate access token object
access_token = oauth.Token(key=user_token, secret=user_secret)

client = oauth.Client(consumer, access_token)

# Make call to LinkedIn

max_requests = 300
count_increment = 20
offset = 0

request_url = "http://api.linkedin.com/v1/job-search:(jobs:(id,customer-job-code,active,posting-date,expiration-date,posting-timestamp,expiration-timestamp,company:(id,name),position:(title,location,job-functions,industries,job-type,experience-level),skills-and-experience,description,salary,job-poster:(id,first-name,last-name,headline),referral-bonus,site-job-url,location-description))?format=json&count=20&keywords=computer%20science&sort=DD&start="

for i in range(max_requests):
    response, content = client.request(
        request_url + str(offset + i * count_increment), "GET", "")
    print content.replace("\n", " ")
Example #12
0
def generate_new_oauth_tokens():
    """
    Script to generate new OAuth tokens.
    Code from this gist: https://gist.github.com/4219558
    """
    consumer_key = os.environ['%s_TUMBLR_APP_KEY' % app_config.CONFIG_NAME]
    consumer_secret = os.environ['%s_TUMBLR_APP_SECRET' % app_config.CONFIG_NAME]

    request_token_url = 'http://www.tumblr.com/oauth/request_token'
    access_token_url = 'http://www.tumblr.com/oauth/access_token'
    authorize_url = 'http://www.tumblr.com/oauth/authorize'

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

    # Step 1: Get a request token. This is a temporary token that is used for
    # having the user authorize an access token and to sign the request to obtain
    # said access token.

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

    request_token = dict(urlparse.parse_qsl(content))

    print "Request Token:"
    print "    - oauth_token        = %s" % request_token['oauth_token']
    print "    - oauth_token_secret = %s" % request_token['oauth_token_secret']
    print

    # Step 2: Redirect to the provider. Since this is a CLI script we do not
    # redirect. In a web application you would redirect the user to the URL
    # below.

    print "Go to the following link in your browser:"
    print "%s?oauth_token=%s" % (authorize_url, request_token['oauth_token'])
    print

    # After the user has granted access to you, the consumer, the provider will
    # redirect you to whatever URL you have told them to redirect to. You can
    # usually define this in the oauth_callback argument as well.
    accepted = 'n'
    while accepted.lower() == 'n':
            accepted = raw_input('Have you authorized me? (y/n) ')
            oauth_verifier = raw_input('What is the OAuth Verifier? ')

    # Step 3: Once the consumer has redirected the user back to the oauth_callback
    # URL you can request the access token the user has approved. You use the
    # request token to sign this request. After this is done you throw away the
    # request token and use the access token returned. You should store this
    # access token somewhere safe, like a database, for future use.
    token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
    token.set_verifier(oauth_verifier)
    client = oauth.Client(consumer, token)

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

    print "Access Token:"
    print "    - oauth_token        = %s" % access_token['oauth_token']
    print "    - oauth_token_secret = %s" % access_token['oauth_token_secret']
    print
    print "You may now access protected resources using the access tokens above."
    print
Example #13
0
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from rest_framework.generics import ListAPIView, GenericAPIView
from rest_framework.generics import DestroyAPIView
from oauth2_provider.contrib.rest_framework.authentication import OAuth2Authentication
from rest_framework.views import APIView

from .models import TwitterTemporaryToken, TwitterAccount, OAuth2AccessToken
from .tasks import fetch_user_info
from .utils import convert
from .serializers import AuthorizedTwitterAccountSerializer, ProfileDetailSerializer, \
    UsernameConfigurationSerializer, BioConfigurationSerializer

logger = logging.getLogger(__name__)

consumer = oauth.Consumer(settings.TWITTER_CLIENT_ID,
                          settings.TWITTER_CLIENT_SECRET)
client = oauth.Client(consumer)

request_token_url = 'https://api.twitter.com/oauth/request_token'
access_token_url = 'https://api.twitter.com/oauth/access_token'

authenticate_url = 'https://api.twitter.com/oauth/authenticate'


class TwitterLogin(APIView):
    def get(self, request, *args, **kwargs):
        # get request token from twitter
        resp, content = client.request(request_token_url, "GET")
        if resp['status'] != '200':
            print(resp, content)
            raise Exception("Invalid response from Twitter.")
Example #14
0
"""

import oauth2
import time
import urllib2
import json

url1 = "https://api.twitter.com/1.1/search/tweets.json"  # FIXED AUTHENCATION PARAMETERS

params = {
        "oauth_version": "1.0",
        "oauth_nonce": oauth2.generate_nonce(),
        "oauth_timestamp": int(time.time())
    }

consumer = oauth2.Consumer(key="MOLSku6vv7wkDUHyQuKxSDE1h", secret="z3D9D28zW2BuhbcKqADCAN7fhXrbeBGPmm5MTC1lEsWPZCZq1v")

token = oauth2.Token(key="2791721754-UHbZSsJiHKjRRDG8gYQsJfekwyl1nniEopewm1j",
                     secret="J3AUIoGXuygrlrnF74EevMm92vB6KTI5aBkxHGhad4SmP")

params["oauth_consumer_key"] = consumer.key   # VARIABLE AUTHENCATION PARAMETERS

params["oauth_token"] = token.key
params["q"] = "jaipur"
req = oauth2.Request(method="GET", url=url1, parameters=params)

signature_method = oauth2.SignatureMethod_HMAC_SHA1() 
req.sign_request(signature_method, consumer, token)
url = req.to_url()
response = urllib2.Request(url)
data = urllib2.urlopen(response)
Example #15
0
#!/usr/bin/python
import oauth2 as oauth
import urlparse
import time
import webbrowser
from twisted.internet import reactor, protocol, ssl
from twisted.web import http

CONSUMER_KEY = 'CHANGEME'
CONSUMER_SECRET = 'CHANGEME'
CONSUMER = oauth.Consumer(CONSUMER_KEY, CONSUMER_SECRET)

ACCESS_TOKEN_FILE = 'OAUTH_ACCESS_TOKEN'

TWITTER_REQUEST_TOKEN_URL = 'https://twitter.com/oauth/request_token'
TWITTER_ACCESS_TOKEN_URL = 'https://twitter.com/oauth/access_token'
TWITTER_AUTHORIZE_URL = 'https://twitter.com/oauth/authorize'
TWITTER_STREAM_API_HOST = 'stream.twitter.com'
TWITTER_STREAM_API_PATH = '/1/statuses/sample.json'


class TwitterStreamer(http.HTTPClient):
    def connectionMade(self):
        self.sendCommand('GET', self.factory.url)
        self.sendHeader('Host', self.factory.host)
        self.sendHeader('User-Agent', self.factory.agent)
        self.sendHeader('Authorization', self.factory.oauth_header)
        self.endHeaders()

    def handleStatus(self, version, status, message):
        if status != '200':
 def __init__(self):
     self.signature_method = oauth.SignatureMethod_HMAC_SHA1()
     self.consumer = oauth.Consumer(self.key, self.secret)
    @
    @Description:   This python script retrieves all followers (up tp 75000) from a
    @               list of users
    @               and stores those tweets into a txt file.
    @Author:        Joe Chen
    @Last modified: 10/01/2015
"""

import time
import json
import urllib2
import oauth2

# 1)from (r.t)
consumer = oauth2.Consumer(
    key="TWRBSpgSMkEjzcdpcyZxBX01X",
    secret="lyzpMfOfQXi9wzSl2KcPtqtHdcEuklCrAtQBI7y5DdUw1vVS2Q")
token = oauth2.Token(key="2427867182-uNdht7AKnyBIfovdPP36Ly7QPFxiPYQxDUK9v9M",
                     secret="y8u8Tl0sT1pQHJben60EIpaqVVPcVbDTEQjEpEZVjORiW")

# 2)from Joe Chen
# consumer = oauth2.Consumer(key="CuyDAqUbCTF6y6k6mcoGF8owZ", secret="OucJJMnHbYCVNKNgyEJSNBMWBXapwSGuwy1Xc28mXR5vLixrNQ")
# token = oauth2.Token(key="1979279791-8qRguXNd21mgHR8khU9hg8rcyXkHHSE65tkwFlv", secret="HIR4DQEyHVPrvXm2XNsTToVcgIgxWM2WR2eOoaY1iJV6R")

# 3)from Joe Chen, another one
# consumer = oauth2.Consumer(key="z4k1E4pOj8ncQ4MAdjY1r1Ty9", secret="92mLHrYChG5sHRdZsUc90JG7RRh8cewrl5Hjf2IoPunCAL8HRz")
# token = oauth2.Token(key="1979279791-tSDamC8WUIxU9Z8uFnkWe5eLNSUlGYhGu8l5zZ1", secret="FNMSlsqgcIRmjeCf0BqD9TamwAD1ZfMC77n0x0cOpsICZ")

# 4) name: summer research project
# consumer = oauth2.Consumer(key="Vsj9hKjxGPk4JxBj4al3i7JHX", secret="TbPwe5ltq7U4GtaeMtUhyMxxYb6jNvgyXWZsGsjKqcxbZCFhbD")
# token = oauth2.Token(key="1979279791-c9yR5GJlLrg78jTIifIckvllZf8NBRl8K5aU8OZ", secret="FHuPvdPcbU3Xu77I44pqc64FmLGh82Bkftgq0xwqmRHhR")
Example #18
0
#!/usr/bin/env python

# This Script was shared as part of Intro to DataSci Course offered by University of Washington
# https://github.com/uwescience/datasci_course_materials

import oauth2 as oauth
import urllib2 as urllib
import RavsKeys

_debug = 0

oauth_token = oauth.Token(key=RavsKeys.access_token,
                          secret=RavsKeys.access_token_secret)
oauth_consumer = oauth.Consumer(key=RavsKeys.consumer_key,
                                secret=RavsKeys.consumer_secret)

signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()

http_method = "GET"

http_handler = urllib.HTTPHandler(debuglevel=_debug)
https_handler = urllib.HTTPSHandler(debuglevel=_debug)
'''
Construct, sign, and open a twitter request
using the hard-coded credentials above.
'''


def twitterreq(url, method, parameters):
    req = oauth.Request.from_consumer_and_token(oauth_consumer,
                                                token=oauth_token,
def getKey(keyPath):
    d = dict()
    f = open(keyPath, 'r')
    lines = f.readlines()
    for line in lines:
        row = line.split('=')
        row0 = row[0]
        d[row0] = row[1].strip()
    return d


keyPath = os.path.join(os.getcwd(), 'src', 'key.properties')
key = getKey(keyPath)

consumer = oauth2.Consumer(key=key['api_key'], secret=key['api_secret'])
token = oauth2.Token(key=key['access_token'], secret=key['access_secret'])
client = oauth2.Client(consumer, token)

_mclient = MongoClient()
_mclient['ds_twitter']
_db = _mclient.ds_twitter
_col = _db.home_timeline
_table = _db.home_timeline

url = "https://api.twitter.com/1.1/statuses/home_timeline.json"
response, content = client.request(url)
home_timeline = json.loads(content)

for tweet in home_timeline:
    _table.insert_one(tweet)
Example #20
0
import time
from textblob import TextBlob
import datetime
from pytz import timezone
import pytz
import bson
from bson.objectid import ObjectId
from bson import json_util

app = Flask(__name__)
app.config["MONGO_URI"] = (
    "mongodb+srv://momoyay:Pixel%[email protected]/tweetsdb")
mongo = PyMongo(app)
tweet = mongo.db.tweets

consumer = oauth.Consumer(key=twitter_credentials.CONSUMER_KEY,
                          secret=twitter_credentials.CONSUMER_SECRET)
access_token = oauth.Token(key=twitter_credentials.ACCESS_TOKEN,
                           secret=twitter_credentials.ACCESS_TOKEN_SECRET)
client = oauth.Client(consumer, access_token)

url = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=realDonaldTrump&count=1&tweet_mode=extended"
response, data = client.request(url)
results = json.loads(data)
id = results[0]["id_str"]
tweet.insert_many(results)


def insert_tweets():
    created_at = tweet.find({"id_str": id})
    for twts in created_at:
        date = datetime.datetime.strptime(
# Proxy using Goagent to able to access Twitter in this script
#proxy_handler = urllib.ProxyHandler({"http": "http://127.0.0.1:8087"})
#proxy_opener = urllib.build_opener(proxy_handler)
#urllib.install_opener(proxy_opener)

# See Assignment 1 instructions or README for how to get these credentials
access_token_key = "313980745-rr5BX9QxnW1NA9HVp0UmfkMCoqCuFsxAwIhTSAyr"
access_token_secret = "lmr1OKAyLQ2fXudY4neyPdtdbIB6okbIZffo9jOZNY"

consumer_key = "8cef21fsukOKuqiMJ3cBhw"
consumer_secret = "0p0MAkjwfU1Rn1mwig0G5tJvCcG7jow1ImXC49N1o"

_debug = 0

oauth_token = oauth.Token(key=access_token_key, secret=access_token_secret)
oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret)

signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()

http_method = "GET"

http_handler = urllib.HTTPHandler(debuglevel=_debug)
https_handler = urllib.HTTPSHandler(debuglevel=_debug)
'''
Construct, sign, and open a twitter request
using the hard-coded credentials above.
'''


def twitterreq(url, method, parameters):
    req = oauth.Request.from_consumer_and_token(oauth_consumer,
Example #22
0
import oauth2
import constants
import urllib.parse as urlparse

consumer = oauth2.Consumer(constants.CONSUMER_KEY, constants.CONSUMER_SECRET)


def get_request_token():
    client = oauth2.Client(consumer)
    response, content = client.request(constants.REQUEST_TOKEN_URL, 'POST')
    if response.status != 200:
        print("An error occurred getting the request token from Twitter!")

    return dict(urlparse.parse_qsl(content.decode('utf-8')))


def get_oauth_verifier(request_token):
    print("Go to the following site in your browser:")
    print("{}?oauth_token={}".format(constants.AUTHORIZATION_URL,
                                     request_token['oauth_token']))
    return input("What is the PIN? ")


def get_access_token(request_token, oauth_verifier):
    token = oauth2.Token(request_token['oauth_token'],
                         request_token['oauth_token_secret'])
    token.set_verifier(oauth_verifier)

    client = oauth2.Client(consumer, token)

    response, content = client.request(constants.ACCESS_TOKEN_URL, 'POST')
Example #23
0
import oauth2
import json
import urllib.parse

#Adquiridos pelo twitter
consumer_key = '***'
consumer_secret_key = '***'
access_token = '***'
access_secret_token = '***'

consumer = oauth2.Consumer(consumer_key, consumer_secret_key)  # login
token = oauth2.Token(access_token, access_secret_token)  # senha
cliente = oauth2.Client(consumer, token)  # uniao de login e senha, ou seja, o cliente

query = input('Novo Tweet: ')
query_codificada = urllib.parse.quote(query, safe='')

requisicao = cliente.request('https://api.twitter.com/1.1/statuses/update.json?status=' + query_codificada, method='POST')

requisicao_decodificada = requisicao[1].decode()  # teve que fazer isso porque se trata de uma tupla

objeto = json.loads(requisicao_decodificada)

print(objeto)
import oauth2 as oauth
import json
import configparser

config = configparser.RawConfigParser()
configpath = r'config.conf'
config.read(configpath)
consumer_key = config.get('logintwitter', 'consumer_key')
consumer_secret = config.get('logintwitter', 'consumer_secret')
access_key = config.get('logintwitter', 'access_key')
access_secret = config.get('logintwitter', 'access_secret')

consumer = oauth.Consumer(key=consumer_key,
                          secret=consumer_secret)  #twitter: sign me in
access_token = oauth.Token(key=access_key,
                           secret=access_secret)  #grant me access
client = oauth.Client(consumer, access_token)  #object return

timeline_endpoint = "https://api.twitter.com/1.1/statuses/home_timeline.json"
response, data = client.request(timeline_endpoint)

tweets = json.loads(
    data)  #take a JSON string convert it to dictionary structure:
for tweet in tweets:
    print(tweet["text"])
Example #25
0
 def __init__(self, consumer_key, consumer_secret, oauth_token,
              oauth_token_secret):
     self.consumer = oauth2.Consumer(consumer_key, consumer_secret)
     self.token = oauth2.Token(oauth_token, oauth_token_secret)
     self.url = "http://api.tumblr.com"
Example #26
0
#!/usr/local/bin/python3

# Example python code to access the openVuln API
# Based on contributions from Ryan Ruckley
# Requirements:
#  - Python version 3
#  - oauth2 - sudo pip3 install oauth2
#  - request - sudo pip3 install request

import oauth2 as oauth
import json
import urllib.request

print('Connecting to Cisco...')

consumer = oauth.Consumer(key="<yourClientID>", secret="<yourClientSecret>")

request_token_url = "https://cloudsso.cisco.com/as/token.oauth2?grant_type=client_credentials&client_id=<yourClientID>&client_secret=<yourClientSecret>"

client = oauth.Client(consumer)

resp, content = client.request(request_token_url, "POST")

print(content)

j = json.loads(content.decode('utf-8'))

print('Access Token Retrieved...')
print(j['access_token'])

# Replace the Request URL below with the openVuln REST API resource you would like to access.
import couchdb
import oauth2 as oauth
import xml.etree.ElementTree as ET
from datetime import datetime

today = datetime.today()
#url = "http://api.linkedin.com/v1/companies/1337"
#url = "https://api.linkedin.com/v1/job-search?company-name=Facebook"
#url = 'https://api.linkedin.com/v1/job-search?&keywords=python&facet=date-posted,'+yesterday.strftime('%Y%m%d')
#url = "https://api.linkedin.com/v1/job-search?job-title=Software+Engineer"
#url = "https://api.linkedin.com/v1/companies/162479"
baseurl = 'https://api.linkedin.com/v1/job-search?&keywords='

consumer = oauth.Consumer(key="77hjmrg7xoj582", secret="xHDKhWWs4mCLawNH")

token = oauth.Token(key="ae84e3e4-d29a-4492-b925-6b4836b7ceb6",
                    secret="d275a5a2-2494-4807-9540-02e653e46cbe")

server = couchdb.Server('http://localhost:9000')
tagdb = server['tags']
tags = tagdb['a2fa8c775de9bc7d97ea22c5a9135649']['items']
#db = server.create('linkedin')
db = server['linkedin']

client = oauth.Client(consumer, token)

lists = []
tmp = 0
for tagname in tags:
    url = baseurl + tagname['name']
    resp, content = client.request(url)
Example #28
0
 def conexao(self, consumer_key, consumer_secret, token_key, token_secret):
     self.consumer = oauth2.Consumer(consumer_key, consumer_secret)
     self.token = oauth2.Token(token_key, token_secret)
     self.cliente = oauth2.Client(self.consumer, self.token)
Example #29
0
import oauth2
import json
import urllib.parse
import pprint

consumer_key = 'WRXnyJds71yDayQaXFxPpI2jv'
consumer_secret = 'AjpaogRVFUyuZTfvaNgwj08J0pD3n6f1k08BjUUlapnUFca2w4'

token_key = '799122088594460672-vzJloX2qozKzEuJhNuyB1oew8rJSEzF'
token_secret = 'COd1bb65SodeBgD7zPTseuZ9lUBpkeeapROr0MXFprlqz'

consumer = oauth2.Consumer(consumer_key, consumer_secret)
token = oauth2.Token(token_key, token_secret)
cliente = oauth2.Client(consumer, token)

query = input("Pesquisa: ")
query_codificada = urllib.parse.quote(query, safe='')
requisicao = cliente.request(
    'https://api.twitter.com/1.1/search/tweets.json?q=' + query_codificada +
    '&lang=pt')

decodificar = requisicao[1].decode()

objeto = json.loads(decodificar)
twittes = objeto['statuses']

pprint.pprint(objeto)

for twit in twittes:
    print(twit['user']['screen_name'])
    print(twit['text'])
Example #30
0
def initiate(environ, start_response):
  try:
    request = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
    oauth_signature_method = request.getvalue('oauth_signature_method')
    if oauth_signature_method is None:
        oauth_signature_method='RSA-SHA1'
    oauth_signature = str(request.getvalue('oauth_signature'))
    oauth_timestamp = int(request.getvalue('oauth_timestamp'))
    oauth_nonce = int(request.getvalue('oauth_nonce'))
    oauth_version = str(request.getvalue('oauth_version'))
    oauth_consumer_key = str(request.getvalue('oauth_consumer_key'))
    oauth_callback = str(request.getvalue('oauth_callback'))
    certlifetime = request.getvalue('certlifetime')
    if certlifetime is not None:
        certlifetime = int(certlifetime)
    else:
        certlifetime = 86400

    clients = db_session.get_client(Client(oauth_consumer_key=oauth_consumer_key))
    client = None
    if len(clients) > 0:
        client = clients[0]
    if client is None:
        application.logger.error('Unregistered client requested a temporary token.')
        status = "403 Not authorized"
        headers = [
                ("Content-Type", "text/plain") ]
        start_response(status, headers)
        return "Uregistered client"

    if hasattr(Crypto.PublicKey.RSA, 'importKey'):
        key = Crypto.PublicKey.RSA.importKey(client.oauth_client_pubkey)
    else:
        import M2Crypto.RSA
        import M2Crypto.BIO
        import struct
        import sys

        bio = M2Crypto.BIO.MemoryBuffer(str(client.oauth_client_pubkey))

        k = None
        try:
            k = M2Crypto.RSA.load_pub_key_bio(bio)
            def unpack_from(fmt, data, offs):
                unpack_len = struct.calcsize(fmt)

                return struct.unpack(fmt, data[offs:offs+unpack_len])

            def decode(n):
                len = reduce(lambda x,y: long(x*256+y),
                        unpack_from("4B", n, 0))
                return reduce(lambda x,y: long(x*256+y),
                        unpack_from(str(len)+"B", n, 4))
            keytuple = (decode(k.n), decode(k.e))
        except:
            application.logger.error(str(sys.exc_info()))
            raise

        key = Crypto.PublicKey.RSA.construct(keytuple)

    method = environ['REQUEST_METHOD']
    url = url_reconstruct(environ)
    o_request = oauth.Request.from_request(method, url)
    o_consumer = oauth.Consumer(client.oauth_consumer_key, key)
    o_server = oauth.Server()
    o_server.add_signature_method(oauth.SignatureMethod_RSA_SHA1())
    try:
        o_server.verify_request(o_request, o_consumer, None)
    except:
        e = sys.exc_info()
        application.logger.error(str(e[1]))
        status = "403 Not authorized"
        headers = [
                ("Content-Type", "text/plain") ]
        start_response(status, headers, e)
        return str(e[1])

    certreq = str(request.getvalue('certreq'))

    oauth_temp_token = 'myproxy:oa4mp,2012:/tempCred/' \
            + ''.join([random.choice('0123456789abcdef') for i in range(32)]) \
            + '/' + str(int(time.time()))
    transaction = Transaction()
    transaction.temp_token = oauth_temp_token
    transaction.temp_token_valid = 1
    transaction.oauth_callback = oauth_callback
    transaction.certreq = certreq
    transaction.oauth_consumer_key = oauth_consumer_key
    transaction.certlifetime = certlifetime
    transaction.timestamp = int(time.time())
    db_session.add_transaction(transaction)
    db_session.commit()

    status = "200 Ok"
    headers = [
        ("Content-Type", "app/x-www-form-urlencoded") ]
    start_response(status, headers)

    return "oauth_token=%s&oauth_callback_confirmed=true" % oauth_temp_token
  except:
    return bad_request(start_response)