Skip to content
Myr

hooks and things

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Kenneth Reitz · committed by Kenneth Reitz · parent 2c5b020 · Browse files · 3 files+57 added−140 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+57 added−140 removed

  • other:+57 added−140 removed

3 files+57 added−140 removed

modified:requests/auth.py+2 added-125 removed
95 unmodified lines
96 r.url, r.headers, _ = self.client.sign(unicode(r.full_url),97 unicode(r.method),98 None,99 r.headers)100 elif (decoded_body is not None and 100 elif (decoded_body is not None and101 contenttype == CONTENT_TYPE_FORM_URLENCODED):102 # If the Content-Type header is urlencoded and there are no103 # illegal characters in the body, assume that the content actually104 # is urlencoded, and so should be part of the signature.
163 unmodified lines
268 # If we have a saved nonce, skip the 401269 if self.last_nonce:270 r.headers['Authorization'] = self.build_digest_header(r.method, r.url)271 r.register_hook('response', self.handle_401)272 return r273274275def _negotiate_value(r):276 """Extracts the gssapi authentication token from the appropriate header"""277278 authreq = r.headers.get('www-authenticate', None)279280 if authreq:281 rx = re.compile('(?:.*,)*\s*Negotiate\s*([^,]*),?', re.I)282 mo = rx.search(authreq)283 if mo:284 return mo.group(1)285286 return None287288289class HTTPKerberosAuth(AuthBase):290 """Attaches HTTP GSSAPI/Kerberos Authentication to the given Request object."""291 def __init__(self, require_mutual_auth=True):292 if k is None:293 raise Exception("Kerberos libraries unavailable")294 self.context = None295 self.require_mutual_auth = require_mutual_auth296297 def generate_request_header(self, r):298 """Generates the gssapi authentication token with kerberos"""299300 host = urlparse(r.url).netloc301 tail, _, head = host.rpartition(':')302 domain = tail if tail else head303304 result, self.context = k.authGSSClientInit("HTTP@%s" % domain)305306 if result < 1:307 raise Exception("authGSSClientInit failed")308309 result = k.authGSSClientStep(self.context, _negotiate_value(r))310311 if result < 0:312 raise Exception("authGSSClientStep failed")313314 response = k.authGSSClientResponse(self.context)315316 return "Negotiate %s" % response317318 def authenticate_user(self, r):319 """Handles user authentication with gssapi/kerberos"""320321 auth_header = self.generate_request_header(r)322 log.debug("authenticate_user(): Authorization header: %s" % auth_header)323 r.request.headers['Authorization'] = auth_header324 r.request.send(anyway=True)325 _r = r.request.response326 _r.history.append(r)327 log.debug("authenticate_user(): returning %s" % _r)328 return _r329330 def handle_401(self, r):331 """Handles 401's, attempts to use gssapi/kerberos authentication"""332333 log.debug("handle_401(): Handling: 401")334 if _negotiate_value(r) is not None:335 _r = self.authenticate_user(r)336 log.debug("handle_401(): returning %s" % _r)337 return _r338 else:339 log.debug("handle_401(): Kerberos is not supported")340 log.debug("handle_401(): returning %s" % r)341 return r342343 def handle_other(self, r):344 """Handles all responses with the exception of 401s.345346 This is necessary so that we can authenticate responses if requested"""347348 log.debug("handle_other(): Handling: %d" % r.status_code)349 self.deregister(r)350 if self.require_mutual_auth:351 if _negotiate_value(r) is not None:352 log.debug("handle_other(): Authenticating the server")353 _r = self.authenticate_server(r)354 log.debug("handle_other(): returning %s" % _r)355 return _r356 else:357 log.error("handle_other(): Mutual authentication failed")358 raise Exception("Mutual authentication failed")359 else:360 log.debug("handle_other(): returning %s" % r)361 return r362363 def authenticate_server(self, r):364 """Uses GSSAPI to authenticate the server"""365366 log.debug("authenticate_server(): Authenticate header: %s" % _negotiate_value(r))367 result = k.authGSSClientStep(self.context, _negotiate_value(r))368 if result < 1:369 raise Exception("authGSSClientStep failed")370 _r = r.request.response371 log.debug("authenticate_server(): returning %s" % _r)372 return _r373374 def handle_response(self, r):375 """Takes the given response and tries kerberos-auth, as needed."""376377 if r.status_code == 401:378 _r = self.handle_401(r)379 log.debug("handle_response returning %s" % _r)380 return _r381 else:382 _r = self.handle_other(r)383 log.debug("handle_response returning %s" % _r)384 return _r385386 log.debug("handle_response returning %s" % r)387 return r388389 def deregister(self, r):390 """Deregisters the response handler"""391 r.request.deregister_hook('response', self.handle_response)392393 def __call__(self, r):394 r.register_hook('response', self.handle_response)395 return r272 return r
modified:requests/hooks.py+8 added-1 removed
12 unmodified lines
1314"""151617HOOKS = ('response')17HOOKS = ['response']1819def default_hooks():20 hooks = {}21 for event in HOOKS:22 hooks[event] = []23 return hooks2425# TODO: response is the only one2627def dispatch_hook(key, hooks, hook_data):28 """Dispatches a hook dictionary on a given piece of data."""
15 unmodified lines
modified:requests/models.py+47 added-14 removed
7 unmodified lines
8"""910# import os11# import socket12# import collections12import collections13import logging1415# from datetime import datetime16from io import BytesIO1718from .hooks import dispatch_hook, HOOKS18from .hooks import dispatch_hook, default_hooks19from .structures import CaseInsensitiveDict20from .status_codes import codes2122from .auth import HTTPBasicAuth, HTTPProxyAuth
22 unmodified lines
4546log = logging.getLogger(__name__)474849class RequestMixin(object):49class RequestEncodingMixin(object):5051 @property52 def path_url(self):53 """Build the path URL to use."""
88 unmodified lines
142143 return body, content_type144145146class Request(object):146class RequestHooksMixin(object):147 def register_hook(self, event, hook):148 """Properly register a hook."""149 print self150 print event151 print hook152 if isinstance(hook, collections.Callable):153 self.hooks[event].append(hook)154 elif hasattr(hook, '__iter__'):155 self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable))156157 def deregister_hook(self, event, hook):158 """Deregister a previously registered hook.159 Returns True if the hook existed, False if not.160 """161162 try:163 self.hooks[event].remove(hook)164 return True165 except ValueError:166 return False167168169class Request(RequestHooksMixin):170 """A user-created :class:`Request <Request>` object."""171 def __init__(self,172 method=None,173 url=None,
3 unmodified lines
177 params=dict(),178 auth=None,179 cookies=None,180 timeout=None,158 allow_redirects=False,159 proxies=None,160 hooks=None,181 hooks=None):161 prefetch=True,162 verify=None,163 cert=None):182183 # Default empty dicts for dict params.184 data = [] if data is None else data185 files = [] if files is None else files186 headers = {} if headers is None else headers187 params = {} if params is None else params188 hooks = {} if hooks is None else hooks189190 self.hooks = default_hooks()191 for (k, v) in list(hooks.items()):192 self.register_hook(event=k, hook=v)193194 self.method = method195 self.url = url196 self.headers = headers197 self.files = files198 self.data = data199 self.params = params200 self.auth = auth201 self.cookies = cookies173 self.allow_redirects = allow_redirects174 self.proxies = proxies202 # self.allow_redirects = allow_redirects203 # self.proxies = proxies204 self.hooks = hooks205206 def __repr__(self):207 return '<Request [%s]>' % (self.method)
11 unmodified lines
219220 return p221222194class PreparedRequest(RequestMixin):223class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):224 """The :class:`PreparedRequest <PreparedRequest>` object."""225226 def __init__(self):227 self.method = None
3 unmodified lines
231 self.params = None232 self.auth = None233 self.allow_redirects = None234 self.proxies = None206 self.hooks = None235 self.hooks = default_hooks()236237 def __repr__(self):238 return '<PreparedRequest [%s]>' % (self.method)239
101 unmodified lines
341342 def prepare_auth(self, auth):343 """Prepares the given HTTP auth data."""344 if auth:345 # print auth346 if isinstance(auth, tuple) and len(auth) == 2:347 # special-case basic HTTP auth348 auth = HTTPBasicAuth(*auth)349350 # Allow auth to make its changes.351 r = auth(self)352 # print r353 # print r.__dict__354 # print self.__dict__355356 # Update self to reflect the auth changes.357 self.__dict__.update(r.__dict__)358
249 unmodified lines