def process_request(self, request):
     """Import the Twitter token from the Session into the Request."""
     request.twitter_access_token = None
     request.twitter_request_token = None
     request.twitter_userinfo = None
     if ACCESS_KEY in request.session:
         token_str = request.session[ACCESS_KEY]
         token = OAuthToken.from_string(token_str)
         request.twitter_access_token = token
         userinfo = SimpleLazyObject(curry(cached_user_info,
                                           request, token))
         request.twitter_userinfo = userinfo
     if REQUEST_KEY in request.session:
         token_str = request.session[REQUEST_KEY]
         request.twitter_request_token = OAuthToken.from_string(token_str)
Example #2
0
 def process_request(self, request):
     """Import the Twitter token from the Session into the Request."""
     request.twitter_access_token = None
     request.twitter_request_token = None
     request.twitter_userinfo = None
     if ACCESS_KEY in request.session:
         token_str = request.session[ACCESS_KEY]
         token = OAuthToken.from_string(token_str)
         request.twitter_access_token = token
         userinfo = SimpleLazyObject(curry(cached_user_info, request,
                                           token))
         request.twitter_userinfo = userinfo
     if REQUEST_KEY in request.session:
         token_str = request.session[REQUEST_KEY]
         request.twitter_request_token = OAuthToken.from_string(token_str)
Example #3
0
def dropbox_client():
    access_token_file = os.path.join(os.environ["HOME"],
                                     ".dropbox-tools-access-token")
    sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)

    try:
        with open(access_token_file) as f:
            access_token = OAuthToken.from_string(f.read())
        sess.set_token(access_token.key, access_token.secret)

    except (IOError, EOFError, KeyError):
        request_token = sess.obtain_request_token()
        url = sess.build_authorize_url(request_token)
        print "Please visit\n\n    %s\n\nand press the 'Allow' button, then hit 'Enter' here." % url
        raw_input()

        # This will fail if the user didn't visit the above URL and hit 'Allow'
        access_token = sess.obtain_access_token(request_token)
        # dropbox access tokens don't have serialisation methods on them,
        my_token = OAuthToken(access_token.key, access_token.secret)
        with open(access_token_file, "w") as f:
            f.write(my_token.to_string())

    conn = client.DropboxClient(sess)
    print "linked account:", conn.account_info()["display_name"]

    return conn
Example #4
0
	def fetch_url(self, url, token, **kwargs):
		from StringIO import StringIO
		
		token = OAuthToken.from_string(str(token))
		consumer = self.get_consumer()
		connection = self.get_connection(False)
		
		request = OAuthRequest.from_consumer_and_token(
			consumer, token = token, http_method = 'GET',
			http_url = url, parameters = kwargs
		)
		
		request.sign_request(self.signature_method, consumer, token)
		url = request.to_url()
		start = 'http://%s' % self.server
		
		if url.startswith(start):
			url = url[len(start):]
		
		start = 'https://%s' % self.server
		if url.startswith(start):
			url = url[len(start):]
		
		connection.request(request.http_method, url, '', request.to_header())
		resp = connection.getresponse().read()
		return StringIO(resp)
Example #5
0
def get_dropbox(request, sess = None):
    if not sess:
        _keys = settings.DROPBOX_SETTINGS
        sess = session.DropboxSession(_keys['app_key'], _keys['app_secret'],_keys['type'])
    token = request.user.django_dropbox.dropbox_token
    sess.token =  OAuthToken.from_string(token)
    return client.DropboxClient(sess)
    def dropbox_auth_callback(self, site):
        """
        Handle the server callback after user has granted access.
        This callback contains oauth_token and oauth_verifier. The oauth verifier is
        currently not used by dropbox?
        """
        # First get the token we stored with the user
        cookie = self.request.cookies["token"]
        assert cookie, "No cookie!"
        token = OAuthToken.from_string(cookie)
        self.response.headers["Set-Cookie"] = "token="  # erase the auth token

        # Then, get the verifier from the get parameters
        request_token = self.request.get("oauth_token")
        request_verifier = self.request.get("oauth_verifier")

        # Something is wrong if the tokens don't match
        if not request_token == token.key:
            logging.error(
                "AuthHandler.dropbox_oauth_callback: request (%s) and cookie (%s) tokens do not match"
                % (request_token, token.key)
            )

        # Now, get an access token to store for future use
        logging.debug("AuthHandler.dropbox_oauth_callback. oauth_verifier: %s" % request_verifier)
        access_token = models.Site.dropbox_auth.obtain_access_token(token, "")
        logging.debug("AuthHandler.dropbox_oauth_callback. Obtained access_token: %s" % access_token.to_string())

        # Save the access token for later use
        site = models.Site.get_or_insert_current_site()
        site.dropbox_access_token = access_token.to_string()
        site.put()
        self.redirect(self.returnurl)
Example #7
0
def exchange_request_token(request_token):
    consumer = OAuthConsumer(settings.ORCHARD_KEY, settings.ORCHAR_SECRET)
    oauth_request = OAuthRequest.from_consumer_and_token(
        consumer, request_token, http_url=ACCESS_TOKEN_URL)

    return OAuthToken.from_string(
        _make_request(consumer, oauth_request, request_token))
Example #8
0
def dropbox_client():
    access_token_file = os.path.join(os.environ["HOME"], ".dropbox-tools-access-token")
    sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)

    try:
        with open(access_token_file) as f:
            access_token = OAuthToken.from_string(f.read())
        sess.set_token(access_token.key, access_token.secret)

    except (IOError, EOFError, KeyError):
        request_token = sess.obtain_request_token()
        url = sess.build_authorize_url(request_token)
        print "Please visit\n\n    %s\n\nand press the 'Allow' button, then hit 'Enter' here."%url
        raw_input()

        # This will fail if the user didn't visit the above URL and hit 'Allow'
        access_token = sess.obtain_access_token(request_token)
        # dropbox access tokens don't have serialisation methods on them,
        my_token = OAuthToken(access_token.key, access_token.secret)
        with open(access_token_file, "w") as f:
            f.write(my_token.to_string())

    conn = client.DropboxClient(sess)
    print "linked account:", conn.account_info()["display_name"]

    return conn
