Use Django dispatcher instead of CherryPy dispatcher

This commit is big because anything small breaks the code.

- Django dispatcher is based on regular expressions and does not need a tree structure
- Reduces a lot of unnecessary dependencies among modules
- Use Django sessions middlewear instead of CherryPy sessions
- Introduce dependency based modules instead of numeric load order
- Remove PagePlugin and simply use Django views
- Eliminate page rendering wrappers in favor of Django context processors
- Use custom auth for now until replaced by Django auth middlewear
- Use Django templated 404 and 500 error pages
This commit is contained in:
Sunil Mohan Adapa committed 2014-06-12 23:33:25 +05:30
1 parent 657bb11bbc
commit 58d13e3ed8
42 files changed
+1281 -1289

No files matched your search

+18 -83
View File
@@ -1,20 +1,13 @@
# Form based authentication for CherryPy. Requires the
# Session tool to be loaded.
#
# Thanks for this code is owed to Arnar Birgisson -at - gmail.com. It
# is based on code he wrote that was retrieved from
# http://tools.cherrypy.org/wiki/AuthenticationAndAccessRestrictions
# on 1 February 2011.
import cherrypy
import urllib
from django.http.response import HttpResponseRedirect
import functools
from passlib.hash import bcrypt
from passlib.exc import PasswordSizeError
import cfg
import random
from model import User
cfg.session_key = '_cp_username'
cfg.session_key = '_username'
def add_user(username, passphrase, name='', email='', expert=False):
"""Add a new user with specified username and passphrase.
@@ -49,6 +42,7 @@ def add_user(username, passphrase, name='', email='', expert=False):
cfg.log(error)
return error
def check_credentials(username, passphrase):
"""Verifies credentials for username and passphrase.
@@ -87,79 +81,20 @@ def check_credentials(username, passphrase):
if error:
cfg.log(error)
return error
def check_auth(*args, **kwargs):
"""A tool that looks in config for 'auth.require'. If found and it
is not None, a login is required and the entry is evaluated as a
list of conditions that the user must fulfill"""
conditions = cherrypy.request.config.get('auth.require', None)
# format GET params
get_params = urllib.quote(cherrypy.request.request_line.split()[1])
if conditions is not None:
username = cherrypy.session.get(cfg.session_key)
if username:
cherrypy.request.login = username
for condition in conditions:
# A condition is just a callable that returns true or false
if not condition():
# Send old page as from_page parameter
raise cherrypy.HTTPRedirect(cfg.server_dir + "/auth/login?from_page=%s" % get_params)
else:
# Send old page as from_page parameter
raise cherrypy.HTTPRedirect(cfg.server_dir + "/auth/login?from_page=%s" % get_params)
cherrypy.tools.auth = cherrypy.Tool('before_handler', check_auth)
def require(*conditions):
"""A decorator that appends conditions to the auth.require config
variable."""
def decorate(f):
if not hasattr(f, '_cp_config'):
f._cp_config = dict()
if 'auth.require' not in f._cp_config:
f._cp_config['auth.require'] = []
f._cp_config['auth.require'].extend(conditions)
return f
return decorate
# Conditions are callables that return True
# if the user fulfills the conditions they define, False otherwise
#
# They can access the current username as cherrypy.request.login
#
# Define those at will however suits the application.
def member_of(groupname):
def check():
# replace with actual check if <username> is in <groupname>
return cherrypy.request.login == 'joe' and groupname == 'admin'
return check
def name_is(reqd_username):
return lambda: reqd_username == cherrypy.request.login
# These might be handy
def any_of(*conditions):
"""Returns True if any of the conditions match"""
def check():
for c in conditions:
if c():
return True
return False
return check
# By default all conditions are required, but this might still be
# needed if you want to use it inside of an any_of(...) condition
def all_of(*conditions):
"""Returns True if all of the conditions match"""
def check():
for c in conditions:
if not c():
return False
return True
return check
# XXX: Only required until we start using Django authentication system properly
def login_required(func):
"""A decorator to ensure that user is logged in before accessing a view"""
@functools.wraps(func)
def wrapper(request, *args, **kwargs):
"""Check that user is logged in"""
if not request.session.get(cfg.session_key, None):
return HttpResponseRedirect(
cfg.server_dir + "/auth/login?from_page=%s" % request.path)
return func(request, *args, **kwargs)
return wrapper
+31 -44
View File
@@ -2,19 +2,17 @@
Controller to provide login and logout actions
"""
import cherrypy
import cfg
from django import forms
from django.http.response import HttpResponseRedirect
from django.template.response import TemplateResponse
from gettext import gettext as _
from plugin_mount import PagePlugin
import auth
import util
from . import auth
class LoginForm(forms.Form): # pylint: disable-msg=W0232
"""Login form"""
from_page = forms.CharField(widget=forms.HiddenInput(), required=False)
username = forms.CharField(label=_('Username'))
password = forms.CharField(label=_('Passphrase'),
widget=forms.PasswordInput())
@@ -33,48 +31,37 @@ class LoginForm(forms.Form): # pylint: disable-msg=W0232
return self.cleaned_data
class AuthController(PagePlugin):
"""Login and logout pages"""
def login(request):
"""Serve the login page"""
form = None
def __init__(self):
super(AuthController, self).__init__()
if request.method == 'POST':
form = LoginForm(request.POST, prefix='auth')
# pylint: disable-msg=E1101
if form.is_valid():
username = form.cleaned_data['username']
request.session[cfg.session_key] = username
return HttpResponseRedirect(_get_from_page(request))
else:
form = LoginForm(prefix='auth')
self.register_page('auth')
return TemplateResponse(request, 'form.html',
{'title': _('Login'),
'form': form,
'submit_text': _('Login')})
def on_login(self, username):
"""Called on successful login"""
def on_logout(self, username):
"""Called on logout"""
def logout(request):
"""Logout and redirect to origin page"""
try:
del request.session[cfg.session_key]
request.session.flush()
except KeyError:
pass
@cherrypy.expose
def login(self, from_page=cfg.server_dir+"/", **kwargs):
"""Serve the login page"""
form = None
return HttpResponseRedirect(_get_from_page(request))
if kwargs:
form = LoginForm(kwargs, prefix='auth')
# pylint: disable-msg=E1101
if form.is_valid():
username = form.cleaned_data['username']
cherrypy.session[cfg.session_key] = username
cherrypy.request.login = username
self.on_login(username)
raise cherrypy.HTTPRedirect(from_page or
(cfg.server_dir + "/"))
else:
form = LoginForm(prefix='auth')
return util.render_template(template='form', title=_('Login'),
form=form, submit_text=_('Login'))
@cherrypy.expose
def logout(self, from_page=cfg.server_dir+"/"):
sess = cherrypy.session
username = sess.get(cfg.session_key, None)
sess[cfg.session_key] = None
if username:
cherrypy.request.login = None
self.on_logout(username)
raise cherrypy.HTTPRedirect(from_page or (cfg.server_dir + "/"))
def _get_from_page(request):
"""Return the 'from page' of a request"""
return request.GET.get('from_page', cfg.server_dir + '/')
+24 -14
View File
@@ -1,4 +1,3 @@
import cherrypy
import cfg
from model import User
from plugin_mount import UserStoreModule
@@ -16,25 +15,36 @@ class UserStore(UserStoreModule, sqlite_db):
def close(self):
self.__exit__(None,None,None)
def current(self, name=False):
def current(self, request=None, name=False):
"""Return current user, if there is one, else None.
If name = True, return the username instead of the user."""
try:
username = cherrypy.session.get(cfg.session_key)
if name:
return username
else:
return self.get(username)
except AttributeError:
if not request:
return None
def expert(self, username=None):
try:
username = request.session[cfg.session_key]
except KeyError:
return None
if name:
return username
return self.get(username)
def expert(self, username=None, request=None):
"""Return whether the current or provided user is an expert"""
if not username:
username = self.current(name=True)
groups = self.attr(username,"groups")
if not request:
return False
username = self.current(request=request, name=True)
groups = self.attr(username, 'groups')
if not groups:
return False
return 'expert' in groups
return 'expert' in groups
def attr(self, username=None, field=None):
return self.get(username)[field]