auth_basic.py (2024B)
1 #Embedded file name: C:\BuildAgent\work\20d73f1b24eed06e\eve\release\V24.01\carbon\common\lib\cherrypy\lib\auth_basic.py 2 """This module provides a CherryPy 3.x tool which implements 3 the server-side of HTTP Basic Access Authentication, as described in :rfc:`2617`. 4 5 Example usage, using the built-in checkpassword_dict function which uses a dict 6 as the credentials store:: 7 8 userpassdict = {'bird' : 'bebop', 'ornette' : 'wayout'} 9 checkpassword = cherrypy.lib.auth_basic.checkpassword_dict(userpassdict) 10 basic_auth = {'tools.auth_basic.on': True, 11 'tools.auth_basic.realm': 'earth', 12 'tools.auth_basic.checkpassword': checkpassword, 13 } 14 app_config = { '/' : basic_auth } 15 16 """ 17 __author__ = 'visteya' 18 __date__ = 'April 2009' 19 import binascii 20 from cherrypy._cpcompat import base64_decode 21 import cherrypy 22 23 def checkpassword_dict(user_password_dict): 24 25 def checkpassword(realm, user, password): 26 p = user_password_dict.get(user) 27 return p and p == password or False 28 29 return checkpassword 30 31 32 def basic_auth(realm, checkpassword, debug = False): 33 if '"' in realm: 34 raise ValueError('Realm cannot contain the " (quote) character.') 35 request = cherrypy.serving.request 36 auth_header = request.headers.get('authorization') 37 if auth_header is not None: 38 try: 39 scheme, params = auth_header.split(' ', 1) 40 if scheme.lower() == 'basic': 41 username, password = base64_decode(params).split(':', 1) 42 if checkpassword(realm, username, password): 43 if debug: 44 cherrypy.log('Auth succeeded', 'TOOLS.AUTH_BASIC') 45 request.login = username 46 return 47 except (ValueError, binascii.Error): 48 raise cherrypy.HTTPError(400, 'Bad Request') 49 50 cherrypy.serving.response.headers['www-authenticate'] = 'Basic realm="%s"' % realm 51 raise cherrypy.HTTPError(401, 'You are not authorized to access that resource')