Example #9
0
def get_client(user, sess=None):
    if not sess:
        _keys = settings.DROPBOX_SETTINGS
        sess = session.DropboxSession(_keys['app_key'], _keys['app_secret'],
                                      _keys['type'])
    token = user.django_dropbox.dropbox_token
    sess.token = OAuthToken.from_string(token)
    return client.DropboxClient(sess)
Example #10
0
 def _makeURL(result):
     token = OAuthToken.from_string(result)
     # Store the token by key so we can find it when the callback comes.
     oauthTokenDict[token.key] = token
     request = OAuthRequest.from_token_and_callback(
         token=token, http_url=conf.authorization_url)
     url = request.to_url()
     log.msg('Browser OAuth redirect URL = %r' % url)
     return url
Example #11
0
 def get_request_token(self):
     oa_req = OAuthRequest.from_consumer_and_token(
         self.consumer, http_url=self.request_token_url)
     oa_req.sign_request(self.signature_method, self.consumer, None)
     req = self.http.get_url(self.request_token_url,
                             headers=oa_req.to_header())
     if not str(req.status).startswith('2'):
         self.analyze_error(req)
     return OAuthToken.from_string(req.data)
Example #12
0
    def __init__(self, domain_name=None):
        BaseSpider.__init__(self, domain_name)

        consumer_key = config.get('yammer', 'consumer_key')
        consumer_secret = config.get('yammer', 'consumer_secret')
        app_token = config.get('yammer', 'app_token')

        self.consumer = OAuthConsumer(consumer_key, consumer_secret)
        self.signature = OAuthSignatureMethod_PLAINTEXT()
        self.token = OAuthToken.from_string(app_token)
Example #13
0
    def __init__(self, domain_name=None):
        BaseSpider.__init__(self, domain_name)

        consumer_key    = config.get('yammer', 'consumer_key')
        consumer_secret = config.get('yammer', 'consumer_secret')
        app_token       = config.get('yammer', 'app_token')

        self.consumer  = OAuthConsumer(consumer_key, consumer_secret)
        self.signature = OAuthSignatureMethod_PLAINTEXT()
        self.token     = OAuthToken.from_string(app_token)
Example #14
0
 def get_request_token(self):
     oa_req = OAuthRequest.from_consumer_and_token(
         self.consumer,
         http_url=self.request_token_url)
     oa_req.sign_request(self.signature_method,
                               self.consumer,
                               None)
     req = self.http.get_url(self.request_token_url, headers = oa_req.to_header())
     if not str(req.status).startswith('2'):
         self.analyze_error(req)
     return OAuthToken.from_string(req.data)
Example #15
0
def auth(request, site):
	creds = OAUTH_CREDENTIALS.get(site.upper())
	if not creds:
		raise Http404('Site %s not found' % site)
	
	urls = creds.get('URLS', {})
	
	if 'DIALOG' in urls:
		request.session['preauth_url'] = request.META.get('HTTP_REFERER')
		return HttpResponseRedirect(urls['DIALOG'])
	
	ssl = creds.get('SSL', False)
	server = creds.get('SERVER', '%s.com' % site.lower())
	klass = ssl and HTTPSConnection or HTTPConnection
	
	request.session['preauth_url'] = request.META.get('HTTP_REFERER')
	
	consumer = OAuthConsumer(
		str(creds['CONSUMER_KEY']),
		str(creds['CONSUMER_SECRET'])
	)
	
	oauth_request = OAuthRequest.from_consumer_and_token(
		consumer, http_url = urls.get('REQUEST_TOKEN')
	)
	
	oauth_request.sign_request(SIGNATURE_METHOD(), consumer, None)
	url = oauth_request.to_url()
	
	connection = klass(server)
	connection.request(oauth_request.http_method, url)
	response = connection.getresponse()
	resp = response.read()
	
	token = OAuthToken.from_string(resp)
	request.session['unauth_token'] = token
	
	auth_url = urls.get('AUTHORISATION')
	if isinstance(auth_url, (list, tuple)):
		params = auth_url[1]
		auth_url = auth_url[0]
	else:
		params = {}
	
	oauth_request = OAuthRequest.from_consumer_and_token(
		consumer, token = token,
		http_url = auth_url, parameters = params
	)
	
	oauth_request.sign_request(SIGNATURE_METHOD(), consumer, token)
	return HttpResponseRedirect(
		oauth_request.to_url()
	)
Example #16
0
def callback_view(request):
    if request.GET.has_key('bounceback'):
        request.session['bounceback'] = request.GET['bounceback']

    if request.GET.has_key("oauth_token_secret"):
        oauth_token = OAuthToken.from_string("oauth_token_secret=%s&oauth_token=%s" % (request.GET['oauth_token_secret'], request.GET['oauth_token']))
        api = TroveAPI(TROVE['KEY'], TROVE['SECRET'], TROVE['CONTENT_REQUESTED'], oauth_token)
    elif request.session.has_key('request_token'):
        api = TroveAPI(TROVE['KEY'], TROVE['SECRET'], TROVE['CONTENT_REQUESTED'])
        oauth_token = api.get_access_token(request.session['request_token']) 
        del request.session['request_token']
    else: 
        return redirect('trove-login')

    try:
        at = TroveAccessToken.objects.get(oauth_token_as_string=oauth_token.__str__())
    except TroveAccessToken.DoesNotExist:
        # we have to create one!  -- although this does run into issues with users having different access tokens
        user_info = api.get_user_info() 
        try:
            u = User.objects.get(username=user_info['trove_internal_id'])
        except User.DoesNotExist:            
            u = User() 
            u.username = user_info['trove_internal_id']
            try:
                u.first_name = user_info['first_name']
            except:
                pass
            try:
                u.last_name = user_info['last_name']
            except:
                pass
            u.set_unusable_password()
            u.email = ""
            u.is_active = True
            u.save()
        at = TroveAccessToken()
        at.user = u
        at.oauth_token_as_string = oauth_token.__str__()
        at.save()

        
    user = authenticate(access_token=oauth_token.__str__())
    
    if user is not None:
        if user.is_active:
            login(request, user)
            return __bounceback__(request)
        else:        
            return redirect('trove-login')
    else:        
        return redirect('trove-login')
