summaryrefslogtreecommitdiff
path: root/paste/auth
diff options
context:
space:
mode:
authorianb <devnull@localhost>2006-10-20 22:08:05 +0000
committerianb <devnull@localhost>2006-10-20 22:08:05 +0000
commit44fa5352360b78696c3d81cafa8e24eaa4f6c3ed (patch)
treeccde2c446f352cb5344f3c9a40090f12290bf9a7 /paste/auth
parent9eadab4b64440958f99a2fa1798227bb4a53193c (diff)
downloadpaste-44fa5352360b78696c3d81cafa8e24eaa4f6c3ed.tar.gz
A big commit, primarily aesthetic/whitespace in nature. This is the result of running pylint over the codebase. Some minor/hard-to-reach typos were also picked up.
Diffstat (limited to 'paste/auth')
-rw-r--r--paste/auth/basic.py4
-rw-r--r--paste/auth/cas.py2
-rw-r--r--paste/auth/cookie.py49
-rw-r--r--paste/auth/digest.py34
-rw-r--r--paste/auth/form.py6
-rw-r--r--paste/auth/multi.py4
-rw-r--r--paste/auth/open_id.py3
7 files changed, 53 insertions, 49 deletions
diff --git a/paste/auth/basic.py b/paste/auth/basic.py
index 1a91e04..c51dde5 100644
--- a/paste/auth/basic.py
+++ b/paste/auth/basic.py
@@ -41,11 +41,11 @@ class AuthBasicAuthenticator:
authorization = AUTHORIZATION(environ)
if not authorization:
return self.build_authentication()
- (authmeth, auth) = authorization.split(' ',1)
+ (authmeth, auth) = authorization.split(' ', 1)
if 'basic' != authmeth.lower():
return self.build_authentication()
auth = auth.strip().decode('base64')
- username, password = auth.split(':',1)
+ username, password = auth.split(':', 1)
if self.authfunc(environ, username, password):
return username
return self.build_authentication()
diff --git a/paste/auth/cas.py b/paste/auth/cas.py
index 6e501b5..c3521a0 100644
--- a/paste/auth/cas.py
+++ b/paste/auth/cas.py
@@ -66,7 +66,7 @@ def AuthCASHandler(application, authority):
qs = environ.get('QUERY_STRING','').split("&")
if qs and qs[-1].startswith("ticket="):
# assume a response from the authority
- ticket = qs.pop().split("=",1)[1]
+ ticket = qs.pop().split("=", 1)[1]
environ['QUERY_STRING'] = "&".join(qs)
service = construct_url(environ)
args = urllib.urlencode(
diff --git a/paste/auth/cookie.py b/paste/auth/cookie.py
index df63329..a650436 100644
--- a/paste/auth/cookie.py
+++ b/paste/auth/cookie.py
@@ -41,22 +41,23 @@ corresponding to a database session id) is stored in the cookie.
"""
-import sha, hmac, base64, random, time, string, warnings
+import sha, hmac, base64, random, time, warnings
from paste.request import get_cookies
def make_time(value):
- return time.strftime("%Y%m%d%H%M",time.gmtime(value))
-_signature_size = len(hmac.new('x','x',sha).digest())
+ return time.strftime("%Y%m%d%H%M", time.gmtime(value))
+_signature_size = len(hmac.new('x', 'x', sha).digest())
_header_size = _signature_size + len(make_time(time.time()))
# @@: Should this be using urllib.quote?
# build encode/decode functions to safely pack away values
-_encode = [('\\','\\x5c'),('"','\\x22'),('=','\\x3d'),(';','\\x3b')]
-_decode = [(v,k) for (k,v) in _encode]
+_encode = [('\\', '\\x5c'), ('"', '\\x22'),
+ ('=', '\\x3d'), (';', '\\x3b')]
+_decode = [(v, k) for (k, v) in _encode]
_decode.reverse()
def encode(s, sublist = _encode):
- return reduce((lambda a,(b,c): string.replace(a,b,c)), sublist, str(s))
-decode = lambda s: encode(s,_decode)
+ return reduce((lambda a, (b, c): a.replace(b, c)), sublist, str(s))
+decode = lambda s: encode(s, _decode)
class CookieTooLarge(RuntimeError):
def __init__(self, content, cookie):
@@ -64,10 +65,10 @@ class CookieTooLarge(RuntimeError):
self.content = content
self.cookie = cookie
-_all_chars = ''.join([chr(x) for x in range(0,255)])
+_all_chars = ''.join([chr(x) for x in range(0, 255)])
def new_secret():
""" returns a 64 byte secret """
- return ''.join(random.sample(_all_chars,64))
+ return ''.join(random.sample(_all_chars, 64))
class AuthCookieSigner:
"""
@@ -131,24 +132,24 @@ class AuthCookieSigner:
cookie is handled server-side in the auth() function.
"""
cookie = base64.b64encode(
- hmac.new(self.secret,content,sha).digest() +
- make_time(time.time()+60*self.timeout) +
- content).replace("/","_").replace("=","~")
+ hmac.new(self.secret, content, sha).digest() +
+ make_time(time.time() + 60*self.timeout) +
+ content).replace("/", "_").replace("=", "~")
if len(cookie) > self.maxlen:
- raise CookieTooLarge(content,cookie)
+ raise CookieTooLarge(content, cookie)
return cookie
- def auth(self,cookie):
+ def auth(self, cookie):
"""
Authenticate the cooke using the signature, verify that it
has not expired; and return the cookie's content
"""
decode = base64.b64decode(
- cookie.replace("_","/").replace("~","="))
+ cookie.replace("_", "/").replace("~", "="))
signature = decode[:_signature_size]
expires = decode[_signature_size:_header_size]
content = decode[_header_size:]
- if signature == hmac.new(self.secret,content,sha).digest():
+ if signature == hmac.new(self.secret, content, sha).digest():
if int(expires) > int(make_time(time.time())):
return content
else:
@@ -177,7 +178,7 @@ class AuthCookieEnviron(list):
def append(self, value):
if value in self:
return
- list.append(self,str(value))
+ list.append(self, str(value))
class AuthCookieHandler:
"""
@@ -238,7 +239,7 @@ class AuthCookieHandler:
def __init__(self, application, cookie_name=None, scanlist=None,
signer=None, secret=None, timeout=None, maxlen=None):
if not signer:
- signer = self.signer_class(secret,timeout,maxlen)
+ signer = self.signer_class(secret, timeout, maxlen)
self.signer = signer
self.scanlist = scanlist or ('REMOTE_USER','REMOTE_SESSION')
self.application = application
@@ -247,13 +248,13 @@ class AuthCookieHandler:
def __call__(self, environ, start_response):
if self.environ_name in environ:
raise AssertionError("AuthCookie already installed!")
- scanlist = self.environ_class(self,self.scanlist)
+ scanlist = self.environ_class(self, self.scanlist)
jar = get_cookies(environ)
if jar.has_key(self.cookie_name):
content = self.signer.auth(jar[self.cookie_name].value)
if content:
for pair in content.split(";"):
- (k,v) = pair.split("=")
+ (k, v) = pair.split("=")
k = decode(k)
if k not in scanlist:
scanlist.append(k)
@@ -275,24 +276,24 @@ class AuthCookieHandler:
pack up their values, signs the content and issues a cookie.
"""
scanlist = environ.get(self.environ_name)
- assert scanlist and isinstance(scanlist,self.environ_class)
+ assert scanlist and isinstance(scanlist, self.environ_class)
content = []
for k in scanlist:
- v = environ.get(k,None)
+ v = environ.get(k)
if v is not None:
if type(v) is not str:
raise ValueError(
"The value of the environmental variable %r "
"is not a str (only str is allowed; got %r)"
% (k, v))
- content.append("%s=%s" % (encode(k),encode(v)))
+ content.append("%s=%s" % (encode(k), encode(v)))
if content:
content = ";".join(content)
content = self.signer.sign(content)
cookie = '%s=%s; Path=/;' % (self.cookie_name, content)
if 'https' == environ['wsgi.url_scheme']:
cookie += ' secure;'
- response_headers.append(('Set-Cookie',cookie))
+ response_headers.append(('Set-Cookie', cookie))
return start_response(status, response_headers, exc_info)
return self.application(environ, response_hook)
diff --git a/paste/auth/digest.py b/paste/auth/digest.py
index 0fe380b..ad5e4a3 100644
--- a/paste/auth/digest.py
+++ b/paste/auth/digest.py
@@ -35,7 +35,7 @@ import md5, time, random
def digest_password(realm, username, password):
""" construct the appropriate hashcode needed for HTTP digest """
- return md5.md5("%s:%s:%s" % (username,realm,password)).hexdigest()
+ return md5.md5("%s:%s:%s" % (username, realm, password)).hexdigest()
class AuthDigestAuthenticator:
""" implementation of RFC 2617 - HTTP Digest Authentication """
@@ -46,14 +46,16 @@ class AuthDigestAuthenticator:
def build_authentication(self, stale = ''):
""" builds the authentication error """
- nonce = md5.md5("%s:%s" % (time.time(),random.random())).hexdigest()
- opaque = md5.md5("%s:%s" % (time.time(),random.random())).hexdigest()
+ nonce = md5.md5(
+ "%s:%s" % (time.time(), random.random())).hexdigest()
+ opaque = md5.md5(
+ "%s:%s" % (time.time(), random.random())).hexdigest()
self.nonce[nonce] = None
- parts = { 'realm': self.realm, 'qop': 'auth',
- 'nonce': nonce, 'opaque': opaque }
+ parts = {'realm': self.realm, 'qop': 'auth',
+ 'nonce': nonce, 'opaque': opaque }
if stale:
parts['stale'] = 'true'
- head = ", ".join(['%s="%s"' % (k,v) for (k,v) in parts.items()])
+ head = ", ".join(['%s="%s"' % (k, v) for (k, v) in parts.items()])
head = [("WWW-Authenticate", 'Digest %s' % head)]
return HTTPUnauthorized(headers=head)
@@ -62,11 +64,11 @@ class AuthDigestAuthenticator:
""" computes the authentication, raises error if unsuccessful """
if not ha1:
return self.build_authentication()
- ha2 = md5.md5('%s:%s' % (method,path)).hexdigest()
+ ha2 = md5.md5('%s:%s' % (method, path)).hexdigest()
if qop:
- chk = "%s:%s:%s:%s:%s:%s" % (ha1,nonce,nc,cnonce,qop,ha2)
+ chk = "%s:%s:%s:%s:%s:%s" % (ha1, nonce, nc, cnonce, qop, ha2)
else:
- chk = "%s:%s:%s" % (ha1,nonce,ha2)
+ chk = "%s:%s:%s" % (ha1, nonce, ha2)
if response != md5.md5(chk).hexdigest():
if nonce in self.nonce:
del self.nonce[nonce]
@@ -88,24 +90,24 @@ class AuthDigestAuthenticator:
authorization = AUTHORIZATION(environ)
if not authorization:
return self.build_authentication()
- (authmeth, auth) = authorization.split(" ",1)
+ (authmeth, auth) = authorization.split(" ", 1)
if 'digest' != authmeth.lower():
return self.build_authentication()
amap = {}
for itm in auth.split(", "):
- (k,v) = [s.strip() for s in itm.split("=",1)]
- amap[k] = v.replace('"','')
+ (k,v) = [s.strip() for s in itm.split("=", 1)]
+ amap[k] = v.replace('"', '')
try:
username = amap['username']
authpath = amap['uri']
nonce = amap['nonce']
realm = amap['realm']
response = amap['response']
- assert authpath.split("?",1)[0] in fullpath
+ assert authpath.split("?", 1)[0] in fullpath
assert realm == self.realm
- qop = amap.get('qop','')
- cnonce = amap.get('cnonce','')
- nc = amap.get('nc','00000000')
+ qop = amap.get('qop', '')
+ cnonce = amap.get('cnonce', '')
+ nc = amap.get('nc', '00000000')
if qop:
assert 'auth' == qop
assert nonce and nc
diff --git a/paste/auth/form.py b/paste/auth/form.py
index f13abf8..dd4a06e 100644
--- a/paste/auth/form.py
+++ b/paste/auth/form.py
@@ -25,7 +25,7 @@ serving on...
"""
from paste.request import construct_url, parse_formvars
-TEMPLATE ="""\
+TEMPLATE = """\
<html>
<head><title>Please Login!</title></head>
<body>
@@ -113,8 +113,8 @@ class AuthFormHandler:
return self.application(environ, start_response)
content = self.template % construct_url(environ)
- start_response("200 OK",(('Content-Type', 'text/html'),
- ('Content-Length', len(content))))
+ start_response("200 OK", (('Content-Type', 'text/html'),
+ ('Content-Length', len(content))))
return [content]
middleware = AuthFormHandler
diff --git a/paste/auth/multi.py b/paste/auth/multi.py
index 12c9f26..e3516c2 100644
--- a/paste/auth/multi.py
+++ b/paste/auth/multi.py
@@ -54,7 +54,7 @@ class MultiHandler:
def add_method(self, name, factory, *args, **kwargs):
self.binding[name] = factory(self.application, *args, **kwargs)
def add_predicate(self, name, checker):
- self.predicate.append((checker,self.binding[name]))
+ self.predicate.append((checker, self.binding[name]))
def set_default(self, name):
""" set default authentication method """
self.default = self.binding[name]
@@ -64,7 +64,7 @@ class MultiHandler:
self.add_predicate(name,
lambda environ: lookfor in environ.get('QUERY_STRING',''))
def __call__(self, environ, start_response):
- for (checker,binding) in self.predicate:
+ for (checker, binding) in self.predicate:
if checker(environ):
return binding(environ, start_response)
return self.default(environ, start_response)
diff --git a/paste/auth/open_id.py b/paste/auth/open_id.py
index eb01150..077f049 100644
--- a/paste/auth/open_id.py
+++ b/paste/auth/open_id.py
@@ -153,7 +153,8 @@ class AuthOpenIDHandler(object):
# @@: Do I need to append something to go back to where we
# came from?
was_401.append(1)
- def dummy_writer(v): pass
+ def dummy_writer(v):
+ pass
return dummy_writer
else:
return start_response(status, headers, exc_info)