Permalink
Browse files

add basic_auth decorator

  • Loading branch information...
1 parent f3aa7ae commit c9324bcc9366191f70a2d62bc8358d37315c6192 @ifduyue ifduyue committed Mar 23, 2012
Showing with 32 additions and 0 deletions.
  1. +32 −0 tornado_utils/decorators.py
@@ -1,5 +1,6 @@
from urllib import quote as url_quote
from tornado.web import HTTPError
+import base64
import functools
import urllib
@@ -27,3 +28,34 @@ def wrapper(self, *args, **kwargs):
return method(self, *args, **kwargs)
return wrapper
return wrap
+
+
+def basic_auth(checkfunc, realm="Authentication Required!"):
+ """Decorate methods with this to require basic auth"""
+ def wrap(method):
+ def request_auth(self):
+ self.set_header('WWW-Authenticate', 'Basic realm=%s' % realm)
+ self.set_status(401)
+ self.finish()
+ return False
+
+ @functools.wraps(method)
+ def wrapper(self, *args, **kwargs):
+ auth = self.request.headers.get('Authorization')
+ if auth is None or not auth.startswith('Basic '):
+ return request_auth(self)
+ auth = auth[6:]
+ try:
+ username, password = base64.decodestring(auth).split(':', 2)
+ except:
+ return request_auth(self)
+
+ if checkfunc(username, password):
+ self.request.basic_auth = (username, password)
+ return method(self, *args, **kwargs)
+ else:
+ return request_auth(self)
+
+ return wrapper
+
+ return wrap

0 comments on commit c9324bc

Please sign in to comment.