importbinasciifrompaste.httpheadersimportAUTHORIZATIONfrompaste.httpheadersimportWWW_AUTHENTICATEfrompyramid.securityimportEveryonefrompyramid.securityimportAuthenticateddef_get_basicauth_credentials(request):authorization=AUTHORIZATION(request.environ)try:authmeth,auth=authorization.split(' ',1)exceptValueError:# not enough values to unpackreturnNoneifauthmeth.lower()=='basic':try:auth=auth.strip().decode('base64')exceptbinascii.Error:# can't decodereturnNonetry:login,password=auth.split(':',1)exceptValueError:# not enough values to unpackreturnNonereturn{'login':login,'password':password}returnNoneclassBasicAuthenticationPolicy(object):""" A :app:`Pyramid` :term:`authentication policy` which obtains data from basic authentication headers. Constructor Arguments ``check`` A callback passed the credentials and the request, expected to return None if the userid doesn't exist or a sequence of group identifiers (possibly empty) if the user does exist. Required. ``realm`` Default: ``Realm``. The Basic Auth realm string. """def__init__(self,check,realm='Realm'):self.check=checkself.realm=realmdefauthenticated_userid(self,request):credentials=_get_basicauth_credentials(request)ifcredentialsisNone:returnNoneuserid=credentials['login']ifself.check(credentials,request)isnotNone:# is not None!returnuseriddefeffective_principals(self,request):effective_principals=[Everyone]credentials=_get_basicauth_credentials(request)ifcredentialsisNone:returneffective_principalsuserid=credentials['login']groups=self.check(credentials,request)ifgroupsisNone:# is None!returneffective_principalseffective_principals.append(Authenticated)effective_principals.append(userid)effective_principals.extend(groups)returneffective_principalsdefunauthenticated_userid(self,request):creds=_get_basicauth_credentials(request)ifcredsisnotNone:returncreds['login']returnNonedefremember(self,request,principal,**kw):return[]defforget(self,request):head=WWW_AUTHENTICATE.tuples('Basic realm="%s"'%self.realm)returnhead