This commit is contained in:
James Vasile committed 2011-02-22 13:32:45 -05:00
commit 35071d7212
78 files changed
+5570

No files matched your search

+118
View File
@@ -0,0 +1,118 @@
# 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.
# TODO: DeprecationWarning: the md5 module is deprecated; use hashlib instead import md5
import cherrypy
import urllib, hashlib
import cfg
cfg.session_key = '_cp_username'
def check_credentials(username, passphrase):
"""Verifies credentials for username and passphrase.
Returns None on success or a string describing the error on failure"""
u = cfg.users.get(username)
if u is None:
cfg.log("Unknown user: %s" % username)
return u"Username %s is unknown to me." % username
if u['passphrase'] != hashlib.md5(passphrase).hexdigest():
return u"Incorrect passphrase."
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)
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():
raise cherrypy.HTTPRedirect("/auth/login")
else:
raise cherrypy.HTTPRedirect("/auth/login")
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("/auth/login?from_page=%s" % get_params)
else:
# Send old page as from_page parameter
raise cherrypy.HTTPRedirect("/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
+49
View File
@@ -0,0 +1,49 @@
import cherrypy
import cfg
from plugin_mount import PagePlugin
from modules.forms import Form
from auth import *
# Controller to provide login and logout actions
class AuthController(PagePlugin):
def __init__(self, *args, **kwargs):
PagePlugin.__init__(self, *args, **kwargs)
self.register_page("auth")
def on_login(self, username):
"""Called on successful login"""
def on_logout(self, username):
"""Called on logout"""
def get_loginform(self, username, msg='', from_page="/"):
form = Form(title="Login", action="/auth/login", message=msg)
form.text_input(name="from_page", value=from_page, type="hidden")
form.text_input("Username", name="username", value=username)
form.text_input("Passphrase", name="passphrase", type="password")
form.submit(label="Login")
return self.fill_template(main=form.render(), sidebar_right=" ")
@cherrypy.expose
def login(self, username=None, passphrase=None, from_page="/", **kwargs):
if username is None or passphrase is None:
return self.get_loginform("", from_page=from_page)
error_msg = check_credentials(username, passphrase)
if error_msg:
return self.get_loginform(username, error_msg, from_page)
else:
cherrypy.session[cfg.session_key] = cherrypy.request.login = username
self.on_login(username)
raise cherrypy.HTTPRedirect(from_page or "/")
@cherrypy.expose
def logout(self, from_page="/"):
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 "/")
+123
View File
@@ -0,0 +1,123 @@
class Form():
def __init__(self, action=None, cls='form', title=None, onsubmit=None, name=None, message='', method="get"):
"""Note that there appears to be a bug in cherrypy whereby
forms submitted via post don't have their fields included in
kwargs for the default index method. So we use get by
default, though it's not as neat."""
action = self.get_form_attrib_text('action', action)
onsubmit = self.get_form_attrib_text('onsubmit', onsubmit)
name = self.get_form_attrib_text('name', name)
self.pretext = ' <form class="%s" method="%s" %s%s%s>\n' % (cls, method, action, onsubmit, name)
if title:
self.pretext += ' <h2>%s</h2>\n' % title
if message:
self.message = "<h3>%s</h3>" % message
else:
self.message = ''
self.text = ''
self.end_text = "</form>\n"
def get_form_attrib_text(self, field, val):
if val:
return ' %s="%s"' % (field, val)
else:
return ''
def html(self, html):
self.text += html
def dropdown(self, label='', name=None, id=None, vals=None, select=None, onchange=''):
"""vals is a list of values.
select is the index in vals of the selected item. None means no item is selected yet."""
name, id = self.name_or_id(name, id)
self.text += (""" <label>
<span>%(label)s</span>
<select name="%(name)s" id="%(id)s" onchange="%(onchange)s">\n"""
% {'label':label, 'name':name, 'id':id, 'onchange':onchange})
for i in range(len(vals)):
v = vals[i]
if i == select:
selected = "SELECTED"
else:
selected = ''
self.text +=" <option value=\"%s\" %s>%s</option>\n" % (v, selected, v)
self.text += """ </select>
</label>\n"""
def dotted_quad(self, label='', name=None, id=None, quad=None):
name, id = self.name_or_id(name, id)
if not quad:
quad = [0,0,0,0]
self.text += """ <label>
<span>%(label)s</span>
<input type="text" class="inputtextnowidth" name="%(name)s0" id="%(id)s0" value="%(q0)s" maxlength="3" size="1"/><b>.</b>
<input type="text" class="inputtextnowidth" name="%(name)s1" id="%(id)s1" value="%(q1)s" maxlength="3" size="1"/><b>.</b>
<input type="text" class="inputtextnowidth" name="%(name)s2" id="%(id)s2" value="%(q2)s" maxlength="3" size="1"/><b>.</b>
<input type="text" class="inputtextnowidth" name="%(name)s3" id="%(id)s3" value="%(q3)s" maxlength="3" size="1"/>
</label>""" % {'label':label, 'name':name, 'id':id, 'q0':quad[0], 'q1':quad[1], 'q2':quad[2], 'q3':quad[3]}
def text_input(self, label='', name=None, id=None, type='text', value='', size=20):
name, id = self.name_or_id(name, id)
if type=="hidden":
self.text += '<input type="%s" class="inputtext" name="%s" id="%s" value="%s"/>' % (type, name, id, value)
else:
self.text += """ <label>
<span>%s</span>
<input type="%s" class="inputtext" name="%s" id="%s" value="%s" size="%s"/>
</label>""" % (label, type, name, id, value, size)
def text_box(self, label='', name=None, id=None):
name, id = self.name_or_id(name, id)
self.text += """
<label>
<span>%s</span>
<textarea class="textbox" name="%s" id="%s"></textarea>
</label>""" % (label, name, id)
def submit(self, label='', name=None, id=None):
name, id = self.name_or_id(name, id)
self.text += """
<div class="submit">
<label><span></span>
<input type="submit" class="button" value="%s" name="%s" id="%s" />
</label></div>\n""" % (label, name, id)
def submit_row(self, buttons):
"""buttons is a list of tuples, each containing label, name, id. Name and id are optional."""
self.text += '<div class="submit"><label>'
button_text = ''
for button in buttons:
label = button[0]
try:
name = button[1]
except:
name = None
try:
id = button[2]
except:
id = None
name, id = self.name_or_id(name, id)
if button_text != '':
button_text += "&nbsp;"
button_text += '<input type="submit" class="button" value="%s" name="%s" id="%s" />\n' % (label, name, id)
self.text += '%s</div></label>' % button_text
def name_or_id(self, name, id):
if not name: name = id
if not id: id = name
if not name: name = ''
if not id: id = ''
return name, id
def checkbox(self, label='', name='', id='', checked=''):
name, id = self.name_or_id(name, id)
if checked:
checked = 'checked="on"'
self.text += """
<div class="checkbox">
<label>
<span>%s</span>
<input type=checkbox name="%s" id="%s" %s/>
</label></div>\n""" % (label, name, id, checked)
def get_checkbox(self, name='', id=''):
return '<input type=checkbox name="%s" id="%s" />\n' % self.name_or_id(name, id)
def render(self):
return self.pretext+self.message+self.text+self.end_text
+112
View File
@@ -0,0 +1,112 @@
import os
import simplejson as json
import cherrypy
import cfg
from model import User
from plugin_mount import UserStoreModule
class UserStore(UserStoreModule):
"""The user storage is on disk. Rather than slurp the entire
thing, we read from the disk as needed. Writes are immediate,
though.
TODO: file locking"""
def __init__(self):
self.data_dir = cfg.users_dir
self.users = {}
def sanitize(username):
"""Return username with nonalphanumeric/underscore chars
removed.
TODO: allow international chars in usernames."""
pass
def attr(self, key, username):
"""Return field from username's record. If key does not
exist, don't raise attribute error, just return None.
User defaults to current. If no current user and none
specified, return none."""
try:
return self.get(username)[key]
except AttributeError:
return None
def current(self, 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:
return None
def expert(self, username=None):
"""Return True if user username is an expert, else False.
If username is None, use the current user. If no such user exists, return False."""
user = self.get(username)
if not user:
return False
return 'expert' in user['groups']
def get(self, username=None, reload=False):
"""Returns a user instance with the user's info or else None if the user couldn't be found.
If reload is true, reload from disk, regardless of dict's contents
If username is None, try current user. If no current user, return None.
TODO: implement user_store.get reload"""
if not username:
username = self.current(name=True)
try:
return self.users[username]
except KeyError:
try:
IF = open(os.path.join(self.data_dir, username), "r")
except IOError:
return None
data = IF.read()
IF.close()
# We cache the result, and since we assume a system with
# relatively few users and small user data files, we never
# expire those results. If we revisit that assumption, we
# might need some cache expiry.
self.users[username] = User(json.loads(data))
return self.users[username]
def exists(self, username):
"""Return True if username exists, else False."""
return username in self.users or os.path.exists(os.path.join(cfg.users_dir, username))
def get_all(self):
"Returns a list of all the user objects"
usernames = os.listdir(self.data_dir)
for name in usernames:
self.get(name)
return self.users
def set(self, user):
"""Set the user data, both in memory and as needed in storage."""
OF = open(os.path.join(self.data_dir, user['username']), 'w')
OF.write(json.dumps(user))
OF.close()
def remove(self, user):
"""Delete the user from storage and RAM. User can be a user instance or a username."""
try:
name = user['name']
except TypeError:
if isinstance(user, basestring):
name = user
else:
raise TypeError
os.unlink(os.path.join(cfg.users_dir, name))
try:
del self.users[name]
except KeyError:
pass
cfg.log.info("%s deleted %s" % (cherrypy.session.get(cfg.session_key), name))