add optional username/password protection

This commit is contained in:
j 2019-01-28 15:02:31 +05:30
parent a0a1b21aae
commit b1215fbc1b

View file

@ -6,6 +6,7 @@ import mimetypes
import os
from urllib.request import quote
import zipfile
import base64
import ox
@ -26,7 +27,42 @@ import state
import logging
logger = logging.getLogger(__name__)
class OMLHandler(tornado.web.RequestHandler):
class OptionalBasicAuthMixin(object):
class SendChallenge(Exception):
pass
def prepare(self):
if settings.preferences.get('authentication'):
try:
self.authenticate_user()
except self.SendChallenge:
self.send_auth_challenge()
def send_auth_challenge(self):
realm = "Open Media Library"
hdr = 'Basic realm="%s"' % realm
self.set_status(401)
self.set_header('www-authenticate', hdr)
self.finish()
return False
def authenticate_user(self):
auth_header = self.request.headers.get('Authorization')
if not auth_header or not auth_header.startswith('Basic '):
raise self.SendChallenge()
auth_data = auth_header.split(None, 1)[-1]
auth_data = base64.b64decode(auth_data).decode('ascii')
username, password = auth_data.split(':', 1)
auth = settings.preferences.get('authentication')
if auth.get('username') == username and auth.get('password') == password:
self._current_user = username
else:
raise self.SendChallenge()
class OMLHandler(OptionalBasicAuthMixin, tornado.web.RequestHandler):
def initialize(self):
pass
@ -140,7 +176,7 @@ class ReaderHandler(OMLHandler):
path = os.path.join(settings.static_path, html)
return serve_static(self, path, 'text/html')
class UploadHandler(tornado.web.RequestHandler):
class UploadHandler(OMLHandler):
def initialize(self, context=None):
self._context = context