test_auth_basic.py (2798B)
1 #Embedded file name: C:\BuildAgent\work\20d73f1b24eed06e\eve\release\V24.01\carbon\common\lib\cherrypy\test\test_auth_basic.py 2 import cherrypy 3 from cherrypy._cpcompat import md5, ntob 4 from cherrypy.lib import auth_basic 5 from cherrypy.test import helper 6 7 class BasicAuthTest(helper.CPWebCase): 8 9 def setup_server(): 10 11 class Root: 12 13 def index(self): 14 return 'This is public.' 15 16 index.exposed = True 17 18 class BasicProtected: 19 20 def index(self): 21 return "Hello %s, you've been authorized." % cherrypy.request.login 22 23 index.exposed = True 24 25 class BasicProtected2: 26 27 def index(self): 28 return "Hello %s, you've been authorized." % cherrypy.request.login 29 30 index.exposed = True 31 32 userpassdict = {'xuser': 'xpassword'} 33 userhashdict = {'xuser': md5(ntob('xpassword')).hexdigest()} 34 35 def checkpasshash(realm, user, password): 36 p = userhashdict.get(user) 37 return p and p == md5(ntob(password)).hexdigest() or False 38 39 conf = {'/basic': {'tools.auth_basic.on': True, 40 'tools.auth_basic.realm': 'wonderland', 41 'tools.auth_basic.checkpassword': auth_basic.checkpassword_dict(userpassdict)}, 42 '/basic2': {'tools.auth_basic.on': True, 43 'tools.auth_basic.realm': 'wonderland', 44 'tools.auth_basic.checkpassword': checkpasshash}} 45 root = Root() 46 root.basic = BasicProtected() 47 root.basic2 = BasicProtected2() 48 cherrypy.tree.mount(root, config=conf) 49 50 setup_server = staticmethod(setup_server) 51 52 def testPublic(self): 53 self.getPage('/') 54 self.assertStatus('200 OK') 55 self.assertHeader('Content-Type', 'text/html;charset=utf-8') 56 self.assertBody('This is public.') 57 58 def testBasic(self): 59 self.getPage('/basic/') 60 self.assertStatus(401) 61 self.assertHeader('WWW-Authenticate', 'Basic realm="wonderland"') 62 self.getPage('/basic/', [('Authorization', 'Basic eHVzZXI6eHBhc3N3b3JX')]) 63 self.assertStatus(401) 64 self.getPage('/basic/', [('Authorization', 'Basic eHVzZXI6eHBhc3N3b3Jk')]) 65 self.assertStatus('200 OK') 66 self.assertBody("Hello xuser, you've been authorized.") 67 68 def testBasic2(self): 69 self.getPage('/basic2/') 70 self.assertStatus(401) 71 self.assertHeader('WWW-Authenticate', 'Basic realm="wonderland"') 72 self.getPage('/basic2/', [('Authorization', 'Basic eHVzZXI6eHBhc3N3b3JX')]) 73 self.assertStatus(401) 74 self.getPage('/basic2/', [('Authorization', 'Basic eHVzZXI6eHBhc3N3b3Jk')]) 75 self.assertStatus('200 OK') 76 self.assertBody("Hello xuser, you've been authorized.")