Commits

Sylvain Hellegouarch committed 66a022e

added python oauth2 recipe

Comments (0)

Files changed (3)

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, 'DvX6vGPS03k4mzyoWkwug',
+                      'v6iBV5VWkEbR5GNi7943oQZb7xuesqEHFp7KuXtgkk').subscribe()
+        
+    cherrypy.quickstart(Root(), '', {'/': {'tools.sessions.on': True,
+                                           'tools.sessions.timeout': 360}})
+

web/auth/python_oauth2/oauthapp.py

+# -*- coding: utf-8 -*-
+import cgi
+
+import cherrypy
+
+__all__ = ['OAuthApp']
+
+class OAuthApp(object):
+    def __init__(self, request_token_url, auth_token_url, access_token_url):
+        self.request_token_url = request_token_url
+        self.auth_token_url = auth_token_url
+        self.access_token_url = access_token_url
+
+    @cherrypy.expose
+    def index(self):
+        engine = cherrypy.engine
+        content = engine.publish("oauth-request", self.request_token_url).pop()
+        cherrypy.session['request_token'] = dict(cgi.parse_qsl(content))
+        cherrypy.lib.sessions.save()
+        url = "%s?oauth_token=%s" % (self.auth_token_url,
+                                     cherrypy.session['request_token']['oauth_token'])
+
+        raise cherrypy.HTTPRedirect(url)
+
+    @cherrypy.expose
+    def success(self, *args, **kwargs):
+        engine = cherrypy.engine
+        content = engine.publish("oauth-request", self.access_token_url,
+                                 cherrypy.session['request_token']['oauth_token'],
+                                 cherrypy.session['request_token']['oauth_token_secret']).pop()
+        del cherrypy.session['request_token']
+
+        access_token = dict(cgi.parse_qsl(content))
+        cherrypy.session['auth_token'] = access_token
+        
+        # available...
+        # access_token['user_id']
+        # access_token['oauth_token']
+        # access_token['oauth_token_secret']
+        
+        raise cherrypy.HTTPRedirect("/")
+    

web/auth/python_oauth2/oauthplugin.py

+# -*- coding: utf-8 -*-
+import cherrypy
+from cherrypy.process import wspbus, plugins
+import oauth2
+
+__all__ = ['OAuthEnginePlugin']
+        
+class OAuthEnginePlugin(plugins.SimplePlugin):
+    def __init__(self, bus, consumer_key, consumer_secret):
+        """
+        Allows to interact with the underlying Python-OAuth2 API
+        """
+        plugins.SimplePlugin.__init__(self, bus)
+        self.consumer_key = consumer_key
+        self.consumer_secret = consumer_secret
+        
+    def start(self):
+        self.bus.log('Starting OAuth plugin')
+        self.bus.subscribe("oauth-consumer", self.get_consumer)
+        self.bus.subscribe("oauth-token", self.get_token)
+        self.bus.subscribe("oauth-request", self.request)
+        
+    def stop(self):
+        self.bus.log('Stopping down OAuth plugin')
+        self.bus.unsubscribe("oauth-consumer", self.get_consumer)
+        self.bus.unsubscribe("oauth-token", self.get_token)
+        self.bus.unsubscribe("oauth-request", self.request)
+
+    def get_consumer(self):
+        """
+        Return a ``oauth2.Consumer`` instance initialized
+        with the key and secret values provided to the
+        plugin instance.
+        """
+        return oauth2.Consumer(self.consumer_key, self.consumer_secret)
+
+    def get_token(self, key, secret):
+        """
+        Return a ``oauth2.Token`` instance with the provided
+        ``key`` and ``secret``.
+        """
+        return oauth2.Token(key=key, secret=secret)
+
+    def request(self, url, key=None, secret=None, method='GET'):
+        """
+        Perform a OAuth handshake with the given provider's url using
+        the given ``key`` and ``secret``.
+
+        If the handshake failed, it raises a ``cherrypy.HTTPError``
+        otherwise it returns the content returned by the the provider
+        through the handshake.
+        """
+        consumer = self.get_consumer()
+        token = None
+        if key and secret:
+            token = self.get_token(key, secret)
+        resp, content = oauth2.Client(consumer, token).request(url, method=method)
+        if resp['status'] != '200':
+            self.bus.log(content)
+            raise cherrypy.HTTPError(400, "Invalid response from OAuth provider.")
+        return content