Example #1
0
 def _parse_token_response(self, response):
     resp, content = response
     if resp['status'] != '200': 
         raise Exception('%s HTTP Error' % resp['status'])
     
     result = dict(parse_qsl(content))
     return result['oauth_token'], result['oauth_token_secret']
Example #2
0
    def request(self, uri, method="GET", body=None, headers=None,
                redirections=httplib2.DEFAULT_MAX_REDIRECTS,
                connection_type=None):
        """This function calls httplib2.request after signing request with oauth.
        Parameters used in this function is exactly same with httplib2.request.
        """

        DEFAULT_CONTENT_TYPE = 'application/x-www-form-urlencoded'

        if not isinstance(headers, dict):
            headers = {}
      
        is_multipart = method == 'POST' and \
                       headers.get('Content-Type', DEFAULT_CONTENT_TYPE) != \
                       DEFAULT_CONTENT_TYPE

        if body and method == 'POST' and not is_multipart:
            parameters = dict(parse_qsl(body))
            if self.callback: 
                parameters['oauth_callback'] = self.callback
        else:
            parameters = {}
            if self.callback: 
                parameters['oauth_callback'] = self.callback

        req = oauth2.Request.from_consumer_and_token(self.consumer,
                                                     token=self.token,
                                                     http_method=method,
                                                     http_url=uri,
                                                     parameters=parameters)
        
        req.sign_request(self.method, self.consumer, self.token)

        if method == "POST":
            headers['Content-Type'] = headers.get('Content-Type',
                                                 DEFAULT_CONTENT_TYPE)
            if is_multipart:
                headers.update(req.to_header())
            else:
                body = req.to_postdata()

        elif method == "GET":
            uri = req.to_url()
        else:
            headers.update(req.to_header())

        return httplib2.Http.request(self, uri, method=method, body=body,
                                     headers=headers,
                                     redirections=redirections,
                                     connection_type=connection_type)    
Example #3
0
def authorize_app(request, session):
    """
    Used by callback view that takes the oauth token and verifier from Google 
    and converts them into an access token and secret for this user with 
    our consumer key. If this works we redirect the user to the page which
    actually checks their Gmail feed.
    """
    
    access_url = 'https://www.google.com/accounts/OAuthGetAccessToken'
    
    # this view should only be accessed by Google
    # with the correct request args
    try:
        key = request.args['oauth_token']
        oauth_verifier = request.args['oauth_verifier']
    except KeyError:
        abort(404)
    if session.get('request_token', None) != key:
        raise Exception("Tokens don't match")
    token = oauth.Token(key, session['request_secret'])
    
    token.set_verifier(oauth_verifier)
    client = oauth.Client(CONSUMER, token)
    params = {
        'oauth_consumer_key': CONSUMER.key,
        'oauth_token': token.key,
        'oauth_verifier': oauth_verifier,
        'oauth_timestamp': str(int(time.time())),
        'oauth_nonce': oauth.generate_nonce(),
        'oauth_version': '1.0',
    }
    client.set_signature_method(oauth.SignatureMethod_HMAC_SHA1())
    resp, content = client.request(access_url, "POST", 
                                   body=urllib.urlencode(params))
    if resp['status'] != '200':
        logging.error("Invalid response %s.", resp['status'])
        raise Exception("Invalid response")
    
    token_dict = dict(oauth.parse_qsl(content))
    session['access_token'] = token_dict['oauth_token']
    session['access_secret'] = token_dict['oauth_token_secret']
Example #4
0
def check_mail():
    """
    Grabs Gmail feed and checks it for supplied values.
    
    If user is not authenticated, this view redirects to request Oauth creds
    """
    
    try:
        content = grab_raw_feed(FEED_URL, request, session)
    except NotAuthenticated:
        return redirect(url_for('oauth_request'))
    
    feed = feedparser.parse(content)
    search = request.form.get('search', '') or session.pop('search', '')
    found = []
    # Feed title should show the email address so we can glean the domain name
    # Example: "Gmail - Inbox for [email protected]"
    text, domain = feed['feed']['title'].split('@')
    for email in feed.entries:
        if email['author'].lower().find(search.lower()) >= 0:
            # build single message URL
            message_id = dict(parse_qsl(email['link']))['message_id']
            if domain == 'gmail.com':
                path = 'mail'
            else: # send to GAFYD
                path = 'a/%s' % domain
            print_view = 'https://mail.google.com/%s/h/?v=pt&th=%s' % (path, 
                                                                    message_id)
            timestamp = time.mktime(email['published_parsed'])
            found.append({
                'from': email['author'],
                'subject': email['title'],
                'summary': email['summary'],
                'url': print_view,
                'date': datetime.datetime.fromtimestamp(timestamp),
            })
    return render_template('results.html',
                            feed=found,
                            search=search)
Example #5
0
def get_authorize_url(urls, request, session):
    """
    Handle Google's Oauth request token
    
    Gets request token from Google and URL of page at Google
    allowing them to authorize our app to access their Gmail data.
    """
    request_url = 'https://www.google.com/accounts/OAuthGetRequestToken'
    auth_url = 'https://www.google.com/accounts/OAuthAuthorizeToken'
    
    # if the user already has a request token, we can skip this step
    if 'request_token' not in session:
        host = '/'.join(request.url_root.split('/')[:3])
        params = {
            'oauth_version': '1.0',
            'scope': urls, 
            'oauth_nonce': oauth.generate_nonce(),
            'oauth_timestamp': str(int(time.time())),
            'oauth_callback': '%s/login/' % host,
        }
        client = oauth.Client(CONSUMER)
        client.set_signature_method(oauth.SignatureMethod_HMAC_SHA1())
        resp, content = client.request(request_url, "POST", 
                                       body=urllib.urlencode(params))
    
        if resp['status'] != '200':
            logging.error("Invalid response %s.", resp['status'])
            raise Exception("Invalid response")

        token_dict = dict(oauth.parse_qsl(content))
        
        # store tokens in the user session
        session['request_token'] = token_dict['oauth_token']
        session['request_secret'] = token_dict['oauth_token_secret']

    return '%s?oauth_token=%s' % (auth_url, session['request_token'])