Changeset 77

Show
Ignore:
Timestamp:
06/04/07 20:45:59
Author:
bbangert
Message:

PEP 8 clean-up and removal of commented and non-running code blocks.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • AuthKit/branches/0.4/authkit/authenticate/__init__.py

    r71 r77  
    5151from authkit.permissions import RemoteUser, no_authkit_users_in_environ, AuthKitConfigError 
    5252 
    53 # 
    5453# Setting up logging 
    55 # 
    5654 
    5755log = logging.getLogger('authkit.authenticate') 
    5856     
    59 # 
    60 # Exceptions 
    61 # 
    62  
    63  
    64  
    65  
    66 # 
    67 # Default values 
    68 # 
    69  
    70 #_allowed_options = [ 
    71 #    'method',         
    72 #    'catch',          
    73 #    'exclude', 
    74 #    'enable', 
    75 #     
    76 #    'form_template_obj',      
    77 #    'form_template_file',        
    78 #    'form_template',             
    79 #    'realm',     
    80 #     
    81 #    'users_object', 
    82 #    'users_setup', 
    83 #    'users_valid', 
    84 #    'users_digest', 
    85 # 
    86 #    'passurl_path_process', 
    87 #    'passurl_urltouser', 
    88 #    'passurl_path_verify', 
    89 #    'passurl_path_signedin', 
    90 #    'passurl_baseurl', 
    91 #    'passurl_template', 
    92 #    'passurl_template_obj', 
    93 #    'passurl_template_file', 
    94 #    'passurl_session_middleware', 
    95 #    'passurl_session_key', 
    96 #    'passurl_session_secret', 
    97 #    'passurl_store_config', 
    98 #    'passurl_store_type', 
    99 #     
    100 #    'cookie_secret',            
    101 #    'cookie_name',              
    102 #    'cookie_secure',             
    103 #    'cookie_includeip',          
    104 #    'cookie_signout',       
    105 #    'cookie_params', 
    106 #    'cookie_enforce', 
    107 #    'signin', 
    108 #] 
    109 # 
    110 ## 
    111 ## Useful functions 
    112 ## 
    113 # 
    114 #def _get_value(dictionary, option, prefix, allowed_values=[], **p): 
    115 #    """ 
    116 #    Returns the value ``dictionary[option]`` checking it is one of 
    117 #    ``allowed_values`` 
    118 #    """ 
    119 #    if not dictionary.has_key(option): 
    120 #        if p.has_key('default'): 
    121 #            return p['default'] 
    122 #        else: 
    123 #            raise AuthKitConfigError( 
    124 #                "The required option %r was not specified"%_app2key(option, prefix) 
    125 #            ) 
    126 #    else: 
    127 #        result = dictionary[option] 
    128 #        if allowed_values and result not in allowed_values: 
    129 #            if p.has_key('default'): 
    130 #                return p['default'] 
    131 #            else: 
    132 #                raise AuthKitConfigError( 
    133 #                    "The option %r takes one of the values %r, not %r"%( 
    134 #                        _app2key(option, prefix), 
    135 #                        allowed_values, 
    136 #                        result, 
    137 #                    )     
    138 #                ) 
    139 #        return result 
    140 # 
    141 #def _convert_config(app_conf, prefix): 
    142 #    """ 
    143 #    Return the ``app_conf`` dictionary keys in the form they would have been 
    144 #    entered if the middleware had been setup directly in Python code 
    145 #    """ 
    146 #    authkit_options = {} 
    147 #    for key, value in app_conf.items(): 
    148 #        if key[:len(prefix)].lower() == prefix: 
    149 #            authkit_options[key[len(prefix):].replace('.','_')] = value 
    150 #    return authkit_options 
    151 # 
    152 #def _app2key(key, prefix): 
    153 #    """ 
    154 #    Return the name of the key as it would have specified in the config file 
    155 #    """ 
    156 #    return prefix+key.replace('_','.') 
    157 # 
    158 #def _get_one_option_name(final, options, prefix, raise_on_no_match=True): 
    159 #    """ 
    160 #    Check that the ``final`` dictionary only contains one of the keys  
    161 #    specified in ``options``. If ``raise_on_no_match`` is ``True`` an  
    162 #    ``AuthKitConfigError`` is raised if none of the options are  
    163 #    present. 
    164 #    """ 
    165 #    found = None 
    166 #    for option in options: 
    167 #        if final.has_key(option): 
    168 #            if option != None: 
    169 #                found = option 
    170 #            else: 
    171 #                raise AuthKitConfigError( 
    172 #                    'You cannot specify both %r and %r'%( 
    173 #                        _app2key(found, prefix), 
    174 #                        _app2key(option, prefix), 
    175 #                    ) 
    176 #                ) 
    177 #    if found: 
    178 #        return found 
    179 #    elif raise_on_no_match: 
    180 #        raise AuthKitConfigError( 
    181 #            'Your AuthKit configuration reqiuires one of these options to be ' 
    182 #            'set: %s'%', '.join([_app2key(x, prefix) for x in options]) 
    183 #        ) 
    184 #    return None 
    185 # 
    18657def strip_base(conf, base): 
    18758    result = {} 
     
    401272 
    402273def load_config(options, app_conf, prefix): 
    403     merged = {} 
    404     auth_conf_options = strip_base(app_conf, prefix) 
    405  
    406     # First check all options are valid 
    407 #        for key, value in auth_conf_options: 
    408 #            if key not in allowed_options: 
    409 #                raise AuthKitConfigError( 
    410 #                    'Option key %r specified in config file is not a valid ' 
    411 #                    'authkit option'%_app2key(key, prefix)) 
    412 #        for key, value in options.items(): 
    413 #            if key not in _allowed_options: 
    414 #                raise Exception('Parameter %r is not a valid authkit option'%key) 
    415      
    416     # Then use the auth_conf_options 
    417     merged.update(auth_conf_options) 
    418  
     274    merged = strip_base(app_conf, prefix) 
     275     
    419276    # Now override the auth_conf_options with the manaully specified options 
    420277    for key, value in options.items(): 
     
    431288    return merged 
    432289 
    433  
    434 def middleware( 
    435     app, 
    436     app_conf=None, 
    437     global_conf=None, 
    438     prefix='authkit.', 
    439     **options 
    440 ):    
     290def middleware(app, app_conf=None, global_conf=None, prefix='authkit.',  
     291               **options):    
    441292    """ 
    442293    This function sets up the AuthKit authenticate middleware and its use and options 
     
    480331    variable in the source code. 
    481332    """ 
    482  
    483     # 
    484     # Setup the httpexceptions middleware 
    485     # 
    486  
    487 #    class AddHTTPExceptionMiddleware: 
    488 #        def __init__(self, app): 
    489 #            self.app = app 
    490 #        def __call__(self, environ, start_response): 
    491 #            if not environ.has_key("paste.expected_exceptions"): 
    492 #                self.app = HTTPExceptionHandler(self.app) 
    493 #            return self.app(environ, start_response) 
    494  
    495333    app = HTTPExceptionHandler(app) 
    496  
    497  
    498     # 
     334     
    499335    # Configure the config files 
    500     # 
    501  
     336     
    502337    if global_conf is None: 
    503338        global_conf = {} 
     
    510345        ) 
    511346     
    512     # 
    513347    # Merge config file and options 
    514     # 
    515  
    516  
    517  
    518    # method = options.get('method',app_conf.get(prefix+'method')) 
    519348    available_methods = get_methods() 
    520  
     349     
    521350    all_conf = load_config(options, app_conf, prefix) 
    522  
    523  
     351     
    524352    if not all_conf.has_key('setup.method'): 
    525353        raise AuthKitConfigError('No authkit.setup.method was specified') 
    526  
     354     
    527355    # Check to see if middleware is disabled 
    528356    if asbool(all_conf.get('setup.enable', True)) == False: 
     
    531359        ) 
    532360        return app 
    533  
     361     
    534362    # Status Checking/Changing Middleware 
    535363    intercept = [str(x).strip() for x in all_conf.get('setup.intercept','401').split(',')] 
     
    541369        ) 
    542370    app = AddToEnviron(app, 'authkit.intercept', intercept) 
    543  
     371     
    544372    methods = [method.strip() for method in all_conf['setup.method'].split(',')] 
    545373    log.debug("Trying to load the following methods: %r", methods) 
     
    558386        prefix_ = prefix+method+'.' 
    559387        auth_conf = strip_base(all_conf, method+'.') 
    560  
    561  
     388         
    562389        app = available_methods[method].load()( 
    563390            app, 
     
    567394            prefix=prefix_, 
    568395        ) 
    569  
     396     
    570397    app = AddToEnviron(app, 'authkit.config', strip_base(all_conf, 'config.')) 
    571  
    572     return app 
    573  
    574     # XXXXX This stuff is never called now! 
    575  
    576     # 
    577     # Create the middleware, checking options as we go 
    578     # 
    579      
    580  
    581  
    582  
    583  
    584     # Sign in method 
    585     methods = ['form','forward','basic','digest','passurl'] 
    586     if custom_methods: 
    587         for custom_method in custom_methods.keys(): 
    588             methods.append(custom_method) 
    589  
    590     if method not in ['forward','passurl']:   
    591         app, valid, digest = get_authenticate_function(app, final, prefix, method) 
    592     # define realm 
    593     if method in ['basic','digest']: 
    594         if not final.has_key('realm'): 
    595             final['realm'] = 'AuthKit' 
    596     # Set up the correct middleware 
    597     if method == 'basic': 
    598         from authkit.authenticate.basic import middleware 
    599         app = MultiHandler(app) 
    600         app.add_method( 
    601             'basic',  
    602             middleware,  
    603             final['realm'],  
    604             valid 
    605         ) 
    606         app.add_checker('basic', status_checker) 
    607         return app 
    608     elif method == 'digest': 
    609         from authkit.authenticate.digest import middleware 
    610         app = MultiHandler(app) 
    611         app.add_method( 
    612             'digest',  
    613             middleware,  
    614             final['realm'],  
    615             digest 
    616         ) 
    617         app.add_checker('digest', status_checker) 
    618         return app 
    619     elif method == 'form': 
    620         from authkit.authenticate.form import Form, template 
    621         template = get_template(final, template, 'form_', prefix) 
    622         if final.has_key('cookie_signout') and not \ 
    623             final['cookie_signout'].startswith('/'): 
    624             raise AuthKitConfigError( 
    625                 "The cookie signout path should start with a '/' character" 
    626             ) 
    627         app = MultiHandler(app) 
    628         app.add_method('form', Form, authfunc=valid, template=template) 
    629         app.add_checker('form', status_checker) 
    630         app = load_cookie_middleware(app, final, prefix) 
    631         return app 
    632     elif method == 'forward': 
    633         from authkit.authenticate.forward import Redirect, MyRecursive, RecursiveMiddleware 
    634         app = MultiHandler(app) 
    635         app.add_method( 
    636             'forward',  
    637             Redirect,   
    638             _get_value(final, 'signin', prefix) 
    639         ) 
    640         app.add_checker('forward', status_checker) 
    641         app = MyRecursive(RecursiveMiddleware(app)) 
    642         app = load_cookie_middleware(app, final, prefix) 
    643         return app 
    644     elif method=='passurl': 
    645         # Note, the session middleware should already be setup by now 
    646         # if we are not using beaker 
    647         from authkit.authenticate.passurl import PassURLSignIn, AuthOpenIDHandler, template 
    648         template = get_template(final, template, 'passurl_', prefix) 
    649         app = MultiHandler(app) 
    650         app.add_method( 
    651             'passurl',  
    652             PassURLSignIn,   
    653             template,  
    654             path_verify=_get_value(final, 'passurl_path_verify', prefix, default='/verify'), 
    655             baseurl=_get_value(final, 'passurl_baseurl', prefix, default='') 
    656         ) 
    657         app.add_checker('passurl', status_checker) 
    658         urltouser = _get_value(final, 'passurl_urltouser', prefix, default=None) 
    659         if isinstance(urltouser, str): 
    660             urltouser = eval_import(urltouser) 
    661         app = AuthOpenIDHandler( 
    662             app, 
    663             store_type=_get_value(final, 'passurl_store_type', prefix),  
    664             store_config = _get_value(final, 'passurl_store_config', prefix), 
    665             baseurl=_get_value(final, 'passurl_baseurl', prefix, default=''), 
    666             path_signedin=_get_value(final, 'passurl_path_signedin', prefix), 
    667             path_process=_get_value(final, 'passurl_path_process', prefix, default='/process'), 
    668             template = template, 
    669             urltouser = urltouser 
    670         ) 
    671         session_middleware = 'beaker.session' 
    672         session_secret = 'asdasd' 
    673         session_key = 'authkit_passurl' 
    674         if session_middleware == 'beaker.session': 
    675             if not session_secret: 
    676                 raise AuthKitConfigError('No session_secret set') 
    677             from beaker.session import SessionMiddleware 
    678             app = SessionMiddleware(app, key=session_key, secret=session_secret) 
    679              
    680         app = load_cookie_middleware(app, final, prefix) 
    681         return app 
    682     else: 
    683         raise NotImplementedError('No %r method has been implemented'%method) 
    684             
    685  
     398    return app            
    686399 
    687400def sample_app(environ, start_response): 
     
    690403    ``/private`` is entered, triggering the authenticate middleware to  
    691404    prompt the user to sign in. 
    692  
     405     
    693406    If used with the authenticate middleware's form method, the path  
    694407    ``/signout`` will display a signed out message if  
    695408    ``authkit.cookie.signout = /signout`` is specified in the config file. 
    696  
     409     
    697410    If used with the authenticate middleware's forward method, the path  
    698411    ``/signin`` should be used to display the sign in form. 
     
    717430        result.append('%s: %s\n'%(k,v)) 
    718431    return result 
    719