Changeset 68

Show
Ignore:
Timestamp:
04/22/07 21:04:29
Author:
thejimmyg
Message:

Refactoring based on Ben's suggestions

Files:

Legend:

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

    r67 r68  
    1111* HTTP Basic (``basic``) 
    1212* HTTP Digest (``digest``) 
    13 * OpenID Passurl (``passurl``) 
     13* OpenID Passurl (``openid``) 
    1414* Form and Cookie (``form``) 
    1515* Forward (``forward``) 
     16* Redirect (``redirect``) 
    1617 
    1718The authenticate middleware can be configured directly or by means of a Paste 
     
    371372# 
    372373 
    373 class AddToEnviron
     374class AddToEnviron(object)
    374375    """ 
    375376    Simple middleware which adds a key to the ``environ`` dictionary. 
     
    387388        return self.app(environ, start_response) 
    388389 
    389 class RequireEnvironKey
     390class RequireEnvironKey(object)
    390391    def __init__(self, app, key, missing_error='Missing the key %(key)s from the environ. Have you setup the correct middleware?'): 
    391392        self.app = app 
  • AuthKit/branches/0.4/authkit/authenticate/basic.py

    r67 r68  
    3737from paste.httpexceptions import HTTPUnauthorized 
    3838from paste.httpheaders import * 
     39from authkit.authenticate.multi import MultiHandler, status_checker 
     40from authkit.authenticate import get_template, valid_password, \ 
     41   get_authenticate_function, strip_base, RequireEnvironKey 
    3942 
    40 class AuthBasicAuthenticator
     43class AuthBasicAuthenticator(object)
    4144    """ 
    4245    implements ``Basic`` authentication details 
     
    6669    __call__ = authenticate 
    6770 
    68 class AuthBasicHandler
     71class AuthBasicHandler(object)
    6972    """ 
    7073    HTTP/1.0 ``Basic`` authentication middleware 
     
    99102    def __call__(self, environ, start_response): 
    100103        if environ.has_key('authkit.multi'): 
    101             # Shouldn't ever allow a response if this is called via the multi handler 
     104            # Shouldn't ever allow a response if this is called via the 
     105            # multi handler 
    102106            authenitcation = self.authenticate.build_authentication() 
    103107            return authenitcation.wsgi_application(environ, start_response) 
     
    108112middleware = AuthBasicHandler 
    109113 
    110 class TryToAddUsername
     114class TryToAddUsername(object)
    111115    def __init__(self, application, realm, authfunc, users): 
    112116        self.application = application 
     
    121125            REMOTE_USER.update(environ, result) 
    122126        return self.application(environ, start_response) 
    123  
    124 from authkit.authenticate.multi import MultiHandler, status_checker 
    125 from authkit.authenticate import get_template, valid_password, get_authenticate_function, strip_base, RequireEnvironKey 
    126127 
    127128def make_basic_handler( 
     
    147148    return app 
    148149 
    149    # app = MultiHandler(app) 
    150    # app.add_method('redirect', HandleRedirect, redirect_to = auth_conf['signin']) 
    151    # app.add_checker('redirect', status_checker) 
    152    # return app 
    153  
  • AuthKit/branches/0.4/authkit/authenticate/cookie.py

    r67 r68  
    1 """Cookie handling based on paste.auth.auth_tkt but with some bug fixes and improvements 
     1"""Cookie handling based on paste.auth.auth_tkt but with some bug fixes and 
     2improvements 
    23 
    34Supported cookie options (described in detail in the AuthKit manual):: 
     
    2829    #. We need the BadTicket handling in place 
    2930    #. We need to be able to use a custom AuthTicket 
    30     #. The custom AuthTicket should accept cookie params specifiable in the config file 
    31     #. The cookie timestamp should be available in the environment as paste.auth_tkt.timestamp 
     31    #. The custom AuthTicket should accept cookie params specifiable in the  
     32       config file 
     33    #. The cookie timestamp should be available in the environment as 
     34       paste.auth_tkt.timestamp 
    3235 
    3336.. Warning :: 
    3437     
    35     You shouldn't rely on the bad ticket or server side expires code because when 
    36     they are triggered, the sign in form isn't displayed.  
    37      
    38     Instead it is better to let the cookie expire naturally. For this reason the  
    39     server side expiration allows a second longer than the cookie expire time so it 
    40     only kicks in if the cookie fails to expire. 
     38    You shouldn't rely on the bad ticket or server side expires code because  
     39    when they are triggered, the sign in form isn't displayed.  
     40     
     41    Instead it is better to let the cookie expire naturally. For this reason  
     42    the server side expiration allows a second longer than the cookie expire  
     43    time so it only kicks in if the cookie fails to expire. 
    4144     
    4245Here is an example: 
     
    6972# Imports 
    7073# 
    71 #raise Exception('asdasd') 
     74 
    7275from paste.deploy.converters import asbool 
    7376from paste.auth.auth_tkt import * 
     
    7780from paste.deploy.converters import asbool 
    7881from authkit.authenticate import strip_base, swap_underscore, AuthKitConfigError 
     82 
    7983# 
    8084# Setting up logging 
    8185# 
    8286 
    83 log = logging.getLogger('authkit.authenticate.auth_tkt') 
     87log = logging.getLogger('authkit.authenticate.cookie') 
    8488 
    8589# 
     
    110114        user_data='', 
    111115        time=None,  
    112         cookie_name='auth_tkt', 
     116        cookie_name='authkit', 
    113117        cookie_params=None 
    114118    ): 
     
    117121            self.cookie_params = {} 
    118122        else: 
    119             # This is a bit of a hack to keep the API consistent with the base classs 
     123            # This is a bit of a hack to keep the API consistent with the base 
     124            # classs 
    120125            if cookie_params.has_key('secure'): 
    121126                secure = asbool(cookie_params.get('secure',False)) 
     
    142147            self.ip, self.time, self.secret, self.userid, self.tokens, 
    143148            self.user_data) 
    144         log.debug("Calculating the digest ip %r, time %r, secret %r, userid %r, tokens %r, user_data %r, digest %r", self.ip, self.time, self.secret, self.userid, self.tokens, self.user_data, digest_) 
     149        log.debug( 
     150            "Calculating the digest ip %r, time %r, secret %r, userid %r, " 
     151            "tokens %r, user_data %r, digest %r",  
     152            self.ip,  
     153            self.time,  
     154            self.secret,  
     155            self.userid,  
     156            self.tokens,  
     157            self.user_data, 
     158            digest_ 
     159        ) 
    145160        return digest_ 
    146161 
     
    154169    def cookie(self): 
    155170        c = Cookie.SimpleCookie() 
    156         # XXX This is a bug?! 
     171        # XXX There is is a bug in the base class implementation fixed here 
    157172        c[self.cookie_name] = self.cookie_value().strip().replace('\n', '') 
    158173        for k, v in self.cookie_params.items(): 
    159174            if k not in ['path', 'expires']: 
    160175                c[self.cookie_name][k] = v 
    161         # path and secure are handled differently to keep it consistent with the base class API 
     176        # path and secure are handled differently to keep it consistent with 
     177        # the base class API 
    162178        if not self.cookie_params.has_key('path'): 
    163179            c[self.cookie_name]['path'] = '/' 
     
    170186        if self.secure: 
    171187            c[self.cookie_name]['secure'] = 'true' 
    172  
    173188        return c 
    174189         
    175 # The other methods in the paste file, calculate_digest and encode_ip_timestamp are utility methods 
    176 # which you shouldn't need to use on their own. 
     190# The other methods in the paste file, calculate_digest and encode_ip_timestamp 
     191# are utility methods which you shouldn't need to use on their own. 
    177192 
    178193def parse_ticket(secret, ticket, ip): 
     
    213228     
    214229def calculate_digest(ip, timestamp, secret, userid, tokens, user_data): 
    215     log.debug("calculate_digest(ip=%r, timestamp=%r, secret=%r, userid=%r, tokens=%r, user_data=%r)", ip, timestamp, secret, userid, tokens, user_data) 
    216  
     230    log.debug( 
     231        "calculate_digest(ip=%r, timestamp=%r, secret=%r, userid=%r, " 
     232        "tokens=%r, user_data=%r)", 
     233        ip,  
     234        timestamp,  
     235        secret,  
     236        userid,  
     237        tokens,  
     238        user_data 
     239    ) 
    217240    digest0 = md5.new( 
    218241        encode_ip_timestamp(ip, timestamp) + secret + userid + '\0' 
     
    232255    return ip_chars + ts_chars 
    233256 
    234  
    235  
    236  
    237  
    238257# 
    239258# Custom AuthKitCookieMiddleware 
     
    257276        app, 
    258277        secret,  
    259         name='auth_tkt',  
     278        name='authkit',  
    260279        params=None, 
    261280        includeip=True,  
     
    265284    ): 
    266285        log.debug("Setting up the cookie middleware") 
    267  
    268286        secure = False 
    269287        if params.has_key('secure') and asbool(params['secure']) == True: 
     
    284302        self.cookie_enforce = enforce 
    285303        if self.cookie_enforce and not self.cookie_params.has_key('expires'): 
    286             raise Exception("Cannot enforce cookie expiration since no cookie_params 'expires' has been set") 
     304            raise Exception( 
     305                "Cannot enforce cookie expiration since no cookie_params " 
     306                "'expires' has been set" 
     307            ) 
    287308 
    288309    def __call__(self, environ, start_response): 
     
    293314        else: 
    294315            cookie_value = '' 
    295         log.debug("Our cookie %r value is therefore %r", self.cookie_name, cookie_value) 
    296         remote_addr = environ.get('HTTP_X_FORWARDED_FOR', environ.get('REMOTE_ADDR','0.0.0.0')) 
    297         log.debug("Remote addr %r, value %r, include_ip %r", remote_addr, cookie_value, self.include_ip) 
    298  
     316        log.debug( 
     317            "Our cookie %r value is therefore %r",  
     318            self.cookie_name,  
     319            cookie_value 
     320        ) 
     321        remote_addr = environ.get( 
     322            'HTTP_X_FORWARDED_FOR',  
     323            environ.get('REMOTE_ADDR','0.0.0.0') 
     324        ) 
     325        log.debug( 
     326            "Remote addr %r, value %r, include_ip %r",  
     327            remote_addr,  
     328            cookie_value,  
     329            self.include_ip, 
     330        ) 
    299331        if cookie_value: 
    300332            if self.include_ip: 
     
    318350                ) 
    319351                if not msg: 
    320                     msg = 'Bad cookie, you have been signed out. \n' 
    321                     msg += 'If this problem persists please clear your browser\'s cookies.' 
     352                    msg = 'Bad cookie, you have been signed out.\n If this' 
     353                    msg += 'problem persists please clear your browser\'s ' 
     354                    msg += 'cookies.' 
    322355                return [msg] 
    323356            try: 
    324                 log.debug("Parsing ticket secret %r, cookie value %r, remote address %s", self.secret, cookie_value, remote_addr) 
     357                log.debug( 
     358                    "Parsing ticket secret %r, cookie value %r, " 
     359                    "remote address %s",  
     360                    self.secret,  
     361                    cookie_value,  
     362                    remote_addr, 
     363                ) 
    325364                timestamp, userid, tokens, user_data = parse_ticket( 
    326                     self.secret, cookie_value, remote_addr) 
     365                    self.secret,  
     366                    cookie_value,  
     367                    remote_addr 
     368                ) 
    327369            except BadTicket, e: 
    328370                if e.expected: 
    329                     log.error("BadTicket: %s Expected: %s"%(e, e.expected)
     371                    log.error("BadTicket: %s Expected: %s", e, e.expected
    330372                else: 
    331                     log.error("BadTicket: %s"%e) 
    332  
     373                    log.error("BadTicket: %s", e) 
    333374                return bad_ticket_app(environ, start_response) 
    334375            else: 
    335376                now = time.time() 
    336                 log.debug("Cookie enforce: %s"%self.cookie_enforce) 
    337                 log.debug("Time difference: %s"% str(now-timestamp)) 
    338                 log.debug("Cookie params expire: %s"%self.cookie_params.get('expires')) 
    339                 if self.cookie_enforce and now - timestamp > float(self.cookie_params['expires']) + 1: 
    340                     return bad_ticket_app(environ, start_response, msg="Cookie expired.") 
     377                log.debug("Cookie enforce: %s", self.cookie_enforce) 
     378                log.debug("Time difference: %s", str(now-timestamp)) 
     379                log.debug( 
     380                    "Cookie params expire: %s",  
     381                    self.cookie_params.get('expires') 
     382                ) 
     383                if self.cookie_enforce and now - timestamp > \ 
     384                   float(self.cookie_params['expires']) + 1: 
     385                    return bad_ticket_app( 
     386                        environ,  
     387                        start_response,  
     388                        msg="Cookie expired." 
     389                    ) 
    341390                else: 
    342391                    environ['paste.auth_tkt.timestamp'] = timestamp 
     
    426475        return cookies 
    427476 
    428  
    429  
    430  
    431477def make_cookie_handler( 
    432478    app,  
     
    442488            cookie_args[k] = v 
    443489    if not cookie_args.has_key('secret'): 
    444         raise AuthKitConfigError('No cookie secret specified under %r'%(prefix+'secret')) 
    445  
     490        raise AuthKitConfigError( 
     491            'No cookie secret specified under %r'%(prefix+'secret') 
     492        ) 
    446493    app = AuthKitCookieMiddleware( 
    447494        app, 
     
    452499    return app 
    453500 
    454  
    455  
  • AuthKit/branches/0.4/authkit/authenticate/digest.py

    r67 r68  
    4444from paste.httpheaders import * 
    4545import md5, time, random, urllib2 
     46from authkit.authenticate.multi import MultiHandler, status_checker 
     47from authkit.authenticate import AuthKitConfigError, get_template, \ 
     48   valid_password, get_authenticate_function, strip_base, RequireEnvironKey 
    4649 
    4750def digest_password(realm, username, password): 
     
    4952    return md5.md5("%s:%s:%s" % (username,realm,password)).hexdigest() 
    5053 
    51 class AuthDigestAuthenticator
     54class AuthDigestAuthenticator(object)
    5255    """ implementation of RFC 2617 - HTTP Digest Authentication """ 
    5356    def __init__(self, realm, authfunc): 
     
    6972        return HTTPUnauthorized(headers=head) 
    7073 
    71     def compute(self, ha1, username, response, method, 
    72                       path, nonce, nc, cnonce, qop): 
    73         """ computes the authentication, raises error if unsuccessful """ 
     74    def compute( 
     75        self,  
     76        ha1,  
     77        username,  
     78        response,  
     79        method, 
     80        path,  
     81        nonce,  
     82        nc, 
     83        cnonce, 
     84        qop 
     85    ): 
     86        """Computes the authentication, raises error if unsuccessful """ 
    7487        if not ha1: 
    7588            return self.build_authentication() 
     
    128141    __call__ = authenticate 
    129142 
    130 class AuthDigestHandler
     143class AuthDigestHandler(object)
    131144    """ 
    132145    middleware for HTTP Digest authentication (RFC 2617) 
     
    182195    def __call__(self, environ, start_response): 
    183196        if environ.has_key('authkit.multi'): 
    184             # Shouldn't ever allow a response if this is called via the multi handler 
     197            # Shouldn't ever allow a response if this is called via the 
     198            # multi handler 
    185199            authenitcation = self.authenticate.build_authentication() 
    186200            return authenitcation.wsgi_application(environ, start_response) 
     
    192206            return result.wsgi_application(environ, start_response) 
    193207         
    194 class TryToAddUsername
     208class TryToAddUsername(object)
    195209    def __init__(self, application, realm, authfunc, users): 
    196210        self.application = application 
     
    207221            AUTH_TYPE.update(environ,'digest') 
    208222            REMOTE_USER.update(environ, result) 
    209  
    210223        return self.application(environ, start_response) 
    211224 
    212225middleware = AuthDigestHandler 
    213  
    214 from authkit.authenticate.multi import MultiHandler, status_checker 
    215 from authkit.authenticate import AuthKitConfigError, get_template, valid_password, get_authenticate_function, strip_base, RequireEnvironKey 
    216226 
    217227def make_digest_handler( 
  • AuthKit/branches/0.4/authkit/authenticate/form.py

    r67 r68  
    88from paste.auth.form import AuthFormHandler 
    99from paste.request import construct_url, parse_formvars 
    10 from authkit.authenticate import get_template, valid_password, get_authenticate_function, strip_base, RequireEnvironKey 
     10from authkit.authenticate import get_template, valid_password, \ 
     11   get_authenticate_function, strip_base, RequireEnvironKey 
    1112from authkit.authenticate.multi import MultiHandler, status_checker 
    12  
    1313 
    1414template = """\ 
     
    4343         
    4444    def __call__(self, environ, start_response): 
    45         # Shouldn't ever allow a response if this is called via the multi handler 
     45        # Shouldn't ever allow a response if this is called via the  
     46        # multi handler 
    4647        username = environ.get('REMOTE_USER','') 
    4748        if 'POST' == environ['REQUEST_METHOD']: 
     
    7475        app, 
    7576        'paste.auth_tkt.set_user', 
    76         missing_error='Missing the key %(key)s from the environ. Have you added the cookie method after the form method?' 
     77        missing_error=( 
     78            'Missing the key %(key)s from the environ. ' 
     79            'Have you added the cookie method after the form method?' 
     80        ) 
    7781    ) 
    78  
    7982    template_conf = strip_base(auth_conf, 'template.') 
    8083    if template_conf: 
  • AuthKit/branches/0.4/authkit/authenticate/forward.py

    r59 r68  
    55""" 
    66 
    7 from paste.recursive import RecursiveMiddleware, ForwardRequestException, CheckForRecursionMiddleware 
     7from paste.recursive import RecursiveMiddleware, ForwardRequestException, \ 
     8   CheckForRecursionMiddleware 
    89from authkit.authenticate.multi import MultiHandler, status_checker 
    910from authkit.authenticate import AuthKitConfigError 
    1011 
    11 class Redirect
     12class Redirect(object)
    1213    def __init__(self, app, forward_signin): 
    1314        self.app = app 
     
    1718        raise ForwardRequestException(self.signin_path) 
    1819 
    19 class MyRecursive
     20class MyRecursive(object)
    2021    def __init__(self, app): 
    2122        self.application = app 
     
    4748    app.add_checker('forward', status_checker) 
    4849    app = MyRecursive(RecursiveMiddleware(app)) 
    49     #app = load_cookie_middleware(app, final, prefix) 
    5050    return app 
    51 # 
    52 # 
    53 #    authenticate_conf = strip_base(auth_conf, 'authenticate.') 
    54 #    app, authfunc = get_authenticate_function( 
    55 #        app,  
    56 #        authenticate_conf,  
    57 #        prefix=prefix+'authenticate.',  
    58 #        format='digest' 
    59 #    ) 
    60 #    if not auth_conf.has_key('realm'): 
    61 #        raise AuthKitConfigError('No %s specified'%(prefix+'realm')) 
    62 #    app = MultiHandler(app) 
    63 #    app.add_method('digest', middleware, auth_conf['realm'], authfunc) 
    64 #    app.add_checker('digest', status_checker) 
    65 #    app = TryToAddUsername(app, auth_conf['realm'], authfunc) 
    66 #    return app 
    67 # 
    6851 
  • AuthKit/branches/0.4/authkit/authenticate/multi.py

    r67 r68  
    4444            for (checker,binding) in self.predicate: 
    4545                if checker(environ): 
    46                     log.debug("MultMiddleware self.predicate check() returning %r", binding) 
     46                    log.debug( 
     47                        "MultMiddleware self.predicate check() returning %r",  
     48                        binding 
     49                    ) 
    4750                    environ['authkit.multi'] = True 
    4851                    return binding(environ, logging_start_response) 
    4952            for (checker,binding) in self.checker: 
    5053                if not len(status_): 
    51                     raise Exception('No status was returned by the applicaiton') 
     54                    raise Exception( 
     55                        'No status was returned by the applicaiton' 
     56                    ) 
    5257                if not len(headers_): 
    53                     raise Exception('No headers were returned by the application') 
     58                    raise Exception( 
     59                        'No headers were returned by the application' 
     60                    ) 
    5461                if checker(environ, status_[0], headers_ and headers_[0] or []): 
    55                     log.debug("MultMiddleware self.checker check() returning %r", binding) 
     62                    log.debug( 
     63                        "MultMiddleware self.checker check() returning %r",  
     64                        binding 
     65                    ) 
    5666                    environ['authkit.multi'] = True 
    5767                    return binding(environ, logging_start_response) 
     
    6373        for data in app_iter: 
    6474            if not called: 
    65                 raise Exception('WSGI start_response was not called before a result was returned') 
     75                raise Exception( 
     76                    'WSGI start_response was not called before a result was ' 
     77                    'returned' 
     78                ) 
    6679            else: 
    6780                if not checked: 
     
    7083                        result = check() 
    7184                    except NoBindingFoundError, e: 
    72                         log.debug("MutliMiddleware: No binding was found for the check") 
    73                         start_response(status_[0], headers_ and headers_[0] or [], exc_info_[0]) 
     85                        log.debug( 
     86                            "Multi: No binding was found for the check" 
     87                        ) 
     88                        start_response( 
     89                            status_[0],  
     90                            headers_ and headers_[0] or [], 
     91                            exc_info_[0] 
     92                        ) 
    7493                    else: 
    75                         # Commented out because it could create huge logs very quickly! 
    76                         log.debug("Binding matched, returning result %r", result) 
     94                        # Commented out because it could create huge logs! 
     95                        # log.debug( 
     96                        #     "Binding matched, returning result %r", 
     97                        #     result 
     98                        # ) 
    7799                        return result 
    78100                f.append(data) 
     
    82104 
    83105def status_checker(environ, status, headers): 
    84     log.debug("Status checker recieved status %r, headers %r, intecept %r", status, headers, environ['authkit.intercept']) 
     106    """ 
     107    Used by AuthKit to intercept statuses specified in the config file  
     108    option ``authkit.intercept``. 
     109    """ 
     110    log.debug( 
     111        "Status checker recieved status %r, headers %r, intecept %r",  
     112        status,  
     113        headers,  
     114        environ['authkit.intercept'] 
     115    ) 
    85116    if str(status[:3]) in environ['authkit.intercept']: 
    86117        log.debug("Status checker returns True") 
     
    88119    log.debug("Status checker returns False") 
    89120    return False 
     121 
  • AuthKit/branches/0.4/authkit/authenticate/open_id.py

    r67 r68  
    22 
    33.. Note:: 
    4      
    5     "Passurl" is a trademark of James Gardner 2005. 
    64 
    75    If you want to test this module feel free to setup an account at 
     
    119Full documentation on the use of this OpenID module is in the AuthKit manual. 
    1210""" 
    13  
    14 # TODO: Package up the OpenID Libraries into an egg so they don't need 
    15 # installing manually 
    16  
    1711 
    1812import cgi 
     
    2216from authkit.authenticate import AuthKitConfigError 
    2317from paste.request import construct_url 
    24  
    25 #try: 
    2618from openid.consumer import consumer 
    2719from openid.oidutil import appendArgs 
    2820from yadis.discover import DiscoveryFailure 
    2921from urljr.fetchers import HTTPFetchingError 
    30 #except ImportError: 
    31 #    raise Exception("Could not import all the requried OpenID libraries. Have you manually installed them?") 
     22from authkit.authenticate import get_template, valid_password, \ 
     23   get_authenticate_function, strip_base, RequireEnvironKey 
     24from authkit.authenticate.multi import MultiHandler, status_checker 
    3225 
    3326template = """\ 
     
    3932    <form action="$action" method="post"> 
    4033      <dl> 
    41         <dt>Passurl:</dt> 
    42         <dd><input type="text" name="passurl" value="$value"></dd> 
     34        <dt>OpenID Passurl:</dt> 
     35        <dd><input type="text" name="openid" value="$value"></dd> 
    4336      </dl> 
    4437      <input type="submit" name="authform" /> 
     
    6255        return template 
    6356 
    64 class PassURLSignIn
     57class PassURLSignIn(object)
    6558    """ 
    66     This middleware is triggered when the authenticate middleware catches a 401 response 
    67      
    68     The form is submitted to the verify URL which the other middleware handles 
     59    This middleware is triggered when the authenticate middleware catches  
     60    a 401 response. The form is submitted to the verify URL which the other 
     61    middleware handles 
    6962    """ 
    7063    def __init__(self, app, template, path_verify, baseurl=''): 
     
    7568 
    7669    def __call__(self, environ, start_response): 
    77         baseurl = self.baseurl or construct_url(environ, with_query_string=False, with_path_info=False) 
    78         # XXX For registration support this should render hidden fields with the sreg options 
     70        baseurl = self.baseurl or construct_url( 
     71            environ,  
     72            with_query_string=False,  
     73            with_path_info=False 
     74        ) 
     75        # XXX For registration support this should render hidden fields 
     76        # with the sreg options 
    7977        content = render( 
    8078            self.template, 
     
    124122class AuthOpenIDHandler: 
    125123    """ 
    126     The template should be setup from authkit.passurl.template.file or authkit.passurl.template.obj before we get here! 
     124    The template should be setup from authkit.open_id.template.file or  
     125    authkit.open_id.template.obj before we get here! 
    127126    """ 
    128127    def __init__( 
     
    135134        template=None, 
    136135        session_secret=None, 
    137         session_key='authkit_passurl', 
     136        session_key='authkit_openid', 
    138137        session_middleware='beaker.session', 
    139138        path_verify='/verify',  
     
    144143        self.baseurl = baseurl 
    145144        self.template = template 
    146         #self.path_signin = path_signin 
    147145        self.path_signedin = path_signedin 
    148146        self.path_verify = path_verify 
     
    176174    def verify(self, environ, start_response): 
    177175        # XXX This method should accept sreg options and continue with them 
    178         baseurl = self.baseurl or construct_url(environ, with_query_string=False, with_path_info=False) 
     176        baseurl = self.baseurl or construct_url( 
     177            environ,  
     178            with_query_string=False,  
     179            with_path_info=False 
     180        ) 
    179181        params = dict(paste.request.parse_formvars(environ)) 
    180         openid_url = params.get('passurl') 
     182        openid_url = params.get('openid') 
    181183        if not openid_url: 
    182184            response = render( 
     
    267269 
    268270    def process(self, environ, start_response): 
    269         baseurl = self.baseurl or construct_url(environ, with_query_string=False, with_path_info=False) 
     271        baseurl = self.baseurl or construct_url( 
     272            environ,  
     273            with_query_string=False,  
     274            with_path_info=False 
     275        ) 
    270276        value = '' 
    271277        css_class = 'error' 
     
    278284            fmt = "Verification of %s failed." 
    279285            message = fmt % (cgi.escape(info.identity_url),) 
    280             environ['wsgi.errors'].write("PassURL Message: %s %s"%(message,info.message)) 
     286            environ['wsgi.errors'].write( 
     287                "Passurl Message: %s %s"%(message,info.message) 
     288            ) 
    281289        elif info.status == consumer.SUCCESS: 
    282290            username = info.identity_url 
     
    308316            message = 'Verification cancelled' 
    309317        else: 
    310             environ['wsgi.errors'].write("PassURL Message: %s"%info.message) 
     318            environ['wsgi.errors'].write("Passurl Message: %s"%info.message) 
    311319            message = 'Verification failed.' 
    312320        value = self._quoteattr(info.identity_url) 
     
    341349        qs = cgi.escape(s, 1) 
    342350        return '"%s"' % (qs,) 
    343      
    344  
    345  
    346  
    347 from authkit.authenticate import get_template, valid_password, get_authenticate_function, strip_base, RequireEnvironKey 
    348 from authkit.authenticate.multi import MultiHandler, status_checker 
    349  
    350  
    351  
    352351 
    353352def make_passurl_handler( 
     
    356355    app_conf=None, 
    357356    global_conf=None, 
    358     prefix='authkit.passurl',  
     357    prefix='authkit.openid',  
    359358): 
    360359    global template 
     
    364363        template_ = get_template(template_conf, prefix=prefix+'template.') 
    365364 
    366      
    367365    # Note, the session middleware should already be setup by now 
    368366    # if we are not using beaker 
    369     from authkit.authenticate.passurl import PassURLSignIn, AuthOpenIDHandler, template 
    370367    app = MultiHandler(app) 
    371368    app.add_method( 
    372         'passurl',  
     369        'openid',  
    373370        PassURLSignIn, 
    374371        template_, 
     
    376373        baseurl=auth_conf.get('baseurl',''), 
    377374    ) 
    378     app.add_checker('passurl', status_checker) 
     375    app.add_checker('openid', status_checker) 
    379376    urltouser = auth_conf.get('urltouser', None) 
    380377    if isinstance(urltouser, str): 
    381378        urltouser = eval_import(urltouser) 
    382  
    383379    for option in ['store.type', 'store.config', 'path.signedin']: 
    384380        if not auth_conf.has_key(option): 
    385             raise AuthKitConfigError('Missing the config key %s%s'%(prefix, option)) 
    386  
     381            raise AuthKitConfigError( 
     382                'Missing the config key %s%s'%(prefix, option) 
     383            ) 
    387384    app = AuthOpenIDHandler( 
    388385        app, 
     
    395392        urltouser = urltouser 
    396393    ) 
    397  
    398394    session_middleware = 'beaker.session' 
    399395    session_secret = 'asdasd' 
    400     session_key = 'authkit_passurl
     396    session_key = 'authkit_openid
    401397    if session_middleware == 'beaker.session': 
    402398        if not session_secret: 
     
    404400        from beaker.session import SessionMiddleware 
    405401        app = SessionMiddleware(app, key=session_key, secret=session_secret) 
    406          
    407     #app = load_cookie_middleware(app, final, prefix) 
    408402    return app 
    409403 
  • AuthKit/branches/0.4/authkit/authenticate/redirect.py

    r61 r68  
     1"""\ 
     2Redirect middleware to redirect the browser to a different URL for sign in 
     3""" 
    14from authkit.authenticate import middleware 
    25from authkit.authenticate.multi import MultiHandler, status_checker 
    36 
    4 class HandleRedirect
     7class HandleRedirect(object)
    58    def __init__(self, app, redirect_to): 
    69        self.app = app 
  • AuthKit/branches/0.4/authkit/authorize.py

    r61 r68  
    7171    pass 
    7272 
    73 class _PermissionStartResponse
     73class _PermissionStartResponse(object)
    7474    def __init__(self, status, headers, exc_info=None): 
    7575        pass 
     
    8888# 
    8989 
    90 class _Authorize
     90class _Authorize(object)
    9191    def __init__(self, app, permission): 
    9292        self.app = app 
     
    106106                raise 
    107107 
    108 class _PermissionStartResponse
     108class _PermissionStartResponse(object)
    109109    def __init__(self, status, headers, exc_info=None): 
    110110        pass 
     
    166166        'Try using the authkit.authorize.middleware or the authorize decorator.' 
    167167    ) 
    168     #if permission.require_response: 
    169     #    raise error 
    170     #else: 
    171168    try: 
    172169        def dummy_app(environ, start_response): 
  • AuthKit/branches/0.4/authkit/permissions.py

    r67 r68  
    2121""" 
    2222 
    23 from authkit.authorize import PermissionError, NotAuthenticatedError, NotAuthorizedError, middleware 
     23from authkit.authorize import PermissionError, NotAuthenticatedError 
     24from authkit.authorize import NotAuthorizedError, middleware 
    2425from authkit.authenticate import no_authkit_users_in_environ  
    2526 
     
    3233 
    3334 
    34 class Permission
     35class Permission(object)
    3536    """ 
    3637    The base class for all permissions objects.  
     
    208209                        raise self.error 
    209210                    else: 
    210                         raise NotAuthorizedError("User doesn't have the role %s"%role.lower()) 
     211                        raise NotAuthorizedError( 
     212                            "User doesn't have the role %s"%role.lower() 
     213                        ) 
    211214            return app(environ, start_response) 
    212215        else: 
     
    217220                raise self.error 
    218221            else: 
    219                 raise NotAuthorizedError("User doesn't have any of the specified roles") 
     222                raise NotAuthorizedError( 
     223                    "User doesn't have any of the specified roles" 
     224                ) 
    220225     
    221226class HasAuthKitGroup(RequestPermission): 
     
    261266            raise self.error 
    262267        else: 
    263             raise NotAuthorizedError("User is not a member of the specified group(s) %r"%self.groups) 
     268            raise NotAuthorizedError( 
     269                "User is not a member of the specified group(s) %r"%self.groups 
     270            ) 
    264271 
    265272class ValidAuthKitUser(UserIn): 
     
    277284            raise NotAuthenticatedError('Not Authenticated') 
    278285        if not environ['authkit.users'].user_exists(environ['REMOTE_USER']): 
    279             raise NotAuthorizedError('You are not one of the users allowed to access this resource.') 
    280         return app(environ, start_response) 
     286            raise NotAuthorizedError( 
     287                'You are not one of the users allowed to access this resource.' 
     288            ) 
     289        return app(environ, start_response) 
     290 
  • AuthKit/branches/0.4/authkit/users/__init__.py

    r67 r68  
    7676    pass 
    7777     
    78 class Users
     78class Users(object)
    7979    """ 
    8080    Base class from which all other Users classes should be derived.