Skip to content

Instantly share code, notes, and snippets.

@leafduo
Created May 18, 2011 12:30
Show Gist options
  • Select an option

  • Save leafduo/978489 to your computer and use it in GitHub Desktop.

Select an option

Save leafduo/978489 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python2.6
# -*- coding: utf-8 -*-
 
import base64
import hashlib
import functools
import tornado.web
import tornado.ioloop
import tornado.options
import tornado.httpserver
from tornado.options import define, options
 
user_permissions = {
    'root': {
        'password': 'e6e66b8981c1030d5650da159e79539a'
    },
    'kitten': {
        'password': 'e6e66b8981c1030d5650da159e795312'
    }
}
 
def httpbasicauth(method):
 
    """Decorate methods with this to require that the user be logged in."""
 
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
 
        error_authentication = self.application.settings.get('error_auth')
        authorization_header = self.request.headers.get('Authorization', None)
 
        ## Check HTTP_AUTHORIZATION header.
        if authorization_header is None:
            return self.write(error_authentication)
        ## Analytic authentication information.
        s, base64string = authorization_header.split()
        username, password = base64.decodestring(base64string).split(':')
 
        ## Check user and password.
        if hashlib.new('md5', password).hexdigest() != user_permissions.get(username, {}).get('password', ''):
            return self.write(error_authentication)
 
        return method(self, *args, **kwargs)
    return wrapper
 
define('port', default=8888, help='run on the given port', type=int)
 
class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/', IndexHandler)
        ]
        settings = dict(
            debug = True,
            error_auth = {'error': 'errorauthentication'},
            template_path = os.path.join(os.path.dirname(__file__), '')
        )
        tornado.web.Application.__init__(self, handlers, **settings)
 
class IndexHandler(tornado.web.RequestHandler):
 
    @httpbasicauth
    def get(self):
        self.render('index.html')
 
def main():
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application(), xheaders=True)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()
 
if __name__ == '__main__':
    main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment