PK¬5¿³ñ##authkit/commands.pyfrom paste.script.command import Command import os import glob from paste.script.command import Command, BadCommand from paste.script.filemaker import FileOp from paste.script import pluginlib, copydir class SecurityCommand(Command): summary = "Add Security Facilities" usage = 'SECURE_CONTROLLER_NAME' parser = Command.standard_parser(simulate=True) min_args = 0 max_args = 0 group_name = 'pylons' def command(self): try: self.verbose = 3 fo = FileOp(source_dir=os.path.dirname(__file__) + '/templates/pylons'.replace('/',os.sep)) #try: # name, dir = fo.parse_path_name_args(self.args[0]) #except: # raise BadCommand('No egg_info directory was found') fo.copy_file( template='security.py_tmpl', dest='controllers', filename='security.py', add_py = False, ) fo.ensure_dir('templates/security') for file in [ 'alreadyin.myt', 'alreadyout.myt', 'signedin.myt', 'signedout.myt', 'signin.myt', ]: fo.copy_file( template=file, dest='templates/security', filename=file, add_py = False, ) except: import sys msg = str(sys.exc_info()[1]) raise BadCommand('An unknown error ocurred, %s'%msg) PK 5‡@}¿¿authkit/commands.pyc;ò EJêDc@sldklZdkZdkZdklZlZdklZdklZl Z defd„ƒYZ dS((sCommandN(sCommands BadCommand(sFileOp(s pluginlibscopydirsSecurityCommandcBsAtZdZdZeideƒZdZdZ dZ d„Z RS(NsAdd Security FacilitiessSECURE_CONTROLLER_NAMEssimulateispylonsc Cséy¬d|_tdtiitƒdidtiƒƒ}|i ddddd d d t ƒ|i d ƒx?d ddddgD](}|i d|dd d |d t ƒqWWn6dk}t|iƒdƒ}td|ƒ‚nXdS(Nis source_dirs/templates/pylonss/stemplatessecurity.py_tmplsdests controllerssfilenames security.pysadd_pystemplates/securitys alreadyin.mytsalreadyout.myts signedin.myts signedout.myts signin.mytisAn unknown error ocurred, %s(sselfsverbosesFileOpsosspathsdirnames__file__sreplacessepsfos copy_filesFalses ensure_dirsfilessyssstrsexc_infosmsgs BadCommand(sselfssyssfilesmsgsfo((s)build\bdist.win32\egg\authkit\commands.pyscommands$ .     ( s__name__s __module__ssummarysusagesCommandsstandard_parsersTruesparsersmin_argssmax_argss group_namescommand(((s)build\bdist.win32\egg\authkit\commands.pysSecurityCommands( spaste.script.commandsCommandsossglobs BadCommandspaste.script.filemakersFileOps paste.scripts pluginlibscopydirsSecurityCommand(sSecurityCommands pluginlibsglobsFileOpscopydirsCommandsoss BadCommand((s)build\bdist.win32\egg\authkit\commands.pys?s    PK$¿ÿ4²7AXŠ+Š+authkit/middleware.py""" Use like this from authkit.middleware import Security, Authenticator class SimplestAuthenticator(Authenticator): def check_auth(self, username, password): if username == 'james' and password == 'bananas': return True else: return False app = Security( app, global_conf=global_conf, http_login=False, cookie_prefix='', login_page='security/signin', logout_page='security/signout', secret=None, authenticator=SimplestAuthenticator, ) """ # # Start Old paste.login code (slightly modified) # # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php """ Login/authentication middleware NOT YET FINISHED """ import paste.wsgilib as wsgilib # JG Modified import sha from paste.deploy import converters from paste.util import import_string def middleware( application, global_conf=None, http_login=False, http_realm='Secure Website', http_overwrite_realm=True, http_and_cookie=True, cookie_prefix='', login_page='_login/login_form', logout_page='_login/logout_form', secret=None, authenticator=None, ): """ Configuration: http_login: If true, then we'll prefer HTTP Basic logins, passing a 401 to the user. If false, we'll use form logins with Cookie authentication. http_realm: The realm to use. If http_overwrite_realm is true then we will force this to be the realm (even if the application supplies its own realm). http_and_cookie: If true, we'll give the user a login cookie even if they use HTTP. Then we don't have to throw a 401 on every page to get them to re-login. cookie_prefix: Used before all cookie names; like a domain. login_page: If using cookie login and we get a 401, we'll turn it into a 200 and do an internal redirect to this page (using recursive). logout_page: Ditto the logout (logout will at some point be triggered with another key we add to the environment). secret: We use this for signing cookies. We'll generate it automatically if it's not provided explicitly (set it explicitly to be sure it is stable). authenticator: When we do HTTP logins we need to tell if they are using the correct login immediately. See the Authenticator object for the framework of an implementation. When you require a login, return a 401 error. When a login has occurred, the logged-in username will be in REMOTE_USER. When the user is logged in, but denied access, use a 403 error (not a 401). It might be useful to have another middleware that wraps an application and returns a 401 error, based on parsing the URL. Currently, the login form, if used, is rendered at the URL requested by the user, instead of issuing an HTTP redirect. This will require some attention to caching issues, but allows forms to be POSTed without losing data after the login (as long as the login page contains the appropriate hidden fields.) Also, the cookie is not deleted on an unsuccessful login attempt. The cookie is issued with path '/' and no expiration date. This should probably be overridable. Environment variables used: paste.login.signer: signer, created from UsernameSigner class paste.login._dologin: user name to be logged in, either from HTTP auth or from form submission (XXX form not implement) paste.login._doredirect: login page to which to redirect paste.login._loginredirect: set to True iff _doredirect set and login_page is relative, else undefined. Used where? """ global_conf = global_conf or {} http_login = converters.asbool(http_login) http_overwrite_realm = converters.asbool(http_overwrite_realm) http_and_cookie = converters.asbool(http_and_cookie) if authenticator and isinstance(authenticator, (str, unicode)): authenticator = import_string.eval_import(authenticator) if http_login: assert authenticator, ( "You must provide an authenticator argument if you " "are using http_login") if secret is None: secret = global_conf.get('secret') if secret is None: secret = create_secret() cookie_name = cookie_prefix + '_login_auth' signer = UsernameSigner(secret) def login_application(environ, start_response): orig_script_name = environ['SCRIPT_NAME'] orig_path_info = environ['PATH_INFO'] cookies = wsgilib.get_cookies(environ) cookie = cookies.get(cookie_name) username = None environ['paste.login.signer'] = signer environ['paste.login.cookie_name'] = cookie_name # JG Modified environ['paste.login.authenticator'] = authenticator # JG Modified environ['paste.login.http_login'] = http_login if cookie and cookie.value: username = signer.check_signature( cookie.value, environ['wsgi.errors']) authenticatee = ( environ.get('HTTP_AUTHORIZATION') or environ.get('HTTP_CGI_AUTHORIZATION')) if (not username and authenticator and authenticatee): username = authenticator().check_basic_auth(authenticatee) if http_and_cookie: environ['paste.login._dologin'] = username if username: environ['REMOTE_USER'] = username def login_start_response(status, headers, exc_info=None): if environ.get('paste.login._dologin'): cookie = SimpleCookie(cookie_name, signer.make_signature(username), '/') headers.append(('Set-Cookie', str(cookie))) del environ['paste.login._dologin'] status_int = int(status.split(None, 1)[0].strip()) if status_int == 401 and http_login: if (http_overwrite_realm or not wsgilib.has_header(headers, 'www-authenticate')): headers.append(('WWW-Authenticate', 'Basic realm="%s"' % http_realm)) elif status_int == 401: status = '200 OK' if login_page.startswith('/'): assert environ.has_key('paste.recursive.include'), ( "You must use the recursive middleware to " "use a non-relative page for the login_page") environ['paste.login._doredirect'] = login_page return garbage_writer return start_response(status, headers, exc_info) app_iter = application(environ, login_start_response) if environ.get('paste.login._doredirect'): page_name = environ['paste.login._doredirect'] del environ['paste.login._doredirect'] eat_app_iter(app_iter) if login_page.startswith('/'): app_iter = environ['paste.recursive.forward']( login_page[1:]) else: # Don't use recursive, since login page is # internal to new_environ = environ.copy() new_environ['SCRIPT_NAME'] = orig_script_name new_environ['PATH_INFO'] = '/' + login_page new_environ['paste.login._loginredirect'] = True app_iter = login_application(new_environ, start_response) return app_iter return login_application def encodestrip(s): return s.encode('base64').strip('\n') class UsernameSigner(object): def __init__(self, secret): self.secret = secret def digest(self, username): return sha.new(self.secret+username).digest() def __call__(self, username): return encodestrip(self.digest(username)) def check_signature(self, b64value, errors): value = b64value.decode('base64') if ' ' not in value: errors.write('Badly formatted cookie: %r\n' % value) return None signature, username = value.split(' ', 1) sig_hash = self.digest(username) if sig_hash == signature: return username errors.write('Bad signature: %r\n' % value) return None def make_signature(self, username): return encodestrip(self.digest(username) + " " + username) def login_user(self, username, environ): """ Adds a username so that the login middleware will later set the user to be logged in (with a cookie). """ environ['paste.login._dologin'] = username class SimpleCookie(object): def __init__(self, cookie_name, signed_val, path): self.cookie_name = cookie_name self.signed_val = signed_val self.path = '/' def __str__(self): return "%s=%s; Path=%s" % (self.cookie_name, self.signed_val, self.path) class Authenticator(object): """ This is the basic framework for an authenticating object. """ def check_basic_auth(self, auth): """Returns either the authenticated username or, if unauthorized, None.""" assert auth.lower().startswith('basic ') type, auth = auth.split() auth = auth.strip().decode('base64') username, password = auth.split(':') if self.check_auth(username, password): return username return None def check_auth(self, username, password): raise NotImplementedError ######################################## ## Utility functions ######################################## def create_secret(): # @@: obviously not a good secret generator: should be randomized # somehow, and maybe store the secret somewhere for later use. return 'secret' def garbage_writer(s): """ When we don't care about the written output. """ pass def eat_app_iter(app_iter): """ When we don't care about the iterated output. """ try: for s in app_iter: pass finally: if hasattr(app_iter, 'close'): app_iter.close() # # End old paste.login code # # Currently broken, soon to be replaced by AuthKit anyway #~ from pylons.middleware import BaseMiddleware class ShowSignInOn403: def __init__(self, app): self.app = app def __call__(self, environ, start_response): def authkit_start_response(status, headers, exc_info=None): if status[:3] == '403': status = '401 Access was denied. Please sign in.' return start_response(status, headers, exc_info) return self.app(environ, authkit_start_response) Security = middlewarePK 5› Ý÷8÷8authkit/middleware.pyc;ò ÅŠÎDc @sßdZdkiZdkZdklZdklZee de e dddeed„ Z d „Z d e fd „ƒYZd e fd „ƒYZde fd„ƒYZd„Zd„Zd„Zdfd„ƒYZe ZdS(s Use like this from authkit.middleware import Security, Authenticator class SimplestAuthenticator(Authenticator): def check_auth(self, username, password): if username == 'james' and password == 'bananas': return True else: return False app = Security( app, global_conf=global_conf, http_login=False, cookie_prefix='', login_page='security/signin', logout_page='security/signout', secret=None, authenticator=SimplestAuthenticator, ) N(s converters(s import_stringsSecure Websitess_login/login_forms_login/logout_formc  s|ph}tiˆƒ‰tiˆƒ‰tiˆƒ‰ˆotˆtt fƒot i ˆƒ‰nˆoˆp t d‚n| tjo|idƒ} n| tjo tƒ} n|d‰t| ƒ‰ ‡‡‡‡‡‡‡‡‡‡ d†‰ˆSdS(s‰ Configuration: http_login: If true, then we'll prefer HTTP Basic logins, passing a 401 to the user. If false, we'll use form logins with Cookie authentication. http_realm: The realm to use. If http_overwrite_realm is true then we will force this to be the realm (even if the application supplies its own realm). http_and_cookie: If true, we'll give the user a login cookie even if they use HTTP. Then we don't have to throw a 401 on every page to get them to re-login. cookie_prefix: Used before all cookie names; like a domain. login_page: If using cookie login and we get a 401, we'll turn it into a 200 and do an internal redirect to this page (using recursive). logout_page: Ditto the logout (logout will at some point be triggered with another key we add to the environment). secret: We use this for signing cookies. We'll generate it automatically if it's not provided explicitly (set it explicitly to be sure it is stable). authenticator: When we do HTTP logins we need to tell if they are using the correct login immediately. See the Authenticator object for the framework of an implementation. When you require a login, return a 401 error. When a login has occurred, the logged-in username will be in REMOTE_USER. When the user is logged in, but denied access, use a 403 error (not a 401). It might be useful to have another middleware that wraps an application and returns a 401 error, based on parsing the URL. Currently, the login form, if used, is rendered at the URL requested by the user, instead of issuing an HTTP redirect. This will require some attention to caching issues, but allows forms to be POSTed without losing data after the login (as long as the login page contains the appropriate hidden fields.) Also, the cookie is not deleted on an unsuccessful login attempt. The cookie is issued with path '/' and no expiration date. This should probably be overridable. Environment variables used: paste.login.signer: signer, created from UsernameSigner class paste.login._dologin: user name to be logged in, either from HTTP auth or from form submission (XXX form not implement) paste.login._doredirect: login page to which to redirect paste.login._loginredirect: set to True iff _doredirect set and login_page is relative, else undefined. Used where? sFYou must provide an authenticator argument if you are using http_loginssecrets _login_authc sÕˆd}ˆd}tiˆƒ}|iˆƒ} t ‰ˆ ˆd<ˆˆd<ˆ ˆd<ˆ ˆd<| o| ioˆ i| iˆdƒ‰nˆidƒp ˆid ƒ}ˆ o ˆ o|o+ˆ ƒi|ƒ‰ˆoˆˆd tZd„Zd„Zd„Zd„Zd„Zd„ZRS(NcCs ||_dS(N(ssecretsself(sselfssecret((s+build\bdist.win32\egg\authkit\middleware.pys__init__âscCsti|i|ƒiƒSdS(N(sshasnewsselfssecretsusernamesdigest(sselfsusername((s+build\bdist.win32\egg\authkit\middleware.pysdigeståscCst|i|ƒƒSdS(N(s encodestripsselfsdigestsusername(sselfsusername((s+build\bdist.win32\egg\authkit\middleware.pys__call__èscCsŠ|idƒ}d|jo|id|ƒtSn|iddƒ\}}|i |ƒ}||jo|Sn|id|ƒtSdS(Nsbase64s sBadly formatted cookie: %r isBad signature: %r ( sb64valuesdecodesvalueserrorsswritesNonessplits signaturesusernamesselfsdigestssig_hash(sselfsb64valueserrorssusernamesvalues signaturessig_hash((s+build\bdist.win32\egg\authkit\middleware.pyscheck_signatureës  cCst|i|ƒd|ƒSdS(Ns (s encodestripsselfsdigestsusername(sselfsusername((s+build\bdist.win32\egg\authkit\middleware.pysmake_signature÷scCs||dtZeideƒZeideƒZeideƒZ RS(Ns not_emptysresolve_domain( s__name__s __module__s validatorssStringsTrues first_names last_namesEmailsFalsesemail(((s+build\bdist.win32\egg\authkit\validators.pysFullResgistration!ssAuthenticateValidatorcBstZd„ZRS(NcCs<|i|d|dƒo|Sntid||ƒ‚dS(NsusernamespasswordsIncorrect password(sstates authenticatesvalues formencodesInvalid(sselfsvaluesstate((s+build\bdist.win32\egg\authkit\validators.pys _to_python's(s__name__s __module__s _to_python(((s+build\bdist.win32\egg\authkit\validators.pysAuthenticateValidator&ssExistingUsernamecBstZd„ZRS(NcCs\|i}| otid||ƒ‚n+|i|ƒ otid||ƒ‚n|SdS(NsPlease enter a valuesNo such username(sstatesauthsvalues formencodesInvalids user_exists(sselfsvaluesstatesauth((s+build\bdist.win32\egg\authkit\validators.pys _to_python.s  (s__name__s __module__s _to_python(((s+build\bdist.win32\egg\authkit\validators.pysExistingUsername-ssSignIncBs;tZeiƒZeƒZeideƒZe ƒgZ RS(Ns not_empty( s__name__s __module__s validatorssStringsgosExistingUsernamesusernamesTruespasswordsAuthenticateValidatorschained_validators(((s+build\bdist.win32\egg\authkit\validators.pysSignIn8s  ( s formencodes validatorssFancyValidatorsUniqueUsernamesSecurePasswordsSchemasBasicRegistrationsFullResgistrationsAuthenticateValidatorsExistingUsernamesSignIn( sSecurePasswordsExistingUsernamesBasicRegistrations formencodesUniqueUsernamesSignInsAuthenticateValidators validatorssFullResgistration((s+build\bdist.win32\egg\authkit\validators.pys?s     PK¬5 ßô²T²Tauthkit/__init__.py"""AuthKit - authentication and authorisation facilities (C) James Gardner 2005 MIT Licence see AuthKit.__copyright__ """ __docformat__ = "restructuredtext" __copyright__ = """ Copyright (c) 2005 James Gardner All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author or contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ #__all__ = ['SQLObjectAuthStore','DatabaseAuthStore','AuthError','driver_names'] from extras.time import seconds import datetime # Python 2.1 support try: True False except NameError: True = 1 False = 0 import time, md5 #import web.auth def driver_names(): # XXX Needs to use egg plugins return ('DatabaseAuthStore', 'SQLObjectAuthStore') class AuthError(Exception): """ Error Class for the Auth Module. Use as follows:: try: raise AuthError(ERROR_PASSWORD) except AuthError, e: print 'Auth exception occurred, value:', e.value """ def __init__(self, value): self.value = value def __str__(self): return str(self.value) class IAuthStoreDriver: pass class IAuthStore: # # Session Functions (These functions do not authorisation or authentication, they just store auth session information # def authorise(self, username, application='default', role=None, active=1, group=[], signed_in=None, idle_max=None, session_max=None): username = username.lower() user = self.user(username) self._driver_update_accessed(username) if active not in [1,0,None]: raise AuthError('active can only be True, False or None, not %s'%repr(active)) #if application != None and level == None and role==None: # raise AuthError('You must specify a role or access level as well as the application') if group != []: if not self._driver_group_exists(group): raise AuthError('No such group %s'%repr(group)) elif user['group'] != group: return False if active in [1,0] and user['active'] != active: return False if role != None and (not user['roles'].has_key(application) or role not in user['roles'][application]): return False if signed_in != None or session_max != None or idle_max != None: is_signed_in = False history = self._driver_history(username) #raise Exception(history) if history: if history[0][0] == None: is_signed_in = True if (signed_in == True and is_signed_in == False) or (signed_in == False and is_signed_in == True): return False if (session_max != None or idle_max != None) and is_signed_in == False: return False if session_max != None: #raise Exception(datetime.datetime(2005,12,12,12).now() - history[0][0]) if datetime.datetime(2005,12,12,12).now() - history[0][1] >= datetime.timedelta(seconds=seconds(session_max)): return False if idle_max != None: if datetime.datetime(2005,12,12,12).now() - history[0][2] >= datetime.timedelta(seconds=seconds(idle_max)): return False return True authorize = authorise def authenticate(self, username, password): if not self.user_exists(username): return False realpassword = self._driver_user(username, property='password') if self._encryption == 'md5': password = md5.new(password).hexdigest() return realpassword == password def sign_out(self, username): if self.authorise(username, signed_in=1): return self._driver_sign_out(username) # XXX should return 1 if signed out return 0 #~ if self.store.has_key('username'): #~ del self.store['username'] #~ if self.store.has_key('started'): #~ del self.store['started'] #~ if self.store.has_key('accessed'): #~ del self.store['accessed'] #~ if self.store.has_key('expire'): #~ del self.store['expire'] #~ if self.store.has_key('idle'): #~ del self.store['idle'] #~ self.signedInUser = None def sign_in(self, username): code = 0 #if self.authorise(username, signed_in=1): # self._driver_sign_out(username) # code = 1 # XXX should return 1 if signed out return self._driver_sign_in(username) #~ username = username.lower() #~ currentTime = int(time.time()) #~ self.store['username'] = username.lower() #~ self.store['started'] = currentTime #~ self.store['accessed'] = currentTime #~ self.store['expire'] = self.expire #~ self.store['idle'] = self.idle #~ self.signedInUser = self.user() def history(self, username):#, before=None, After=None, operation='and'): #~ if username and usernames and usernames.count(username) == 0: #~ usernames.append(username) #~ if usernames == None: #~ raise TypeError('No usernames specified') return self._driver_history(username) #~ def username(self): #~ if self.store.has_key('username'): # We have signed in in the past #~ started = self.store['started'] #~ accessed = self.store['accessed'] #~ currentTime = int(time.time()) #~ if self.expire and ((self.expire + started) <= currentTime): #~ # store Expired #~ self.signOut() #~ return None #~ elif self.idle and ((self.idle + accessed) <= currentTime): #~ # store Idled #~ self.signOut() #~ return None #~ else: #~ self.store['accessed'] = int(time.time()) #~ return self.store['username'] #~ else: #~ # No username #~ return None #~ def userInfo(self): # Changed #~ username = self.username() #~ if username: #~ return { #~ 'username':username, #~ 'started' :self.store['started'], #~ 'accessed':self.store['accessed'], #~ 'expire' :self.store['expire'], #~ 'idle' :self.store['idle'], #~ } #~ else: #~ return None # Manager Functions # def user(self, username, property=None): #~ userInfo = { #~ 'username':username, #~ 'started' :None, #~ 'accessed':None, #~ 'expire' :None, #~ 'idle' :None, #~ } if not property: user = self._driver_user(username.lower()) return AuthUser(self, user, self._encryption) else: return self._driver_user(username.lower(), property) # # Environment # def create_store(self): self._driver_create_store() self._driver_add_application(name='default') def remove_store(self): return self._driver_remove_store() def store_exists(self): """Checks whether *all* the components of the auth store exist""" return self._driver_store_exists() # # Applications # def applications(self): return self._driver_applications() def application_exists(self, name): if not isinstance(name, str): raise AuthError('The application name should be a string') return self._driver_application_exists(name) def add_application(self, name): if not isinstance(name, str): raise AuthError('The application name should be a string') if self.application_exists(name): raise AuthError("The application '%s' already exists."%name) return self._driver_add_application(name) def remove_application(self, name, unset_roles=False): if not isinstance(name, str): raise AuthError('The application name should be a string') if not self.application_exists(name): raise AuthError("The application '%s' doesn't exist in the database."%name) return self._driver_remove_application(name, unset_roles) # # Users # def users(self, group=[], active=None, application=None, role=None): if not (isinstance(group, str) or group in [None,[]]): raise AuthError('Expected group to be a string, None, or [] to indicate any group, not %s'%repr(group)) if not (isinstance(role, str) or role==None): raise AuthError('Expected role to be a string or None, not %s'%repr(role)) if not active in [None, True, False]: raise AuthError('Expected active to be None, True or False, not %s'%repr(role)) if not (isinstance(application, str) or application==None): raise AuthError('Expected application to be a string or None, not %s'%repr(application)) if group != [] and group!=None and not self.group_exists(group): raise AuthError('No such group %s'%repr(group)) if application!=None and not self.application_exists(application): raise AuthError('No such application %s'%repr(application)) if role != [] and role!=None and not self.role_exists(role): raise AuthError('No such role %s'%repr(role)) return self._driver_users(group, active, application, role) def user_exists(self, username): return self._driver_user_exists(username.lower()) def add_user(self, username, password='', firstname='', surname='', email='', active=1, group=None): # CHANGED if self.user_exists(username): raise AuthError('That user already exists.') if group != None and not self.group_exists(group): raise AuthError('That group doesn\'t exist.') for property in [firstname, surname, email, password]: if not isinstance(property, str): raise AuthError("The params firstname, surname, email, password should all be strings") if active not in [True, False ,None]: raise AuthError('The param \'active\' can only be True, False or None, not %s'%repr(active)) if self._encryption == 'md5': password = md5.new(password).hexdigest() return self._driver_add_user(username.lower(), password, firstname, surname, email, active, group) def remove_user(self, username): return self._driver_remove_user(username.lower()) def set_user(self, username, **p): return self._driver_set_user(username, **p) #~ # #~ # Access Levels #~ # #~ def levels(self, username, application='default',): #~ username = username.lower() #~ return self._driver_levels(username, application) #~ def setLevel(self, username, application='default', level): #~ username = username.lower() #~ return self._driver_setLevel(username, application='default', level) # # Roles # def add_role(self, role): if not isinstance(role, str): raise AuthError('The application name should be a string') if self.role_exists(role): raise AuthError("The '%s' role already exists."%role) return self._driver_add_role(role) def role_exists(self, role): if not isinstance(role, str): raise AuthError('The application name should be a string') return self._driver_role_exists(role) def remove_role(self, role, unset_roles=False): if not isinstance(role, str): raise AuthError('The application name should be a string') if not self.role_exists(role): raise AuthError("The '%s' role doesn't exist in the database."%role) return self._driver_remove_role(role, unset_roles) def roles(self, username=None, application=None): # this is correct app shouldn't be default if username != None: username = username.lower() return self._driver_roles(username, application) def has_role(self, username, role, application='default',): if username == None or role == None: return False else: username = username.lower() roles = self._driver_roles(username, application) return (role in roles) def set_group(self, username, group): self.user(username.lower()).group = group def set_role(self, username, role, application='default',): username = username.lower() roles = role if not (isinstance(roles, tuple) or isinstance(roles, list)): roles = [roles] return self._driver_set_role(username, roles, application) def unset_role(self, username, role, application='default'): username = username.lower() return self._driver_unset_role(username, role, application) def unset_all_roles(self, username): for application, roles in self.user(username).roles.items(): for role in roles: self.unset_role(username, application=application, role=role) # # Groups # def group_exists(self, group): if not isinstance(group, str): raise AuthError('The application name should be a string') return self._driver_group_exists(group) def add_group(self, group): if not isinstance(group, str): raise AuthError('The application name should be a string') if self.group_exists(group): raise AuthError("The '%s' group already exists."%group) return self._driver_add_group(group) def remove_group(self, group, remove_users=False): if not isinstance(group, str): raise AuthError('The application name should be a string') if not self.group_exists(group): raise AuthError("The '%s' group doesn't exist in the database."%group) return self._driver_remove_group(group, remove_users) def groups(self): return self._driver_groups() def permissions(**kw): for key in kw.keys(): if key not in ['username', 'signed_in', 'idle_max', 'session_max', 'group','role','application']: raise AuthError('Invalid permission parameter %s'%repr(key)) return kw class AuthUser: def __init__(self, driver, user, encryption): self.__dict__['_driver'] = driver self.__dict__['encryption'] = encryption if self.encryption not in [None, 'md5']: raise AuthError('Invalid encryption format %s'%self.encryption) #self.__dict__['username'] = userInfo['username'] #self.__dict__['started'] = userInfo['started'] #self.__dict__['accessed'] = userInfo['accessed'] #self.__dict__['expire'] = userInfo['expire'] # self.__dict__['idle'] = userInfo['idle'] #user = self._driver_user(self.username) self.__dict__['username'] = user['username'] self.__dict__['password'] = user['password'] self.__dict__['firstname'] = user['firstname'] self.__dict__['surname'] = user['surname'] self.__dict__['email'] = user['email'] #self.__dict__['levels'] = user['levels'] self.__dict__['roles'] = user['roles'] self.__dict__['active'] = user['active'] self.__dict__['group'] = user['group'] self.__dict__['history'] = self._driver.history(user['username']) #if self.history #self.__dict__['history'] = self._driver.history(user['username']) def __setattr__(self, name, value): return self.__setitem__(name, value) def __setitem__(self, name, value): if name in ['firstname', 'surname', 'email', 'group', 'active']: p = {name:value} self._driver._driver_set_user(self.username, **p) # Set in the database self.__dict__[name] = value # Set in the class elif name == 'password': if self.encryption == 'md5': value = md5.new(value).hexdigest() p = {name:value} self._driver._driver_set_user(self.username, **{name:value}) # Set in the database self.__dict__[name] = value # Set in the class else: if name in self.__dict__.keys(): raise AttributeError('You cannot set the value of the %s attribute'%name) else: raise AttributeError('No such attribute %s'%name) def __getitem__(self, name): if name in ['firstname', 'surname', 'email', 'group', 'active', 'password', 'roles', 'history']: return getattr(self, name) raise KeyError('No such key %s'%name) #~ class AuthManager(AuthAdmin, AuthSession): #~ def __init__(self, store, driver, expire=0, idle=0, autoCreate=0, encryption=None, **driverParams): #~ self.__dict__['encryption'] = encryption #~ if self.encryption not in [None, 'md5']: #~ raise AuthError('Invalid encryption format %s'%self.encryption) #~ self.autoCreate = autoCreate #~ self.store = store #~ self.expire = seconds(expire) #~ self.idle = seconds(idle) #~ if driver == 'database': #~ import drivers.database #~ self._driver = drivers.database.DatabaseAuthDriver(**driverParams) #~ else: #~ raise AuthError('No such driver %s'%driver) #~ self.autoCreated = 0 #~ if self.autoCreate: #~ if not self.completeAuthEnvironment(): #~ self.removeAuthEnvironment(ignoreErrors=True) #~ self.createAuthEnvironment() #~ self.addApp('application') #~ self.addUser( #~ 'john', #~ 'bananas', #~ 'John', #~ 'Smith', #~ 'johnsmith@example.com', #~ ) #~ self.setLevel('john', 'application', 1) #~ self.autoCreated = 1 #~ self.signedInUser = self.user() #~ # #~ # Manager Functions #~ # #~ def user(self, username=None): #~ if username == None: #~ userInfo = self.userInfo() #~ else: #~ username = username.lower() #~ userInfo = { #~ 'username':username, #~ 'started' :None, #~ 'accessed':None, #~ 'expire' :None, #~ 'idle' :None, #~ } #~ if userInfo == None: #~ return None #~ return AuthUser(self._driver, userInfo, self.encryption) class AuthStore(IAuthStore, IAuthStoreDriver): def __init__(self, encryption=None): #~ self.autoCreate = autoCreate #~ if driver == 'database': #~ import drivers.database #~ self._driver = drivers.database.DatabaseAuthDriver(**driverParams) #~ else: #~ raise AuthError('No such driver %s'%driver) #~ self.autoCreated = 0 #~ if self.autoCreate: #~ if not self.completeAuthEnvironment(): #~ self.removeAuthEnvironment(ignoreErrors=True) #~ self.createAuthEnvironment() #~ self.addApp('application') #~ self.addUser( #~ 'john', #~ 'bananas', #~ 'John', #~ 'Smith', #~ 'johnsmith@example.com', #~ ) #~ self.setLevel('john', 'application', 1) #~ self.autoCreated = 1 self._store_exists = self.store_exists() self._encryption = encryption if self._encryption not in [None, 'md5']: raise AuthError('Invalid encryption format %s'%self._encryption) from authkit.drivers.SQLObject_driver import SQLObjectAuthStore, connectionForURI from authkit.drivers.database import DatabaseAuthStore from authkit.controllers import * PK 5þmO;Q;Qauthkit/__init__.pyc;ò EJêDc@s dZdZdZdklZdkZy eeWnej odZdZnXdk Z dk Z d„Z de fd „ƒYZ d fd „ƒYZd fd „ƒYZd„Zdfd„ƒYZdeefd„ƒYZdklZlZdklZdkTdS(stAuthKit - authentication and authorisation facilities (C) James Gardner 2005 MIT Licence see AuthKit.__copyright__ srestructuredtexts» Copyright (c) 2005 James Gardner All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author or contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ssecondsNiicCsddfSdS(NsDatabaseAuthStoresSQLObjectAuthStore((((s)build\bdist.win32\egg\authkit\__init__.pys driver_names3ss AuthErrorcBs tZdZd„Zd„ZRS(sÙ Error Class for the Auth Module. Use as follows:: try: raise AuthError(ERROR_PASSWORD) except AuthError, e: print 'Auth exception occurred, value:', e.value cCs ||_dS(N(svaluesself(sselfsvalue((s)build\bdist.win32\egg\authkit\__init__.pys__init__CscCst|iƒSdS(N(sstrsselfsvalue(sself((s)build\bdist.win32\egg\authkit\__init__.pys__str__Es(s__name__s __module__s__doc__s__init__s__str__(((s)build\bdist.win32\egg\authkit\__init__.pys AuthError7s  sIAuthStoreDrivercBstZRS(N(s__name__s __module__(((s)build\bdist.win32\egg\authkit\__init__.pysIAuthStoreDriverHss IAuthStorecBsstZdedgeeed„ZeZd„Zd„Zd„Zd„Zed„Z d „Z d „Z d „Z d „Z d „Zd„Zed„Zgeeed„Zd„Zddddded„Zd„Zd„Zd„Zd„Zed„Zeed„Zdd„Zd„Zdd„Zdd„Zd„Zd„Z d „Z!ed!„Z"d"„Z#RS(#Nsdefaultic Cs­|iƒ}|i|ƒ} |i|ƒ|ddtgjotdt|ƒƒ‚n|gjoH|i |ƒ otdt|ƒƒ‚q­| d|jot Sq­n|ddgjo| d|jot Sn|tjo'| di |ƒ p|| d|jot Sn|tjp|tjp |tjoft } |i|ƒ} | o#| ddtjo t} q~n|tjo | t jp|t jo | tjot Sn|tjp |tjo | t jot Sn|tjoOtidd d d ƒiƒ| ddtid t|ƒƒjot SqEn|tjoOtidd d d ƒiƒ| dd tid t|ƒƒjot Sq¡q¥ntSdS( Niis.active can only be True, False or None, not %ssNo such group %ssgroupsactivesrolesiÕi ssecondsi(susernameslowersselfsusers_driver_update_accessedsactivesNones AuthErrorsreprsgroups_driver_group_existssFalsesroleshas_keys applications signed_ins session_maxsidle_maxs is_signed_ins_driver_historyshistorysTruesdatetimesnows timedeltasseconds( sselfsusernames applicationsrolesactivesgroups signed_insidle_maxs session_maxs is_signed_insusershistory((s)build\bdist.win32\egg\authkit\__init__.pys authoriseRs>    $7'4' C  CcCse|i|ƒ otSn|i|ddƒ}|idjoti|ƒi ƒ}n||jSdS(Nspropertyspasswordsmd5( sselfs user_existssusernamesFalses _driver_users realpasswords _encryptionsmd5snewspasswords hexdigest(sselfsusernamespasswords realpassword((s)build\bdist.win32\egg\authkit\__init__.pys authenticateys cCs/|i|ddƒo|i|ƒSndSdS(Ns signed_inii(sselfs authorisesusernames_driver_sign_out(sselfsusername((s)build\bdist.win32\egg\authkit\__init__.pyssign_outscCsd}|i|ƒSdS(Ni(scodesselfs_driver_sign_insusername(sselfsusernamescode((s)build\bdist.win32\egg\authkit\__init__.pyssign_in“scCs|i|ƒSdS(N(sselfs_driver_historysusername(sselfsusername((s)build\bdist.win32\egg\authkit\__init__.pyshistory¤scCsN| o,|i|iƒƒ}t|||iƒSn|i|iƒ|ƒSdS(N(spropertysselfs _driver_usersusernameslowersusersAuthUsers _encryption(sselfsusernamespropertysuser((s)build\bdist.win32\egg\authkit\__init__.pysuserÑs cCs|iƒ|iddƒdS(Nsnamesdefault(sselfs_driver_create_stores_driver_add_application(sself((s)build\bdist.win32\egg\authkit\__init__.pys create_storeås cCs|iƒSdS(N(sselfs_driver_remove_store(sself((s)build\bdist.win32\egg\authkit\__init__.pys remove_storeéscCs|iƒSdS(s;Checks whether *all* the components of the auth store existN(sselfs_driver_store_exists(sself((s)build\bdist.win32\egg\authkit\__init__.pys store_existsìscCs|iƒSdS(N(sselfs_driver_applications(sself((s)build\bdist.win32\egg\authkit\__init__.pys applicationsôscCs2t|tƒ otdƒ‚n|i|ƒSdS(Ns'The application name should be a string(s isinstancesnamesstrs AuthErrorsselfs_driver_application_exists(sselfsname((s)build\bdist.win32\egg\authkit\__init__.pysapplication_exists÷scCsVt|tƒ otdƒ‚n|i|ƒotd|ƒ‚n|i|ƒSdS(Ns'The application name should be a strings$The application '%s' already exists.(s isinstancesnamesstrs AuthErrorsselfsapplication_existss_driver_add_application(sselfsname((s)build\bdist.win32\egg\authkit\__init__.pysadd_applicationüs cCsZt|tƒ otdƒ‚n|i|ƒ otd|ƒ‚n|i||ƒSdS(Ns'The application name should be a strings3The application '%s' doesn't exist in the database.(s isinstancesnamesstrs AuthErrorsselfsapplication_existss_driver_remove_applications unset_roles(sselfsnames unset_roles((s)build\bdist.win32\egg\authkit\__init__.pysremove_applications cCs»t|tƒp|tggj otdt|ƒƒ‚nt|tƒp |tj otdt|ƒƒ‚n|ttt gj otdt|ƒƒ‚nt|tƒp |tj otdt|ƒƒ‚n|gjo|tjo|i |ƒ otdt|ƒƒ‚n|tjo|i |ƒ otdt|ƒƒ‚n|gjo|tjo|i|ƒ otdt|ƒƒ‚n|i||||ƒSdS(NsHExpected group to be a string, None, or [] to indicate any group, not %ss,Expected role to be a string or None, not %ss1Expected active to be None, True or False, not %ss3Expected application to be a string or None, not %ssNo such group %ssNo such application %ssNo such role %s(s isinstancesgroupsstrsNones AuthErrorsreprsrolesactivesTruesFalses applicationsselfs group_existssapplication_existss role_existss _driver_users(sselfsgroupsactives applicationsrole((s)build\bdist.win32\egg\authkit\__init__.pysuserss$++cCs|i|iƒƒSdS(N(sselfs_driver_user_existssusernameslower(sselfsusername((s)build\bdist.win32\egg\authkit\__init__.pys user_existsssc Cs|i|ƒotdƒ‚n|tjo|i|ƒ otdƒ‚nx;||||gD]'}t |t ƒ otdƒ‚qaqaW|tttgjotdt|ƒƒ‚n|idjoti|ƒiƒ}n|i|iƒ||||||ƒSdS(NsThat user already exists.sThat group doesn't exist.sDThe params firstname, surname, email, password should all be stringss:The param 'active' can only be True, False or None, not %ssmd5(sselfs user_existssusernames AuthErrorsgroupsNones group_existss firstnamessurnamesemailspasswordspropertys isinstancesstrsactivesTruesFalsesreprs _encryptionsmd5snews hexdigests_driver_add_userslower( sselfsusernamespasswords firstnamessurnamesemailsactivesgroupsproperty((s)build\bdist.win32\egg\authkit\__init__.pysadd_user#scCs|i|iƒƒSdS(N(sselfs_driver_remove_usersusernameslower(sselfsusername((s)build\bdist.win32\egg\authkit\__init__.pys remove_user1scKs|i||SdS(N(sselfs_driver_set_usersusernamesp(sselfsusernamesp((s)build\bdist.win32\egg\authkit\__init__.pysset_user4scCsVt|tƒ otdƒ‚n|i|ƒotd|ƒ‚n|i|ƒSdS(Ns'The application name should be a stringsThe '%s' role already exists.(s isinstancesrolesstrs AuthErrorsselfs role_existss_driver_add_role(sselfsrole((s)build\bdist.win32\egg\authkit\__init__.pysadd_roleGs cCs2t|tƒ otdƒ‚n|i|ƒSdS(Ns'The application name should be a string(s isinstancesrolesstrs AuthErrorsselfs_driver_role_exists(sselfsrole((s)build\bdist.win32\egg\authkit\__init__.pys role_existsNscCsZt|tƒ otdƒ‚n|i|ƒ otd|ƒ‚n|i||ƒSdS(Ns'The application name should be a strings,The '%s' role doesn't exist in the database.(s isinstancesrolesstrs AuthErrorsselfs role_existss_driver_remove_roles unset_roles(sselfsroles unset_roles((s)build\bdist.win32\egg\authkit\__init__.pys remove_roleSs cCs1|tjo|iƒ}n|i||ƒSdS(N(susernamesNoneslowersselfs _driver_roless application(sselfsusernames application((s)build\bdist.win32\egg\authkit\__init__.pysrolesZs cCsN|tjp |tjotSn)|iƒ}|i||ƒ}||jSdS(N( susernamesNonesrolesFalseslowersselfs _driver_roless applicationsroles(sselfsusernamesroles applicationsroles((s)build\bdist.win32\egg\authkit\__init__.pyshas_role_s  cCs||i|iƒƒ_dS(N(sgroupsselfsusersusernameslower(sselfsusernamesgroup((s)build\bdist.win32\egg\authkit\__init__.pys set_groupgscCsW|iƒ}|}t|tƒp t|tƒ o |g}n|i|||ƒSdS(N( susernameslowersrolesroless isinstancestupleslistsselfs_driver_set_roles application(sselfsusernamesroles applicationsroles((s)build\bdist.win32\egg\authkit\__init__.pysset_rolejs  ! cCs#|iƒ}|i|||ƒSdS(N(susernameslowersselfs_driver_unset_rolesroles application(sselfsusernamesroles application((s)build\bdist.win32\egg\authkit\__init__.pys unset_roleqs cCsWxP|i|ƒiiƒD]6\}}x'|D]}|i|d|d|ƒq,WqWdS(Ns applicationsrole(sselfsusersusernamesrolessitemss applicationsroles unset_role(sselfsusernames applicationsrolesroles((s)build\bdist.win32\egg\authkit\__init__.pysunset_all_rolesus  cCs2t|tƒ otdƒ‚n|i|ƒSdS(Ns'The application name should be a string(s isinstancesgroupsstrs AuthErrorsselfs_driver_group_exists(sselfsgroup((s)build\bdist.win32\egg\authkit\__init__.pys group_exists~scCsVt|tƒ otdƒ‚n|i|ƒotd|ƒ‚n|i|ƒSdS(Ns'The application name should be a stringsThe '%s' group already exists.(s isinstancesgroupsstrs AuthErrorsselfs group_existss_driver_add_group(sselfsgroup((s)build\bdist.win32\egg\authkit\__init__.pys add_groupƒs cCsZt|tƒ otdƒ‚n|i|ƒ otd|ƒ‚n|i||ƒSdS(Ns'The application name should be a strings-The '%s' group doesn't exist in the database.(s isinstancesgroupsstrs AuthErrorsselfs group_existss_driver_remove_groups remove_users(sselfsgroups remove_users((s)build\bdist.win32\egg\authkit\__init__.pys remove_groupŠs cCs|iƒSdS(N(sselfs_driver_groups(sself((s)build\bdist.win32\egg\authkit\__init__.pysgroups‘s($s__name__s __module__sNones authorises authorizes authenticatessign_outssign_inshistorysusers create_stores remove_stores store_existss applicationssapplication_existssadd_applicationsFalsesremove_applicationsuserss user_existssadd_users remove_usersset_usersadd_roles role_existss remove_rolesrolesshas_roles set_groupsset_roles unset_rolesunset_all_roless group_existss add_groups remove_groupsgroups(((s)build\bdist.win32\egg\authkit\__init__.pys IAuthStoreLs@%    -                     c Ks[xP|iƒD]B}|dddddddgjotdt|ƒƒ‚q q W|SdS( Nsusernames signed_insidle_maxs session_maxsgroupsroles applicationsInvalid permission parameter %s(skwskeysskeys AuthErrorsrepr(skwskey((s)build\bdist.win32\egg\authkit\__init__.pys permissions”s  "sAuthUsercBs,tZd„Zd„Zd„Zd„ZRS(NcCsð||id<||id<|itdgjotd|iƒ‚n|d|id<|d|id<|d|id<|d|id<|d |id <|d |id <|d |id <|d |id <|ii|dƒ|id 2002-2005 All Rights Reserved # Licensed under LGPL # """Database driver for AuthKit. Developer Notes: * User columns are named ``user`` rather than ``username`` to avoid problems with Gadfly * The Group column is named ``grp`` rather than ``group`` to avoid confusion with SQL ``GROUP BY`` """ from authkit import AuthError, AuthStore import datetime try: True False except NameError: True = 1==1 False = 0==1 class DatabaseAuthStore(AuthStore): """ An auth store which makes use of the PythonWeb.org ``database`` module to store auth information in an SQL database. This driver is know to work with pysqlite 1.1.6 and MySQLdb 1.0. ``DatabaseAuthStore`` is used as follows:: import database connection = database.connect(dsn="sqlite:///test.db") cursor = connection.cursor() auth = DatabaseAuthStore(cursor=connection.cursor()) Do whatever you want with the newly created ``auth`` object then save changes:: connection.commit() """ def __init__(self, cursor, table_prepend='AuthKit_', **auth_store_params): self.cursor = cursor self._table_prepend = table_prepend AuthStore.__init__(self, **auth_store_params) # # Environment Methods # def _driver_create_store(self): """ Destroy any existing store and create the auth store. If any errors are generated when creating the store an ``authkit.AuthError`` is raised. """ errors = [] if not self.cursor.tableExists(self._table_prepend+'User'): self.cursor.create( table=self._table_prepend+'User', columns=[ ('user', 'String' ), ('password', 'String'),# required=True, default=''), ('firstname','String'),#required=True, default=''), ('surname', 'String'),# required=True, default=''), ('email', 'String'),# required=True, default=''), ('active', 'Bool'),# required=True, default=1), ('grp', 'String' ), ] ) else: errors.append("The '"+self._table_prepend+'User'+"' table already exists.") if not self.cursor.tableExists(self._table_prepend+'App'): self.cursor.create( table=self._table_prepend+'App', columns=[ ('name', 'String' ), ] ) else: errors.append("The '"+self._table_prepend+'App'+"' table already exists.") if not self.cursor.tableExists(self._table_prepend+'Group'): self.cursor.create( table=self._table_prepend+'Group', columns=[ ('name', 'String' ), ] ) else: errors.append("The '"+self._table_prepend+'Group'+"' table already exists.") if not self.cursor.tableExists(self._table_prepend+'Role'): self.cursor.create( table=self._table_prepend+'Role', columns=[ ('name', 'String' ), ] ) else: errors.append("The '"+self._table_prepend+'Role'+"' table already exists.") if not self.cursor.tableExists(self._table_prepend+'Roles'): self.cursor.create( table=self._table_prepend+'Roles', columns=[ ('user', 'String'), ('application', 'String'), ('role', 'String'), ] ) else: errors.append("The '"+self._table_prepend+'Roles'+"' table already exists.") if not self.cursor.tableExists(self._table_prepend+'History'): self.cursor.create( table=self._table_prepend+'History', columns=[ ('user', 'String'), ('signed_in', 'DateTime'), ('last_accessed', 'DateTime'), ('signed_out', 'DateTime'), ] ) else: errors.append("The '"+self._table_prepend+'History'+"' table already exists.") if errors: raise AuthError(', '.join(errors)) def _driver_remove_store(self): """ Remove the auth store, destroying any data it contains. If there are no problems, ``[]`` is returned. If any errors occurs preventing the store from being removed an ``authkit.AuthError`` is raised. If the store doesn't exist or only partially exists, any warnings are returned as a list of strings. """ errors = [] for table in [ 'User', 'App', 'Group', 'Role', 'Roles' 'History' ]: try: self.cursor.drop(self._table_prepend+table) except: errors.append("The "+self._table_prepend+table+" table may not exist. Error: %s"%str(sys.exc_info()[1])) return errors def _driver_store_exists(self): """ Returns ``True`` if every component of the store exists, ``False`` otherwise. Typically used as follows:: if not auth.store_exists(): try: warnings = auth.remove_store() if warnings: print warnings except AuthError: print "Failed" raise else: auth.create_store() print "Success" """ if self.cursor.tableExists(self._table_prepend+'User') and \ self.cursor.tableExists(self._table_prepend+'App') and \ self.cursor.tableExists(self._table_prepend+'Group') and \ self.cursor.tableExists(self._table_prepend+'Role') and \ self.cursor.tableExists(self._table_prepend+'History') and \ self.cursor.tableExists(self._table_prepend+'Roles'): return True else: return False # # Applications # def _driver_applications(self): """ Return a list of applications in the store, including the ``default`` application. """ rows = self.cursor.select( 'name', '%sApp'%self._table_prepend, fetch=True, format='tuple', convert=True, ) apps = [] if rows: for row in rows: apps.append(row[0]) return tuple(apps) def _driver_application_exists(self, name): """ Return ``True`` if the application ``name`` exists, ``False`` otherwise. """ rows = self.cursor.select( 'name', '%sApp'%self._table_prepend, where="name='"+name+"'", fetch=True, format='tuple', convert=True, ) if rows: return True return False def _driver_add_application(self, name): """ Add an appliation Add an application ``name``. ``A call to _driver_application_exists()`` will already have been made. """ self.cursor.insert('%sApp'%self._table_prepend, ['name'], [name]) def _driver_remove_application(self, name, unset_roles): # Changed - can't remove application if it is in use """ Remove the application ``name`` if certain conditions are met If ``unset_roles`` is False and any users have roles associated with the application being removed raise an ``authkit.AuthError``. If ``unset_roles`` is set to ``True`` remove all roles assoicated with the application. If ``name`` is ``default`` and ``unset_roles`` is ``True``, remove all roles associated with the default application but DO NOT remove it. If ``unset_roles`` is ``False`` raise an ``authkit.AuthError`` stating ``"The default application cannot be removed"``. If ``name`` is not ``default`` and no error is raised remove the appliaction. """ if unset_roles: self.cursor.delete('%sRoles'%self._table_prepend,where="application='"+name+"'") else: if name == 'default': raise AuthError('The default application cannot be removed') rows = self.cursor.select( 'user', '%sRoles'%self._table_prepend, where="application='"+name+"'", fetch=True, format='tuple', convert=True, ) if rows: users = '' for row in rows: users += ", "+row[0] raise AuthError('The application %s is still in use specifying roles for the following users: %s'%(repr(name), users[2:])) self.cursor.delete('%sApp'%self._table_prepend, where="name='"+name+"'") # # Users # def _driver_user_exists(self, username): """ Return ``True`` if the user with the username ``username`` exists, ``False`` otherwise. The username is lowercase. """ rows = self.cursor.select( 'user', '%sUser'%self._table_prepend, where="user='"+username+"'", fetch=True, format='tuple', convert=True, ) if rows: return True return False def _driver_add_user(self, username, password='', firstname='', surname='', email='', active=True, group=None): """ Add a user Add a user ``username`` unless the username already exists in which case raise an ``authkit.AuthError``. Optionally specify a ``password``, ``firstname``, ``surname``, ``email`` and ``group`` for the user and set the user's account status with ``active``. User passwords are already encrypted, if necessary, by the time this method is called so can be treated as strings without needing any modification. ``password``, ``firstname``, ``surname``, ``email`` can never be ``None`` but can be ``''``. ``group`` can be ``None`` to indicate no group assignment. ``active`` can only be ``True`` or ``False``. User is guaranteed not to already exist. """ self.cursor.insert( '%sUser'%self._table_prepend, ('user', 'password', 'firstname', 'surname', 'email', 'active', 'grp'), (username, password, firstname, surname, email, active, group), ) def _driver_remove_user(self, username): """ Remove a user and their associated roles. Remove the user ``username`` unless the username doesn't exist in which case raise an ``authkit.AuthError``. Remove all roles associated with the user. """ if self.user_exists(username): self.cursor.delete('%sUser'%self._table_prepend,where="user='"+username+"'") else: raise AuthError("The user '%s' doesn't exist."%(username)) self.cursor.delete('%sRoles'%self._table_prepend,where="user='"+username+"'") def _driver_users(self, group=[], active=None, application=None, role=None): """ Return a list of current usernames according to various options ``group`` Can be ``None`` to select the group of users where no group is assigned Can be ``[]`` to select evey user regardless of group or can be the name of a group to select just users in that group ``active`` Can be ``None`` to select all users, ``True`` to select users with active accounts or ``False`` to select users with disabled accounts ``application`` Can be ``None`` to select all users reardless of the appliaction they have roles with or the application name to select users associated with that application ``role`` Can be ``None`` to select all users reardless of roles or the name of a role to select users with that role All options are used in combination so to select users of the ``default`` application with the role ``editor`` for example you could specify ``application='default', role='editor'`` in the parameters. """ rows = [] if (application==None and role!= None) or (application != None and role == None): raise AuthError('You must specify both role and application or neither of them') if group != [] and group!=None and not self.group_exists(group): raise AuthError('No such group %s'%repr(group)) if application == None: if group == []: # ie all if active == None: rows = self.cursor.select( 'user', tables='%sUser'%self._table_prepend, fetch=True, format='tuple', convert=True, ) else: rows = self.cursor.select( 'user', tables='%sUser'%self._table_prepend, where="active=? ", values = [active], fetch=True, format='tuple', convert=True, ) else: if active == None: rows = self.cursor.select( 'user', tables='%sUser'%self._table_prepend, where="grp=?", values = [group], fetch=True, format='tuple', convert=True, ) else: rows = self.cursor.select( 'user', tables='%sUser'%self._table_prepend, where="grp= ? and active= ? ", values = [group, active], fetch=True, format='tuple', convert=True, ) else: if group == []: # ie all if active == None: rows = self.cursor.select( 'user', tables=['%sRoles'%self._table_prepend], where="application=? and role=? ", values = [application, role], fetch=True, format='tuple', convert=True, ) else: rows = self.cursor.select( ('%sUser'%self._table_prepend+'.user'), tables=['%sUser'%self._table_prepend, '%sRoles'%self._table_prepend], where="%sUser.active=? and %sRoles.application=? and %sRoles.role=? and %sUser.user=%sRoles.user "%( self._table_prepend, self._table_prepend, self._table_prepend, self._table_prepend, self._table_prepend, ), values = [active, application, role], fetch=True, format='tuple', convert=True, ) else: if active == None: rows = self.cursor.select( ('%sUser'%self._table_prepend+'.user'), tables=['%sUser'%self._table_prepend, '%sRoles'%self._table_prepend], where="%sUser.grp=? and %sUser.user=%sRoles.user and %sRoles.application=? and %sRoles.role=?"%( self._table_prepend, self._table_prepend, self._table_prepend, self._table_prepend, self._table_prepend ), values = [group, application, role], fetch=True, format='tuple', convert=True, ) else: rows = self.cursor.select( ('%sUser'%self._table_prepend+'.user'), tables=['%sUser'%self._table_prepend, '%sRoles'%self._table_prepend], where="%sUser.grp=? and %sUser.active=? and %sRoles.application=? and %sRoles.role=? and %sUser.user=%sRoles.user"%( self._table_prepend, self._table_prepend, self._table_prepend, self._table_prepend, self._table_prepend, self._table_prepend ), values = [group, active, application, role], fetch=True, format='tuple', convert=True, ) users = [] for row in rows: users.append(row[0]) return tuple(users) # # Roles # def _driver_add_role(self, role): """ Adds the role ``role`` to the store unless it already exists in which case an ``authkit.AuthError`` is raised. """ self.cursor.insert('%sRole'%self._table_prepend, ['name'], [role]) def _driver_role_exists(self, role): """ Return ``True`` if the role ``role`` exists, ``False`` otherwise. """ rows = self.cursor.select( 'name', '%sRole'%self._table_prepend, where="name='"+role+"'", fetch=True, format='tuple', convert=True, ) if rows: return True else: return False def _driver_remove_role(self, role, unset_roles): """ Remove the ``role`` if certain conditions are met If the ``role`` doesn't exist raise an ``authkit.AuthError``. If ``unset_roles`` is False and any users are currently assinged the role raise an ``authkit.AuthError``. If ``unset_roles`` is set to ``True`` remove all roles assoicated with the application. If an ``authkit.AuthError`` was not raised, remove the role. """ # Check the roles aren't already in use: if unset_roles: self.cursor.delete( table='%sRoles'%self._table_prepend, where="role='"+role+"'", ) else: rows = self.cursor.select( 'user', '%sRoles'%self._table_prepend, where="role='"+role+"'", fetch=True, format='tuple', convert=True, ) if rows: users = '' for row in rows: users += ", "+row[0] raise AuthError('The role %s is still in use by the following users: %s'%(repr(role), users[2:])) self.cursor.delete('%sRole'%self._table_prepend,where="name='"+role+"'") def _driver_roles(self, username=None, application=None): if username != None and application != None: rows = self.cursor.select( ['role', 'application'], '%sRoles'%self._table_prepend, where = "application='"+application+"' and user='"+username+"'", fetch=True, format='tuple', convert=True, ) roles = [] for row in rows: roles.append(row[0]) return tuple(roles) else: if username != None and application == None: rows = self.cursor.select( ['role','application'], '%sRoles'%self._table_prepend, where = "user='"+username+"'", fetch=True, format='tuple', convert=True, ) d = {} for row in rows: d[row[1]] = row[0] return d else: rows = self.cursor.select( 'name', '%sRole'%self._table_prepend, fetch=True, format='tuple', convert=True, ) roles = [] for row in rows: roles.append(row[0]) return tuple(roles) def _driver_set_role(self, username, role, application): roles = role if not (isinstance(role, tuple) or isinstance(role, list)): roles = [role] for role in roles: if not self.role_exists(role): raise AuthError("The '%s' role doesn't exist in the database."%role) if role in self.roles(username, application): raise AuthError('User %s already has the role %s for the application %s'%(repr(username), repr(role), repr(application))) else: self.cursor.insert('%sRoles'%self._table_prepend, ['role','application','user'], [role, application, username]) def _driver_unset_role(self, username, role, application): if not self.role_exists(role): raise AuthError("The '%s' role doesn't exist in the database."%role) if role not in self.roles(username, application): raise AuthError('User %s does not have the role %s for the application %s'%(repr(username), repr(role), repr(application))) else: self.cursor.delete('%sRoles'%self._table_prepend, where = "application='"+application+"' and user='"+username+"' and role='"+role+"'",) # # Groups # def _driver_group_exists(self, group): """ Return ``True`` if ``group`` exists or is ``None`` (since no group should always exist), ``False`` otherwise. """ if group == None: return True else: rows = self.cursor.select( 'name', '%sGroup'%self._table_prepend, where="name='"+group+"'", fetch=True, format='tuple', convert=True, ) if rows: return True else: return False def _driver_add_group(self, group): if self.group_exists(group): raise AuthError("The '%s' group already exists."%group) else: self.cursor.insert('%sGroup'%self._table_prepend, ['name'], [group]) def _driver_remove_group(self, group, force=0): # Check the roles aren't already in use: if force: self.cursor.update( '%sUser'%self._table_prepend, ['grp'],[None, group], where="grp=?", ) else: rows = self.cursor.select( 'user', '%sUser'%self._table_prepend, where="grp=?", values = [group], fetch=True, format='tuple', convert=True, ) users = '' for row in rows: users += ", "+row[0] raise AuthError('The group %s is still in use by the following users: %s'%(repr(group), users[2:])) self.cursor.delete('%sGroup'%self._table_prepend, where="name='"+group+"'") def _driver_groups(self): rows = self.cursor.select( 'name', '%sGroup'%self._table_prepend, fetch=True, format='tuple', convert=True, ) groups = [] for row in rows: groups.append(row[0]) return tuple(groups) # # History Methods # def _driver_history(self, username): where = "user='%s'"%username #for username in usernames: # where += "user='%s' or "%username rows = self.cursor.select( ['signed_in','last_accessed','signed_out'], '%sHistory'%self._table_prepend, where=where, fetch=True, format='tuple', convert=True, ) return rows def _driver_sign_out(self, username): self.cursor.update( table='%sHistory'%self._table_prepend, columns=['signed_out'], values = [datetime.datetime(2005,12,12,12).now()], where="user='%s'"%username, ) #raise Exception(rows) def _driver_sign_in(self, username): now = datetime.datetime(2005,12,12,12).now() self.cursor.insert( table='%sHistory'%self._table_prepend, columns=['user', 'signed_in', 'last_accessed'], values = [username, now, now], ) def _driver_signed_in(self, username): rows = self.cursor.select( 'user', '%sHistory'%self._table_prepend, where="user='%s' and signed_out IS NULL"%username, fetch=True, format='tuple', convert=True, order = 'signed_in' ) if len(rows) > 0: return 1 return 0 def _driver_update_accessed(self, username): self.cursor.update( '%sHistory'%self._table_prepend, ('last_accessed',), (datetime.datetime(2005,12,12,12).now(),), where="%s='%s' and signed_out is NULL"%('user',username) ) #self.tables['History'].selectBy(user=username, signed_out=None)[0].last_accessed = # # User class methods # def _driver_user(self, username, property=None): # Changed - removed property if self.user_exists(username): rows = self.cursor.select( ('user','password','firstname','surname','email','active','grp'), '%sUser'%self._table_prepend, where="user='%s'"%username, fetch=True, format='dict', convert=True, ) object = rows[0] user = { 'username':object['user'], 'password':object['password'], 'firstname':object['firstname'], 'surname':object['surname'], 'email':object['email'], 'active':object['active'], 'group':object['grp'], #'levels':self.levels(username), # Changed from level 'roles':self.roles(username), } if property: if user.has_key(property): return user[property] else: raise AuthError('Invalid user property %s'%(repr(property))) return user else: raise AuthError("No such username '%s'."%username) def _driver_set_user(self, username, **properties): """Private method to set the value of one of 'password', 'firstname', 'surname' and 'email' for a particular user.""" username = username.lower() for property in properties.keys(): value = properties[property] if property in ['password','firstname','surname','email']: if self.user_exists(username): self.cursor.update('%sUser'%self._table_prepend, (property,), (value,), where="%s='%s'"%('user',username)) else: raise AuthError('That user doesn\'t exist.') elif property == 'group': if self.group_exists(value): self.cursor.update('%sUser'%self._table_prepend, ('grp',), (value,), where="%s='%s'"%('user',username)) else: raise AuthError('No such group %s'%repr(value)) elif property == 'active': if value in [0,1]: self.cursor.update('%sUser'%self._table_prepend, (property,), (value,), where="%s='%s'"%('user',username)) else: raise AuthError('active can only br True or False not %s'%repr(value)) else: raise AuthError("You can only set the properties password, firstname, surname, email, active and group") PK 5¯lQµiiauthkit/drivers/database.pyc;ò DJêDc@svdZdklZlZdkZy eeWn+ej oddjZddjZnXdefd„ƒYZdS(sìDatabase driver for AuthKit. Developer Notes: * User columns are named ``user`` rather than ``username`` to avoid problems with Gadfly * The Group column is named ``grp`` rather than ``group`` to avoid confusion with SQL ``GROUP BY`` (s AuthErrors AuthStoreNiisDatabaseAuthStorecBs@tZdZdd„Zd„Zd„Zd„Zd„Zd„Zd„Z d „Z d „Z d d d d e e d „Zd „Zge e e d„Zd„Zd„Zd„Ze e d„Zd„Zd„Zd„Zd„Zdd„Zd„Zd„Zd„Zd„Zd„Zd„Ze d„Z d „Z!RS(!sA An auth store which makes use of the PythonWeb.org ``database`` module to store auth information in an SQL database. This driver is know to work with pysqlite 1.1.6 and MySQLdb 1.0. ``DatabaseAuthStore`` is used as follows:: import database connection = database.connect(dsn="sqlite:///test.db") cursor = connection.cursor() auth = DatabaseAuthStore(cursor=connection.cursor()) Do whatever you want with the newly created ``auth`` object then save changes:: connection.commit() sAuthKit_cKs&||_||_ti||dS(N(scursorsselfs table_prepends_table_prepends AuthStores__init__sauth_store_params(sselfscursors table_prependsauth_store_params((s1build\bdist.win32\egg\authkit\drivers\database.pys__init__+s  c Csåg}|ii|idƒ oc|iid|iddddfddfddfddfd dfd d fd dfgƒn|id |iddƒ|ii|idƒ o-|iid|iddddfgƒn|id |iddƒ|ii|idƒ o-|iid|iddddfgƒn|id |iddƒ|ii|idƒ o-|iid|iddddfgƒn|id |iddƒ|ii|idƒ o?|iid|iddddfddfddfgƒn|id |iddƒ|ii|idƒ oH|iid|iddddfddfddfddfgƒn|id |iddƒ|otdi|ƒƒ‚ndS(s° Destroy any existing store and create the auth store. If any errors are generated when creating the store an ``authkit.AuthError`` is raised. sUserstablescolumnssusersStringspasswords firstnamessurnamesemailsactivesBoolsgrpsThe 's' table already exists.sAppsnamesGroupsRolesRoless applicationsrolesHistorys signed_insDateTimes last_accesseds signed_outs, N( serrorssselfscursors tableExistss_table_prependscreatesappends AuthErrorsjoin(sselfserrors((s1build\bdist.win32\egg\authkit\drivers\database.pys_driver_create_store4s8M )2cCsƒg}xrdddddgD][}y|ii|i|ƒWq|id|i|dtti ƒdƒƒqXqW|Sd S( sW Remove the auth store, destroying any data it contains. If there are no problems, ``[]`` is returned. If any errors occurs preventing the store from being removed an ``authkit.AuthError`` is raised. If the store doesn't exist or only partially exists, any warnings are returned as a list of strings. sUsersAppsGroupsRoles RolesHistorysThe s table may not exist. Error: %siN( serrorsstablesselfscursorsdrops_table_prependsappendsstrssyssexc_info(sselfstableserrors((s1build\bdist.win32\egg\authkit\drivers\database.pys_driver_remove_stores8cCs¬|ii|idƒo|ii|idƒoe|ii|idƒoK|ii|idƒo1|ii|idƒo|ii|idƒotSntSdS(s Returns ``True`` if every component of the store exists, ``False`` otherwise. Typically used as follows:: if not auth.store_exists(): try: warnings = auth.remove_store() if warnings: print warnings except AuthError: print "Failed" raise else: auth.create_store() print "Success" sUsersAppsGroupsRolesHistorysRolesN(sselfscursors tableExistss_table_prependsTruesFalse(sself((s1build\bdist.win32\egg\authkit\drivers\database.pys_driver_store_exists•sœc Cso|iidd|idtdddtƒ}g}|o&x#|D]}|i|dƒqBWnt |ƒSdS( sd Return a list of applications in the store, including the ``default`` application. snames%sAppsfetchsformatstuplesconvertiN( sselfscursorsselects_table_prependsTruesrowssappssrowsappendstuple(sselfsrowssappssrow((s1build\bdist.win32\egg\authkit\drivers\database.pys_driver_applicationsµs   c CsS|iidd|idd|ddtddd tƒ}|otSntSd S( s[ Return ``True`` if the application ``name`` exists, ``False`` otherwise. snames%sAppswheresname='s'sfetchsformatstuplesconvertN(sselfscursorsselects_table_prependsnamesTruesrowssFalse(sselfsnamesrows((s1build\bdist.win32\egg\authkit\drivers\database.pys_driver_application_existsÆs   cCs'|iid|idg|gƒdS(s™ Add an appliation Add an application ``name``. ``A call to _driver_application_exists()`` will already have been made. s%sAppsnameN(sselfscursorsinserts_table_prependsname(sselfsname((s1build\bdist.win32\egg\authkit\drivers\database.pys_driver_add_applicationÖsc Cs|o)|iid|idd|dƒn®|djotdƒ‚n|iidd|idd|ddtd d d tƒ}|oMd }x |D]}|d |d7}qWtdt |ƒ|dfƒ‚n|iid|idd|dƒdS(sÑ Remove the application ``name`` if certain conditions are met If ``unset_roles`` is False and any users have roles associated with the application being removed raise an ``authkit.AuthError``. If ``unset_roles`` is set to ``True`` remove all roles assoicated with the application. If ``name`` is ``default`` and ``unset_roles`` is ``True``, remove all roles associated with the default application but DO NOT remove it. If ``unset_roles`` is ``False`` raise an ``authkit.AuthError`` stating ``"The default application cannot be removed"``. If ``name`` is not ``default`` and no error is raised remove the appliaction. s%sRolesswheres application='s'sdefaults)The default application cannot be removedsusersfetchsformatstuplesconvertss, isOThe application %s is still in use specifying roles for the following users: %sis%sAppsname='N( s unset_rolessselfscursorsdeletes_table_prependsnames AuthErrorsselectsTruesrowssuserssrowsrepr(sselfsnames unset_rolessrowssrowsusers((s1build\bdist.win32\egg\authkit\drivers\database.pys_driver_remove_applicationÞs$ )    $c CsS|iidd|idd|ddtddd tƒ}|otSntSd S( s„ Return ``True`` if the user with the username ``username`` exists, ``False`` otherwise. The username is lowercase. susers%sUserswheresuser='s'sfetchsformatstuplesconvertN(sselfscursorsselects_table_prependsusernamesTruesrowssFalse(sselfsusernamesrows((s1build\bdist.win32\egg\authkit\drivers\database.pys_driver_user_existss   sc CsK|iid|idddddddf|||||||fƒd S( s Add a user Add a user ``username`` unless the username already exists in which case raise an ``authkit.AuthError``. Optionally specify a ``password``, ``firstname``, ``surname``, ``email`` and ``group`` for the user and set the user's account status with ``active``. User passwords are already encrypted, if necessary, by the time this method is called so can be treated as strings without needing any modification. ``password``, ``firstname``, ``surname``, ``email`` can never be ``None`` but can be ``''``. ``group`` can be ``None`` to indicate no group assignment. ``active`` can only be ``True`` or ``False``. User is guaranteed not to already exist. s%sUsersuserspasswords firstnamessurnamesemailsactivesgrpN( sselfscursorsinserts_table_prependsusernamespasswords firstnamessurnamesemailsactivesgroup(sselfsusernamespasswords firstnamessurnamesemailsactivesgroup((s1build\bdist.win32\egg\authkit\drivers\database.pys_driver_add_userscCsr|i|ƒo)|iid|idd|dƒntd|ƒ‚|iid|idd|dƒdS(sÿ Remove a user and their associated roles. Remove the user ``username`` unless the username doesn't exist in which case raise an ``authkit.AuthError``. Remove all roles associated with the user. s%sUserswheresuser='s'sThe user '%s' doesn't exist.s%sRolesN(sselfs user_existssusernamescursorsdeletes_table_prepends AuthError(sselfsusername((s1build\bdist.win32\egg\authkit\drivers\database.pys_driver_remove_user+s )cCsÿg}|tjo |tjp|tjo |tjotdƒ‚n|gjo|tjo|i|ƒ otdt|ƒƒ‚n|tjo+|gjo†|tjo5|i i ddd|i dt ddd t ƒ}qÃ|i i ddd|i d d d |gdt ddd t ƒ}qÉ|tjoD|i i ddd|i d d d |gdt ddd t ƒ}qÉ|i i ddd|i d dd ||gdt ddd t ƒ}n|gjoÛ|tjoJ|i i ddd|i gd dd ||gdt ddd t ƒ}qÉ|i i d|i ddd|i d|i gd d|i |i |i |i |i fd |||gdt ddd t ƒ}n|tjo„|i i d|i ddd|i d|i gd d|i |i |i |i |i fd |||gdt ddd t ƒ}nŠ|i i d|i ddd|i d|i gd d|i |i |i |i |i |i fd ||||gdt ddd t ƒ}g}x|D]}|i|dƒqÖWt|ƒSdS(sn Return a list of current usernames according to various options ``group`` Can be ``None`` to select the group of users where no group is assigned Can be ``[]`` to select evey user regardless of group or can be the name of a group to select just users in that group ``active`` Can be ``None`` to select all users, ``True`` to select users with active accounts or ``False`` to select users with disabled accounts ``application`` Can be ``None`` to select all users reardless of the appliaction they have roles with or the application name to select users associated with that application ``role`` Can be ``None`` to select all users reardless of roles or the name of a role to select users with that role All options are used in combination so to select users of the ``default`` application with the role ``editor`` for example you could specify ``application='default', role='editor'`` in the parameters. s=You must specify both role and application or neither of themsNo such group %ssuserstabless%sUsersfetchsformatstuplesconvertswheres active=? svaluessgrp=?sgrp= ? and active= ? s%sRolessapplication=? and role=? s.usersZ%sUser.active=? and %sRoles.application=? and %sRoles.role=? and %sUser.user=%sRoles.user sV%sUser.grp=? and %sUser.user=%sRoles.user and %sRoles.application=? and %sRoles.role=?sj%sUser.grp=? and %sUser.active=? and %sRoles.application=? and %sRoles.role=? and %sUser.user=%sRoles.useriN(srowss applicationsNonesroles AuthErrorsgroupsselfs group_existssreprsactivescursorsselects_table_prependsTruesuserssrowsappendstuple(sselfsgroupsactives applicationsrolesrowssuserssrow((s1build\bdist.win32\egg\authkit\drivers\database.pys _driver_users:s4+                   ( (. cCs'|iid|idg|gƒdS(s‰ Adds the role ``role`` to the store unless it already exists in which case an ``authkit.AuthError`` is raised. s%sRolesnameN(sselfscursorsinserts_table_prependsrole(sselfsrole((s1build\bdist.win32\egg\authkit\drivers\database.pys_driver_add_roleÉsc CsS|iidd|idd|ddtddd tƒ}|otSntSd S( sT Return ``True`` if the role ``role`` exists, ``False`` otherwise. snames%sRoleswheresname='s'sfetchsformatstuplesconvertN(sselfscursorsselects_table_prependsrolesTruesrowssFalse(sselfsrolesrows((s1build\bdist.win32\egg\authkit\drivers\database.pys_driver_role_existsÐs   c Csì|o,|iidd|idd|dƒn‘|iidd|idd|ddtdd d tƒ}|oMd }x |D]}|d |d 7}qƒWt dt |ƒ|dfƒ‚n|iid|idd|dƒdS(s« Remove the ``role`` if certain conditions are met If the ``role`` doesn't exist raise an ``authkit.AuthError``. If ``unset_roles`` is False and any users are currently assinged the role raise an ``authkit.AuthError``. If ``unset_roles`` is set to ``True`` remove all roles assoicated with the application. If an ``authkit.AuthError`` was not raised, remove the role. stables%sRolesswheresrole='s'susersfetchsformatstuplesconvertss, is6The role %s is still in use by the following users: %sis%sRolesname='N( s unset_rolessselfscursorsdeletes_table_prependsrolesselectsTruesrowssuserssrows AuthErrorsrepr(sselfsroles unset_rolessrowssuserssrow((s1build\bdist.win32\egg\authkit\drivers\database.pys_driver_remove_roleás"   $c Cs‹|tjo |tjo€|iiddgd|idd|d|ddtd d d tƒ}g}x|D]}|i |d ƒqqWt |ƒSnî|tjo |tjos|iiddgd|idd |ddtd d d tƒ}h}x |D]}|d ||d 2002-2005 All Rights Reserved # Licensed under LGPL # """SQLObject driver for AuthKit. Developer Notes: * User columns are named ``user`` rather than ``username`` to avoid problems with Gadfly * The Group column is named ``grp`` rather than ``group`` to avoid confusion with SQL ``GROUP BY`` """ from authkit import AuthError, AuthStore import datetime from sqlobject import SQLObject, StringCol, BoolCol, ForeignKey, MultipleJoin, DateTimeCol, connectionForURI try: True False except NameError: True = 1==1 False = 0==1 class SQLObjectAuthStore(AuthStore): """ An auth store which uses `SQLObject `_ to store auth information in an SQL database. ``SQLObjectAuthStore`` is used as follows:: >>> from authkit.drivers.SQLObject_driver import SQLObjectAuthStore >>> from SQLObject import * >>> connection = connectionForURI(connection_string) >>> auth = SQLObjectAuthStore(connection=connection) """ def __init__(self, connection, table_prepend='', **auth_store_params): self.connection = connection self._table_prepend = table_prepend class User(SQLObject): class sqlmeta: table = self._table_prepend+'User' _connection = self.connection user = StringCol() password = StringCol() firstname = StringCol() surname = StringCol() email = StringCol() active = BoolCol() grp = ForeignKey(self._table_prepend+'Group_') # SQLObject Joins roles = MultipleJoin(self._table_prepend+'Roles') history = MultipleJoin(self._table_prepend+'History') class App(SQLObject): class sqlmeta: table = self._table_prepend+'App' _connection = self.connection name = StringCol() roles = MultipleJoin(self._table_prepend+'Roles') class Group_(SQLObject): class sqlmeta: table = self._table_prepend+'Group_' _connection = self.connection name = StringCol() users = MultipleJoin(self._table_prepend+'User') class Role(SQLObject): class sqlmeta: table = self._table_prepend+'Role' _connection = self.connection name = StringCol() roles = MultipleJoin(self._table_prepend+'Roles') class Roles(SQLObject): class sqlmeta: table = self._table_prepend+'Roles' _connection = self.connection user = ForeignKey(self._table_prepend+'User') application = ForeignKey(self._table_prepend+'App') role = ForeignKey(self._table_prepend+'Role') class History(SQLObject): class sqlmeta: table = self._table_prepend+'History' _connection = self.connection user = ForeignKey(self._table_prepend+'User') signed_in = DateTimeCol() last_accessed = DateTimeCol() signed_out = DateTimeCol() self.tables = { 'User':User, 'App':App, 'Group_':Group_, 'Role':Role, 'Roles':Roles, 'History':History, } AuthStore.__init__(self, **auth_store_params) # # Change Store # def _driver_create_store(self): """ Destroy any existing store and create the auth store. If any errors are generated when creating the store an ``authkit.AuthError`` is raised. After this method is called, the default application is added, you don't need to implement any code for this. """ for name, table in self.tables.items(): fullname = self._table_prepend+name if self.connection.tableExists(fullname): raise AuthError('The table %s already exists'%repr(fullname)) else: table.createTable() def _driver_remove_store(self): """ Remove the auth store, destroying any data it contains. If there are no problems, ``[]`` is returned. If any errors occurs preventing the store from being removed an ``authkit.AuthError`` is raised. If the store doesn't exist or only partially exists, any warnings are returned as a list of strings. """ errors = [] for name, table in self.tables.items(): fullname = self._table_prepend+name if not self.connection.tableExists(fullname): errors.append('The table %s doesn\'t exist'%repr(fullname)) else: table.dropTable() return errors def _driver_store_exists(self): """ Returns ``True`` if every component of the store exists, ``False`` otherwise. Typically used as follows:: if not auth.store_exists(): try: warnings = auth.remove_store() if warnings: print warnings except AuthError: print "Failed" raise else: auth.create_store() print "Success" """ for name, table in self.tables.items(): if not self.connection.tableExists(self._table_prepend+name): return False return True # # Get Objects # def _driver_applications(self): """ Return a list of applications in the store, including the ``default`` application. """ return tuple([obj.name for obj in self.tables['App'].select()]) def _driver_groups(self): return tuple([obj.name for obj in self.tables['Group_'].select()]) def _driver_users(self, group=[], active=None, application=None, role=None): """ Return a list of current usernames according to various options ``group`` Can be ``None`` to select the group of users where no group is assigned Can be ``[]`` to select evey user regardless of group or can be the name of a group to select just users in that group ``active`` Can be ``None`` to select all users, ``True`` to select users with active accounts or ``False`` to select users with disabled accounts ``application`` Can be ``None`` to select all users reardless of the appliaction they have roles with or the application name to select users associated with that application ``role`` Can be ``None`` to select all users reardless of roles or the name of a role to select users with that role All options are used in combination so to select users of the ``default`` application with the role ``editor`` for example you could specify ``application='default', role='editor'`` in the parameters. Users are returned in alphabetical order. """ rows = [] #~ if (application==None and role!= None) or (application != None and role == None): #~ #raise Exception(application, role) #~ raise AuthError('You must specify both role and application or neither of them') if application == None and role == None: if group == []: # ie all if active == None: objs = self.tables['User'].select() else: objs = self.tables['User'].selectBy(active=active) else: if active == None: if group == None: group_ = None else: group_ = self.tables['Group_'].selectBy(name=group).getOne() objs = self.tables['User'].selectBy(grp=group_) else: if group == None: group_ = None else: group_ = self.tables['Group_'].selectBy(name=group).getOne() objs = self.tables['User'].selectBy(active=active, group=group_) elif application==None and role != None: if group == []: # ie all roles = self.tables['Role'].selectBy(name=role) roles = self.tables['Roles'].selectBy(role=roles.getOne()) objs = [] for role in roles: if role.user not in objs: if active == None: objs.append(role.user) elif role.user.active == active: objs.append(role.user) else: role_ = self.tables['Role'].selectBy(name=role).getOne() roles = self.tables['Roles'].selectBy(role=role_) if group == None: group_ = None else: group_ = self.tables['Group_'].selectBy(name=group).getOne() objs = [] for role in roles: if role.user not in objs: if role.user.grp == group_: if active == None: objs.append(role.user) elif role.user.active == active: objs.append(role.user) else: print group elif role==None and application != None: application_ = self.tables['App'].selectBy(name=application).getOne().id if group == []: # ie all apps = self.tables['App'].selectBy(name=application) roles = self.tables['Roles'].selectBy(application=apps.getOne()) objs = [] for role in roles: if role.user not in objs: if active == None: objs.append(role.user) elif role.user.active == active: objs.append(role.user) else: if group == None: group_ = None else: group_ = self.tables['Group_'].selectBy(name=group).getOne() apps = self.tables['App'].selectBy(name=application) roles = self.tables['Roles'].selectBy(application=apps.getOne()) objs = [] for role in roles: if role.user not in objs: if role.user.grp == group_: if active == None: objs.append(role.user) elif role.user.active == active: objs.append(role.user) else: if group == []: # ie all role_ = self.tables['Role'].selectBy(name=role).getOne() app_ = self.tables['App'].selectBy(name=application).getOne() roles = self.tables['Roles'].selectBy(application=app_, role=role_) objs = [] for role in roles: if role.user not in objs: if active == None: objs.append(role.user) elif role.user.active == active: objs.append(role.user) else: role_ = self.tables['Role'].selectBy(name=role).getOne() app_ = self.tables['App'].selectBy(name=application).getOne() if group == None: group_ = None else: group_ = self.tables['Group_'].selectBy(name=group).getOne() roles = self.tables['Roles'].selectBy(application=app_, role=role_) objs = [] for role in roles: if role.user not in objs: if role.user.grp == group_: if active == None: objs.append(role.user) elif role.user.active == active: objs.append(role.user) users = [] for obj in objs: users.append(obj.user) users.sort() return tuple(users) def _driver_roles(self, username=None, application=None): if username == None and application == None: roles = [] objs = self.tables['Role'].select() for role in objs: roles.append(role.name) return tuple(roles) if username != None and application != None: user = self.tables['User'].selectBy(user=username).getOne() app = self.tables['App'].selectBy(name=application).getOne() r = [] for role in self.tables['Roles'].selectBy(application=app, user=user): #raise Exception(role, dir(role)) r.append(role.role.name) return tuple(r) else: if username != None: #and application == None: objs = self.tables['User'].selectBy(user=username).getOne().roles d = {} for obj in objs: if d.has_key(obj.application.name): d[obj.application.name].append(obj.role.name) else: d[obj.application.name]=[obj.role.name] d1 = {} for k,v in d.items(): d1[k] = tuple(v) if application == None: return d1 else: return d1[application] if application != None: app = self.tables['App'].selectBy(application=application).getOne() objs = self.tables['Roles'].selectBy(application=app) roles = [] for obj in objs: roles.append(obj.role) return tuple(roles) # # Remove Objects # def _driver_remove_user(self, username): """ Remove a user and their associated roles. Remove the user ``username`` unless the username doesn't exist in which case raise an ``authkit.AuthError``. Remove all roles associated with the user. """ user = self.tables['User'].selectBy(user=username).getOne() for role in user.roles: role.destroySelf() user.destroySelf() def _driver_remove_application(self, name, unset_roles): # Changed - can't remove application if it is in use """ Remove the application ``name`` if certain conditions are met If ``unset_roles`` is False and any users have roles associated with the application being removed raise an ``authkit.AuthError``. If ``unset_roles`` is set to ``True`` remove all roles assoicated with the application. If ``name`` is ``default`` and ``unset_roles`` is ``True``, remove all roles associated with the default application but DO NOT remove it. If ``unset_roles`` is ``False`` raise an ``authkit.AuthError`` stating ``"The default application cannot be removed"``. If ``name`` is not ``default`` and no error is raised remove the appliaction. """ if unset_roles: app = self.tables['App'].selectBy(name=name).getOne(None) if app: #print repr(app) for role in self.tables['Roles'].selectBy(application=app): role.destroySelf() else: if name == 'default': raise AuthError('The default application cannot be removed') app = self.tables['App'].selectBy(name=name).getOne(None) if app: roles = self.tables['Roles'].selectBy(application=app) users = '' for role in roles: users += ", "+role.user if len(users)>0: raise AuthError('The application %s is still in use specifying roles for the following users: %s'%(repr(name), users[2:])) app.destroySelf() def _driver_remove_role(self, role, unset_roles): """ Remove the ``role`` if certain conditions are met If the ``role`` doesn't exist raise an ``authkit.AuthError``. If ``unset_roles`` is False and any users are currently assinged the role raise an ``authkit.AuthError``. If ``unset_roles`` is set to ``True`` remove all roles assoicated with the application. If an ``authkit.AuthError`` was not raised, remove the role. """ if unset_roles: role_ = self.tables['Role'].selectBy(name=role).getOne() for role in self.tables['Roles'].selectBy(role=role_): role.destroySelf() else: role_ = self.tables['Role'].selectBy(name=role).getOne() roles = self.tables['Roles'].selectBy(name=role_) users = '' for row in roles: users += ", "+row.user if len(users)>0: raise AuthError('The role %s is still in use by the following users: %s'%(repr(role), users[2:])) role_.destroySelf() def _driver_remove_group(self, group, remove_users=False): # Check the roles aren't already in use: if remove_users: group_ = self.tables['Group_'].selectBy(name=group).getOne() for user in self.tables['User'].selectBy(grp=group_): user.destroySelf() else: group_ = self.tables['Group_'].selectBy(name=group).getOne() users = self.tables['User'].selectBy(grp=group_) users_ = '' for user in users: users_ += ", "+user.user if len(users_)>0: raise AuthError('The group %s is still in use by the following users: %s'%(repr(group), users_[2:])) group_.destroySelf() # # Object Exists # def _driver_application_exists(self, name): """ Return ``True`` if the application ``name`` exists, ``False`` otherwise. """ if self.tables['App'].selectBy(name=name).getOne(None): return True return False def _driver_user_exists(self, username): """ Return ``True`` if the user with the username ``username`` exists, ``False`` otherwise """ for x in self.tables['User'].selectBy(user=username): return True return False def _driver_role_exists(self, role): """ Return ``True`` if the role ``role`` exists, ``False`` otherwise. """ if self.tables['Role'].selectBy(name=role).getOne(None): return True return False def _driver_group_exists(self, group): """ Return ``True`` if ``group`` exists or is ``None`` (since no group should always exist), ``False`` otherwise. """ if group == None: return True else: if self.tables['Group_'].selectBy(name=group).getOne(None): return True return False # # Add Object # def _driver_add_user(self, username, password='', firstname='', surname='', email='', active=True, group=None): """ Add a user Add a user ``username`` unless the username already exists in which case raise an ``authkit.AuthError``. Optionally specify a ``password``, ``firstname``, ``surname``, ``email`` and ``group`` for the user and set the user's account status with ``active``. User passwords are already encrypted, if necessary, by the time this method is called so can be treated as strings without needing any modification. ``password``, ``firstname``, ``surname``, ``email`` can never be ``None`` but can be ``''``. ``group`` can be ``None`` to indicate no group assignment. ``active`` can only be ``True`` or ``False``. """ if group != None: # The fact the group exists has already been checked group_id = self.tables['Group_'].selectBy(name=group).getOne() else: group_id = None new_user = self.tables['User']( user=username, password=password, firstname=firstname, surname=surname, email=email, active=active, grp=group_id, ) def _driver_add_application(self, name): """ Add an appliation Add an application ``name``. ``A call to _driver_application_exists()`` will already have been made. """ new_app = self.tables['App'](name=name) def _driver_add_group(self, group): new_role = self.tables['Group_'](name=group) # # Roles # def _driver_set_role(self, username, roles, application): user = self.tables['User'].selectBy(user=username).getOne().id app = self.tables['App'].selectBy(name=application).getOne().id for role in roles: if not self.role_exists(role): raise AuthError("The '%s' role doesn't exist in the database."%role) if role in self.roles(username, application): raise AuthError('User %s already has the role %s for the application %s'%(repr(username), repr(role), repr(application))) else: r = self.tables['Role'].selectBy(name=role).getOne().id new_role = self.tables['Roles'](role=r, application=app, user=user) def _driver_add_role(self, role): """ Adds the role ``role`` to the store unless it already exists in which case an ``authkit.AuthError`` is raised. """ new_role = self.tables['Role'](name=role) def _driver_unset_role(self, username, role, application): if not self.role_exists(role): raise AuthError("The '%s' role doesn't exist in the database."%role) if role not in self.roles(username, application): raise AuthError('User %s does not have the role %s for the application %s'%(repr(username), repr(role), repr(application))) else: user = self.tables['User'].selectBy(user=username).getOne() app = self.tables['App'].selectBy(name=application).getOne() role = self.tables['Role'].selectBy(name=role).getOne() for role in self.tables['Roles'].selectBy(role=role, application=app, user=user): role.destroySelf() # # History Methods # def _driver_history(self, username): history = self.tables['User'].selectBy(user=username).getOne().history rows = [] if history: for h in history: rows.append((h.signed_out, h.signed_in, h.last_accessed)) def cmp(a, b): for x in [0,1,2]: if a[x] == None : if b[x] == None: pass else: return -1 elif b[x] == None: return 1 elif a[x] > b[x]: return 1 elif a[x] < b[x]: return -1 else: pass return 0 rows.sort(cmp) return rows def _driver_sign_out(self, username): user = self.tables['User'].selectBy(user=username).getOne() histories = self.tables['History'].selectBy(user=user) for history in histories: history.signed_out=datetime.datetime(2005,12,12,12).now() def _driver_sign_in(self, username): now = datetime.datetime(2005,12,12,12).now() user = self.tables['User'].selectBy(user=username).getOne() new_sign_in = self.tables['History'](user=user, signed_in=now, last_accessed=now, signed_out=None) def _driver_signed_in(self, username): if self.tables['History'].selectBy(user=username, signed_out=None).getOne(None): return True return False def _driver_update_accessed(self, username): history = self.tables['User'].selectBy(user=username).getOne().history if history:#raise Exception(history) for h in history:#history = self.tables['History'].selectBy(user=, signed_out=None).getOne() if h.last_accessed == None: h.last_accessed = datetime.datetime(2005,12,12,12).now() # # User class methods # def _driver_user(self, username, property=None): # Changed - removed property if self.user_exists(username): object = self.tables['User'].selectBy(user=username).getOne() group = None a = object.grp if a: group = a.name #group = self.tables['Group_'].get(object.grp)#.getOne().name user = { 'username':object.user, 'password':object.password, 'firstname':object.firstname, 'surname':object.surname, 'email':object.email, 'active':object.active, 'group':group, #'levels':self.levels(username), # Changed from level 'roles':self.roles(username), } if property: if user.has_key(property): return user[property] else: raise AuthError('Invalid user property %s'%(repr(property))) return user else: raise AuthError("No such username '%s'."%username) def _driver_set_user(self, username, **properties): """Private method to set the value of one of 'password', 'firstname', 'surname' and 'email' for a particular user.""" username = username.lower() for property in properties.keys(): value = properties[property] if property in ['password','firstname','surname','email']: if self.user_exists(username): setattr(self.tables['User'].selectBy(user=username).getOne(), property, value) else: raise AuthError('That user doesn\'t exist.') elif property == 'group': if self.group_exists(value): group_ = self.tables['Group_'].selectBy(name=value).getOne() self.tables['User'].selectBy(user=username).getOne().grp = group_ #setattr(self.tables['User'].selectBy(user=username).getOne(), property, ) else: raise AuthError('No such group %s'%repr(value)) elif property == 'active': if value in [0,1]: setattr(self.tables['User'].selectBy(user=username).getOne(), property, value) else: raise AuthError('active can only br True or False not %s'%repr(value)) else: raise AuthError("You can only set the properties password, firstname, surname, email, active and group") PK 5„|z|z$authkit/drivers/SQLObject_driver.pyc;ò DJêDc@s§dZdklZlZdkZdklZlZlZl Z l Z l Z l Z y e eWn+ej oddjZ ddjZnXdefd„ƒYZdS(síSQLObject driver for AuthKit. Developer Notes: * User columns are named ``user`` rather than ``username`` to avoid problems with Gadfly * The Group column is named ``grp`` rather than ``group`` to avoid confusion with SQL ``GROUP BY`` (s AuthErrors AuthStoreN(s SQLObjects StringColsBoolCols ForeignKeys MultipleJoins DateTimeColsconnectionForURIiisSQLObjectAuthStorecBs@tZdZdd„Zd„Zd„Zd„Zd„Zd„Zge e e d„Z e e d „Z d „Z d „Z d „Zed „Zd„Zd„Zd„Zd„Zddddee d„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Z e d„Z!d„Z"RS(s§ An auth store which uses `SQLObject `_ to store auth information in an SQL database. ``SQLObjectAuthStore`` is used as follows:: >>> from authkit.drivers.SQLObject_driver import SQLObjectAuthStore >>> from SQLObject import * >>> connection = connectionForURI(connection_string) >>> auth = SQLObjectAuthStore(connection=connection) sc  sû|ˆ_|ˆ_dtf‡d†ƒY}dtf‡d†ƒY}dtf‡d†ƒY}dtf‡d†ƒY}d tf‡d †ƒY}d tf‡d †ƒY} hd|<d|<d|<d|<d |<d | <ˆ_ t i ˆ|dS( NsUsercs–tZdf‡d†ƒYZˆiZeƒZeƒZeƒZ eƒZ eƒZ e ƒZ eˆidƒZeˆidƒZeˆidƒZRS(NssqlmetacstZˆidZRS(NsUser(s__name__s __module__sselfs_table_prependstable((sself(s9build\bdist.win32\egg\authkit\drivers\SQLObject_driver.pyssqlmeta-ssGroup_sRolessHistory(s__name__s __module__ssqlmetasselfs connections _connections StringColsuserspasswords firstnamessurnamesemailsBoolColsactives ForeignKeys_table_prependsgrps MultipleJoinsrolesshistory((sself(s9build\bdist.win32\egg\authkit\drivers\SQLObject_driver.pysUser,s       sAppcsCtZdf‡d†ƒYZˆiZeƒZeˆi dƒZ RS(NssqlmetacstZˆidZRS(NsApp(s__name__s __module__sselfs_table_prependstable((sself(s9build\bdist.win32\egg\authkit\drivers\SQLObject_driver.pyssqlmeta<ssRoles( s__name__s __module__ssqlmetasselfs connections _connections StringColsnames MultipleJoins_table_prependsroles((sself(s9build\bdist.win32\egg\authkit\drivers\SQLObject_driver.pysApp;s  sGroup_csCtZdf‡d†ƒYZˆiZeƒZeˆi dƒZ RS(NssqlmetacstZˆidZRS(NsGroup_(s__name__s __module__sselfs_table_prependstable((sself(s9build\bdist.win32\egg\authkit\drivers\SQLObject_driver.pyssqlmetaCssUser( s__name__s __module__ssqlmetasselfs connections _connections StringColsnames MultipleJoins_table_prependsusers((sself(s9build\bdist.win32\egg\authkit\drivers\SQLObject_driver.pysGroup_Bs  sRolecsCtZdf‡d†ƒYZˆiZeƒZeˆi dƒZ RS(NssqlmetacstZˆidZRS(NsRole(s__name__s __module__sselfs_table_prependstable((sself(s9build\bdist.win32\egg\authkit\drivers\SQLObject_driver.pyssqlmetaJssRoles( s__name__s __module__ssqlmetasselfs connections _connections StringColsnames MultipleJoins_table_prependsroles((sself(s9build\bdist.win32\egg\authkit\drivers\SQLObject_driver.pysRoleIs  sRolescs`tZdf‡d†ƒYZˆiZeˆidƒZeˆidƒZ eˆidƒZ RS(NssqlmetacstZˆidZRS(NsRoles(s__name__s __module__sselfs_table_prependstable((sself(s9build\bdist.win32\egg\authkit\drivers\SQLObject_driver.pyssqlmetaQssUsersAppsRole( s__name__s __module__ssqlmetasselfs connections _connections ForeignKeys_table_prependsusers applicationsrole((sself(s9build\bdist.win32\egg\authkit\drivers\SQLObject_driver.pysRolesPs  sHistorycsUtZdf‡d†ƒYZˆiZeˆidƒZe ƒZ e ƒZ e ƒZ RS(NssqlmetacstZˆidZRS(NsHistory(s__name__s __module__sselfs_table_prependstable((sself(s9build\bdist.win32\egg\authkit\drivers\SQLObject_driver.pyssqlmetaYssUser( s__name__s __module__ssqlmetasselfs connections _connections ForeignKeys_table_prependsusers DateTimeCols signed_ins last_accesseds signed_out((sself(s9build\bdist.win32\egg\authkit\drivers\SQLObject_driver.pysHistoryXs    (s connectionsselfs table_prepends_table_prepends SQLObjectsUsersAppsGroup_sRolesRolessHistorystabless AuthStores__init__sauth_store_params( sselfs connections table_prependsauth_store_paramssRolessRolesUsersGroup_sAppsHistory((sselfs9build\bdist.win32\egg\authkit\drivers\SQLObject_driver.pys__init__(s   ? cCshxa|iiƒD]P\}}|i|}|ii|ƒot dt |ƒƒ‚q|i ƒqWdS(s/ Destroy any existing store and create the auth store. If any errors are generated when creating the store an ``authkit.AuthError`` is raised. After this method is called, the default application is added, you don't need to implement any code for this. sThe table %s already existsN( sselfstablessitemssnamestables_table_prependsfullnames connections tableExistss AuthErrorsreprs createTable(sselfsnamestablesfullname((s9build\bdist.win32\egg\authkit\drivers\SQLObject_driver.pys_driver_create_storeps  cCstg}xc|iiƒD]R\}}|i|}|ii |ƒ o|i dt |ƒƒq|i ƒqW|SdS(sW Remove the auth store, destroying any data it contains. If there are no problems, ``[]`` is returned. If any errors occurs preventing the store from being removed an ``authkit.AuthError`` is raised. If the store doesn't exist or only partially exists, any warnings are returned as a list of strings. sThe table %s doesn't existN( serrorssselfstablessitemssnamestables_table_prependsfullnames connections tableExistssappendsreprs dropTable(sselfserrorssnamestablesfullname((s9build\bdist.win32\egg\authkit\drivers\SQLObject_driver.pys_driver_remove_store€s  cCsKx@|iiƒD]/\}}|ii|i|ƒ otSqqWt SdS(s Returns ``True`` if every component of the store exists, ``False`` otherwise. Typically used as follows:: if not auth.store_exists(): try: warnings = auth.remove_store() if warnings: print warnings except AuthError: print "Failed" raise else: auth.create_store() print "Success" N( sselfstablessitemssnamestables connections tableExistss_table_prependsFalsesTrue(sselfstablesname((s9build\bdist.win32\egg\authkit\drivers\SQLObject_driver.pys_driver_store_existss   cCs?tgi}|idiƒD]}||iƒq~ƒSdS(sd Return a list of applications in the store, including the ``default`` application. sAppN(stuplesappends_[1]sselfstablessselectsobjsname(sselfs_[1]sobj((s9build\bdist.win32\egg\authkit\drivers\SQLObject_driver.pys_driver_applications«scCs?tgi}|idiƒD]}||iƒq~ƒSdS(NsGroup_(stuplesappends_[1]sselfstablessselectsobjsname(sselfs_[1]sobj((s9build\bdist.win32\egg\authkit\drivers\SQLObject_driver.pys_driver_groups±scCs/g}|tjo |tjo|gjoA|tjo|idiƒ} q#|idi d|ƒ} qð|tjoS|tjo t} n |idi d|ƒi ƒ} |idi d| ƒ} qð|tjo t} n |idi d|ƒi ƒ} |idi d|d| ƒ} nÊ|tjo |tjo½|gjo¯|idi d|ƒ}|idi d |i ƒƒ}g} xk|D]b}|i| joL|tjo| i|iƒqõ|ii|jo| i|iƒqõq“q“Wqð|idi d|ƒi ƒ}|idi d |ƒ}|tjo t} n |idi d|ƒi ƒ} g} x||D]~}|i| joc|ii| joL|tjo| i|iƒqí|ii|jo| i|iƒqíqöqx|GHqxWnó|tjo |tjoÚ|id i d|ƒi ƒi} |gjo¯|id i d|ƒ} |idi d | i ƒƒ}g} xf|D]b}|i| joL|tjo| i|iƒqî|ii|jo| i|iƒqîqŒqŒWqð|tjo t} n |idi d|ƒi ƒ} |id i d|ƒ} |idi d | i ƒƒ}g} xƒ|D]y}|i| joc|ii| joL|tjo| i|iƒqæ|ii|jo| i|iƒqæqêqqqqWnÿ|gjoÔ|idi d|ƒi ƒ}|id i d|ƒi ƒ}|idi d |d |ƒ}g} x‹|D]b}|i| joL|tjo| i|iƒqË|ii|jo| i|iƒqËqiqiWn|idi d|ƒi ƒ}|id i d|ƒi ƒ}|tjo t} n |idi d|ƒi ƒ} |idi d |d |ƒ}g} x|D]y}|i| joc|ii| joL|tjo| i|iƒqè|ii|jo| i|iƒqèqìqsqsWg}x| D]} |i| iƒqýW|iƒt|ƒSd S( s© Return a list of current usernames according to various options ``group`` Can be ``None`` to select the group of users where no group is assigned Can be ``[]`` to select evey user regardless of group or can be the name of a group to select just users in that group ``active`` Can be ``None`` to select all users, ``True`` to select users with active accounts or ``False`` to select users with disabled accounts ``application`` Can be ``None`` to select all users reardless of the appliaction they have roles with or the application name to select users associated with that application ``role`` Can be ``None`` to select all users reardless of roles or the name of a role to select users with that role All options are used in combination so to select users of the ``default`` application with the role ``editor`` for example you could specify ``application='default', role='editor'`` in the parameters. Users are returned in alphabetical order. sUsersactivesGroup_snamesgrpsgroupsRolesRolessrolesApps applicationN(srowss applicationsNonesrolesgroupsactivesselfstablessselectsobjssselectBysgroup_sgetOnesrolessusersappendsrole_sgrpsids application_sappssapp_suserssobjssortstuple(sselfsgroupsactives applicationsrolesapp_srowssuserssrolessappssobjss application_sobjsgroup_srole_((s9build\bdist.win32\egg\authkit\drivers\SQLObject_driver.pys _driver_users´sÎ       #       "      $        cCss|tjo |tjoHg}|idiƒ}x|D]}|i |i ƒq:Wt |ƒSn|tjo |tjo|idi d|ƒi ƒ} |idi d|ƒi ƒ} g}x:|idi d| d| ƒD]}|i |ii ƒqàWt |ƒSne|tjoÝ|idi d|ƒi ƒi}h}x^|D]V}|i|ii ƒo!||ii i |ii ƒqG|ii g||ii Signed In