Example #17
0
def exchange_pin_for_access_token(pin, request_token):

    parameters=dict(oauth_verifier=pin)
    oauth_request = OAuthRequest.from_consumer_and_token(
        consumer, request_token, http_method="POST", http_url=ACCESS_TOKEN_URL,
        parameters=parameters)
    oauth_request.sign_request(HMAC(), consumer, request_token)
    headers = oauth_request.to_header()

    client = Http()
    response, body = client.request(ACCESS_TOKEN_URL, "POST", headers=headers)
    token = OAuthToken.from_string(body)
    return token, body
Example #18
0
def get_request_token():

    oauth_request = OAuthRequest.from_consumer_and_token(
        consumer, http_method="POST", http_url=REQUEST_TOKEN_URL,
        callback="oob")

    oauth_request.sign_request(HMAC(), consumer, "")
    headers = oauth_request.to_header()

    client = Http()
    response, body = client.request(REQUEST_TOKEN_URL, "POST", headers=headers)
    token = OAuthToken.from_string(body)
    return token
Example #19
0
 def _storeAccessToken(self, result, request):
     accessToken = OAuthToken.from_string(result)
     log.msg('Got access token: %s' % accessToken)
     conf = self._conf
     consumer = OAuthConsumer(conf.consumer_key, conf.consumer_secret)
     oaRequest = OAuthRequest.from_consumer_and_token(
         consumer, token=accessToken,
         http_url=conf.verify_credentials_url)
     oaRequest.sign_request(
         OAuthSignatureMethod_HMAC_SHA1(), consumer, accessToken)
     log.msg('Verifying credentials.')
     d = client.getPage(oaRequest.to_url())
     d.addCallback(self._storeUser, accessToken, request)
     d.addErrback(log.err)
     return d
Example #20
0
def get_request_token():

    oauth_request = OAuthRequest.from_consumer_and_token(
        consumer,
        http_method="POST",
        http_url=REQUEST_TOKEN_URL,
        callback="oob")

    oauth_request.sign_request(HMAC(), consumer, "")
    headers = oauth_request.to_header()

    client = Http()
    response, body = client.request(REQUEST_TOKEN_URL, "POST", headers=headers)
    token = OAuthToken.from_string(body)
    return token
Example #21
0
	def swap_tokens(self, *args, **kwargs):
		if self.token_required:
			consumer, token = args
			token = OAuthToken.from_string(token)
			
			request = OAuthRequest.from_consumer_and_token(
				consumer, token = token,
				http_url = self.access_token_url,
				parameters = kwargs
			)
			
			request.sign_request(self.signature_method, consumer, token)
			url = request.to_url()
			
			if url.startswith('http://'):
				url = url[7:]
			elif url.startswith('https://'):
				url = url[8:]
			
			if url.startswith(self.server):
				url = url[len(self.server):]
			
			q = url.find('?')
			if q > 01:
				qs = url[q + 1:]
				url = url[:q]
			else:
				qs = ''
			
			connection = self.get_connection(False)
			connection.request(request.http_method, url, qs, request.to_header())
			
			resp = connection.getresponse().read()
			return OAuthToken.from_string(resp)
		else:
			raise NotImplementedError('Method not implemented for non-standard OAuth provider.')
Example #22
0
def callback(request):
    sess = get_session()

    dropbox_uid = request.GET.get('uid', None)
    oauth_token = request.GET.get('oauth_token', None)

    request_token = REDIS.get('rt:%s' % oauth_token)
    request_token = OAuthToken.from_string(request_token)

    access_token = sess.obtain_access_token(request_token)
    REDIS.set('ac:%s' % dropbox_uid, access_token.to_string())

    request.session['uid'] = dropbox_uid

    return redirect('home')
def twitter_done(request):
    request_token = request.session.get('request_token', None)
    verifier = request.GET.get('oauth_verifier', None)
    denied = request.GET.get('denied', None)
    # If we've been denied, put them back to the signin page
    # They probably meant to sign in with facebook >:D
    if denied:
        return HttpResponseRedirect(reverse("auth_login"))

    # If there is no request_token for session,
    # Means we didn't redirect user to twitter
    if not request_token:
        # Redirect the user to the login page,
        return HttpResponseRedirect(reverse("auth_login"))

    token = OAuthToken.from_string(request_token)

    # If the token from session and token from twitter does not match
    #   means something bad happened to tokens
    if token.key != request.GET.get('oauth_token', 'no-token'):
        del request.session['request_token']
        # Redirect the user to the login page
        return HttpResponseRedirect(reverse("auth_login"))

    twitter = oauthtwitter.OAuthApi(settings.TWITTER_CONSUMER_KEY,
                                    settings.TWITTER_CONSUMER_SECRET, token)
    access_token = twitter.getAccessToken()

    request.session['access_token'] = access_token.to_string()
    user = authenticate(request=request, twitter_access_token=access_token)

    # if user is authenticated then login user
    if user:
        login(request, user)
    else:
        # We were not able to authenticate user
        # Redirect to login page
        del request.session['access_token']
        del request.session['request_token']
        return HttpResponseRedirect(reverse('auth_login'))

    # authentication was successful, use is now logged in
    referer = request.session.get('request_referer')
    next_url = str(getattr(settings, "LOGIN_REDIRECT_URL", "/"))
    if referer:
        next_url = urlparse.urljoin(referer, next_url)
        del request.session['request_referer']
    return HttpResponseRedirect(next_url)
