1
# This file is part of CherryPy <http://www.cherrypy.org/>
2
# -*- coding: utf-8 -*-
3
# vim:ts=4:sw=4:expandtab:fileencoding=utf-8
5
from cherrypy.test import test
6
test.prefer_parent_path()
9
from hashlib import md5
11
# Python 2.4 and earlier
12
from md5 import new as md5
15
from cherrypy.lib import auth_basic
20
return "This is public."
25
return "Hello %s, you've been authorized." % cherrypy.request.login
28
class BasicProtected2:
30
return "Hello %s, you've been authorized." % cherrypy.request.login
33
userpassdict = {'xuser' : 'xpassword'}
34
userhashdict = {'xuser' : md5('xpassword').hexdigest()}
36
def checkpasshash(realm, user, password):
37
p = userhashdict.get(user)
38
return p and p == md5(password).hexdigest() or False
40
conf = {'/basic': {'tools.auth_basic.on': True,
41
'tools.auth_basic.realm': 'wonderland',
42
'tools.auth_basic.checkpassword': auth_basic.checkpassword_dict(userpassdict)},
43
'/basic2': {'tools.auth_basic.on': True,
44
'tools.auth_basic.realm': 'wonderland',
45
'tools.auth_basic.checkpassword': checkpasshash},
49
root.basic = BasicProtected()
50
root.basic2 = BasicProtected2()
51
cherrypy.tree.mount(root, config=conf)
53
from cherrypy.test import helper
55
class BasicAuthTest(helper.CPWebCase):
59
self.assertStatus('200 OK')
60
self.assertHeader('Content-Type', 'text/html;charset=utf-8')
61
self.assertBody('This is public.')
64
self.getPage("/basic/")
65
self.assertStatus(401)
66
self.assertHeader('WWW-Authenticate', 'Basic realm="wonderland"')
68
self.getPage('/basic/', [('Authorization', 'Basic eHVzZXI6eHBhc3N3b3JX')])
69
self.assertStatus(401)
71
self.getPage('/basic/', [('Authorization', 'Basic eHVzZXI6eHBhc3N3b3Jk')])
72
self.assertStatus('200 OK')
73
self.assertBody("Hello xuser, you've been authorized.")
76
self.getPage("/basic2/")
77
self.assertStatus(401)
78
self.assertHeader('WWW-Authenticate', 'Basic realm="wonderland"')
80
self.getPage('/basic2/', [('Authorization', 'Basic eHVzZXI6eHBhc3N3b3JX')])
81
self.assertStatus(401)
83
self.getPage('/basic2/', [('Authorization', 'Basic eHVzZXI6eHBhc3N3b3Jk')])
84
self.assertStatus('200 OK')
85
self.assertBody("Hello xuser, you've been authorized.")
88
if __name__ == "__main__":