예제 #1
0
class JIRA:
    auth = BasicAuth ("", "")
    url = ""
    username = ""
    password = ""

    # -- Contructor
    def __init__ (self, username, password, url):
        self.username = username
        self.password = password
        self.url = url

    # -- Private Functions
    def __authenticate (self):
        if self.username == "" or self.password == "" or self.url == "":
            return JIRA_ERROR_CREDENTIALS_MISSING
        else:
            self.auth = BasicAuth (self.username, self.password)
            return JIRA_SUCCESS

    def __get_json_response (self, resource):
        try:
            response = resource.get (headers = {'Content-type' : 'application/json'})
        except Exception, ex:
            print "Exception: %s" % ex.msg;

        if response.status_int != 200:
            print "ERROR: status %s" % response.status_int
            return False, response
        else:
            return True, response
예제 #2
0
def post_authenticated_data(data, url, username, password):
    """
    Post basic authenticated data, using restkit
    """ 
    auth = BasicAuth(username, password)
    r = Resource(url, filters=[auth, ])
    return r.post(payload=data).body_string(), None
예제 #3
0
        def _create_repository(self, username, password, repo_name):
            '''Makes a REST call to Bitbucket to create the new remote repository
            before we can push.'''
            try:
                resp = request('https://api.bitbucket.org/1.0/repositories/',
                               method='POST',
                               body=form_encode({'name': repo_name}),
                               filters=[BasicAuth(username, password)],
                               headers={
                                   'Content-Type':
                                   'application/x-www-form-urlencoded'
                               },
                               follow_redirect=True)

                if resp.status_int == 401:
                    return CREATE_RESULT.UNAUTHORIZED
                elif resp.status_int == 400:
                    return CREATE_RESULT.BAD_REQUEST
                elif (resp.status_int // 100) != 2:
                    print 'Call failed:', resp.status_int, resp.body_string()
                    return CREATE_RESULT.REMOTE_ERROR
                else:
                    return CREATE_RESULT.OK
            except:
                type_, message, tb = sys.exc_info()
                print type_, message
                print util.traceback_to_str(tb)
                return CREATE_RESULT.UNKNOWN
예제 #4
0
def main(db_name, db_user, db_pass, db_host, sequence_file, zone_dir, **tls_args):
    # Starting Sequence for change stream
    sequence = sequence_read(sequence_file)
    click.echo('Skipping %s changes.' % sequence)
    # CouchDB Connection
    tls_args['cert_reqs'] = ssl.CERT_REQUIRED
    tls_args['ssl_version'] = ssl.PROTOCOL_TLSv1_2
    auth = CouchdbResource(filters=[BasicAuth(db_user, db_pass)], **tls_args)
    server = Server(uri=db_host, resource_instance=auth)
    db = server[db_name]

    if sequence == 0:
        click.echo('Fast track syncing all zones...')
        c = Consumer(db)
        result = c.fetch(descending=True, limit=1)
        # Fast track to this sequence
        sequence = result['last_seq']
        # Go get all the current zones.
        zones = c.fetch()
        for zone in zones['results']:
            domain = zone['id']
            try:
                doc = db.get(docid=domain)
            except ResourceNotFound, e:
                click.echo('%s not found (this is normal if the zone was deleted)' % domain)
            else:
                zone_update(domain, doc['data'], zone_dir)
        sequence_write(sequence_file, sequence)  # Keep track of our sync point
        click.echo('Fast track syncing done')
예제 #5
0
 def __init__(self, bot):
     IPlugin.__init__(self, bot)
     
     self.data = {
         'last-bug-created': 0,
         'ignored-names': [
             '/^Not\-[0-9]+/' # Notifico bots
         ]
     }
     
     self.LoadPluginData()
     
     self.url = globalConfig.get('plugins.redmine.url', None)
     if self.url is None:
         logging.error('Redmine: Disabled.') 
         return
     self.ignored = []
     for ignoretok in self.data.get('ignored-names',['/^Not\-[0-9]/']):
         if ignoretok.startwith('/') and ignoretok.endwith('/'):
             self.ignored+=[re.compile(ignoretok[1:-1])]
         else:
             self.ignored+=[re.compile('^'+re.escape(ignoretok)+'$')]
     self.auth = BasicAuth(globalConfig.get('plugins.redmine.apikey', None), str(random.random()))
     self.project_id = globalConfig.get('plugins.redmine.project', None)
     if self.project_id is None: logging.warning('Redmine: Not going to check for bug updates.')
     self.bug_info_format = globalConfig.get('plugins.redmine.bug-info-format', 'Redmine #{ID} - {AUTHOR} - {STATUS} - {SUBJECT}{CRLF}{URL}')
     self.new_bug_format = globalConfig.get('plugins.redmine.new-bug-format', 'NEW ISSUE: {URL} (#{ID}: {SUBJECT})')
     self.resource = Resource(self.url, filters=[self.auth])
     
     self.bug_regex = re.compile(r'#(\d+)\b')
     
     self.lastCheck = 0
예제 #6
0
 def __init__(self, url, database, user, password, obj):
     self.database = database
     self.url = url
     auth = BasicAuth(user, password)
     self.resource = Resource("%s/rest/object/%s/%s" % (url, database, obj),
                              filters=[auth],
                              basic_auth_url=True)
예제 #7
0
def main(args):
  verbose = args.verbose
  server_base_url = args.url
  user = args.user
  password = args.password

  # This sends the user and password with the request.
  filters = []
  if user:
    auth = BasicAuth(user, password)
    filters = [auth]

  url = "%s/rest/api/latest" % (server_base_url)
  resource = Resource(url, filters=filters)

  issueList = get_json(resource, "search", jql=jql_search, fields="key,issuetype,created,status,summary", expand="renderedFields", maxResults=500)
  if verbose: pprint(issueList)

  tests = []
  for issue in issueList['issues']:
    id = issue['key']
    summary = issue['fields']['summary']
    match = re.search(r'\w+Test', summary)
    if match:
      test = match.group(0)
      tests.append((test, id, summary))

  tests = sorted(tests)

  csvwriter = csv.writer(sys.stdout, dialect='excel-tab')
  for row in tests:
    csvwriter.writerow(row)
예제 #8
0
파일: fisheye.py 프로젝트: szaydel/ralph
 def __init__(self):
     user = settings.FISHEYE_USER
     password = settings.FISHEYE_PASSWORD
     jira_url = settings.FISHEYE_URL
     self.project_name = settings.FISHEYE_PROJECT_NAME
     self.auth = BasicAuth(user, password)
     self.base_url = "%s/rest-service-fe" % jira_url
예제 #9
0
 def __init__(self, serverURL, dbname, username, pwd):
     self.serverURL = serverURL
     self.dbname = dbname
     self.username = username
     self.pwd = pwd
     self.server = Server(self.serverURL,
                          filters=[BasicAuth(self.username, self.pwd)])
예제 #10
0
 def __init__(self, host_url, api_version, username, password, **kwargs):
     prefix_path = '{}/api/{}'.format(host_url, api_version)
     super(EDRClient,
           self).__init__(prefix_path,
                          filters=[BasicAuth(username, password)],
                          **kwargs)
     self.headers = {"Content-Type": "application/json"}
예제 #11
0
 def create(url, user, pwd, *args, **kwargs):
     filters = [BasicAuth(user, pwd)]
     try:
         _filters = kwargs.pop('filters')
         filters.extend(_filters)
     except KeyError:
         pass
     return Connection(url, filters=filters, *args, **kwargs)
예제 #12
0
 def __init__(self, serverURL, dbname, username, pwd):
     self.serverURL = serverURL
     self.dbname = dbname
     self.username = username
     self.pwd = pwd
     self.server = Server(self.serverURL,
                          filters=[BasicAuth(self.username, self.pwd)])
     set_logging('info')  # suppress DEBUG output of the couchdbkit/restkit
예제 #13
0
def get_credentials():
    """ gets user credentials from stdin and returns a auth filter list """

    username = raw_input('Username: '******'Password: ')
    return [BasicAuth(username, password)]
예제 #14
0
파일: jira.py 프로젝트: rainsome-org1/ralph
 def __init__(self):
     self.accepted_transition = settings.ISSUETRACKERS['default']['OPA'][
         'ACTIONS']['IN_PROGRESS']
     user = settings.ISSUETRACKERS['default']['USER']
     password = settings.ISSUETRACKERS['default']['PASSWORD']
     jira_url = settings.ISSUETRACKERS['default']['URL']
     self.auth = BasicAuth(user, password)
     self.base_url = "%s/rest/api/latest" % jira_url
     self.resource_headers = {'Content-type': 'application/json'}
예제 #15
0
 def __init__(self, token, **kwargs):
     if getattr(self, 'api_url', None) is None:
         self.api_url = self.api_url_base
     self.token = token
     super(PCBase, self).__init__(self.api_url,
                                  filters=[BasicAuth(token, "")],
                                  follow_redirect=True,
                                  max_follow_redirect=10,
                                  **kwargs)
예제 #16
0
def github_req(user, token, fmt='json', suburl=None, method='get'):
    auth = BasicAuth(user, token)
    if not suburl:
        suburl = '/user/show/%s' % user
    url = 'https://github.com/api/v2/%s%s' % (fmt, suburl)
    r = Resource(url, filters=[auth])
    ret = getattr(r, method)().body_string()
    if fmt == 'json':
        ret = demjson.decode(ret)
    return ret
예제 #17
0
def get_mail_aliases(username, password):
    mail_aliases = defaultdict(dict)
    for line in Resource(MAIL_ALIAS_URL, filters=[BasicAuth(username, password)], timeout=10).get().body_stream():
        apache_email, alias_email, member = [canonical_email_address(field.strip()) for field in line.split(',')]
        mail_aliases[apache_email]['member'] = bool(member)
        if 'aliases' not in mail_aliases[apache_email]:
            mail_aliases[apache_email]['aliases'] = set()
        mail_aliases[apache_email]['aliases'].add(alias_email)

    return mail_aliases
예제 #18
0
 def create_token(self, user, password):
     serverurl = "https://api.github.com"
     auth = BasicAuth(user, password)
     authreqdata = {"scopes": ["repo"], "note": "admin script"}
     resource = Resource('https://api.github.com/authorizations',
                         pool=self.pool,
                         filters=[auth])
     response = resource.post(headers={"Content-Type": "application/json"},
                              payload=json.dumps(authreqdata))
     self.token = json.loads(response.body_string())['token']
예제 #19
0
    def setUp(self):
        auth = BasicAuth('john', 'teste')
        res = Resource(server, filters=[
            auth,
        ])
        r = res.get('/authenticate')
        data = loads(r.body_string())

        self.auth = AuthToken(data.get('token'))
        self.res = Resource(server, filters=[
            self.auth,
        ])
예제 #20
0
    def __init__(self, irc):

        self.__parent = super(Redmine, self)
        self.__parent.__init__(irc)

        self.saidBugs = ircutils.IrcDict()
        sayTimeout = self.registryValue('bugSnarferTimeout')
        for k in irc.state.channels.keys():
            self.saidBugs[k] = TimeoutQueue(sayTimeout)

        self.url = self.registryValue('urlbase')
        self.auth = BasicAuth(self.registryValue('apikey'),
                              str(random.random()))
        self.resource = Resource(self.url, filters=[self.auth])
예제 #21
0
def upload_file(fname, uri, dbname):
    print 'Upload contents of %s to %s/%s' % (fname, uri, dbname)
    theServer = Server(
        uri, filters=[BasicAuth(cloudant_username, cloudant_password)])
    db = theServer.get_or_create_db(dbname)
    reader = DictReader(open(fname, 'rU'), dialect='excel')
    docs = list()
    checkpoint = 100
    for doc in reader:
        newdoc = parse_doc(doc)
        docs.append(newdoc)
        if len(docs) % checkpoint == 0:
            docs = upload(db, docs)
    docs = upload(db, docs)
예제 #22
0
    def setUp(self):
        config = ConfigParser.ConfigParser()
        config.read('test.cfg')
        self.baseurl = config.get('tests', 'baseurl')

        email, password = config.get('tests', 'testsuperuser').split(",", 1)
        self.dbsuperuser = util.getAccountByEmail(email)
        self.testsuperuser = BasicAuth(email, password)

        email, password = config.get('tests', 'testpoweruser').split(",", 1)
        self.dbpoweruser = util.getAccountByEmail(email)
        self.testpoweruser = BasicAuth(email, password)

        email, password = config.get('tests', 'testconfiguser').split(",", 1)
        self.dbconfiguser = util.getAccountByEmail(email)
        self.testconfiguser = BasicAuth(email, password)

        email, password = config.get('tests', 'testfilluser').split(",", 1)
        self.dbfilluser = util.getAccountByEmail(email)
        self.testfilluser = BasicAuth(email, password)

        email, password = config.get('tests', 'testuser').split(",", 1)
        self.dbuser = util.getAccountByEmail(email)
        self.testuser = BasicAuth(email, password)
예제 #23
0
 def __init__(self,
              key,
              host_url,
              api_version,
              resource,
              params=None,
              **kwargs):
     super(APIBaseClient, self).__init__(host_url,
                                         filters=[BasicAuth(key, "")],
                                         **kwargs)
     self.prefix_path = '/api/{}/{}'.format(api_version, resource)
     if not isinstance(params, dict):
         params = {"mode": "_all_"}
     self.params = params
     self.headers = {"Content-Type": "application/json"}
     # To perform some operations (e.g. create a tender)
     # we first need to obtain a cookie. For that reason,
     # here we send a HEAD request to a neutral URL.
     self.head('/api/{}/spore'.format(api_version))
예제 #24
0
def get_jira_issue(server_base_url, user, password, key, fields=None):

    verbose = False

    # A pool of connections
    #pool = SimplePool(keepalive = 2)

    # This sends the user and password with the request.
    auth = BasicAuth(user, password)

    resource = Resource(server_base_url + 'rest/api/2/issue/%s?fields=%s' %
                        (key, fields),
                        filters=[auth])

    try:
        response = resource.get(headers={'Content-Type': 'application/json'})

    except Exception, err:
        print "EXCEPTION: %s " % str(err)
        return
예제 #25
0
    def __init__(self, databases):
        """ initialize couchdbkit handler with COUCHDB_DATABASES
        settings """

        self.__dict__ = self.__shared_state__

        # Convert old style to new style
        if isinstance(databases, (list, tuple)):
            databases = dict((app_name, {
                'URL': uri
            }) for app_name, uri in databases)

        # create databases sessions
        for app_name, app_setting in databases.items():
            uri = app_setting['URL']

            # Do not send credentials when they are both None as admin party will give a 401
            user = app_setting.get('USER')
            password = app_setting.get('PASSWORD')
            filters = [BasicAuth(user, password)
                       ] if (user or password) is not None else []

            try:
                if isinstance(uri, (list, tuple)):
                    # case when you want to specify server uri
                    # and database name specifically. usefull
                    # when you proxy couchdb on some path
                    server_uri, dbname = uri
                else:
                    server_uri, dbname = uri.rsplit("/", 1)
            except ValueError:
                raise ValueError("couchdb uri [%s:%s] invalid" %
                                 (app_name, uri))

            res = CouchdbResource(server_uri,
                                  timeout=COUCHDB_TIMEOUT,
                                  filters=filters)

            server = Server(server_uri, resource_instance=res)
            app_label = app_name.split('.')[-1]
            self._databases[app_label] = (server, dbname)
def homepage(request):
    
    _message = ""

    if request.method == 'POST':
        
        if 'login' in request.POST:

            _username = request.POST['username']
                
            _password = request.POST['password']
            
            auth = BasicAuth(_username, _password)
            
            issuedic =  issues(auth, 1)
            
            if issuedic is None:

                _message = "either your jira username or password is incorrect"
            
            else:
                
                global Auth
                
                Auth = auth
                
                global username
                
                username = _username
                
                global password
                
                password = _password
                
                return redirect('filter')

    context = {'message' : _message }
    
    return render(request, 'myaccount/home.html', context)
예제 #27
0
def get_committer(committer, username, password):
    global COMMITTERS
    if committer not in COMMITTERS:
        try:
            committer_json = json.loads(
                Resource('%s/%s' % (COMMITTERS_URL, committer),
                         filters=[BasicAuth(username, password)],
                         timeout=10).get(headers={
                             'Accept': 'application/json'
                         }).body_string())
        except ResourceNotFound:
            log.warning('Unable to find committer %s' % committer)
        else:
            availid = committer_json['availid']
            member = bool(committer_json['member'])
            fullname = committer_json['name']

            emails = set()
            for email in committer_json['emails']:
                try:
                    emails.add(canonical_email_address(email))
                except ValueError:
                    log.warning(
                        'Malformed email address %s not added to committer %s',
                        email, committer)

            urls = committer_json['urls']
            committees = committer_json['committees']
            projects = set(committer_json['groups'])
            if 'apsite' in projects: projects.remove('apsite')
            if 'committers' in projects: projects.remove('committers')
            if 'member' in projects: projects.remove('member')
            mentoring = committer_json['auth']

            COMMITTERS[committer] = Committer(availid, member, fullname,
                                              emails, urls, committees,
                                              projects, mentoring)

    return COMMITTERS[committer]
예제 #28
0
 def __init__(self, bot):
     IPlugin.__init__(self, bot)
     
     self.data = {
         'last-bug-created': 0
     }
     
     self.LoadPluginData()
     
     self.url = globalConfig.get('plugins.redmine.url', None)
     if self.url is None:
         logging.error('Redmine: Disabled.') 
         return
     self.auth = BasicAuth(globalConfig.get('plugins.redmine.apikey', None), str(random.random()))
     self.project_id = globalConfig.get('plugins.redmine.project', None)
     if self.project_id is None: logging.warning('Redmine: Not going to check for bug updates.')
     self.bug_info_format = globalConfig.get('plugins.redmine.bug-info-format', 'Redmine #{ID} - {AUTHOR} - {STATUS} - {SUBJECT}{CRLF}{URL}')
     self.new_bug_format = globalConfig.get('plugins.redmine.new-bug-format', 'NEW ISSUE: {URL} (#{ID}: {SUBJECT})')
     self.resource = Resource(self.url, filters=[self.auth])
     
     self.bug_regex = re.compile(r'#(\d+)\b')
     
     self.lastCheck = 0
예제 #29
0
def createTask(server_base_url, user, password, project, task_summary):
    auth = BasicAuth(user, password)

    resource_name = "issue"
    complete_url = "%s/rest/api/latest/%s/" % (server_base_url, resource_name)
    resource = Resource(complete_url, filters=[auth])

    try:
        data = {
            "fields": {
                "project": {
                    "key": project
                },
                "summary": task_summary,
                "issuetype": {
                    "name": "Task"
                }
            }
        }
        response = resource.post(headers={'Content-Type': 'application/json'},
                                 payload=json.dumps(data))
    except Exception, ex:
        print "EXCEPTION: %s " % ex.msg
        return None
예제 #30
0
                      default='http://jira.example.com',
                      help='JIRA Base URL')
    parser.add_option('-f',
                      '--file',
                      dest='image_file',
                      default='issue_graph.png',
                      help='Filename to write image to')

    return parser.parse_args()


def get_password():
    return getpass("Please enter the Jira Password:")


if __name__ == '__main__':
    (options, args) = parse_args()

    # Basic Auth is usually easier for scripts like this to deal with than Cookies.
    auth = BasicAuth(options.user, options.password or get_password())
    issue_fetcher = fetcher_factory(options.jira_url, auth)

    if len(args) != 1:
        die('Must specify exactly one issue key. (e.g. JRADEV-1107, JRADEV-1391)'
            )
    start_issue_key = args[0]

    epic_id = get_epic_id(options.jira_url, start_issue_key, auth)

    graph = build_graph_data(start_issue_key, issue_fetcher, epic_id)
    create_local_graph_image(graph, options.image_file)