def twitter_done(request):
    request_token = request.session.get('request_token', None)
    verifier = request.GET.get('oauth_verifier', None)
    denied = request.GET.get('denied', None)
    # If we've been denied, put them back to the signin page
    # They probably meant to sign in with facebook >:D
    if denied:
        return HttpResponseRedirect(reverse("auth_login"))
 
    # If there is no request_token for session,
    # Means we didn't redirect user to twitter
    if not request_token:
        # Redirect the user to the login page,
        return HttpResponseRedirect(reverse("auth_login"))
    
    token = OAuthToken.from_string(request_token)
    
    # If the token from session and token from twitter does not match
    #   means something bad happened to tokens
    if token.key != request.GET.get('oauth_token', 'no-token'):
        del request.session['request_token']
        # Redirect the user to the login page
        return HttpResponseRedirect(reverse("auth_login"))
    
    twitter = oauthtwitter.OAuthApi(settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET, token)  
    access_token = twitter.getAccessToken()
    
    request.session['access_token'] = access_token.to_string()
    user = authenticate(request=request, twitter_access_token=access_token)
    
    # if user is authenticated then login user
    if user:
        login(request, user)
    else:
        # We were not able to authenticate user
        # Redirect to login page
        del request.session['access_token']
        del request.session['request_token']
        return HttpResponseRedirect(reverse('auth_login'))
 
    # authentication was successful, use is now logged in
    referer = request.session.get('request_referer')
    next_url = str(getattr(settings, "LOGIN_REDIRECT_URL", "/"))
    if referer:
        next_url = urlparse.urljoin(referer, next_url)
        del request.session['request_referer']
    return HttpResponseRedirect(next_url)
        
Example #25
0
def requestToken(omb):
    current_site = Site.objects.get_current()
    url = urlparse.urlparse(omb[OAUTH_REQUEST].uris[0].uri)
    params = {}
    if url[4] != '':
        # We need to copy over the query string params for sites like laconica
        params.update(dict([part.split('=') for part in url[4].split('&')]))
    params['omb_version'] = OMB_VERSION_01
    params['omb_listener'] = omb[OAUTH_REQUEST].localid.text
    consumer = OAuthConsumer(current_site.domain, "")
    req = OAuthRequest().from_consumer_and_token(consumer, http_url=url.geturl(), parameters=params, http_method="POST")
    req.sign_request(OAuthSignatureMethod_HMAC_SHA1(), consumer, None)
    f = urllib.urlopen(url.geturl(), req.to_postdata())
    data = f.read()
    requestToken = OAuthToken.from_string(data)
    return requestToken
Example #26
0
def requestAccessToken(omb_session, oauth_request):
    current_site = Site.objects.get_current()
    token = OAuthToken(omb_session["token"], omb_session["secret"])
    url = urlparse.urlparse(omb_session["access_token_url"])
    params = {}
    if url[4] != '':
        # We need to copy over the query string params for sites like laconica
        params.update(dict([part.split('=') for part in url[4].split('&')]))
    params['omb_version'] = OMB_VERSION_01
    consumer = OAuthConsumer(current_site.domain, "")
    req = OAuthRequest().from_consumer_and_token(consumer, token=token, http_url=url.geturl(), parameters=params, http_method="POST")
    req.sign_request(OAuthSignatureMethod_HMAC_SHA1(), consumer, token)
    f = urllib.urlopen(url.geturl(), req.to_postdata())
    data = f.read()
    accessToken = OAuthToken.from_string(data)
    return accessToken
Example #27
0
def exchange_pin_for_access_token(pin, request_token):

    parameters = dict(oauth_verifier=pin)
    oauth_request = OAuthRequest.from_consumer_and_token(
        consumer,
        request_token,
        http_method="POST",
        http_url=ACCESS_TOKEN_URL,
        parameters=parameters)
    oauth_request.sign_request(HMAC(), consumer, request_token)
    headers = oauth_request.to_header()

    client = Http()
    response, body = client.request(ACCESS_TOKEN_URL, "POST", headers=headers)
    token = OAuthToken.from_string(body)
    return token, body
Example #28
0
def twitter_notify_now_playing(track, next_track):
    if TWITTER_CONSUMER_KEY and TWITTER_CONSUMER_SECRET:
        import oauthtwitter
        from oauth.oauth import OAuthToken
        api = oauthtwitter.OAuthApi(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET,\
            OAuthToken.from_string(TWITTER_TOKEN))

        status = 'Now playing "%s" (%d:%02d)' % (track.name[:30], track.length/60, track.length % 60)
        if track.uploader and track.uploader.twitter:
            status += ' by @%s' % track.uploader.twitter
        if next_track:
            status += ', next one "%s" (%d:%02d)'\
                % (next_track.name[:30], next_track.length/60, next_track.length % 60)
            if next_track.uploader and next_track.uploader.twitter:
                status += ' by @%s' % next_track.uploader.twitter
                
        api.PostUpdate(status)
Example #29
0
    def begin(self, request, data):
        """
        Try to get Request Token from OAuth Provider and 
        redirect user to provider's site for approval.
        """
        consumer = OAuthConsumer(self.CONSUMER_KEY, self.CONSUMER_SECRET)
        signature_method = OAuthSignatureMethod_HMAC_SHA1()
        callback = request.build_absolute_uri(reverse('publicauth-complete', args=[self.provider]))
        oauth_req = OAuthRequest.from_consumer_and_token(consumer, callback=callback, http_url=self.REQUEST_TOKEN_URL)
        oauth_req.sign_request(signature_method, consumer, None)
        response = urllib.urlopen(oauth_req.to_url()).read()

        token = OAuthToken.from_string(response) # instatiate token

        oauth_req = OAuthRequest.from_consumer_and_token(consumer, token, http_url=self.AUTHORIZE_URL)
        oauth_req.sign_request(signature_method, consumer, token)
        raise Redirect(oauth_req.to_url())
