示例#1
0
 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': 'user1',
                                      'password': 'userpass'}}
             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)
示例#2
0
 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')
示例#3
0
 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)
示例#4
0
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)
示例#5
0
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)
示例#6
0
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)
示例#7
0
 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', '[email protected]')
     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('[email protected]',
                      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('[email protected]',
                          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']))
示例#8
0
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)
示例#9
0
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)
示例#10
0
 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
示例#12
0
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)
#!/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 \
#  '[email protected]' --fullname \
#  'Bender RPM Factory' --ssh-key /var/lib/jenkins/.ssh/id_rsa.pub

auth_cookie = {'auth_pubtkt': get_cookie(config.rpmfactory,
                                         'sfrdobender', 'userpass')}
 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})