Source

CherryPy Recipes / web / auth / python_oauth2 / __init__.py

# -*- coding: utf-8 -*-
import cherrypy

from oauthapp import OAuthApp

class Root(object):
    def __init__(self):
        self.auth = OAuthApp('https://api.twitter.com/oauth/request_token',
                             'https://api.twitter.com/oauth/authorize',
                             'https://api.twitter.com/oauth/access_token')
        
    @cherrypy.expose
    def index(self):
        page = """<html>
<head />
<body>
<a href='/auth/'>Click me to authenticate through OAuth</a>
<br />
%s
</body>
</html>
"""
        message = "Not authenticated yet..."
        if 'auth_token' in cherrypy.session:
            screen_name = cherrypy.session['auth_token']['screen_name']
            message = "Authenticated as %s" % screen_name

        page = page % message
        return page
    
if __name__ == '__main__':
    cherrypy.config.update({'server.socket_port': 8090})
    
    # You must get a key/secret pair from Twitter
    # https://dev.twitter.com/docs/auth/oauth/faq
    from oauthplugin import OAuthEnginePlugin
    OAuthEnginePlugin(cherrypy.engine, 'TWITTER_OAUTH_KEY',
                      'TWITTER_OAUTH_SECRET').subscribe()
        
    cherrypy.quickstart(Root(), '', {'/': {'tools.sessions.on': True,
                                           'tools.sessions.timeout': 360}})