Example #30
0
	def get_unauthorised_request_token(self, consumer, connection):
		from django.contrib.sites.models import Site
		from django.core.urlresolvers import reverse
		
		request = OAuthRequest.from_consumer_and_token(
			consumer, http_url = self.request_token_url,
			parameters = {
				'oauth_callback': 'http://%s%s' % (
					Site.objects.get_current().domain, reverse('megaphone_callback')
				)
			}
		)
		
		request.sign_request(self.signature_method, consumer, None)
		resp = self.fetch_response(request, connection)
		token = OAuthToken.from_string(resp)
		return token
Example #31
0
 def dropbox_auth_callback(self):
     # now use the authorized token to grab an access token
     token = OAuthToken.from_string(self.request.cookies['token'])
     access_token = dropbox_auth.obtain_access_token(token, "")
     self.response.headers['Set-Cookie'] = 'token=' # erase the auth token
     
     # lookup your account info
     client = dropbox_client(access_token)
     account_info = client.account_info().data
     
     template_params = {
         'access_token':access_token.to_string(),
         'email':account_info['email'],
     }
     
     # prompt you to fill in the account credentials for our system
     path = os.path.join(os.path.dirname(__file__), 'password.html')
     self.response.out.write(template.render(path, template_params))
Example #32
0
    def auth_complete(self, *args, **kwargs):
        """Returns user, might be logged in"""
        name = self.AUTH_BACKEND.name + "unauthorized_token_name"
        unauthed_token = self.request.session.get(name)
        if not unauthed_token:
            raise ValueError("Missing unauthorized token")

        token = OAuthToken.from_string(unauthed_token)
        if token.key != self.data.get("oauth_token", "no-token"):
            raise ValueError("Incorrect tokens")

        access_token = self.access_token(token)
        data = self.user_data(access_token)
        if data is not None:
            data["access_token"] = access_token.to_string()

        kwargs.update({"response": data, self.AUTH_BACKEND.name: True})
        return authenticate(*args, **kwargs)
Example #33
0
    def auth_complete(self, *args, **kwargs):
        """Returns user, might be logged in"""
        name = self.AUTH_BACKEND.name + 'unauthorized_token_name'
        unauthed_token = self.request.session.get(name)
        if not unauthed_token:
            raise ValueError('Missing unauthorized token')

        token = OAuthToken.from_string(unauthed_token)
        if token.key != self.request.GET.get('oauth_token', 'no-token'):
            raise ValueError('Incorrect tokens')

        access_token = self.access_token(token)
        data = self.user_data(access_token)
        if data is not None:
            data['access_token'] = access_token.to_string()

        kwargs.update({'response': data, self.AUTH_BACKEND.name: True})
        return authenticate(*args, **kwargs)
Example #34
0
File: app.py Project: skopp/dropdav
 def handle_request(self, environ, request, response):
     method = environ['REQUEST_METHOD']
     
     if True:# or (method == 'GET' or method == 'POST') and request.path == '/':
         return self.handle_main(environ, request, response)
     
     # Check authentication
     (email, password) = self.get_credentials(request)
     
     if email:
         user = DropboxUser.find_by_email(email)
         
         if user and user.is_password_valid(password):
             self._handler.client = dropbox_client(OAuthToken.from_string(user.access_token))
             return super(DropboxWebDAVApplication,self).handle_request(environ,request,response)
         else:
             return self.request_authentication(response)
     else:
         return self.request_authentication(response)
Example #35
0
    def authorize(self, token):
        """Authorize a user with netflix and return a user id and an
        access token."""
        oa_req = OAuthRequest.from_consumer_and_token(
            self.consumer,
            token=token,
            parameters={'application_name': self.application_name}
            if self.application_name else None,
            http_url=self.access_token_url)

        oa_req.sign_request(self.signature_method, self.consumer, token)
        req = self.http.get_url(oa_req.to_url())
        if not str(req.status).startswith('2'):
            self.analyze_error(req)
        res = req.data
        logging.debug(res)
        id = cgi.parse_qs(res)['user_id'][0]

        return id, OAuthToken.from_string(res)
Example #36
0
def start_auth(request, fail_redirect='/account/other_services/'):
    consumer = OAuthConsumer(settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET)
    # Request the OAuth Token
    req = OAuthRequest().from_consumer_and_token(consumer, http_url=TWITTER_REQUEST_TOKEN_URL,
        parameters={}, http_method="POST")
    req.sign_request(OAuthSignatureMethod_HMAC_SHA1(), consumer, None)
    try:
        res = urllib.urlopen(TWITTER_REQUEST_TOKEN_URL, req.to_postdata())
        requestToken = OAuthToken.from_string(res.read())
        # Authorise the OAuth Token
        oauth_request = OAuthRequest().from_consumer_and_token(consumer, http_url=TWITTER_AUTHORIZE_URL, 
            parameters={}, http_method="GET", token=requestToken)
        oauth_request.sign_request(OAuthSignatureMethod_HMAC_SHA1(), consumer, requestToken)
        return HttpResponseRedirect(oauth_request.to_url())
    except IOError:
        request.user.message_set.create(
            message=ugettext(u"Twitter authorization failed.")
        )
        return HttpResponseRedirect(fail_redirect)
Example #37
0
 def handle_request(self, environ, request, response):
     method = environ['REQUEST_METHOD']
     
     if (method == 'GET' or method == 'POST') and request.path == '/':
         return self.handle_main(environ, request, response)
     
     # Check authentication
     (email, password) = self.get_credentials(request)
     
     if email:
         user = DropboxUser.find_by_email(email)
         
         if user and user.is_password_valid(password):
             self._handler.client = dropbox_client(OAuthToken.from_string(user.access_token))
             return super(DropboxWebDAVApplication,self).handle_request(environ,request,response)
         else:
             return self.request_authentication(response)
     else:
         return self.request_authentication(response)
