def _netrc_auth(self): if get_netrc_auth(self._url): netrc_id, netrc_pw = get_netrc_auth(self._url) else: raise CredentialsNotFound("No Credentials for %s found in .netrc" % self._url) return netrc_id, netrc_pw
def _netrc_auth(self): if get_netrc_auth(self._url): netrc_id, netrc_pw = get_netrc_auth(self._url) else: raise CredentialsNotFound( "No Credentials for %s found in .netrc" % self._url) return netrc_id, netrc_pw
def __init__(self, url): """See class docstring.""" auth = get_netrc_auth(url) if not auth: raise ValueError("netrc missing or no credentials found in netrc") username, password = auth super(HTTPBasicAuthFromNetrc, self).__init__(username, password)
def rebuild_auth(self, prepared_request: PreparedRequest, response: Response) -> None: """ Override Session.rebuild_auth. Strips the Authorization header if neither original URL nor redirected URL belong to an Earthdata Login (EDL) host. Also allows the default requests behavior of searching for relevant .netrc credentials if and only if a username and password weren't provided during object instantiation. Args: prepared_request: Object for the redirection destination. response: Object for the where we just came from. """ headers = prepared_request.headers redirect_hostname = cast(str, urlparse(prepared_request.url).hostname) original_hostname = cast(str, urlparse(response.request.url).hostname) if ('Authorization' in headers and (original_hostname != redirect_hostname) and not _is_edl_hostname(redirect_hostname)): del headers['Authorization'] if self.auth is None: # .netrc might have more auth for us on our new host. new_auth = get_netrc_auth( prepared_request.url) if self.trust_env else None if new_auth is not None: prepared_request.prepare_auth(new_auth) return
def __init__(self, url): auth = get_netrc_auth(url) if not auth: raise GerritRestAPIError("netrc missing or no credentials found " "in netrc") username, password = auth super(HTTPBasicAuthFromNetrc, self).__init__(username, password)
def description(self): config_list = [ ("Listen port:", self.listen_port), ("Log level:", self.log_level), ("Kibana URL:", self.kibana_url), ] # check if netrc is available netrc_auth = get_netrc_auth(self.kibana_url) if netrc_auth: config_list.append(("Kibana login (from netrc):", netrc_auth[0])) config_list.append(("Kibana password (from netrc):", "***")) elif self.kibana_login: config_list.append(("Kibana login:"******"Kibana password:"******"***")) if self.ignore_ssl: config_list.append(("SSL verification:", "disabled")) else: config_list.append(("SSL verification:", "enabled")) if self.requests_ca_bundle: config_list.append(("Requests CA bundle path:", self.requests_ca_bundle)) max_length = max(map(lambda x: len(x[0]), config_list)) desc = "== CONFIGURATION ==\n" line_template = "%-" + str(max_length) + "s\t%s\n" for line in config_list: desc += line_template % line return desc
def __call__(self, r): ''' checks the authentication when the auth is called ''' # check access and authentication if self.authtype == 'token': assert bconfig.token is not None, 'You must have a valid token set to use the API. Please login.' r.headers['Authorization'] = 'Bearer {0}'.format(bconfig.token) elif self.authtype == 'http': from requests_toolbelt import GuessAuth r.auth = GuessAuth('user', 'passwd') elif self.authtype == 'netrc' and bconfig.has_netrc: netauth = get_netrc_auth(r.url) if netauth: r.headers['Authorization'] = _basic_auth_str(*get_netrc_auth(r.url)) elif self.authtype == 'oauth': raise BrainNotImplemented('OAuth authentication') return r
def get_all(): """Gets most recent posts from pinboard.in""" endpoint = "https://api.pinboard.in/v1/" user, token = get_netrc_auth(endpoint) auth_token = "{user}:{token}".format(user=user, token=token) params = {'auth_token': auth_token} params.update(default_params) r = requests.get(endpoint + "posts/all", params=params) return r.json()
def _apply_basic_auth(request): # this logic duplicated from Session.prepare_request and PreparedRequest.prepare_auth url_auth = get_auth_from_url(request.url) auth = url_auth if any(url_auth) else None if auth is None: # look for auth information in a .netrc file auth = get_netrc_auth(request.url) if isinstance(auth, tuple) and len(auth) == 2: request.headers['Authorization'] = _basic_auth_str(*auth) return request
def prepare_request(self, request: BitexRequest) -> BitexPreparedRequest: """Prepare a :class:`BitexPreparedRequest` object for transmission. This implementation extends :class:`requests.Session.prepare_request` by making a call to :data:`bitex.list_loaded_plugins` and checking if we have any plugins that may provide a custom :class:`BitexPreparedRequest` class. """ cookies = request.cookies or {} # Bootstrap CookieJar. if not isinstance(cookies, cookielib.CookieJar): cookies = cookiejar_from_dict(cookies) # Merge with session cookies session_cookies = merge_cookies(RequestsCookieJar(), self.cookies) merged_cookies = merge_cookies(session_cookies, cookies) # Set environment's basic authentication if not explicitly set. auth = request.auth if self.trust_env and not auth and not self.auth: auth = get_netrc_auth(request.url) # Inject any custom classes for handling the exchange stated in the # BitexRequest object. custom_classes = list_loaded_plugins().get(request.exchange, None) if custom_classes: p = custom_classes["PreparedRequest"](request.exchange) # Only use the custom auth class if no auth object was # provided explicitly. Otherwise we would overwrite user-specified # auth objects passed to self.request. if not self.auth and request.private: self.auth = custom_classes["Auth"](self.key, self.secret) else: p = BitexPreparedRequest(request.exchange) p.prepare( method=request.method.upper(), url=request.url, files=request.files, data=request.data, json=request.json, headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict), params=merge_setting(request.params, self.params), auth=merge_setting(auth, self.auth), cookies=merged_cookies, hooks=merge_hooks(request.hooks, self.hooks), ) return p
def session(requests_session=None, uri=None): global gerrit_session global api_uri if requests_session: gerrit_session = requests_session if uri: api_uri = uri if gerrit_session is None: gerrit_session = Session() # get credentials from .netrc: (user, password) = get_netrc_auth(api_uri) # Gerrit uses HTTP Digest authentication instead of basic: gerrit_session.auth = HTTPDigestAuth(user, password) return gerrit_session
def verify_access(org=ORG_NAME_DEFAULT): if not get_netrc_auth(get_org_member_url(org)): logger.fatal('Heroku API credentials not found in `~/.netrc`' ' or `~/_netrc`.' ' Log in using the Heroku CLI to generate them,' ' or decrypt your ~/.netrc.gpg file') update_status_code(1) raise SystemExit(get_status_code()) try: org_perms = fetch_api_json(get_org_url(org)) role = org_perms.get("role", "public") if role not in ["admin"]: logger.warn("You only have {} perms for {}".format(role, org)) except requests.exceptions.HTTPError: logger.fatal("You don't have access to {}".format(org)) update_status_code(3) raise SystemExit(get_status_code()) return
def main(args): if not get_netrc_auth(ORG_USERS_URL): print( "Heroku API credentials not found in `~/.netrc` or `~/_netrc`.\n" "Log in using the Heroku CLI to generate them." ) update_exit_code(1) return users_missing_2fa = find_users_missing_2fa() affected_apps = find_affected_apps(users_missing_2fa) if args.email: output_mail_merge(affected_apps) elif args.csv: generate_csv(users_missing_2fa, affected_apps) else: output_results(users_missing_2fa, affected_apps) update_exit_code(0 if not users_missing_2fa else 2)
def prepare_request(self, request): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. """ cookies = request.cookies or {} # Bootstrap CookieJar. if not isinstance(cookies, cookielib.CookieJar): cookies = cookiejar_from_dict(cookies) # Merge with session cookies merged_cookies = RequestsCookieJar() merged_cookies.update(self.cookies) merged_cookies.update(cookies) # Set environment's basic authentication if not explicitly set. auth = request.auth if self.trust_env and not auth and not self.auth: auth = get_netrc_auth(request.url) p = PreparedRequest() p.prepare( method=request.method.upper(), url=request.url, files=request.files, data=request.data, json=request.json, headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict), params=merge_setting(request.params, self.params), auth=merge_setting(auth, self.auth), cookies=merged_cookies, hooks=merge_hooks(request.hooks, self.hooks), ) return p
def __init__(self, url, auth_id=None, auth_pw=None, debug=True): """ :param url: URL to the gerrit server :type url: str :param auth_id: Username to authenticate with :type auth_id: str :param auth_pw: Password for username to authenticate with :type auth_pw: str :param debug: Verbosity for the lib :type debug: bool """ # Should we print out the messages? # Default is yes, but for testing we can set this to False self._debug = debug # HTTP REST API HEADERS self._requests_headers = { 'content-type': 'application/json', } self._url = url.rstrip('/') # Assume netrc file if no auth_id or auth_pw was given. if auth_id is None and auth_pw is None: netrc_auth = get_netrc_auth(self._url) if not netrc_auth: raise GerritError.CredentialsNotFound( "No Credentials for %s found in .netrc" % self._url) auth_id, auth_pw = netrc_auth if auth_id is None or auth_pw is None: raise GerritError.CredentialsNotFound("Partial credenials given.") # We got everything as we expected, create the HTTPBasicAuth object. self._auth = HTTPBasicAuth(auth_id, auth_pw)
def __init__(self, url): self.url = url.rstrip('/') self.session = requests.session() self.endpoint = '' hostname = urlparse(self.url).netloc HAVE_AUTH = False # load gitcookies gitcookies = os.path.expanduser('~/.gitcookies') if os.path.isfile(gitcookies): cookiejar = cookielib.MozillaCookieJar() cookiejar.load(gitcookies, ignore_discard=True, ignore_expires=True) HAVE_AUTH = any(filter(lambda x: x.domain == hostname, cookiejar)) if HAVE_AUTH: self.session.cookies = cookiejar # load netrc auth = get_netrc_auth(self.url) if auth: username, password = auth self.session.auth = requests.auth.HTTPBasicAuth(username, password) HAVE_AUTH = True if HAVE_AUTH and not self.url.endswith(GERRIT_AUTH_SUFFIX): self.url += GERRIT_AUTH_SUFFIX super().__init__(self, '') self.projects = Projects(self) self.changes = Changes(self) self.accounts = Accounts(self) self.accesses = Accesses(self) self.importer = Importer(self)
def _process_auth(self): # TODO: refactor & simplify this method. self.args.auth_plugin = None default_auth_plugin = plugin_manager.get_auth_plugins()[0] auth_type_set = self.args.auth_type is not None url = urlsplit(self.args.url) if self.args.auth is None and not auth_type_set: if url.username is not None: # Handle http://username:password@hostname/ username = url.username password = url.password or '' self.args.auth = AuthCredentials( key=username, value=password, sep=SEPARATOR_CREDENTIALS, orig=SEPARATOR_CREDENTIALS.join([username, password]) ) if self.args.auth is not None or auth_type_set: if not self.args.auth_type: self.args.auth_type = default_auth_plugin.auth_type plugin = plugin_manager.get_auth_plugin(self.args.auth_type)() if (not self.args.ignore_netrc and self.args.auth is None and plugin.netrc_parse): # Only host needed, so it’s OK URL not finalized. netrc_credentials = get_netrc_auth(self.args.url) if netrc_credentials: self.args.auth = AuthCredentials( key=netrc_credentials[0], value=netrc_credentials[1], sep=SEPARATOR_CREDENTIALS, orig=SEPARATOR_CREDENTIALS.join(netrc_credentials) ) if plugin.auth_require and self.args.auth is None: self.error('--auth required') plugin.raw_auth = self.args.auth self.args.auth_plugin = plugin already_parsed = isinstance(self.args.auth, AuthCredentials) if self.args.auth is None or not plugin.auth_parse: self.args.auth = plugin.get_auth() else: if already_parsed: # from the URL credentials = self.args.auth else: credentials = parse_auth(self.args.auth) if (not credentials.has_password() and plugin.prompt_password): if self.args.ignore_stdin: # Non-tty stdin read by now self.error( 'Unable to prompt for passwords because' ' --ignore-stdin is set.' ) credentials.prompt_password(url.netloc) if (credentials.key and credentials.value): plugin.raw_auth = credentials.key + ":" + credentials.value self.args.auth = plugin.get_auth( username=credentials.key, password=credentials.value, ) if not self.args.auth and self.args.ignore_netrc: # Set a no-op auth to force requests to ignore .netrc # <https://github.com/psf/requests/issues/2773#issuecomment-174312831> self.args.auth = ExplicitNullAuth()
def main(): parser = argparse.ArgumentParser(description='Convert Bugzilla/Mantis issue to JIRA issue') parser.add_argument('bz_id', help='Bugzilla ID') group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-b', metavar='', help='Bugzilla Server URL') group.add_argument('-m', metavar='', help='Mantis Server URL') parser.add_argument('-j', metavar='', help='JIRA Server URL') parser.add_argument('-k', metavar='', help='JIRA Project Key') parser.add_argument('-o', metavar='', help='JIRA Board ID for moving commented issue to current sprint') parser.add_argument('-y', action='store_true', default=False, help='Yes to all') parser.add_argument('-q', action='store_true', default=False, help='Query') parser.add_argument('-r', action='store_true', default=False, help='Revert') parser.add_argument('-p', metavar='', help='Mantis Project ID') parser.add_argument('-f', metavar='', help='Mantis Filter ID') args = parser.parse_args() jira_server = args.j if not get_netrc_auth(jira_server): user = input("Jira Username:"******"Bugzilla Username:"******"BugZilla ID" is not empty ' 'AND status not in ("Resolved", "Closed", "Remind", "Verified")' % (args.k)) for issue in issues: bz_id = issue.fields.customfield_10216 if bz_id.startswith('Mantis-'): continue sync_bz_to_jira(bz, bz_id, jira, args.k, args.y) else: # single bz id sync_bz_to_jira(bz, args.bz_id, jira, args.k, args.y) elif args.m: auth = get_netrc_auth(args.m) if not auth: username = input("Username:"******"BugZilla ID" is not empty ' 'AND status not in ("Resolved", "Closed", "Remind", "Verified")' % (args.k)) for issue in issues: bz_id = issue.fields.customfield_10216 if not bz_id.startswith('Mantis-'): continue bz_id = bz_id.lstrip('Mantis-') sync_mantis_to_jira(args.m, username, passwd, bz_id, jira, args.k, args.o, args.y) else: sync_mantis_to_jira(args.m, username, passwd, args.bz_id, jira, args.k, args.o, args.y)
def _get_netrc_auth(url): return get_netrc_auth(url)
def __init__(self, url): auth = get_netrc_auth(url) if not auth: raise ValueError("netrc missing or no credentials found in netrc") username, password = auth super(HTTPDigestAuthFromNetrc, self).__init__(username, password)
def main(): parser = argparse.ArgumentParser( description='Convert Bugzilla/Mantis issue to JIRA issue') parser.add_argument('bz_id', help='Bugzilla ID') group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-b', metavar='', help='Bugzilla Server URL') group.add_argument('-m', metavar='', help='Mantis Server URL') group.add_argument('-nj', metavar='', help='New Jira Server URL') parser.add_argument('-j', metavar='', help='JIRA Server URL') parser.add_argument('-k', metavar='', help='JIRA Project Key') parser.add_argument( '-o', metavar='', help='JIRA Board ID for moving commented issue to current sprint') parser.add_argument('-y', action='store_true', default=False, help='Yes to all') parser.add_argument('-q', action='store_true', default=False, help='Query') parser.add_argument('-r', action='store_true', default=False, help='Revert') parser.add_argument('-p', metavar='', help='Mantis Project ID') parser.add_argument('-f', metavar='', help='Mantis Filter ID') args = parser.parse_args() jira_server = args.j if not get_netrc_auth(jira_server): user = input("Jira Username:"******"Bugzilla Username:"******"BugZilla ID" is not empty ' 'AND status not in ("Resolved", "Closed", "Remind", "Verified")' % (args.k)) for issue in issues: bz_id = issue.fields.customfield_10216 if bz_id.startswith('Mantis-'): continue if bz_id.startswith('QTSHBS'): continue sync_bz_to_jira(bz, bz_id, jira, args.k, args.y) else: # single bz id sync_bz_to_jira(bz, args.bz_id, jira, args.k, args.y) elif args.m: auth = get_netrc_auth(args.m) if not auth: username = input("Username:"******"BugZilla ID" is not empty ' 'AND status not in ("Resolved", "Closed", "Remind", "Verified")' % (args.k)) for issue in issues: bz_id = issue.fields.customfield_10216 if not bz_id.startswith('Mantis-'): continue bz_id = bz_id.lstrip('Mantis-') sync_mantis_to_jira(args.m, username, passwd, bz_id, jira, args.k, args.o, args.y) else: sync_mantis_to_jira(args.m, username, passwd, args.bz_id, jira, args.k, args.o, args.y) elif args.nj: new_jira_server = args.nj if not get_netrc_auth(new_jira_server): user = input("New Jira Username:"******"not implemented") else: # single jira id bug = new_jira.issue(args.bz_id) sync_new_jira_to_jira(new_jira_server, new_jira, bug, jira, args.k, args.y)