1
2
3
4
5 import cherrypy
6 from cherrypy._cpcompat import md5, ntob
7 from cherrypy.lib import auth_basic
8 from cherrypy.test import helper
9
10
12
14 class Root:
15 def index(self):
16 return "This is public."
17 index.exposed = True
18
19 class BasicProtected:
20 def index(self):
21 return "Hello %s, you've been authorized." % cherrypy.request.login
22 index.exposed = True
23
24 class BasicProtected2:
25 def index(self):
26 return "Hello %s, you've been authorized." % cherrypy.request.login
27 index.exposed = True
28
29 userpassdict = {'xuser' : 'xpassword'}
30 userhashdict = {'xuser' : md5(ntob('xpassword')).hexdigest()}
31
32 def checkpasshash(realm, user, password):
33 p = userhashdict.get(user)
34 return p and p == md5(ntob(password)).hexdigest() or False
35
36 conf = {'/basic': {'tools.auth_basic.on': True,
37 'tools.auth_basic.realm': 'wonderland',
38 'tools.auth_basic.checkpassword': auth_basic.checkpassword_dict(userpassdict)},
39 '/basic2': {'tools.auth_basic.on': True,
40 'tools.auth_basic.realm': 'wonderland',
41 'tools.auth_basic.checkpassword': checkpasshash},
42 }
43
44 root = Root()
45 root.basic = BasicProtected()
46 root.basic2 = BasicProtected2()
47 cherrypy.tree.mount(root, config=conf)
48 setup_server = staticmethod(setup_server)
49
55
57 self.getPage("/basic/")
58 self.assertStatus(401)
59 self.assertHeader('WWW-Authenticate', 'Basic realm="wonderland"')
60
61 self.getPage('/basic/', [('Authorization', 'Basic eHVzZXI6eHBhc3N3b3JX')])
62 self.assertStatus(401)
63
64 self.getPage('/basic/', [('Authorization', 'Basic eHVzZXI6eHBhc3N3b3Jk')])
65 self.assertStatus('200 OK')
66 self.assertBody("Hello xuser, you've been authorized.")
67
69 self.getPage("/basic2/")
70 self.assertStatus(401)
71 self.assertHeader('WWW-Authenticate', 'Basic realm="wonderland"')
72
73 self.getPage('/basic2/', [('Authorization', 'Basic eHVzZXI6eHBhc3N3b3JX')])
74 self.assertStatus(401)
75
76 self.getPage('/basic2/', [('Authorization', 'Basic eHVzZXI6eHBhc3N3b3Jk')])
77 self.assertStatus('200 OK')
78 self.assertBody("Hello xuser, you've been authorized.")
79