def test_get_cookie(self): with patch('pysflib.sfauth.requests.get') as g: methods = ['Password', 'GithubPersonalAccessToken'] header = {'Content-Type': 'application/json'} info = {'service': {'name': 'cauth', 'version': '0.4.1', 'auth_methods': methods}} g.return_value = FakeJSONResponse(info) with patch('pysflib.sfauth.requests.post') as p: p.return_value = Fake() self.assertEqual( '1234', sfauth.get_cookie('auth.tests.dom', 'user1', 'userpass')) auth_context = {'back': '/', 'method': 'Password', 'args': {'username': '******', 'password': '******'}} p.assert_called_with('http://auth.tests.dom/auth/login', json.dumps(auth_context), allow_redirects=False, headers=header) self.assertEqual( '1234', sfauth.get_cookie('auth.tests.dom', github_access_token='abcd')) auth_context = {'back': '/', 'method': 'GithubPersonalAccessToken', 'args': {'token': 'abcd'}} p.assert_called_with('http://auth.tests.dom/auth/login', json.dumps(auth_context), allow_redirects=False, headers=header)
def test_get_cookie_old_style(self): with patch('pysflib.sfauth.requests.get') as g: g.return_value = FakeJSONResponse({}) g.return_value.status_code = 404 with patch('pysflib.sfauth.requests.post', new_callable=lambda: fake_send_request): self.assertEqual( '1234', sfauth.get_cookie('auth.tests.dom', 'user1', 'userpass')) self.assertEqual( '1234', sfauth.get_cookie('auth.tests.dom', github_access_token='abcd')) self.assertRaises(ValueError, sfauth.get_cookie, 'auth.tests.dom')
def get_client(self, cookie=None): if not cookie: try: basic = HTTPBasicAuth(self.conf['admin_user'], 'password') msg = '[%s] using direct basic auth to connect to gerrit' logger.debug(msg % self.service_name) g = GerritUtils(self.conf['url'] + 'api', auth=basic) return g except Exception as e: # if we can't get the admin credentials from the config, # let's not panic msg = ('[%s] simple auth raised error: %s, ' 'going with SF cauth-based authentication') logger.debug(msg % (self.service_name, e)) # Use an admin cookie if int(time.time()) - globals()['ADMIN_COOKIE_DATE'] > \ globals()['COOKIE_VALIDITY']: cookie = get_cookie(self._full_conf.auth['host'], self._full_conf.admin['name'], self._full_conf.admin['http_password']) globals()['ADMIN_COOKIE'] = cookie globals()['ADMIN_COOKIE_DATE'] = int(time.time()) else: cookie = globals()['ADMIN_COOKIE'] return GerritUtils(self.conf['url'], auth_cookie=cookie)
def delete_user(sf_url, login, password, username=None, email=None): auth_cookie = {'auth_pubtkt': get_cookie(sf_url, login, password)} if username: query = '?username=%s' % username requests.delete('http://' + sf_url + "/manage/services_users/" + query, cookies=auth_cookie) # if both are given we'll just be extra cautious and delete two times if email: query = '?email=%s' % email requests.delete('http://' + sf_url + "/manage/services_users/" + query, cookies=auth_cookie)
def add_group_in_gerrit_group(sf_url, username, password, in_id, to_include_id): c = GerritUtils('http://' + sf_url, auth_cookie=get_cookie(sf_url, username, password)) try: c.g.get('groups/%s/groups/%s' % (in_id, to_include_id)) print '%s Already included in %s !' % (to_include_id, in_id) except HTTPError: # Suppose here the groups in not included c.g.post('groups/%s/groups/%s' % (in_id, to_include_id), headers={}) print '%s included in %s.' % (to_include_id, in_id)
def get_cookie(args): if args.cookie is not None: return args.cookie url_stripper = re.compile('http[s]?://(.+)') use_ssl = False try: url = args.auth_server_url.rstrip('/') m = url_stripper.match(url) if m: if url.lower().startswith('https'): use_ssl = True url = m.groups()[0] if args.auth is not None: (username, password) = args.auth.split(':') cookie = sfauth.get_cookie(url, username=username, password=password, use_ssl=use_ssl, verify=(not args.insecure)) elif args.github_token is not None: token = args.github_token cookie = sfauth.get_cookie(url, github_access_token=token, use_ssl=use_ssl, verify=(not args.insecure)) elif args.api_key is not None: api_key = args.api_key cookie = sfauth.get_cookie(url, api_key=api_key, use_ssl=use_ssl, verify=(not args.insecure)) else: die('Please provide credentials') if cookie: return cookie else: die('Authentication failed') except Exception as e: die(e.message)
def test_delete_user_in_backends_by_username(self): """ Delete a user previously registered user by username """ # first, create a user and register it with services try: self.msu.create_user('bootsy', 'collins', '*****@*****.**') except NotImplementedError: skip("user management not supported in this version of managesf") self.logout() self.login('bootsy', 'collins', config.GATEWAY_URL) # make sure user is in redmine and gerrit self.assertEqual('*****@*****.**', self.gu.get_account('bootsy').get('email')) if has_issue_tracker(): users = self.rm.active_users() users = [u for u in users if u[0] == 'bootsy'] self.assertEqual(1, len(users)) user = users[0] self.assertEqual('*****@*****.**', user[1]) # now suppress it del_url = config.GATEWAY_URL +\ '/manage/services_users/?username=bootsy' # try with a a non-admin user, it should not work ... auth_cookie = get_cookie(config.GATEWAY_HOST, 'user5', config.ADMIN_PASSWORD) d = requests.delete(del_url, cookies={'auth_pubtkt': auth_cookie}) self.assertTrue(400 < int(d.status_code) < 500) # try with an admin ... auth_cookie = config.USERS[config.ADMIN_USER]['auth_cookie'] d = requests.delete(del_url, cookies={'auth_pubtkt': auth_cookie}) self.assertTrue(int(d.status_code) < 400, d.status_code) # make sure the user does not exist anymore self.assertEqual(False, self.gu.get_account('bootsy')) if has_issue_tracker(): users = self.rm.active_users() self.assertEqual(0, len([u for u in users if u[0] == 'bootsy']))
def __init__(self, url, api_key, project_group, board): self.url = url self.cookie = get_cookie(url, api_key=api_key) self.client = SFStoryboard(urljoin(url, "storyboard_api"), self.cookie) try: self.project_group = self.client.project_groups.find( name=project_group) except exceptions.NotFound: raise Exception('projects group not found') self.stories = self.client.stories.get_all( project_group_id=self.project_group.id) self.board_id = None if board: try: self.board_id = self.client.boards.find(title=board).id except exceptions.NotFound: raise Exception('board not found') self.board_lanes = {} for lane in self.client.worklists.get_all(board_id=self.board_id): if not lane.archived and lane.title in LANES: self.board_lanes[lane.title] = lane
def test_delete_user_in_backends_by_username(self): """ Delete a user previously registered user by username """ # first, create a user and register it with services try: self.msu.create_user('bootsy', 'collins', '*****@*****.**') except NotImplementedError: skip("user management not supported in this version of managesf") self.logout() self.login('bootsy', 'collins', config.GATEWAY_URL) # make sure user is in redmine and gerrit self.assertEqual('*****@*****.**', self.gu.get_account('bootsy').get('email')) if is_present("SFRedmine"): users = self.rm.r.user.filter(limit=20) users = [u for u in users if u.firstname == 'bootsy'] self.assertEqual(1, len(users)) user = users[0] self.assertEqual('*****@*****.**', user.mail) # now suppress it del_url = config.GATEWAY_URL + 'manage/services_users/?username=bootsy' # try with a a non-admin user, it should not work ... auth_cookie = get_cookie(config.GATEWAY_HOST, 'user5', config.ADMIN_PASSWORD) d = requests.delete(del_url, cookies={'auth_pubtkt': auth_cookie}) self.assertEqual(401, int(d.status_code)) # try with an admin ... auth_cookie = config.USERS[config.ADMIN_USER]['auth_cookie'] d = requests.delete(del_url, cookies={'auth_pubtkt': auth_cookie}) self.assertTrue(int(d.status_code) < 400, d.status_code) # make sure the user does not exist anymore self.assertEqual(False, self.gu.get_account('bootsy')) if is_present("SFRedmine"): users = self.rm.r.user.filter(limit=20) self.assertEqual( 0, len([u for u in users if u.firstname == 'bootsy']))
#!/usr/bin/env python from pysflib.sfauth import get_cookie from sfrdo import config # Need to run that before fetching the cookie: # sfmanager --url https://rpmfactory.beta.rdoproject.org --auth admin:xxx \ # user create --username sfbender --password 'userpass' --email \ # '*****@*****.**' --fullname \ # 'Bender RPM Factory' --ssh-key /var/lib/jenkins/.ssh/id_rsa.pub auth_cookie = {'auth_pubtkt': get_cookie(config.rpmfactory, 'sfrdobender', 'userpass')}
def get_group_id(sf_url, username, password, grpname): c = GerritUtils('http://' + sf_url, auth_cookie=get_cookie(sf_url, username, password)) return c.get_group_id(grpname)
def provision_user(sf_url, username, password, user_data): auth_cookie = {'auth_pubtkt': get_cookie(sf_url, username, password)} return requests.post('http://' + sf_url + "/manage/services_users/", json=user_data, cookies=auth_cookie)
def listAllProjectDetails(self): auth_cookie = {'auth_pubtkt': get_cookie(self.url.lstrip('http://'), self.user, self.passwd)} return requests.get(self.url + "/manage/project/", cookies=auth_cookie).json()
import yaml import requests import json import os from pysflib import sfauth if __name__ == '__main__': cwd = os.getcwd() conf_path = argv[2] with open(conf_path) as f: config = yaml.load(f) admin_pass = config['authentication']['admin_password'] url = config['fqdn'] cookie = {'auth_pubtkt': sfauth.get_cookie(url, 'admin', admin_pass)} if argv[1] == 'dump': try: os.remove('/tmp/users_provision.json') except OSError: pass o = requests.get('http://%s/manage/project/membership/' % url, cookies=cookie) with open('/tmp/users_provision.json', 'w') as f: json.dump(o.json(), f) elif argv[1] == 'provision': with open('/tmp/users_provision.json') as f: users = json.load(f) for user in users: username, email, full_name = user
def get(description, host, sfcookie): cookies = {'auth_pubtkt': sfcookie} response = requests.get( "http://%s/jenkins/credential-store/domain/_/" % host, cookies=cookies) for line in response.text.split('\n'): m = re.search('<a href="credential/(\S+)" tooltip="%s">' % description, line) if m: print m.groups()[0] sys.exit(0) if __name__ == "__main__": host = sys.argv[1] auth = sys.argv[2] user, password = auth.split(':') sfcookie = get_cookie(host, user, password) if sys.argv[3] == 'get': description = sys.argv[4] get(description, host, sfcookie) sys.exit(1) if sys.argv[3] == 'add': data_path = sys.argv[4] assert os.path.isfile(data_path) description = sys.argv[5] add(data_path, description, host, sfcookie)
from sys import argv, exit import yaml import requests import json import os from pysflib import sfauth if __name__ == '__main__': cwd = os.getcwd() conf_path = argv[2] with open(conf_path) as f: config = yaml.load(f) admin_pass = config['authentication']['admin_password'] url = config['fqdn'] cookie = {'auth_pubtkt': sfauth.get_cookie(url, 'admin', admin_pass)} if argv[1] == 'dump': try: os.remove('/tmp/users_provision.json') except OSError: pass o = requests.get('http://%s/manage/project/membership/' % url, cookies=cookie) with open('/tmp/users_provision.json', 'w') as f: json.dump(o.json(), f) elif argv[1] == 'provision': with open('/tmp/users_provision.json') as f: users = json.load(f) for user in users: username, email, full_name = user
def _create_connector(self): c = sfauth.get_cookie(self.sf_domain, self.username, self.password, use_ssl=self.use_ssl, verify=self.verify_ssl) self.redmine = sfredmine.SFRedmine(self.url, auth_cookie=c, requests={'verify': False})
def _create_connector(self): c = sfauth.get_cookie( self.sf_domain, self.username, self.password, use_ssl=self.use_ssl, verify=self.verify_ssl ) self.redmine = sfredmine.SFRedmine(self.url, auth_cookie=c, requests={"verify": False})