Example #38
0
    def get(self, token):
        dba = auth.Authenticator(config)
        req_token = OAuthToken.from_string(base64.b64decode(urllib.unquote(token)))
        uid = self.request.get('uid')
        self.response.headers.add_header('Set-Cookie', 'uid=%s; path=/' % uid)
        
        token = dba.obtain_access_token(req_token, '')
        
        db_client = client.DropboxClient(config['server'], config['content_server'], config['port'], dba, token)
        account = json.loads(db_client.account_info().body)
        
        user = DropboxUser.get_by_uid(uid)
        user.oauth_token = token.key
        user.oauth_token_secret = token.secret
        user.email = account['email']
        user.put()
            
        taskqueue.add(url='/tasks/poll', params={'uid': uid})

        self.redirect('/')
Example #39
0
    def begin(self, request, data):
        """
        Try to get Request Token from OAuth Provider and 
        redirect user to provider's site for approval.
        """
        consumer = OAuthConsumer(self.CONSUMER_KEY, self.CONSUMER_SECRET)
        signature_method = OAuthSignatureMethod_HMAC_SHA1()
        callback = request.build_absolute_uri(
            reverse('publicauth-complete', args=[self.provider]))
        oauth_req = OAuthRequest.from_consumer_and_token(
            consumer, callback=callback, http_url=self.REQUEST_TOKEN_URL)
        oauth_req.sign_request(signature_method, consumer, None)
        response = urllib.urlopen(oauth_req.to_url()).read()

        token = OAuthToken.from_string(response)  # instatiate token

        oauth_req = OAuthRequest.from_consumer_and_token(
            consumer, token, http_url=self.AUTHORIZE_URL)
        oauth_req.sign_request(signature_method, consumer, token)
        raise Redirect(oauth_req.to_url())
Example #40
0
	def post_url(self, url, token, *args, **kwargs):
		from StringIO import StringIO
		
		token = OAuthToken.from_string(str(token))
		consumer = self.get_consumer()
		connection = self.get_connection(False)
		
		request = OAuthRequest.from_consumer_and_token(
			consumer, token = token, http_method = 'POST',
			http_url = url, parameters = kwargs
		)
		
		request.sign_request(self.signature_method, consumer, token)
		connection.request(
			request.http_method,
			request.to_url(),
			''.join(args)
		)

		resp = connection.getresponse().read()
		return StringIO(resp)
Example #41
0
    def set_dropdav_password(self):
        access_token = OAuthToken.from_string(self.request.POST.get('access_token'))
        password = self.request.POST.get('password')
        
        # lookup your account info again to confirm
        client = dropbox_client(access_token)
        account_info = client.account_info().data
        email = account_info['email']
        
        user = DropboxUser.find_by_email(email)
        
        if not user:
            user = DropboxUser(email=email)
                    
        # create or update your user entry in our system
        user.access_token = access_token.to_string()
        user.set_password(password)
        user.put()

        # prompt you to fill in the account credentials for our system
        path = os.path.join(os.path.dirname(__file__), 'success.html')
        self.response.out.write(template.render(path, {'email':email,'server':site_root()}))
Example #42
0
def newtweet(request):
    if request.user.is_authenticated():
        user_meta=UserMeta.objects.filter(user=request.user)
        usermeta={}
        for u in user_meta:
            usermeta[u.key]=u.value
        
        status=self.request.get('status')
        if len(status) > 140:
            status=status[0:140]
        
        twitter_access_token_string=UserMeta.objects.get(user=request.user,key="twitter_access_token_string").value
        access_token=OAuthToken.from_string(twitter_access_token_string)
        twitter=OAuthApi(CONSUMER_KEY,CONSUMER_SECRET,access_token)
        try:
            twitter.PostUpdate(status.encode('utf-8'))
        except:
            logging.error('Failed to tweet: '+status)
            
        return HttpResponseRedirect("/home")
    else:
        return HttpResponseRedirect("/login")
Example #43
0
def messages(request):
    """docstring for messages"""
    if request.user.is_authenticated():
        user_meta=UserMeta.objects.filter(user=request.user)
        usermeta={}
        for u in user_meta:
            usermeta[u.key]=u.value
        
        twitter_access_token_string=UserMeta.objects.get(user=request.user,key="twitter_access_token_string").value
        access_token=OAuthToken.from_string(twitter_access_token_string)
        twitter=OAuthApi(CONSUMER_KEY,CONSUMER_SECRET,access_token)
        statuses=twitter.GetDirectMessages()
        i=0
        for status in statuses:
            # statuses[i].source=statuses[i].source.replace('<a', '<a class="dark"')
            statuses[i].datetime = datetime.datetime.fromtimestamp(time.mktime(time.strptime(status.created_at, '%a %b %d %H:%M:%S +0000 %Y')))
            statuses[i].text = twitter.ConvertMentions(status.text)
            i=i+1
        
        return render_to_response('desktop/twitter_messages.html',{'statuses':statuses,'usermeta':usermeta})
    else:
        return HttpResponseRedirect("/login")
Example #44
0
def callback(key, secret, request):
    token = request.session.get('unauth_token')
    if not token:
        raise Exception('No unauthorised token')

    if token.key != request.GET.get('oauth_token', None):
        raise Exception('Token does not match')

    verifier = request.GET.get('oauth_verifier')
    consumer = OAuthConsumer(str(key), str(secret))

    oauth_request = OAuthRequest.from_consumer_and_token(
        consumer,
        token=token,
        http_url='https://twitter.com/oauth/access_token',
        parameters={'oauth_verifier': verifier})

    oauth_request.sign_request(SIGNATURE_METHOD(), consumer, token)
    url = oauth_request.to_url()

    access_token = OAuthToken.from_string(urlopen(url).read())

    return access_token
