Commits

Hsiaoming Yang committed 3af2365

using submodules

Comments (0)

Files changed (5)

+[submodule "third"]
+	path = third
+	url = git@github.com:lepture/tornado.third.git
 from tornado.httpserver import HTTPServer
 from tornado import web
 
-from douban import DoubanMixin
-from renren import RenrenGraphMixin
+from third import DoubanMixin
+from third import RenrenGraphMixin
 
 _app_cache = {}
 

douban.py

-#!/usr/bin/env python
-
-import re
-import logging
-import urllib
-
-from tornado.escape import xhtml_escape
-from tornado.httputil import url_concat
-from tornado.auth import httpclient, OAuthMixin
-
-class DoubanMixin(OAuthMixin):
-    """Douban OAuth authentication.
-
-    Register your apps at http://www.douban.com/service/apikey/apply
-    Then copy your CONSUMER KEY and CONSUMER SECRET to the application
-    setings 'douban_consumer_key' and 'douban_consumer_secret'.
-
-    Example usage::
-
-        class DoubanHandler(tornado.web.RequestHandler, DoubanMixin):
-            @tornado.web.asynchronous
-            def get(self):
-                if self.get_argument("oauth_token", None):
-                    self.get_authenticated_user(self.async_callback(self._on_auth))
-                    return
-                self.authorize_redirect()
-            
-            def _on_auth(self, user):
-                if not user:
-                    raise tornado.web.HTTPError(500, "Douban auth failed")
-                # do something else
-                self.finish()
-
-    """
-    _OAUTH_VERSION = "1.0"
-    _OAUTH_REQUEST_TOKEN_URL = "http://www.douban.com/service/auth/request_token"
-    _OAUTH_ACCESS_TOKEN_URL = "http://www.douban.com/service/auth/access_token"
-    _OAUTH_AUTHORIZE_URL = "http://www.douban.com/service/auth/authorize"
-    _OAUTH_NO_CALLBACKS = False
-
-    def douban_request(self, path, callback, access_token=None,
-            post_args=None, **args):
-        url = "http://api.douban.com" + path
-        if access_token:
-            all_args = {}
-            all_args.update(args)
-            #all_args.update(post_args or {})
-            consumer_token = self._oauth_consumer_token()
-            method = "POST" if post_args is not None else "GET"
-            oauth = self._oauth_request_parameters(
-                    url, access_token, all_args, method=method)
-            args.update(oauth)
-
-        callback = self.async_callback(self._on_douban_request, callback)
-        http = httpclient.AsyncHTTPClient()
-        if post_args is not None:
-            headers = _to_header(args)
-            headers['Content-Type'] = 'application/atom+xml; charset=utf-8'
-            http.fetch(url, method="POST", headers=headers,
-                    body=post_args, callback=callback)
-        else:
-            http.fetch(url_concat(url, args), callback=callback)
-
-    def douban_saying(self, callback, access_token=None, content=None, **args):
-        """ douban miniblog
-        Example usage::
-            
-            class MainHandler(tornado.web.RequestHandler, DoubanMixin):
-                @tornado.web.authenticated
-                @tornado.web.asynchronous
-                def get(self):
-                    self.douban_saying(self.async_callback(self._on_saying),
-                            access_token=user["access_token"], content="test content")
-
-                def _on_saying(self, xml):
-                    if not xml:
-                        raise tornado.web.HTTPError(500, 'Douban saying failed')
-                    self.write(xml)
-                    self.finish()
-        """
-        path = "/miniblog/saying"
-        if not access_token or not content:
-            raise
-        try: content = content.encode('utf-8')
-        except UnicodeDecodeError: pass
-        content = xhtml_escape(content)
-        post_args = '<entry><content>%s</content></entry>' % content
-        self.douban_request(path, callback, access_token, post_args, **args)
-
-    def _on_douban_request(self, callback, response):
-        if response.error:
-            logging.warning("Error response %s fetching %s", response.error,
-                    response.request.url)
-            callback(None)
-            return
-        callback(response.body)
-
-    def _oauth_consumer_token(self):
-        self.require_setting("douban_consumer_key", "Douban OAuth")
-        self.require_setting("douban_consumer_secret", "Douban OAuth")
-        token = dict(key=self.settings["douban_consumer_key"],
-                secret=self.settings["douban_consumer_secret"])
-        return token
-
-    def _oauth_get_user(self, access_token, callback):
-        callback = self.async_callback(self._parse_user_response, callback)
-        self.douban_request("/people/%40me",
-                access_token=access_token, callback=callback)
-
-
-    def _parse_user_response(self, callback, xml):
-        user = {}
-        _uid = re.findall(r'<db:uid>(\S+?)</db:uid>', xml)
-        _nick = re.findall(r'<title>(.*?)</title>', xml)
-        _loc = re.findall(r'<db:location\s+id="(\S+?)">', xml)
-        _avatar = re.findall(r'<link\s+href="(\S+?)"\s+rel="icon"', xml)
-        if _uid:
-            user['uid'] = _uid[0]
-        if _nick:
-            user['nickname'] = _nick[0]
-        if _loc:
-            user['location'] = _loc[0]
-        if _avatar:
-            user['avatar'] = _avatar[0]
-        callback(user)
-
-def _to_header(kw):
-    s = ", ".join(['%s="%s"' % (k, _quote(v)) for k, v in kw.iteritems() if k.startswith('oauth_')])
-    h = 'OAuth realm="", %s' % s
-    return {'Authorization': h}
-
-def _quote(s):
-    return urllib.quote(str(s), '~')

