Example #1
0
def updateProfile(token, secret, update_profile_url, profile):
    current_site = Site.objects.get_current()
    user_profile_url = "%s%s" % (current_site.domain, reverse('profile_detail', args=[profile.user.username]))
    oauthToken = OAuthToken(token, secret)
    url = urlparse.urlparse(update_profile_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
    params['omb_listenee'] = user_profile_url
    params['omb_listenee_profile'] = user_profile_url
    params['omb_listenee_nickname'] = profile.username
    params['omb_listenee_license'] = '%s/license/' % current_site.domain # TODO link to the real license
    params['omb_listenee_fullname'] = profile.name
    params['omb_listenee_homepage'] = profile.website
    params['omb_listenee_bio'] = profile.about
    params['omb_listenee_location'] = profile.location
    #params['omb_listenee_avatar'] = TODO get the gravatar of the user
    
    consumer = OAuthConsumer(current_site.domain, "")
    req = OAuthRequest().from_consumer_and_token(consumer, token=oauthToken, http_url=url.geturl(), parameters=params, http_method="POST")
    req.sign_request(OAuthSignatureMethod_HMAC_SHA1(), consumer, oauthToken)
    f = urllib.urlopen(url.geturl(), req.to_postdata())
    data = f.read()
    # TODO log failures
Example #2
0
def requestAuthorization(token, url, listener, user):
    current_site = Site.objects.get_current()
    user_profile_url = "%s%s" % (current_site.domain, reverse('profile_detail', args=[user.username]))
    profile = user.get_profile()
    url = urlparse.urlparse(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
    params['omb_listener'] = listener
    params['omb_listenee'] = "http://%s" % user_profile_url
    params['omb_listenee_profile'] = "http://%s" % user_profile_url
    params['omb_listenee_nickname'] = user.username
    params['omb_listenee_license'] = 'http://%s/license/' % current_site.domain # TODO link to the real license
    params['omb_listenee_fullname'] = "%s %s" % (user.first_name, user.last_name)
    params['omb_listenee_homepage'] = "" # TOOD Pinax doesn't have this
    params['omb_listenee_bio'] = profile.about
    params['omb_listenee_location'] = profile.location
    params['omb_listenee_avatar'] = '' # TODO get the avatar url
    params['oauth_callback'] = 'http://%s/omb/finish_follow/' % current_site.domain
    consumer = OAuthConsumer(current_site.domain, "")
    oauth_request = OAuthRequest().from_consumer_and_token(consumer, http_url=url.geturl(), parameters=params, http_method="GET", token=token)
    oauth_request.sign_request(OAuthSignatureMethod_HMAC_SHA1(), consumer, token)
    return oauth_request
Example #3
0
def initialize_server_request(request):
    """Shortcut for initialization."""
    # Django converts Authorization header in HTTP_AUTHORIZATION
    # Warning: it doesn't happen in tests but it's useful, do not remove!
    
    # Check to see if it's a dict if it's being called from the LRS app. The LRS app parses everything in a dict first
    # then will call this in Authorization with the request dict.
    if type(request) == dict:
        auth_header = {}
        if 'Authorization' in request:
            auth_header = {'Authorization': request['Authorization']}
        elif 'HTTP_AUTHORIZATION' in request:
            auth_header =  {'Authorization': request['HTTP_AUTHORIZATION']}

        parameters = {}
        # TODO-WHAT TO DO WITH THIS?
        # if request['method'] == "POST":
        #     parameters = ast.literal_eval(request['body'])       

        oauth_request = OAuthRequest.from_request(request['method'], 
                                                  request['absolute_uri'], 
                                                  headers=auth_header,
                                                  parameters=parameters,
                                                  query_string=request['query_string'])
    else:
        auth_header = {}
        if 'Authorization' in request.META:
            auth_header = {'Authorization': request.META['Authorization']}
        elif 'HTTP_AUTHORIZATION' in request.META:
            auth_header =  {'Authorization': request.META['HTTP_AUTHORIZATION']}
       
        # Don't include extra parameters when request.method is POST and 
        # request.MIME['CONTENT_TYPE'] is "application/x-www-form-urlencoded" 
        # (See http://oauth.net/core/1.0a/#consumer_req_param).
        # But there is an issue with Django's test Client and custom content types
        # so an ugly test is made here, if you find a better solution...
        parameters = {}
        
        if request.method == "POST" and \
            (request.META.get('CONTENT_TYPE') == "application/x-www-form-urlencoded" \
                or request.META.get('SERVER_NAME') == 'testserver'):
            parameters = dict(request.REQUEST.items())
        # pdb.set_trace() 
        oauth_request = OAuthRequest.from_request(request.method, 
                                                  request.build_absolute_uri(), 
                                                  headers=auth_header,
                                                  parameters=parameters,
                                                  query_string=request.META.get('QUERY_STRING', ''))
    if oauth_request:
        oauth_server = OAuthServer(DataStore(oauth_request))
        if 'plaintext' in OAUTH_SIGNATURE_METHODS:
            oauth_server.add_signature_method(OAuthSignatureMethod_PLAINTEXT())
        if 'hmac-sha1' in OAUTH_SIGNATURE_METHODS:
            oauth_server.add_signature_method(OAuthSignatureMethod_HMAC_SHA1())
    else:
        oauth_server = None
    return oauth_server, oauth_request
Example #4
0
def cookie_for_token(t):
    app=t.share.with_app
    try:
        activity = AppActivity.objects.get(name="main", app=app)
    except AppActivity.DoesNotExist:    
        activity = AppActivity.objects.get(app=app)
        
    app_index_req = utils.url_request_build(activity.url, "GET", {}, "")
    oauth_request = OAuthRequest(app, None, app_index_req, oauth_parameters=t.passalong_params)
    oauth_request.sign()
    auth = oauth_request.to_header()["Authorization"]
    return {'oauth_cookie' : auth}
Example #5
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 #6
0
def initialize_server_request(request):
    """Shortcut for initialization."""
    # Django converts Authorization header in HTTP_AUTHORIZATION
    # Warning: it doesn't happen in tests but it's useful, do not remove!
    auth_header = {}
    if 'Authorization' in request.META:
        auth_header = {'Authorization': request.META['Authorization']}
    elif 'HTTP_AUTHORIZATION' in request.META:
        auth_header = {'Authorization': request.META['HTTP_AUTHORIZATION']}

    parameters = dict(request.REQUEST.items())
    oauth_request = OAuthRequest.from_request(request.method,
                                              request.build_absolute_uri(),
                                              headers=auth_header,
                                              parameters=parameters,
                                              query_string=request.META.get(
                                                  'QUERY_STRING', ''))
    if oauth_request:
        oauth_server = OAuthServer(DataStore(oauth_request))
        if 'plaintext' in OAUTH_SIGNATURE_METHODS:
            oauth_server.add_signature_method(OAuthSignatureMethod_PLAINTEXT())
        if 'hmac-sha1' in OAUTH_SIGNATURE_METHODS:
            oauth_server.add_signature_method(OAuthSignatureMethod_HMAC_SHA1())
    else:
        oauth_server = None
    return oauth_server, oauth_request
Example #7
0
def set_session_oauth_token(sender, user, request, **kwargs):
    # user is an Account instance here

    headers = {'Authorization': request.META.get('HTTP_AUTHORIZATION', '')}
    orequest = OAuthRequest.from_request(request.method, '', headers=headers)

    if orequest and 'oauth_token' in orequest.parameters:
        # check for token in headers (handle login_by_token case)
        token_key = orequest.get_parameter('oauth_token')
    elif settings.READ_ONLY_MODE:
        try:
            token_key = ''
            consumer_user = user.user
            if consumer_user is not None:
                # check for already existent token
                token = Token.objects.get(
                    name=SESSION_TOKEN_NAME, consumer__user=consumer_user)
                token_key = token.token
        except Token.DoesNotExist:
            # no token, this session will be invalidated when RO mode is off
            pass
    else:
        oauth_token, _ = user.get_or_create_oauth_token(
            token_name=SESSION_TOKEN_NAME)
        token_key = oauth_token.token

    request.session[SESSION_TOKEN_KEY] = token_key
Example #8
0
    def get_request(self, headers=None, **kwargs):
        request = super(Flixject, self).get_request(headers=headers, **kwargs)
        method = request.get('method', 'GET')

        # Apply OAuthness.
        csr = OAuthConsumer(*self.api_token)
        orq = OAuthRequest.from_consumer_and_token(csr,
                                                   http_method=method,
                                                   http_url=request['uri'])

        # OAuthRequest will strip our query parameters, so add them back in.
        parts = list(urlparse.urlparse(self._location))
        queryargs = cgi.parse_qs(parts[4], keep_blank_values=True)
        for key, value in queryargs.iteritems():
            orq.set_parameter(key, value[0])

        # Sign the request.
        osm = OAuthSignatureMethod_HMAC_SHA1()
        orq.set_parameter('oauth_signature_method', osm.get_name())
        orq.sign_request(osm, csr, None)

        if method == 'GET':
            request['uri'] = orq.to_url()
        else:
            request['headers'].update(orq.to_header())

        return request
Example #9
0
def getTwitterOAuthURL(conf, oauthTokenDict):
    """
    Obtain a URL from twitter.com that we can redirect a user to so they
    can authenticate themselves and authorize loveme.do to act on their
    behalf.

    @param conf: the lovemedo configuration.
    @param oauthTokenDict: A C{dict} mapping token keys to tokens.
    @return: A C{Deferred} that fires with the URL for OAuth verification.
    """
    log.msg('Got login URL request.')

    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

    consumer = OAuthConsumer(conf.consumer_key, conf.consumer_secret)
    request = OAuthRequest.from_consumer_and_token(
        consumer, callback=conf.callback_url,
        http_url=conf.request_token_url)
    request.sign_request(OAuthSignatureMethod_HMAC_SHA1(), consumer, None)
    r = RetryingCall(
        client.getPage, conf.request_token_url, headers=request.to_header())
    d = r.start()
    d.addCallback(_makeURL)
    d.addErrback(log.err)
    return d
Example #10
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 #11
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 #12
0
 def get_authorize_url(self):
     parameters = {'client_id': GITHUB_CLIENT_ID}
     oauth_request = OAuthRequest.from_consumer_and_token(
         self.consumer,
         http_url=GITHUB_AUTHORIZE_URL,
         parameters=parameters)
     return oauth_request.to_url()
Example #13
0
    def _fetch_resource(self, url, parameters=None, method = 'GET'):
        """ Retrieve a Yammer API resource.

        Keyword arguments:
        url -- a Yammer API URL (excluding query parameters)
        parameters -- used to pass query parameters to add to the request
                      (optional).

        """
        if not self._access_token:
            raise YammerError("Can't fetch resource. Missing access token!")

        try:
            oauth_request = OAuthRequest.from_consumer_and_token(
                                                self._consumer,
                                                token=self._access_token,
                                                http_method=method,
                                                http_url=url,
                                                parameters=parameters)
            headers = oauth_request.to_header()
            oauth_request.sign_request(self._signature,
                                       self._consumer,
                                       self._access_token)
            url = oauth_request.to_url()
        except OAuthError, m:
            raise YammerError(m.message)
Example #14
0
def signed_header_for_token(t):
    app = t.share.with_app
    headers = {}
    app_index_req = utils.url_request_build(app.index_url, "GET", headers, "")

    # sign as a two-legged OAuth request for the app
    oauth_request = OAuthRequest(
        consumer=app,
        token=None,         # no access tokens: 2-legged request
        http_request=app_index_req,
        oauth_parameters=t.passalong_params
    )

    oauth_request.sign()
    auth = oauth_request.to_header()["Authorization"]
    return auth
Example #15
0
    def get_request(self, headers=None, **kwargs):
        request = super(Flixject, self).get_request(headers=headers, **kwargs)
        method = request.get('method', 'GET')

        # Apply OAuthness.
        csr = OAuthConsumer(*self.api_token)
        orq = OAuthRequest.from_consumer_and_token(csr, http_method=method,
            http_url=request['uri'])

        # OAuthRequest will strip our query parameters, so add them back in.
        parts = list(urlparse.urlparse(self._location))
        queryargs = cgi.parse_qs(parts[4], keep_blank_values=True)
        for key, value in queryargs.iteritems():
            orq.set_parameter(key, value[0])

        # Sign the request.
        osm = OAuthSignatureMethod_HMAC_SHA1()
        orq.set_parameter('oauth_signature_method', osm.get_name())
        orq.sign_request(osm, csr, None)

        if method == 'GET':
            request['uri'] = orq.to_url()
        else:
            request['headers'].update(orq.to_header())

        return request
Example #16
0
    def fetch_access_token(self, unauth_request_token_key,
                           unauth_request_token_secret, oauth_verifier):
        """ After the user has authorizated API access via the authorization
        URL, get the (semi-)permanent access key using the user-authorized
        request token.

        Keyword arguments:
        unauth_request_token -- the user-authorized OAuth request token
        oauth_verifier -- per OAuth 1.0 Revision A

        """
        url = "%s?oauth_verifier=%s" % (YAMMER_ACCESS_TOKEN_URL,
                                        oauth_verifier)
        try:
            unauth_request_token = OAuthToken(unauth_request_token_key,
                                              unauth_request_token_secret)
            oauth_request = OAuthRequest.from_consumer_and_token(
                self._consumer,
                token=unauth_request_token,
                http_method='POST',
                http_url=url)
            oauth_request.sign_request(self._signature, self._consumer,
                                       unauth_request_token)
            headers = oauth_request.to_header()
        except OAuthError, m:
            raise YammerError(m.message)
Example #17
0
    def _fetch_resource(self, url, parameters=None):
        """ Retrieve a Yammer API resource.

        Keyword arguments:
        url -- a Yammer API URL (excluding query parameters)
        parameters -- used to pass query parameters to add to the request
                      (optional).

        """
        if not self._access_token:
            raise YammerError("Can't fetch resource. Missing access token!")

        try:
            oauth_request = OAuthRequest.from_consumer_and_token(
                self._consumer,
                token=self._access_token,
                http_method='GET',
                http_url=url,
                parameters=parameters)
            headers = oauth_request.to_header()
            oauth_request.sign_request(self._signature, self._consumer,
                                       self._access_token)
            url = oauth_request.to_url()
        except OAuthError, m:
            raise YammerError(m.message)
Example #18
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 #19
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 #20
0
    def fetch_access_token(self,
                           unauth_request_token_key,
                           unauth_request_token_secret,
                           oauth_verifier):
        """ After the user has authorizated API access via the authorization
        URL, get the (semi-)permanent access key using the user-authorized
        request token.

        Keyword arguments:
        unauth_request_token -- the user-authorized OAuth request token
        oauth_verifier -- per OAuth 1.0 Revision A

        """
        url = "%s?oauth_verifier=%s" % (YAMMER_ACCESS_TOKEN_URL,
                                        oauth_verifier)
        try:
            unauth_request_token = OAuthToken(unauth_request_token_key,
                                              unauth_request_token_secret)
            oauth_request = OAuthRequest.from_consumer_and_token(
                                                self._consumer,
                                                token=unauth_request_token,
                                                http_method='POST',
                                                http_url=url)
            oauth_request.sign_request(self._signature,
                                       self._consumer,
                                       unauth_request_token)
            headers = oauth_request.to_header()
        except OAuthError, m:
            raise YammerError(m.message)
Example #21
0
    def request(self, url, token=None, verb='GET', filename=None, **args):
        """`url` may be relative with regard to Netflix. Verb is a
        HTTP verb.

        """
        if isinstance(url, NetflixObject) and not isinstance(url, basestring):
            url = url.id
        if not url.startswith('http://'):
            url = self.protocol + self.host + url
        if 'output' not in args:
            args['output'] = 'json'
        args['method'] = verb.upper()

        postbody = None
        if verb.upper() == 'POST':
            args['method'] = 'GET'
            postbody = '&'.join(['%s=%s' % (escape(str(k)), escape(str(v))) \
                for k, v in args.iteritems()])
            args = {}

        # we don't want unicode in the parameters
        for k,v in args.iteritems():
            try:
                args[k] = v.encode('utf-8')
            except AttributeError:
                pass

        oa_req = OAuthRequest.from_consumer_and_token(self.consumer,
                                                      http_url=url,
                                                      parameters=args,
                                                      token=token)
        oa_req.sign_request(self.signature_method,
                            self.consumer,
                            token)
        if filename is None:
            def do_request():
                req = self.http.urlopen(verb, oa_req.to_url(), body=postbody)
                if not str(req.status).startswith('2'):
                    self.analyze_error(req)
                return req
        else:
            def do_request():
                try:
                    subprocess.check_call(["curl", oa_req.to_url(),
                                           "--location",
                                           "--compressed",
                                           "--output", filename])
                    sys.stderr.write('\nSaved to: %s\n' % filename)
                except OSError:
                    raise RuntimeError, "You need to have curl installed to use this command"
        try:
            req = do_request()
        except TooManyRequestsPerSecondError:
            time.sleep(1)
            req = do_request()
        if filename:
            return
        o = json.loads(req.data, object_hook=self.object_hook)
        return o
Example #22
0
 def _compose_auth_header(self, url):
     """Return additional header entries for request to `url`."""
     params = {
         'oauth_version': "1.0",
         'oauth_nonce': generate_nonce(),
         'oauth_timestamp': int(time()),
         'oauth_token': self.token.key,
         'oauth_consumer_key': self.consumer.key,
     }
     req = OAuthRequest(http_url=url, parameters=params)
     req.sign_request(OAuthSignatureMethod_PLAINTEXT(), self.consumer,
                      self.token)
     header = req.to_header()
     # Django uses the 'HTTP_AUTHORIZATION' to look up Authorization
     # credentials.
     header['HTTP_AUTHORIZATION'] = header['Authorization']
     return header
Example #23
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 #24
0
 def _compose_auth_header(self, url):
     """Return additional header entries for request to `url`."""
     params = {
         'oauth_version': "1.0",
         'oauth_nonce': generate_nonce(),
         'oauth_timestamp': int(time()),
         'oauth_token': self.token.key,
         'oauth_consumer_key': self.consumer.key,
     }
     req = OAuthRequest(http_url=url, parameters=params)
     req.sign_request(
         OAuthSignatureMethod_PLAINTEXT(), self.consumer, self.token)
     header = req.to_header()
     # Django uses the 'HTTP_AUTHORIZATION' to look up Authorization
     # credentials.
     header['HTTP_AUTHORIZATION'] = header['Authorization']
     return header
Example #25
0
 def get_access_token(self, code):
     parameters = {}
     parameters['client_id'] = GITHUB_CLIENT_ID
     parameters['client_secret'] = GITHUB_CLIENT_SECRET
     parameters['code'] = code
     oauth_request = OAuthRequest.from_consumer_and_token(self.consumer, http_url=GITHUB_ACCESS_TOKEN_URL, parameters=parameters)
     access_token = get_response_from_url(oauth_request.to_url())       
     return access_token
Example #26
0
    def make_requests_from_url(self, url):
        oauth_request = OAuthRequest.from_consumer_and_token(
                                            self.consumer,
                                            token=self.token,
                                            http_method='GET',
                                            http_url=url)
        oauth_request.sign_request(self.signature, self.consumer, self.token)

        return Request(oauth_request.to_url(), callback=self.parse, dont_filter=True)
Example #27
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 #28
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 #29
0
    def make_requests_from_url(self, url):
        oauth_request = OAuthRequest.from_consumer_and_token(self.consumer,
                                                             token=self.token,
                                                             http_method='GET',
                                                             http_url=url)
        oauth_request.sign_request(self.signature, self.consumer, self.token)

        return Request(oauth_request.to_url(),
                       callback=self.parse,
                       dont_filter=True)
Example #30
0
def signed_header_for_token(t):
    app=t.share.with_app
    try:
        activity = AppActivity.objects.get(name="main", app=app)
    except AppActivity.DoesNotExist:    
        activity = AppActivity.objects.get(app=app)

    headers = {}
    app_index_req = utils.url_request_build(activity.url, "GET", headers, "")

    # sign as a two-legged OAuth request for the app
    oauth_request = OAuthRequest(consumer=app,
                                 token=None, # no access tokens: 2-legged request
                                 http_request=app_index_req,
                                 oauth_parameters=t.passalong_params)

    oauth_request.sign()
    auth = oauth_request.to_header()["Authorization"]
    return auth
Example #31
0
	def get_authorisation_url(self, consumer = None, token = None):
		if self.token_required and (not consumer and not token):
			raise Exception('Consumer and token are required')
		
		oauth_request = OAuthRequest.from_consumer_and_token(
			consumer, token = token, http_url = self.authorise_url
		)
		
		oauth_request.sign_request(self.signature_method, consumer, token)
		return oauth_request.to_url()
Example #32
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 #33
0
    def oauth_request(self, token, url, extra_params=None):
        """Generate OAuth request, setups callback url"""
        params = {"oauth_callback": self.redirect_uri}
        if extra_params:
            params.update(extra_params)

        if "oauth_verifier" in self.data:
            params["oauth_verifier"] = self.data["oauth_verifier"]
        request = OAuthRequest.from_consumer_and_token(self.consumer, token=token, http_url=url, parameters=params)
        request.sign_request(OAuthSignatureMethod_HMAC_SHA1(), self.consumer, token)
        return request
Example #34
0
 def get_access_token(self, code):
     parameters = {}
     parameters['client_id'] = GITHUB_CLIENT_ID
     parameters['client_secret'] = GITHUB_CLIENT_SECRET
     parameters['code'] = code
     oauth_request = OAuthRequest.from_consumer_and_token(
         self.consumer,
         http_url=GITHUB_ACCESS_TOKEN_URL,
         parameters=parameters)
     access_token = get_response_from_url(oauth_request.to_url())
     return access_token
Example #35
0
def signed_header_for_token(t):
    app = t.share.with_app
    try:
        activity = AppActivity.objects.get(name="main", app=app)
    except AppActivity.DoesNotExist:
        activity = AppActivity.objects.get(app=app)

    headers = {}
    app_index_req = utils.url_request_build(activity.url, "GET", headers, "")

    # sign as a two-legged OAuth request for the app
    oauth_request = OAuthRequest(
        consumer=app,
        token=None,  # no access tokens: 2-legged request
        http_request=app_index_req,
        oauth_parameters=t.passalong_params)

    oauth_request.sign()
    auth = oauth_request.to_header()["Authorization"]
    return auth
Example #36
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 #37
0
    def request(self, url, token=None, verb='GET', filename=None, **args):
        """`url` may be relative with regard to Netflix. Verb is a
        HTTP verb.

        """
        if isinstance(url, NetflixObject) and not isinstance(url, basestring):
            url = url.id
        if not url.startswith('http://'):
            url = self.protocol + self.host + url
        if 'output' not in args:
            args['output'] = 'json'
        args['method'] = verb.upper()

        # we don't want unicode in the parameters
        for k, v in args.iteritems():
            try:
                args[k] = v.encode('utf-8')
            except AttributeError:
                pass

        oa_req = OAuthRequest.from_consumer_and_token(self.consumer,
                                                      http_url=url,
                                                      parameters=args,
                                                      token=token)
        oa_req.sign_request(self.signature_method, self.consumer, token)
        if filename is None:

            def do_request():
                req = self.http.urlopen('GET', oa_req.to_url())
                if not str(req.status).startswith('2'):
                    self.analyze_error(req)
                return req
        else:

            def do_request():
                try:
                    subprocess.check_call([
                        "curl",
                        oa_req.to_url(), "--location", "--compressed",
                        "--output", filename
                    ])
                    sys.stderr.write('\nSaved to: %s\n' % filename)
                except OSError:
                    raise RuntimeError, "You need to have curl installed to use this command"

        try:
            req = do_request()
        except TooManyRequestsPerSecondError:
            time.sleep(1)
            req = do_request()
        if filename:
            return
        o = json.loads(req.data, object_hook=self.object_hook)
        return o
Example #38
0
def do_webhook(request, webhook_name):
    hook = None
    headers = {}

    # Find the preferred app for this webhook...
    try:
        hook = AppWebHook.objects.filter(name=webhook_name)[0]
    except:
        raise Exception("No hook exists with name:  '%s'" % webhook_name)

    data = request.raw_post_data
    if (request.method == 'GET'): data = request.META['QUERY_STRING']

    print "requesting web hook", hook.url, request.method, data

    hook_req = utils.url_request_build(hook.url, request.method, headers, data)

    # If the web hook needs patient context, we've got to generate + pass along tokens
    if (hook.requires_patient_context):
        app = hook.app
        record = request.principal.share.record
        account = request.principal.share.authorized_by
        # Create a new token for the webhook to access the in-context patient record
        token = HELPER_APP_SERVER.generate_and_preauthorize_access_token(
            app, record=record, account=account)

        # And supply the token details as part of the Authorization header, 2-legged signed
        # Using the helper app's consumer token + secret
        # (the 2nd parameter =None --> 2-legged OAuth request)
        oauth_request = OAuthRequest(app,
                                     None,
                                     hook_req,
                                     oauth_parameters=token.passalong_params)
        oauth_request.sign()
        for (hname, hval) in oauth_request.to_header().iteritems():
            hook_req.headers[hname] = hval

    response = utils.url_request(hook.url, request.method, headers, data)
    print "GOT,", response
    return utils.x_domain(
        HttpResponse(response, mimetype='application/rdf+xml'))
Example #39
0
def fetch_access_token(request, consumer, request_token, url, parameters=None, 
                        sig_method=None):
  parameters = parameters and parameters or {}
  sig_method = sig_method and sig_method or LocalOAuthSignatureMethod_RSA_SHA1()
 
  logging.info('* Obtain an access token ...')
  oauth_request = OAuthRequest.from_consumer_and_token(
      consumer, request_token, http_url=url, parameters=parameters
      )
  oauth_request.sign_request(sig_method, consumer, None)
  
  return _fetch_token(oauth_request)
Example #40
0
def postNotice(token, secret, post_notice_url, notice_content, notice_url, user):
    current_site = Site.objects.get_current()
    user_profile_url = "%s%s" % (current_site.domain, reverse('profile_detail', args=[user.username]))
    oauthToken = OAuthToken(token, secret)
    url = urlparse.urlparse(post_notice_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
    params['omb_listenee'] = user_profile_url
    params['omb_notice'] = "%s%s" % (current_site.domain, notice_url)
    params['omb_notice_content'] = notice_content
    params['omb_notice_url'] = "%s%s" % (current_site.domain, notice_url)
    params['omb_notice_license'] = '%s/license/' % current_site.domain # TODO link to the real license
    
    consumer = OAuthConsumer(current_site.domain, "")
    req = OAuthRequest().from_consumer_and_token(consumer, token=oauthToken, http_url=url.geturl(), parameters=params, http_method="POST")
    req.sign_request(OAuthSignatureMethod_HMAC_SHA1(), consumer, oauthToken)
    f = urllib.urlopen(url.geturl(), req.to_postdata())
    data = f.read()
Example #41
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 #42
0
 def sign_request(self, url, method, body, headers):
     """Sign a request with OAuth credentials."""
     # Import oauth here so that you don't need it if you're not going
     # to use it.  Plan B: move this out into a separate oauth module.
     from oauth.oauth import (OAuthRequest, OAuthConsumer, OAuthToken,
         OAuthSignatureMethod_PLAINTEXT)
     consumer = OAuthConsumer(self.consumer_key, self.consumer_secret)
     token = OAuthToken(self.token_key, self.token_secret)
     oauth_request = OAuthRequest.from_consumer_and_token(
         consumer, token, http_url=url)
     oauth_request.sign_request(OAuthSignatureMethod_PLAINTEXT(),
         consumer, token)
     headers.update(oauth_request.to_header(self.oauth_realm))
Example #43
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 #44
0
 def get_authorization_url(self, callback=None):
     """Return the authorization url and token."""
     token = self.get_request_token()
     parameters = dict(application_name=self.application_name)
     if callback:
         parameters['oauth_callback'] = callback
     oauth_request = OAuthRequest.from_consumer_and_token(
         self.consumer,
         token=token,
         parameters=parameters,
         http_url=self.authorization_url,
     )
     oauth_request.sign_request(self.signature_method, self.consumer, token)
     return oauth_request.to_url(), token
Example #45
0
    def fetch_request_token(self):
        """ Retrieve an unauthorized request token that, in the next step of
        the OAuth process, will be used to authorize the application.

        """
        try:
            oauth_request = OAuthRequest.from_consumer_and_token(
                self._consumer,
                http_method='POST',
                http_url=YAMMER_REQUEST_TOKEN_URL)
            oauth_request.sign_request(self._signature, self._consumer, None)
            headers = oauth_request.to_header()
        except OAuthError, m:
            raise YammerError(m.message)
Example #46
0
    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)
            url = oauth_request.to_url()
        except OAuthError, m:
            raise YammerError(m.message)
Example #47
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 #48
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())
    def oauth_request(self, token, url, extra_params=None):
        params = {'oauth_callback': self.redirect_uri}
        if extra_params:
            params.update(extra_params)

        if 'oauth_verifier' in self.data:
            params['oauth_verifier'] = self.data['oauth_verifier']

        request = OAuthRequest.from_consumer_and_token(self.consumer,
                                                       token=token,
                                                       http_url=url,
                                                       parameters=params)
        request.sign_request(SignatureMethod_HMAC_SHA1(), self.consumer, token)

        return request
Example #50
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 #51
0
    def _fetch_resource(self, url, params=None, method=None, body=None):
        if not body and not method or method == 'GET':
            return Yammer._fetch_resource(self, url, params)

        if not self._access_token: raise YammerError('missing access token')
        try:
            o = OAuthRequest.from_consumer_and_token(self._consumer,
                                                     token=self._access_token,
                                                     http_method=method,
                                                     http_url=url,
                                                     parameters=params)
            headers = o.to_header()
            o.sign_request(self._signature, self._consumer, self._access_token)
            url = o.to_url()
        except OAuthError, m:
            raise YammerError(m.message)
Example #52
0
def fetch_request_token(request,
                        consumer,
                        url,
                        parameters=None,
                        sig_method=None):
    parameters = parameters and parameters or {}
    sig_method = sig_method and sig_method or LocalOAuthSignatureMethod_RSA_SHA1(
    )

    logging.info('* Obtain a request token ...')
    oauth_request = OAuthRequest.from_consumer_and_token(consumer,
                                                         http_url=url,
                                                         parameters=parameters)
    oauth_request.sign_request(sig_method, consumer, None)

    return _fetch_token(oauth_request)
Example #53
0
def initialize_server_request(request):
    """Shortcut for initialization."""
    # OAuth change
    # Django converts Authorization header in HTTP_AUTHORIZATION
    # Warning: it doesn't happen in tests but it's useful, do not remove!

    auth_header = {}
    if 'Authorization' in request.META:
        auth_header = {'Authorization': request.META['Authorization']}
    elif 'HTTP_AUTHORIZATION' in request.META:
        auth_header = {'Authorization': request.META['HTTP_AUTHORIZATION']}

    # Don't include extra parameters when request.method is POST and
    # request.MIME['CONTENT_TYPE'] is "application/x-www-form-urlencoded"
    # (See http://oauth.net/core/1.0a/#consumer_req_param).
    # But there is an issue with Django's test Client and custom content types
    # so an ugly test is made here, if you find a better solution...
    parameters = {}
    if request.method == "POST" and request.META.get('CONTENT_TYPE') != "application/json" \
        and (request.META.get('CONTENT_TYPE') == "application/x-www-form-urlencoded" \
            or request.META.get('SERVER_NAME') == 'testserver'):
        # lou -w -When POST statement data, the actual data is a dict key and has a value of ''
        # have to parse it out correctly...
        p = dict(request.REQUEST.items())
        if p.values()[0] == '':
            # literal eval is putting them in differnt order
            parameters = ast.literal_eval(p.keys()[0])
        else:
            parameters = p

    oauth_request = OAuthRequest.from_request(request.method,
                                              request.build_absolute_uri(),
                                              headers=auth_header,
                                              parameters=parameters,
                                              query_string=request.META.get(
                                                  'QUERY_STRING', ''))

    if oauth_request:
        oauth_server = OAuthServer(DataStore(oauth_request))
        if 'plaintext' in OAUTH_SIGNATURE_METHODS:
            oauth_server.add_signature_method(OAuthSignatureMethod_PLAINTEXT())
        if 'hmac-sha1' in OAUTH_SIGNATURE_METHODS:
            oauth_server.add_signature_method(OAuthSignatureMethod_HMAC_SHA1())
    else:
        oauth_server = None
    return oauth_server, oauth_request
Example #54
0
 def validate(self, request, data):
     signature_method = OAuthSignatureMethod_HMAC_SHA1()
     consumer = OAuthConsumer(self.CONSUMER_KEY, self.CONSUMER_SECRET)
     try:
         oauth_token = data['oauth_token']
         oauth_verifier = data.get('oauth_verifier', None)
     except MultiValueDictKeyError:
         messages.error(request, lang.BACKEND_ERROR)
         raise Redirect('publicauth-login')
     oauth_req = OAuthRequest.from_consumer_and_token(
         consumer, http_url=self.ACCESS_TOKEN_URL)
     oauth_req.set_parameter('oauth_token', oauth_token)
     if oauth_verifier:
         oauth_req.set_parameter('oauth_verifier', oauth_verifier)
     oauth_req.sign_request(signature_method, consumer, None)
     response = urllib.urlopen(oauth_req.to_url()).read()
     self.identity = urlparse.parse_qs(
         response, keep_blank_values=False)['oauth_token'][0]
     return response
Example #55
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 #56
0
def initialise_server_request(request):
    if request.method == "POST":
        params = dict(request.REQUEST.items())
    else:
        params = {}

    request.META['Authorization'] = request.META.get('HTTP_AUTHORIZATION', '')
    oauth_request = OAuthRequest.from_request(request.method,
                                              request.build_absolute_uri(),
                                              headers=request.META,
                                              parameters=params,
                                              query_string=request.environ.get(
                                                  'QUERY_STRING', ''))

    if oauth_request:
        oauth_server = OAuthServer(DataStore(oauth_request))
        oauth_server.add_signature_method(OAuthSignatureMethod_PLAINTEXT())
    else:
        oauth_server = None

    return oauth_server, oauth_request
Example #57
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 #58
0
def get_connect_credentials(request, account, pha):
    """ Get oAuth credentials for an app to run in Connect or SMART REST mode.

    Generates access tokens for *pha* to run against the *record_id* specified in ``request.POST``, authorized by
    *account*. Generates 2 tokens: one for SMART Connect use, and one for SMART REST use.

    If the app is not yet enabled for the record/carenet, this will return a :http:statuscode:`403`.
    
    """

    carenet = record = None
    carenet_id = request.POST.get('carenet_id', None)
    record_id = request.POST.get('record_id', None)

    if carenet_id:
        try:
            carenet = Carenet.objects.get(id=carenet_id)
        except Carenet.DoesNotExist:
            raise Http404
        except Carenet.MultipleObjectsReturned:
            raise Exception(
                "Multiple carenets with same id--database is corrupt")

    elif record_id:
        try:
            record = Record.objects.get(id=record_id)
        except Record.DoesNotExist:
            raise Http404
        except Record.MultipleObjectsReturned:
            raise Exception(
                "Multiple records with same id--database is corrupt")

    # Make sure that the app is enabled
    if (record and not PHAShare.objects.filter(record=record, with_pha=pha).exists()) or \
            (carenet and not CarenetPHA.objects.filter(carenet=carenet, pha=pha).exists()):
        raise PermissionDenied(
            "Cannot generate credentials before app is enabled")

    # Generate the tokens
    from indivo.accesscontrol.oauth_servers import OAUTH_SERVER
    rest_token = OAUTH_SERVER.generate_and_preauthorize_access_token(
        pha, record=record, carenet=carenet, account=account)
    connect_token = OAUTH_SERVER.generate_and_preauthorize_access_token(
        pha, record=record, carenet=carenet, account=account)
    connect_token.connect_auth_p = True
    connect_token.save()

    # Generate a 2-legged oauth header for the rest token, based on the pha's start_url
    url = utils.url_interpolate(pha.start_url_template, {
        'record_id': record_id or '',
        'carenet_id': carenet_id or ''
    })
    request = HTTPRequest("GET", url, HTTPRequest.FORM_URLENCODED_TYPE, '', {})
    oauth_params = {
        'smart_container_api_base': settings.SITE_URL_PREFIX,
        'smart_oauth_token': rest_token.token,
        'smart_oauth_token_secret': rest_token.token_secret,
        'smart_user_id': account.email,
        'smart_app_id': pha.email,
        'smart_record_id': record_id,
    }
    oauth_request = OAuthRequest(
        consumer=pha,
        token=None,  # no access tokens: 2-legged request
        http_request=request,
        oauth_parameters=oauth_params)
    oauth_request.sign()
    auth_header = oauth_request.to_header()["Authorization"]

    return render_template('connect_credentials', {
        'connect_token': connect_token,
        'rest_token': rest_token,
        'api_base': settings.SITE_URL_PREFIX,
        'oauth_header': auth_header,
        'app_email': pha.email
    },
                           type='xml')
Example #59
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('')