Attempt to fetch a crumb (needed if CSRF protection is enabled)

This commit is contained in:
Soren Hansen 2013-09-27 22:17:06 +02:00
parent 3291694068
commit 81ddbcf01e

View File

@ -58,6 +58,7 @@ LAUNCHER_COMMAND = 'hudson.slaves.CommandLauncher'
LAUNCHER_WINDOWS_SERVICE = 'hudson.os.windows.ManagedWindowsServiceLauncher'
INFO = 'api/json'
CRUMB_URL = 'crumbIssuer/api/json'
JOB_INFO = 'job/%(name)s/api/json?depth=0'
JOB_NAME = 'job/%(name)s/api/json?tree=name'
Q_INFO = 'queue/api/json?depth=0'
@ -154,6 +155,13 @@ class Jenkins(object):
else:
self.auth = None
def add_crumb(self, req):
response = self.jenkins_open(urllib2.Request(
self.server + CRUMB_URL), add_crumb=False)
if response:
data = json.loads(response)
req.add_header(data['crumbRequestField'], data['crumb'])
def get_job_info(self, name):
'''
Get job information dictionary.
@ -200,14 +208,17 @@ class Jenkins(object):
for k, v in self.get_job_info(job_name).iteritems():
print k, v
def jenkins_open(self, req):
def jenkins_open(self, req, add_crumb=True):
'''
Utility routine for opening an HTTP request to a Jenkins server. This
should only be used to extends the :class:`Jenkins` API.
'''
try:
if self.auth:
req.add_header('Authorization', self.auth)
if add_crumb:
self.add_crumb(req)
return urllib2.urlopen(req).read()
except urllib2.HTTPError, e:
# Jenkins's funky authentication means its nigh impossible to