recaptcha.py

-#!/usr/bin/env python
-
-import logging
-import urllib
-
-from tornado.auth import httpclient
-
-class RecaptchaMixin(object):
-    """
-    Example usage::
-
-        class SignupHandler(BaseHandler, RecaptchaMixin):
-            def get(self):
-                if self.current_user:
-                    return self.redirect('/')
-                form = SignupForm()
-                recaptcha = self.recaptcha_render()
-                return self.render('auth/signup.html', form=form, recaptcha=recaptcha)
-
-            @asynchronous
-            def post(self):
-                form = SignupForm(self.request.arguments)
-                if form.validate():
-                    user = form.save()
-                    user.signup_ip = user.signin_ip = self.request.remote_ip
-                    self.recaptcha_validate(self.async_callback(self._on_validate, user))
-                    return
-
-                recaptcha = self.recaptcha_render()
-                html = self.render_string('auth/signup.html', form=form, recaptcha=recaptcha)
-                self.write(html)
-                self.finish()
-
-            def _on_validate(self, user, response):
-                if not response:
-                    form = SignupForm(self.request.arguments)
-                    recaptcha = self.recaptcha_render()
-                    html = self.render_string('auth/signup.html', form=form, recaptcha=recaptcha)
-                    self.write(html)
-                    self.finish()
-                    return
-                self.db.add(user)
-                self.db.commit()
-                self.set_secure_cookie('user', user.email)
-                return self.redirect('/')
-    """
-    RECAPTCHA_VERIFY_URL = "http://www.google.com/recaptcha/api/verify"
-
-    def recaptcha_render(self):
-        token = self._recaptcha_token()
-        html = u'<div id="recaptcha_div"></div>'
-        html += u'<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>'
-        s = u'<script type="text/javascript">Recaptcha.create("%(key)s", "recaptcha_div", {theme: "%(theme)s",callback: Recaptcha.focus_response_field});</script>'
-        html += s % token
-        return html
-
-    def recaptcha_validate(self, callback):
-        token = self._recaptcha_token()
-        challenge = self.get_argument('recaptcha_challenge_field', None)
-        response = self.get_argument('recaptcha_response_field', None)
-        callback = self.async_callback(self._on_recaptcha_request, callback)
-        http = httpclient.AsyncHTTPClient()
-        post_args = {
-            'privatekey': token['secret'],
-            'remoteip': self.request.remote_ip,
-            'challenge': challenge,
-            'response': response
-        }
-        http.fetch(self.RECAPTCHA_VERIFY_URL, method="POST",
-                   body=urllib.urlencode(post_args), callback=callback)
-
-    def _on_recaptcha_request(self, callback, response):
-        if response.error:
-            logging.warning("Error response %s fetching %s", response.error,
-                    response.request.url)
-            callback(None)
-            return
-        verify, message = response.body.split()
-        if verify == 'true':
-            callback(response.body)
-        else:
-            logging.warning("Recaptcha verify failed %s", message)
-            callback(None)
-
-
-    def _recaptcha_token(self):
-        self.require_setting("recaptcha_public_key", "Recaptcha Public Key")
-        self.require_setting("recaptcha_private_key", "Recaptcha Private Key")
-        self.require_setting("recaptcha_theme", "Recaptcha Theme")
-        token = dict(
-            key=self.settings["recaptcha_public_key"],
-            secret=self.settings["recaptcha_private_key"],
-            theme=self.settings["recaptcha_theme"],
-        )
-        return token