You are already signed in. Sign out.

PK¬5øð:RŒŒ'authkit/templates/pylons/alreadyout.myt

Not Signed In

You are not signed in. Sign in again.

PK¬5Ÿÿ޲——)authkit/templates/pylons/security.py_tmplfrom ${base_package}.lib.base import * from authkit.controllers import * class SecurityController(PylonsSecureController): def index(self, **params): return self.signin(**params) def signin(self, ARGS, **params): if len(ARGS): from authkit.validators import SignIn validator = SignIn() try: if not request.environ.has_key('paste.login.http_login'): raise Exception('Action permissions specified but security middleware not present.') state = State() state.auth = g.auth state.authenticate = request.environ['paste.login.authenticator']().check_auth results = validator.to_python(ARGS, state=state) except formencode.Invalid, e: # Note error_dict doesn't contain strings errors = e.error_dict if not e.error_dict: errors = {'password':str(e)} self.c.form = formbuild.Form(defaults=ARGS, errors=errors) m.subexec('/security/signin.myt') else: self.__signin__(username=ARGS.get('username')) m.subexec('/security/signedin.myt', **ARGS) else: self.c.form = formbuild.Form(defaults=ARGS) m.subexec('/security/signin.myt') def signout(self, ARGS, **params): if request.environ.has_key('REMOTE_USER'): self.__signout__(request.environ['REMOTE_USER']) m.subexec('/security/signedout.myt', **ARGS) else: m.subexec('/security/alreadyout.myt', **ARGS) PK¬5™¢K<……%authkit/templates/pylons/signedin.myt

