Source

pist / pist / auth.py

Full commit
from tornado import web, auth

from constants import AUTH_GOOGLE, AUTH_TWITTER
from core import BaseHandler
from models import User

class AuthHandler(BaseHandler):

    def _on_auth(self, info):
        if not info:
            return self.send_error(401)

        field = {
            AUTH_GOOGLE: 'email',
            AUTH_TWITTER: 'username',
        }[self.method]
        username = info[field]

        user = User.by_username(username, self.method)

        if user is None:
            # create a new user
            try:
                user = User.create(username, self.method)
            except sqlite3.IntgrityError:
                return self.send_error(401)

        self.set_secure_cookie('user_id', str(user.id))
        self.redirect(self.reverse_url('home'))

class GoogleAuth(AuthHandler, auth.GoogleMixin):

    @web.asynchronous
    def get(self):
        self.method = AUTH_GOOGLE
        if self.get_argument('openid.mode', None):
            self.get_authenticated_user(self.async_callback(self._on_auth))
            return

        self.authenticate_redirect()

class TwitterAuth(AuthHandler, auth.TwitterMixin):

    @web.asynchronous
    def get(self):
        self.method = AUTH_TWITTER
        if self.get_argument('oauth_token', None):
            self.get_authenticated_user(self.async_callback(self._on_auth))
            return

        self.authorize_redirect()

class LoginHandler(BaseHandler):

    def get(self):
        self.render('login.html')

class LogoutHandler(web.RequestHandler):

    def get(self):
        self.clear_cookie('user_id')
        self.redirect('/')