renren.py

-#!/usr/bin/env python
-
-import logging
-import urllib
-from tornado import httpclient
-from tornado.escape import json_decode
-from tornado.httputil import url_concat
-
-
-class RenrenGraphMixin(object):
-    _OAUTH_AUTHORIZE_URL = "https://graph.renren.com/oauth/authorize"
-    _OAUTH_ACCESS_TOKEN_URL = "https://graph.renren.com/oauth/token"
-
-    _API_URL = 'http://api.renren.com/restserver.do'
-
-    def authorize_redirect(self, redirect_uri, response_type='code', scope=None, **args):
-        consumer_token = self._oauth_consumer_token()
-        all_args = {
-            'client_id': consumer_token['client_id'],
-            'redirect_uri': redirect_uri,
-            'response_type': response_type,
-        }
-        if scope: all_args.update({'scope': scope})
-        args.update(all_args)
-        self.redirect(url_concat(self._OAUTH_AUTHORIZE_URL, args))
-    
-    def renren_request(self, path, args):
-        #TODO
-        pass
-
-    def get_authenticated_user(self, callback, redirect_uri):
-        """
-        class RenrenHandler(tornado.web.RequestHandler, RenrenGraphMixin):
-            @tornado.web.asynchronous
-            def get(self):
-                if self.get_argument("code", None):
-                    self.get_authenticated_user(self.async_callback(self._on_auth))
-                    return
-                self.authorize_redirect()
-            
-            def _on_auth(self, user):
-                if not user:
-                    raise tornado.web.HTTPError(500, "Renren auth failed")
-                # do something else
-                self.finish()
-        """
-
-        code = self.get_argument('code')
-        return self.get_access_token(callback, code, 'code', redirect_uri)
-
-    def get_access_token(self, callback, code, grant_type='code', redirect_uri=None):
-        if grant_type == 'refresh_token':
-            args = {
-                'grant_type': 'refresh_token',
-                'refresh_token': code,
-            }
-        elif redirect_uri:
-            args = {
-                'grant_type': 'authorization_code',
-                'code': code,
-                'redirect_uri': redirect_uri,
-            }
-        else:
-            logging.error('Renren Get Access Token Error. redirect_uri required')
-            return
-        args.update(self._oauth_consumer_token())
-
-        callback = self.async_callback(self._on_get_access_token, callback)
-        http = httpclient.AsyncHTTPClient()
-        http.fetch(url_concat(self._OAUTH_ACCESS_TOKEN_URL, args), callback=callback)
-
-    def _on_get_access_token(self, callback, response):
-        if response.error:
-            logging.warning("Error response %s fetching %s", response.error,
-                    response.request.url)
-            callback(None)
-            return
-        res = json_decode(response.body)
-        if 'error' in res:
-            logging.warning("Error response %s fetching %s", res['error_description'],
-                    response.request.url)
-            callback(None)
-            return
-        callback(res)
-
-    def _oauth_consumer_token(self):
-        self.require_setting("renren_client_id", "Renren Client ID")
-        self.require_setting("renren_client_secret", "Renren Client Secret")
-        token = dict(client_id=self.settings["renren_client_id"],
-                     client_secret=self.settings["renren_client_secret"])
-        return token
-