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
16 def index(self):
17 return "This is public."
18 index.exposed = True
19
20 class BasicProtected:
21
22 def index(self):
23 return "Hello %s, you've been authorized." % (
24 cherrypy.request.login)
25 index.exposed = True
26
27 class BasicProtected2:
28
29 def index(self):
30 return "Hello %s, you've been authorized." % (
31 cherrypy.request.login)
32 index.exposed = True
33
34 userpassdict = {'xuser': 'xpassword'}
35 userhashdict = {'xuser': md5(ntob('xpassword')).hexdigest()}
36
37 def checkpasshash(realm, user, password):
38 p = userhashdict.get(user)
39 return p and p == md5(ntob(password)).hexdigest() or False
40
41 basic_checkpassword_dict = auth_basic.checkpassword_dict(userpassdict)
42 conf = {
43 '/basic': {
44 'tools.auth_basic.on': True,
45 'tools.auth_basic.realm': 'wonderland',
46 'tools.auth_basic.checkpassword': basic_checkpassword_dict
47 },
48 '/basic2': {
49 'tools.auth_basic.on': True,
50 'tools.auth_basic.realm': 'wonderland',
51 'tools.auth_basic.checkpassword': checkpasshash
52 },
53 }
54
55 root = Root()
56 root.basic = BasicProtected()
57 root.basic2 = BasicProtected2()
58 cherrypy.tree.mount(root, config=conf)
59 setup_server = staticmethod(setup_server)
60
66
68 self.getPage("/basic/")
69 self.assertStatus(401)
70 self.assertHeader('WWW-Authenticate', 'Basic realm="wonderland"')
71
72 self.getPage('/basic/',
73 [('Authorization', 'Basic eHVzZXI6eHBhc3N3b3JX')])
74 self.assertStatus(401)
75
76 self.getPage('/basic/',
77 [('Authorization', 'Basic eHVzZXI6eHBhc3N3b3Jk')])
78 self.assertStatus('200 OK')
79 self.assertBody("Hello xuser, you've been authorized.")
80
82 self.getPage("/basic2/")
83 self.assertStatus(401)
84 self.assertHeader('WWW-Authenticate', 'Basic realm="wonderland"')
85
86 self.getPage('/basic2/',
87 [('Authorization', 'Basic eHVzZXI6eHBhc3N3b3JX')])
88 self.assertStatus(401)
89
90 self.getPage('/basic2/',
91 [('Authorization', 'Basic eHVzZXI6eHBhc3N3b3Jk')])
92 self.assertStatus('200 OK')
93 self.assertBody("Hello xuser, you've been authorized.")
94