Example #45
0
    def dropbox_auth_callback(self, site):
        """
        Handle the server callback after user has granted access.
        This callback contains oauth_token and oauth_verifier. The oauth verifier is
        currently not used by dropbox?
        """
        # First get the token we stored with the user
        cookie = self.request.cookies['token']
        assert cookie, 'No cookie!'
        token = OAuthToken.from_string(cookie)
        self.response.headers['Set-Cookie'] = 'token='  # erase the auth token

        # Then, get the verifier from the get parameters
        request_token = self.request.get('oauth_token')
        request_verifier = self.request.get('oauth_verifier')

        # Something is wrong if the tokens don't match
        if not request_token == token.key:
            logging.error(
                'AuthHandler.dropbox_oauth_callback: request (%s) and cookie (%s) tokens do not match'
                % (request_token, token.key))

        # Now, get an access token to store for future use
        logging.debug(
            'AuthHandler.dropbox_oauth_callback. oauth_verifier: %s' %
            request_verifier)
        access_token = models.Site.dropbox_auth.obtain_access_token(token, "")
        logging.debug(
            'AuthHandler.dropbox_oauth_callback. Obtained access_token: %s' %
            access_token.to_string())

        # Save the access token for later use
        site = models.Site.get_or_insert_current_site()
        site.dropbox_access_token = access_token.to_string()
        site.put()
        self.redirect(self.returnurl)
Example #46
0
    def get(self, token):
        dba = auth.Authenticator(config)
        req_token = OAuthToken.from_string(
            base64.b64decode(urllib.unquote(token)))
        uid = self.request.get('uid')
        self.response.headers.add_header('Set-Cookie', 'uid=%s; path=/' % uid)

        token = dba.obtain_access_token(req_token, '')

        db_client = client.DropboxClient(config['server'],
                                         config['content_server'],
                                         config['port'], dba, token)
        account = json.loads(db_client.account_info().body)

        user = DropboxUser.get_by_uid(uid)
        user.oauth_token = token.key
        user.oauth_token_secret = token.secret
        user.email = account['email']
        user.put()

        if user.size is None:
            taskqueue.add(url='/tasks/poll', params={'uid': uid})

        self.redirect('/')
Example #47
0
def redirect(key, secret, request):
    consumer = OAuthConsumer(str(key), str(secret))

    oauth_request = OAuthRequest.from_consumer_and_token(
        consumer, http_url='https://twitter.com/oauth/request_token')

    oauth_request.sign_request(SIGNATURE_METHOD(), consumer, None)
    url = oauth_request.to_url()

    connection = HTTPSConnection('twitter.com')
    connection.request(oauth_request.http_method, url)
    response = connection.getresponse()
    resp = response.read()

    token = OAuthToken.from_string(resp)
    request.session['unauth_token'] = token

    auth_url = 'https://twitter.com/oauth/authorize'
    if isinstance(auth_url, (list, tuple)):
        params = auth_url[1]
        auth_url = auth_url[0]
    else:
        params = {}

    oauth_request = OAuthRequest.from_consumer_and_token(consumer,
                                                         token=token,
                                                         http_url=auth_url,
                                                         parameters=params)

    oauth_request.sign_request(SIGNATURE_METHOD(), consumer, token)

    if request.is_ajax():
        return HttpResponse('<script>document.location = \'%s\';</script>' %
                            oauth_request.to_url())
    else:
        return HttpResponseRedirect(oauth_request.to_url())
Example #48
0
            response = self._connection.getresponse()
            status = response.status

        if status == 401:
            raise YammerError("Consumer key and/or secret not accepted.")
        elif status != 200:
            raise YammerError("Request to '%s' returned HTTP code %d." %
                              (YAMMER_REQUEST_TOKEN_URL, status))

        if _use_pycurl:
            r = content.getvalue()
        else:
            r = response.read()

        try:
            token = OAuthToken.from_string(r)
        except OAuthError, m:
            raise YammerError(m.message)
        return token

    def get_authorization_url(self, token):
        """ Return URL from which a user can authorize Yammer API access for
        a given application.

        Keyword arguments:
        token -- an unauthorized OAuth request token

        """
        try:
            oauth_request = OAuthRequest.from_token_and_callback(
                token=token, http_url=YAMMER_AUTHORIZATION_URL)
Example #49
0
 def get_access_token(self):
     if self.access_token_str:
         return OAuthToken.from_string(self.access_token_str)
     return None
Example #50
0
def return_auth(request, site):
	creds = OAUTH_CREDENTIALS.get(site.upper())
	if not creds:
		raise Http404('Site %s not found' % site)
	
	urls = creds.get('URLS', {})
	ssl = creds.get('SSL', False)
	server = creds.get('SERVER', '%s.com' % site.lower())
	
	if not 'DIALOG' in urls:
		token = request.session.get('unauth_token')
		if not token:
			return HttpResponse('No unauthorised token')
	
		if token.key != request.GET.get('oauth_token', None):
			if request.session.get('preauth_url'):
				return HttpResponseRedirect(
					request.session['preauth_url']
				)
			else:
				return HttpResponse('')
	
		verifier = request.GET.get('oauth_verifier')
		consumer = OAuthConsumer(
			str(creds.get('CONSUMER_KEY')),
			str(creds.get('CONSUMER_SECRET'))
		)

		oauth_request = OAuthRequest.from_consumer_and_token(
			consumer, token = token,
			http_url = urls.get('ACCESS_TOKEN'),
			parameters = {
				'oauth_verifier': verifier
			}
		)

		oauth_request.sign_request(SIGNATURE_METHOD(), consumer, token)
		url = oauth_request.to_url()
		
		access_token = OAuthToken.from_string(
			urlopen(url).read()
		)
		
		if request.user.is_authenticated():
			try:
				token = request.user.oauth_tokens.get(
					site = site
				)
				
				token.token = access_token.key
				token.secret = access_token.secret
				token.save()
			except core.OAuthToken.DoesNotExist:
				request.user.oauth_tokens.create(
					site = site,
					token = access_token.key,
					secret = access_token.secret
				)
		else:
			return HttpResponse('')
	else:
		url = urls.get('ACCESS_TOKEN') % request.GET.get('code')
		resp = urlopen(url).read()
		d = {}
		
		for (key, value) in [i.split('=') for i in resp.split('&')]:
			if key:
				d[key] = value
		
		if request.user.is_authenticated():
			try:
				token = request.user.oauth_tokens.get(
					site = site
				)
				
				token.token = d['access_token']
				token.save()
			except core.OAuthToken.DoesNotExist:
				request.user.oauth_tokens.create(
					site = site,
					token = d['access_token']
				)
		else:
			return HttpResponse('')
	
	if request.session.get('preauth_url'):
		messages.add_message(
			request,
			messages.SUCCESS,
			u'You have been successfully connected to %s.' % creds.get(
				'VERBOSE_NAME', site.capitalize()
			)
		)
		
		return HttpResponseRedirect(
			request.session['preauth_url']
		)
	else:
		return HttpResponse('')