Signed In

You have been signed in. Sign out.

PK¬5¾)1‹‹&authkit/templates/pylons/signedout.myt

Signed Out

You have been signed out. Sign in again.

PK¬5ÈF§h%%#authkit/templates/pylons/signin.myt

Sign In

<% c.form.start(name="signin", action="", method="get") %> <% c.form.layout.simple_start() %> <% c.form.layout.entry( content=c.form.field.text(name="username"), name='Username', error=c.form.get_error('username') ) %> <% c.form.layout.entry( content=c.form.field.password(name="password", value=''), name='Password', error=c.form.get_error('password') ) %> <% c.form.layout.entry(content=c.form.field.submit(name="go", value="Submit")) %> <% c.form.layout.simple_end() %> <% c.form.end() %> PK 5“×2EGG-INFO/dependency_links.txt PK 5ª†®8TTEGG-INFO/entry_points.txt [paste.global_paster_command] authkit=authkit.commands:SecurityCommand PK1 5“×2EGG-INFO/not-zip-safe PK 5&WžÞÞÞEGG-INFO/PKG-INFOMetadata-Version: 1.0 Name: AuthKit Version: 0.1.5a Summary: A complete autentication and authorisation system. Home-page: http://pythonshq.com/ Author: James Gardner Author-email: james@pythonweb.org License: MIT Description: A complete autentication and authorisation system. This is a bugfix release for the old 0.1 branch. You should really use the latest 0.2 branch which is completely different. Platform: UNKNOWN PK 5Db8ööEGG-INFO/requires.txtPaste>=0.5 FormBuild>=0.1.3 FormEncode>=0.4 SQLObject==dev,>=0.8dev [SQLObject] SQLObject==dev,>=0.8dev [docs] docutils>=0.3.9 pudge>=0.1 buildutils>=0.1.1 kid>=0.7 [Paste] Paste>=0.5 PasteDeploy>=0.5 PasteScript>=0.5 [database] database>=0.6PK 5¯HÝ*,,EGG-INFO/SOURCES.txtLICENSE README.txt setup.cfg setup.py AuthKit.egg-info/PKG-INFO AuthKit.egg-info/SOURCES.txt AuthKit.egg-info/dependency_links.txt AuthKit.egg-info/entry_points.txt AuthKit.egg-info/not-zip-safe AuthKit.egg-info/requires.txt AuthKit.egg-info/top_level.txt authkit/__init__.py authkit/commands.py authkit/middleware.py authkit/validators.py authkit/controllers/__init__.py authkit/drivers/SQLObject_driver.py authkit/drivers/__init__.py authkit/drivers/database.py authkit/extras/__init__.py authkit/extras/time.py authkit/templates/__init__.py authkit/templates/pylons/alreadyin.myt authkit/templates/pylons/alreadyout.myt authkit/templates/pylons/security.py_tmpl authkit/templates/pylons/signedin.myt authkit/templates/pylons/signedout.myt authkit/templates/pylons/signin.myt docs/community.txt docs/download.txt docs/driver.txt docs/examples.txt docs/future.txt docs/index.txt docs/manual.txt docs/pylons.txt examples/test_code.py examples/wsgi.py ez_setup/README.txt ez_setup/__init__.py tests/test.py tests/test_users.py PK 5Ú&eþEGG-INFO/top_level.txtauthkit PK¬5¿³ñ##¶authkit/commands.pyPK 5‡@}¿¿¶Tauthkit/commands.pycPK$¿ÿ4²7AXŠ+Š+¶Eauthkit/middleware.pyPK 5› Ý÷8÷8¶:authkit/middleware.pycPK¬5 c’”££¶-sauthkit/validators.pyPK 5e&¡;¶|authkit/validators.pycPK¬5 ßô²T²T¶Jauthkit/__init__.pyPK 5þmO;Q;Q¶-âauthkit/__init__.pycPK¬5É Bxx¶š3authkit/controllers/__init__.pyPK 5„b1‹ëë ¶ODauthkit/controllers/__init__.pycPK¬5.c½äBrBr¶x]authkit/drivers/database.pyPK 5¯lQµii¶óÏauthkit/drivers/database.pycPK¬5Üa<Ïýkýk#¶=9authkit/drivers/SQLObject_driver.pyPK 5„|z|z$¶{¥authkit/drivers/SQLObject_driver.pycPK¬5À€ä¶9 authkit/drivers/__init__.pyPK 5µ^ ªª¶† authkit/drivers/__init__.pycPK¬5ŠÜDß°°¶j!authkit/extras/time.pyPK 5êÆ(  ¶N'authkit/extras/time.pycPK¬5£yûµ¶Š1authkit/extras/__init__.pyPK 5ts©««¶Ø1authkit/extras/__init__.pycPK¬5ÿžep¶¼2authkit/templates/__init__.pyPK 5O%ƒƒ¶ø2authkit/templates/__init__.pycPK¬5ö°<††&¶·3authkit/templates/pylons/alreadyin.mytPK¬5øð:RŒŒ'¶4authkit/templates/pylons/alreadyout.mytPK¬5Ÿÿ޲——)¶R5authkit/templates/pylons/security.py_tmplPK¬5™¢K<……%¶0<authkit/templates/pylons/signedin.mytPK¬5¾)1‹‹&¶ø<authkit/templates/pylons/signedout.mytPK¬5ÈF§h%%#¶Ç=authkit/templates/pylons/signin.mytPK 5“×2¶-@EGG-INFO/dependency_links.txtPK 5ª†®8TT¶i@EGG-INFO/entry_points.txtPK1 5“×2¶ô@EGG-INFO/not-zip-safePK 5&WžÞÞÞ¶(AEGG-INFO/PKG-INFOPK 5Db8öö¶5CEGG-INFO/requires.txtPK 5¯HÝ*,,¶^DEGG-INFO/SOURCES.txtPK 5Ú&eþ¶¼HEGG-INFO/top_level.txtPK##þ øH