Example #51
0
from mocker import Mocker, ANY, MATCH

from oauth.oauth import OAuthToken

from django_oauth_twitter import (ACCESS_KEY, REQUEST_KEY, SUCCESS_URL_KEY,
                                  USERINFO_KEY)
from django_oauth_twitter.middleware import (cached_user_info,
                                             set_access_token,
                                             set_request_token)
from django_oauth_twitter.models import TwitterUser
from django_oauth_twitter.test_urls import oauthtwitter
from django_oauth_twitter.views import LazyReverse, OAuthTwitter
from django_oauth_twitter.utils import TwitterApi, get_user_info

TOKEN = OAuthToken.from_string('oauth_token=a&oauth_token_secret=b')


class MiddlewareTest(TestCase):
    def setUp(self):
        self.mocker = Mocker()

    def test_set_access_token(self):
        request = self.mocker.mock()
        request.session[ACCESS_KEY] = TOKEN.to_string()
        request.twitter_access_token = TOKEN
        with self.mocker:
            set_access_token(request, TOKEN)

    def test_set_request_token(self):
        request = self.mocker.mock()
 def unauthorized_token(self):
     request = self.oauth_request(token=None, url=self.REQUEST_TOKEN_URL)
     response = self.fetch_response(request)
     return Token.from_string(response)
Example #53
0
# 1. Copy oauth_token from callback URL after logging in with auth_url
#auth_url, auth_token = flix.get_authorization_url(callback='http://google.com/')
#print auth_url
#print auth_token
#exit()

# 2. Pass in auth tokens to receive user id for next step; Update string with real token values
#oauth_token = OAuthToken.from_string('oauth_token_secret=&oauth_token=&oauth_verifier=')
#id, token = flix.authorize(oauth_token)
#print id
#print token
#exit()

# 3. Set userid to id from last step; Update string with real token values
userid = None
token = OAuthToken.from_string('oauth_token_secret=&oauth_token=')

# Example of an authorized request
#result = flix.request('/users/%s' % userid, token=token)
#pp.pprint(vars(result))

# 4. Use to retrieve full catalog of netflix titles...This should fail (see commands-used.txt)
#result = flix.request('/catalog/titles/full')
#print result
#exit()

# Print filename for monitoring progress
print sys.argv[1]

with open(sys.argv[1]) as fd:
    title_refs = ','.join([line.strip() for line in fd.readlines()])
Example #54
0
        def when_load():
            self.protocol._verify_databases()
            self.evaljs('window.resdir = %s' % simplejson.dumps(
                (path(__file__).parent / 'res').url()))

            def success(token):
                opts = dict(username=self.username,
                            password=self.password,
                            feeds=userfeeds,
                            accountopts=accountopts or {})

                if token is not None:
                    assert hasattr(token, 'key'), repr(token)
                    opts.update(
                        oauthTokenKey=token.key,
                        oauthTokenSecret=token.secret,
                        oauthConsumerKey=twitter_auth.CONSUMER_KEY,
                        oauthConsumerSecret=twitter_auth.CONSUMER_SECRET)

                    time_correction = twitter_auth.get_time_correction()
                    if time_correction is not None:
                        opts['accountopts'].update(
                            timeCorrectionSecs=-time_correction)

                self.JSCall('initialize', **opts)

            api_server = getattr(self.protocol.account, 'api_server', None)
            if api_server is not None:
                return success(None)

            if self.oauth_token is not None:
                try:
                    token = OAuthToken.from_string(self.oauth_token)
                except Exception:
                    traceback.print_exc()
                else:
                    log.info('using token stored in account')
                    return success(token)

            def on_token(token):
                token_string = token.to_string()
                log.info('on_token received token from network: %r',
                         token_string[:5])
                self.protocol.account.update_info(oauth_token=token_string)
                success(token)

            def on_token_error(e):
                errcode = getattr(e, 'code', None)

                # if obtaining an token fails, it may be because our time is set incorrectly.
                # we can use the Date: header returned by Twitter's servers to adjust for
                # this.
                if errcode == 401:
                    server_date = getattr(e, 'hdrs', {}).get('Date', None)
                    retries_after_401 = getattr(self.protocol,
                                                'retries_after_401', 0)
                    if server_date and retries_after_401 < 1:
                        self.protocol.retries_after_401 = retries_after_401 + 1
                        log.warning('on_token_error: server date is %r',
                                    server_date)
                        server_date = parse_http_date(server_date)
                        log.warning(
                            'on_token_Error: RETRYING WITH NEW SERVER DATE %r',
                            server_date)
                        twitter_auth.set_server_timestamp(server_date)
                        return twitter_auth.get_oauth_token(
                            self.username,
                            self.password,
                            success=on_token,
                            error=on_token_error)

                state = 'autherror' if errcode == 401 else 'connfail'
                log.error('on_token_error: e.code is %r', errcode)
                log.error('  changing state to %r', state)
                self.protocol.events.state_changed(state)

            log.info('getting new oauth token from network')
            twitter_auth.get_oauth_token(self.username,
                                         self.password,
                                         success=on_token,
                                         error=on_token_error)