def test_authorize_with_github_argument(self): """Show that github3.authorize can use an existing GitHub object.""" args = ('login', 'password', ['scope'], 'note', 'url.com', '', '') github = mock.Mock(spec_set=github3.GitHub) with mock.patch('github3.api.GitHub') as gh: github3.authorize(*args, github=github) gh().assert_not_called() github.authorize.assert_called_once_with(*args)
def test_authorize_with_github_argument(self): """Show that github3.authorize can use an existing GitHub object.""" args = ("login", "password", ["scope"], "note", "url.com", "", "") github = mock.Mock(spec_set=github3.GitHub) with mock.patch("github3.api.GitHub") as gh: github3.authorize(*args, github=github) gh().assert_not_called() github.authorize.assert_called_once_with(*args)
def auth_gh_token(): """auth over GH using token, cahcing it under ~/.zpr""" if os.path.isfile(CREDENTIALS_FILE): #cached token exists with open(CREDENTIALS_FILE, "r") as f: lines = [line.rstrip('\n') for line in f] if len(lines) >= 1: token = lines[0] return GitHub(token=token) try: user = inputFunc('GitHub username: '******'' while not password: password = getpass('Password for {0}: '.format(user)) note = 'zpr - keep PRs in sync with Trello!' note_url = 'https://github.com/bzz/z' scopes = ['user', 'repo'] auth = authorize(user, password, scopes, note, note_url) with open(CREDENTIALS_FILE, 'w+') as fd: fd.write(auth.token + '\n') print "Github token {} saved to {}".format(auth.token, CREDENTIALS_FILE) return GitHub(token=auth.token)
def _gen_authorization_token(self, counter=0, creds=None): """ This function creates the authorization token for AerisCloud. If an existing token exists for this computer, it adds a #N counter next to the name. """ if creds: user, pwd = creds['user'], creds['pwd'] else: (user, pwd) = self._ask_credentials() note = 'AerisCloud on %s' % (node()) if counter > 0: note += ' #%d' % counter try: auth = authorize(user, pwd, ['repo', 'read:org'], note=note, two_factor_callback=self._ask_2fa) return auth.token except GitHubError as e: if not e.errors or e.errors[0]['code'] != 'already_exists': raise # token exists, increment counter counter += 1 return self._gen_authorization_token(counter=counter, creds={'user': user, 'pwd': pwd})
def create_token(): user = getuser() password = '' while not password: password = getpass('Password for {}: '.format(user)) note = '{} on {}'.format(APPNAME, socket.gethostname()) note_url = 'https://irkernel.github.io/docs' scopes = [] try: auth = authorize(user, password, scopes, note, note_url, two_factor_callback=two_factor_callback) except UnprocessableEntity as e: print(e, file=sys.stderr) for err in e.errors: if err.get('field') == 'description' and err.get('code') == 'already_exists': print('please delete the token {!r} and try again'.format(note), file=sys.stderr) break else: print(e.errors, file=sys.stderr) if CREDENTIALS_FILE.is_file(): CREDENTIALS_FILE.unlink() sys.exit(1) CREDENTIALS_FILE.parent.mkdir(parents=True, exist_ok=True) with CREDENTIALS_FILE.open('w') as f: print(auth.token, file=f) print(auth.id, file=f) return login(token=auth.token)
def _login(self): """Logs into GitHub. Adapted from https://github.com/sigmavirus24/github-cli. TODO: Two factor authentication does not seem to be triggering the SMS code: https://github.com/sigmavirus24/github3.py/issues/387 Args: * None. Returns: None. """ # Get the full path to the configuration file config = self._github_config(self.CONFIG) parser = configparser.RawConfigParser() # Check to make sure the file exists and we are allowed to read it if os.path.isfile(config) and os.access(config, os.R_OK | os.W_OK): parser.readfp(open(config)) self.user_id = parser.get(self.CONFIG_SECTION, self.CONFIG_USER_ID) self.api = login(token=parser.get(self.CONFIG_SECTION, self.CONFIG_USER_TOKEN), two_factor_callback=self._two_factor_code) else: # Either the file didn't exist or we didn't have the correct # permissions self.user_id = '' while not user_id: user_id = input('Username: '******'' while not user_pass: user_pass = getpass('Password: '******'user', 'repo', 'gist'], note='githubcli', note_url='https://github.com/donnemartin/github-cli') except UnprocessableEntity: click.secho('Error creating token.\nVisit the following ' \ 'page and verify you do not have an existing ' \ 'token named "githubcli":\n' \ 'See https://github.com/settings/tokens\n' \ 'If a token already exists update your ' + \ self.githubconfig + ' file with your user_token.', fg='red') parser.add_section(self.CONFIG_SECTION) parser.set(self.CONFIG_SECTION, self.CONFIG_USER_ID, user_id) parser.set(self.CONFIG_SECTION, self.CONFIG_USER_PASS, user_pass) parser.set(self.CONFIG_SECTION, self.CONFIG_USER_TOKEN, auth.token) self.api = login(token=auth.token, two_factor_callback=self._two_factor_code) # Create the file if it doesn't exist. Otherwise completely blank # out what was there before. Kind of dangerous and destructive but # somewhat necessary parser.write(open(config, 'w+'))
def login(): # Do we have the credentials stored? c = ConfigParser() c.read(CONFIG_FILE) if c.has_section('credentials'): # Get the token from the config file token = c.get('credentials', 'token').strip() else: # Ask for credentials print("Please insert your GitHub credentials below:") user = input("Username: ").strip() password = getpass() auth = authorize(user, password, SCOPES, DESCRIPTION) token = auth.token # Save credentials to the config file c.add_section('credentials') c.set('credentials', 'token', str(token)) c.set('credentials', 'id', str(auth.id)) with open(CONFIG_FILE, 'w') as f: c.write(f) return github_login(token=token)
def create_token(self): import getpass import github3 # Asks user for username/password user = input("Please enter your GitHub username: "******"Please enter your GitHub password: "******"/!\\ WARNING /!\\ Bad GitHub credentials.") print( "Cannot access disease packages. Please contact %s for assistance." .format(self.SUPPORT_EMAIL)) sys.stdout.flush() raise self.AuthorizationError() # Write the info to disk # Update the (local) mysql db with the token from simtools.DataAccess.DataStore import DataStore DataStore.save_setting( DataStore.create_setting(key=self.auth_token_field, value=auth.token)) return auth.token
def get_session(): """Fetch and/or load API authorization token for GITHUB.""" ensure_config_dir() credential_file = os.path.join(CONFIG_DIR, 'github_auth') if os.path.isfile(credential_file): with open(credential_file) as fd: token = fd.readline().strip() gh = GitHub(token=token) try: # Test connection before starting gh.is_starred('github', 'gitignore') return gh except GitHubError as exc: raise_unexpected(exc.code) sys.stderr.write('Invalid saved credential file.\n') from getpass import getpass from github3 import authorize user = prompt('GITHUB Username') try: auth = authorize( user, getpass('Password for {0}: '.format(user)), 'repo', 'Farcy Code Reviewer', two_factor_callback=lambda: prompt('Two factor token')) except GitHubError as exc: raise_unexpected(exc.code) raise FarcyException(exc.message) with open(credential_file, 'w') as fd: fd.write('{0}\n{1}\n'.format(auth.token, auth.id)) return GitHub(token=auth.token)
def login(self): # FIXME: token is not working, still using basic auth token_path = os.path.join(BASE_DIR, '.ghtoken') if self.settings['STATKUBE_ACCESS_TOKEN']: gh_token = self.settings['STATKUBE_ACCESS_TOKEN'] else: if not os.path.exists(token_path): try: auth = authorize(self.settings['STATKUBE_USERNAME'], self.settings['STATKUBE_PASSWORD'], [], 'Statkube - fetch GH stats') except GitHubError as err: print( "ERROR authorization. Copy existing key from " "https://github.com/settings/tokens or delete it." "\n{}".format(err.msg)) return self.basic_login() gh_token = auth.token with open(token_path, 'w') as fp: fp.write(gh_token + '\n') else: with open(token_path) as fp: gh_token = fp.readline().strip() return login(token=gh_token)
def generate_auth_token(section, config_file=CREDENTIALS_FILE): def read_two_factor(): code = '' while not code: code = raw_input('Enter 2FA code: ') return code c = ConfigParser() c.add_section(section) username = raw_input('Enter GitHub username: '******'Enter GitHub password for {0}: '.format(username)) enterprise_url = raw_input( 'Enterprise URL (leave empty if using github.com): ') if enterprise_url: g = GitHubEnterprise(enterprise_url) auth = g.authorize(username, password, DEFAULT_SCOPE, OAUTH_NAME, OAUTH_SITE) c.set(section, 'url', enterprise_url) else: g = GitHub() auth = authorize(username, password, DEFAULT_SCOPE, OAUTH_NAME, OAUTH_SITE, two_factor_callback=read_two_factor) c.set(section, 'token', auth.token) with open(CREDENTIALS_FILE, 'a+') as f: c.write(f)
def emmet(spec, run, issue, sbatch, bb, yes, no_dupe_check, verbose): """Command line interface for emmet""" logger.setLevel(logging.DEBUG if verbose else logging.INFO) ctx = click.get_current_context() ctx.ensure_object(dict) if not sbatch and bb: raise EmmetCliError("Burst buffer only available in SBatch mode (--sbatch).") if spec: client = calcdb_from_mgrant(spec) ctx.obj["CLIENT"] = client # ctx.obj["MONGO_HANDLER"] = BufferedMongoHandler( # host=client.host, # port=client.port, # database_name=client.db_name, # username=client.user, # password=client.password, # level=logging.WARNING, # authentication_db=client.db_name, # collection="emmet_logs", # buffer_periodical_flush_timing=False, # flush manually # ) # logger.addHandler(ctx.obj["MONGO_HANDLER"]) # coll = ctx.obj["MONGO_HANDLER"].collection # ensure_indexes(SETTINGS.log_fields, [coll]) if run: if not issue: raise EmmetCliError(f"Need issue number via --issue!") ctx.obj["LOG_STREAM"] = StringIO() memory_handler = logging.StreamHandler(ctx.obj["LOG_STREAM"]) formatter = logging.Formatter( "%(asctime)s %(name)-12s %(levelname)-8s %(message)s" ) memory_handler.setFormatter(formatter) logger.addHandler(memory_handler) CREDENTIALS = os.path.join(os.path.expanduser("~"), ".emmet_credentials") if not os.path.exists(CREDENTIALS): user = click.prompt("GitHub Username") password = click.prompt("GitHub Password", hide_input=True) auth = authorize( user, password, ["user", "repo", "gist"], "emmet CLI", two_factor_callback=opt_prompt, ) with open(CREDENTIALS, "w") as fd: fd.write(auth.token) with open(CREDENTIALS, "r") as fd: token = fd.readline().strip() ctx.obj["GH"] = login(token=token) else: click.secho("DRY RUN! Add --run flag to execute changes.", fg="green") install_mp_handler(logger=logger)
def authorize_token(user): config = read_config(CREDENTIALS_FILE) if config.get('GitHub', 'token'): print("The token already exists.") sys.exit() password = getpass('Password for {0}: '.format(user)) note = 'OCA (odoo community association) Maintainers Tools' note_url = 'https://github.com/OCA/maintainers-tools' scopes = ['repo', 'read:org', 'write:org', 'admin:org'] try: auth = github3.authorize(user, password, scopes, note, note_url) except github3.GitHubError as err: if err.code == 422: for error in err.errors: if error['code'] == 'already_exists': msg = ("The 'OCA (odoo community association) Maintainers " "Tools' token already exists. You will find it at " "https://github.com/settings/applications and can " "revoke it or set the token manually in the " "configuration file.") sys.exit(msg) raise config.set("GitHub", "token", auth.token) with open(CREDENTIALS_FILE, 'w') as fd: config.write(fd) print("Token stored in configuration file")
def _get_github_client(credentials_file=os.path.expanduser('~/.gh-issue')): if not os.path.exists(credentials_file): user = raw_input('Enter github username: '******'Password for {0}: '.format(user)) auth = authorize( user, password, ['user', 'repo'], 'gh-issue', 'https://github.com/vmalloc/gh-issue', two_factor_callback=_read_two_factor_auth) logbook.debug('Got auth: {} ({})', auth.id, auth.token) with open(credentials_file, 'w') as fd: print(auth.token, file=fd) print(auth.id, file=fd) gh = login(token=auth.token) else: token = id = '' with open(credentials_file) as fd: token = fd.readline().strip() id = int(fd.readline().strip()) gh = login(token=token) #auth = gh.authorization(id) #auth.update(add_scopes=['repo:status', 'gist'], rm_scopes=['user']) return gh
def do_setup(token_file): logging.info("Beginning setup.\n") user = '' while not user: user = input('GitHub username: '******'' while not password: password = getpass('Password for {0}: '.format(user)) note = 'PullBot' note_url = 'http://github.com/greenape/pullbot' scopes = ['user', 'repo'] try: auth = authorize(user, password, scopes, note, note_url, two_factor_callback=two_factor) logging.info("Token acquired.\n") with open(token_file, 'w') as fd: fd.write("{}\n{}".format(auth.token, auth.id)) logging.info("Wrote token to {}.\n".format(token_file)) except Exception as e: logging.error("Auth failed: {}".format(e))
def github(): global _github # Have we made one earlier today? if _github is not None: return _github # See if we have a token _github = _github_w_token() if _github is not None: return _github password = getpass.getpass("Github user {0}, password [empty: read-only]: ".format(GITHUB_AUTH_USER)) if not password: _github = github3.GitHub() # anonymous return _github # Create OAuth token note = "github2jenkins" note_url = "https://github.com/stain/github2jenkins" auth = github3.authorize(GITHUB_AUTH_USER, password, GITHUB_SCOPES, note, note_url) print auth print auth.token print auth.id if not config().has_section("github"): config().add_section("github") config().set("github", "token", auth.token) config().set("github", "id", auth.id) save_config() return _github_w_token()
def _get_new_git_token(self, user, password): """ Get a newly refreshed token from Github :param user: :param password: :return: """ randstr = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(8)) note = user + '-token-' + randstr note_url = 'https://raw.githubusercontent.com/mpw07458/K8S-Deploy-Shell/master/pure-play/drivers/' \ 'K8S_App_Shell/src/tokens/' scopes = ['user', 'repo'] auth = authorize(user, password, scopes, note, note_url) print('Authorization token: ') pprint(auth.token) print('Authorization id: ') pprint(auth.id) strid = str(int(auth.id) + 1) print(strid) with open(self.gitcredsfile, 'w') as fd: fd.seek(0) fd.write(auth.token + '\n') fd.write(strid) pass
def login(self): # FIXME: token is not working, still using basic auth token_path = os.path.join(BASE_DIR, '.ghtoken') if self.settings['STATKUBE_ACCESS_TOKEN']: gh_token = self.settings['STATKUBE_ACCESS_TOKEN'] else: if not os.path.exists(token_path): try: auth = authorize( self.settings['STATKUBE_USERNAME'], self.settings['STATKUBE_PASSWORD'], [], 'Statkube - fetch GH stats') except GitHubError as err: print ("ERROR authorization. Copy existing key from " "https://github.com/settings/tokens or delete it." "\n{}".format(err.msg)) return self.basic_login() gh_token = auth.token with open(token_path, 'w') as fp: fp.write(gh_token + '\n') else: with open(token_path) as fp: gh_token = fp.readline().strip() return login(token=gh_token)
def attempt_auth(note): return github3.authorize(login=user_name, password=user_pwd, scopes=self.SCOPES, note_url=self._config["github_auth"]["url"], note=note, two_factor_callback=two_factor_callback)
def authorize_new_token(): username, password = _get_username_password() auth = github3.authorize(username, password, AUTH_SCOPES, AUTH_NOTE, AUTH_NOTE_URL) with open(CREDENTIALS_FILE, 'w') as fd: fd.write('{token}\n{id}'.format(token=auth.token, id=auth.id)) return github3.login(token=auth.token)
def get_github_token(): """Fetch and/or load API authorization token for Github.""" if isfile(const.GH_CREDENTIAL_FILE): with open(const.GH_CREDENTIAL_FILE) as file_descriptor: token = file_descriptor.readline().strip() auth_id = file_descriptor.readline().strip() return token, auth_id from github3 import authorize from getpass import getpass def two_factor_callback(): """Obtain input for 2FA token.""" stdout.write('Two factor token: ') stdout.flush() return stdin.readline().strip() user = input("Github admin username: ") auth = authorize(user, getpass('Password for {0}: '.format(user)), ['public_repo', 'admin:org'], 'Scalable Internet Services Create Repo Script {0}' .format(randint(100, 999)), 'http://example.com', two_factor_callback=two_factor_callback) with open(const.GH_CREDENTIAL_FILE, 'w') as file_descriptor: file_descriptor.write('{0}\n{1}\n'.format(auth.token, auth.id)) return auth.token, auth.id
def generate_token(github_client: github3.GitHub) -> str: ui.info_1("Creating new GitHub token") username = ui.ask_string("Please enter you GitHub username") password = getpass.getpass("Password: "******"repo"] # Need a different note for each device, otherwise # gh_api.authorize() will fail note = "tsrc-" + str(uuid.uuid4()) note_url = "https://TankerHQ.github.io/tsrc" def ask_2fa() -> str: return cast(str, ui.ask_string("2FA code: ")) authorization = github3.authorize( username, password, scopes, note=note, note_url=note_url, two_factor_callback=ask_2fa, github=github_client, ) return cast(str, authorization.token)
def token_request(): """Request app token from GitHub to operate gists""" try: prompt = raw_input except NameError: prompt = input user = prompt('GitHub username(default is {0}): '.format(getuser())) \ or getuser() password = '' while not password: password = getpass('GitHub password for {0}: '.format(user)) # Ensure github tokens have a unique description note = 'the unique pgist -> {0}'.format(uuid.uuid4()) note_url = 'https://github.com/douglarek/pgist' scopes = ['gist'] try: auth = authorize(user, password, scopes, note, note_url) except GitHubError as ghe: if 'two-factor' in str(ghe): raise SystemExit('GitHub 2-factor auth is not supported ' \ 'temporarily o(>_<)o, please disable it to use pgist !') raise SystemExit('Gist authorize failed, please check your username '\ 'or password!') with open(os.path.expanduser('~/.pgist'), 'w') as tkf: tkf.write(auth.token) click.echo('Done ...')
def __init__(self): token = id = '' try: with open(CREDENTIALS_FILE, 'r') as fd: token = fd.readline().strip() id = fd.readline().strip() except IOError: print "No token found. Requesting new." user = getuser() password = '' while not password: password = getpass('Password for {0}: '.format(user)) note = 'Trac2Github app' note_url = 'https://www.github.com/atiti/trac2github' scopes = ['user', 'repo'] auth = github3.authorize(user, password, scopes, note, note_url) with open(CREDENTIALS_FILE, 'w') as fd: fd.write(auth.token + '\n') fd.write(str(auth.id)) token = auth.token id = str(auth.id) self.gh = github3.login(token=token) print "We are in!"
def write_user_file(username, password, admin, email, realname, git_username, git_password, git_2fa=False): #this is used to write information into a text file to serve as a debugging tool and log #change logging=True to start logging userdir = prefix + "users" + os.sep f = open(userdir + username + '.ini', "w") f.write('username='******'\n') f.write('password='******'\n') f.write('realname=' + realname + '\n') f.write('admin=' + str(admin) + '\n') f.write('email=' + email + '\n') f.write('max-age=0' + '\n') f.write('editable=Yes' + '\n') f.write('numlogins = 85\nnumused = 2869\n') # get oauth token for github. Add current date to note since they need to be unique or an error will occur note = project + ", " + time.ctime() try: auth = github3.authorize(git_username, git_password, ['repo'], note, "") f.write('git_username='******'\n') f.write('git_token=' + auth.token + '\n') f.write('git_id=' + str(auth.id) + '\n') # in case we ever need to update authorizations f.write('git_2fa=' + str(git_2fa).lower() + '\n') except: # would be ideal to show an error, but just fail silently pass f.close()
def get_github_token(): """Fetch and/or load API authorization token for Github.""" credential_file = os.path.expanduser('~/.config/github_creds') if os.path.isfile(credential_file): with open(credential_file) as fd: token = fd.readline().strip() auth_id = fd.readline().strip() return token, auth_id from github3 import authorize from getpass import getuser, getpass def two_factor_callback(): sys.stdout.write('Two factor token: ') sys.stdout.flush() return sys.stdin.readline().strip() user = raw_input("Github admin username: ") auth = authorize(user, getpass('Password for {0}: '.format(user)), ['public_repo', 'admin:org'], 'Scalable Internet Services Create Repo Script {0}'.format(random.randint(100, 999)), 'http://example.com', two_factor_callback=two_factor_callback) with open(credential_file, 'w') as fd: fd.write('{0}\n{1}\n'.format(auth.token, auth.id)) return auth.token, auth.id
def get_github_token(self): """ Log in to the GitHub API, store the auth token for later use """ # Read in existing auth token if exists if os.path.isfile(self.gh_token): with open(self.gh_token, 'r') as f: return f.readline().strip() # Get authentication username = raw_input("Github username: "******"Password: "******"Github login failed. " \ "Please check your credentials." # Store auth token for later succ("Successfully logged into Github. Stored auth token in\n" "%s for later use." % self.gh_token) with open(self.gh_token, 'w') as f: f.write("%s\n%s" % (auth.token, auth.id)) return auth.token
def setupssett(settings): from github3 import login, authorize from getpass import getpass user = '' password = '' while not user: print "GitHub user name (will be asked only the first time): ", user = raw_input() while not password: password = getpass('GitHub password for {0}: '.format(user)) note = 'h2ggit.py' note_url = 'http://cern.ch/cms' scopes = ['user', 'repo'] auth = authorize(user, password, scopes, note, note_url) fout = open(settings,"w+") settings = { "token" : auth.token, "id" : auth.id, "user" : user } fout.write( json.dumps(settings) ) fout.close() run("chmod 600 %s " % fout,name,"") return login(token=auth.token), settings
def github(try_login=False): config_file = os.path.join(os.path.expanduser('~'), '.githubconfig-golem') old_umask = os.umask(63) # 0o077 shell = whelk.Shell() user = shell.git('config', '--file', config_file, 'github.user').stdout.strip() if not user and try_login: user = raw_input("Github user: "******"Github password: "******"Golem on %s" % socket.gethostname(), "http://seveas.github.com/golem") token = auth.token shell.git('config', '--file', config_file, 'github.token', token) shell.git('config', '--file', config_file, 'github.auth_id', str(auth.id)) if not user or not token: raise GolemError("No github credentials found, try golem --login github") gh = github3.login(username=user, token=token) try: gh.user() except github3.GitHubError: # Token obsolete shell.git('config', '--file', config_file, '--unset', 'github.token') gh = github(try_login) os.umask(old_umask) return gh
def setupssett(settings): from github3 import login, authorize from getpass import getpass user = '' password = '' while not user: print "GitHub user name (will be asked only the first time): ", user = raw_input() while not password: password = getpass('GitHub password for {0}: '.format(user)) note = 'h2ggit.py' note_url = 'http://cern.ch/cms' scopes = ['user', 'repo'] auth = authorize(user, password, scopes, note, note_url) fout = open(settings, "w+") settings = {"token": auth.token, "id": auth.id, "user": user} fout.write(json.dumps(settings)) fout.close() run("chmod 600 %s " % fout, name, "") return login(token=auth.token), settings
def test_authorize(self): if not self.auth: return authorization = github3.authorize(self.user, self.pw, ['user'], 'Test github3.py', 'https://github.com/sigmavirus24/github3.py') expect(authorization).isinstance(github3.github.Authorization) authorization._session.auth = (self.user, self.pw) expect(authorization.delete()).is_True()
def createCredentials(): note = 'Repo cloner' note_url = 'http://phooky.name' scopes = [ 'user', 'repo' ] user = getuser() password = getpass('GitHub password for {0}: '.format(user)) auth = authorize(user, password, scopes, note, note_url) with open(CREDENTIALS_PATH, 'w') as f: f.write(str(auth.token) + '\n' + str(auth.id) + '\n') f.close()
def createCredentials(): note = 'Repo cloner' note_url = 'http://phooky.name' scopes = ['user', 'repo'] user = getuser() password = getpass('GitHub password for {0}: '.format(user)) auth = authorize(user, password, scopes, note, note_url) with open(CREDENTIALS_PATH, 'w') as f: f.write(str(auth.token) + '\n' + str(auth.id) + '\n') f.close()
def get_auth(self): username = self.username password = self.password stamp = datetime.datetime.now( datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f%Z") note = self.NOTE.format(stamp=stamp) print(username, password) auth = github3.authorize(username, password, self.SCOPES, note, self.NOTE_URL) return auth
def github_token(self): if self._github_token is not None: return self._github_token token_note = "token for travis {}".format(datetime.datetime.utcnow().isoformat()) token = github3.authorize(config.data['gh_user'], config.data['gh_password'], scopes=('read:org', 'user:email', 'repo_deployment', 'repo:status', 'write:repo_hook'), note=token_note) self._github_token = token.token return self._github_token
def generate_github_token(): user = "" password = "" scopes = ['user', 'repo', 'write:repo_hook'] while not user: user = input('User: '******'Password: ') auth = authorize(user, password, scopes, "testing", "http://example.com") print("Token: {}".format(auth.token))
def get_token(): from github3 import authorize from getpass import getuser, getpass user = getuser() password = '' while not password: password = getpass('Password for {0}: '.format(user)) note = 'GitToTweet' note_url = 'http://valzevul.ru/' scopes = ['user', 'repo'] auth = authorize(user, password, scopes, note, note_url) with open(CREDENTIALS_FILE, 'w') as fd: fd.write(auth.token + '\n') fd.write(str(auth.id))
def _ask_for_token(): click.echo("Please enter your Github credential. They will not be " "recorded.") username = click.prompt("Username") password = click.prompt("Password", hide_input=True) auth = github3.authorize( username, password, ['user', 'repo'], note="Inbox application" ) with open(TOKEN_FILE, 'w+') as f: f.write("{}\n{}".format(auth.token, auth.id))
def handle(self, *args, **kwargs): user = raw_input("GitHub username: ") password = '' while not password: password = getpass('Password for {0}: '.format(user)) note = 'gitenberg website github token auth' note_url = 'http://www.gitenberg.org' scopes = ['user', 'repo'] auth = authorize(user, password, scopes, note, note_url) auth_token = GitHubAuthToken(auth_id=auth.id, token=auth.token) auth_token.save()
def create_auth_token(path=AUTH_TOKEN_FILE): create_auth_token_directory(path) username = six.moves.input('username: '******'password:'******'repo'], note='gaf', note_url='http://localhost', two_factor_callback=get_two_factor_authentication_code, ) with open(path, 'wb') as fp: buf = auth.as_json().encode() fp.write(buf) return auth
def get_git_token(self, user='', password=''): """Prompt for git token and save it in ~/.fab_token.git """ # Read token for file, return it if we already got it token = '' try: with open(os.path.join(self.local_dir, self.credentials_file), 'r') as fd_git: token = fd_git.readline().strip() # Can't hurt to be paranoid # id = fd.readline().strip() except IOError: pass if token: return token # Taken from # http://github3py.readthedocs.io/en/latest/examples/oauth.html while not user: user = prompt("Please enter your github username", default=getuser()) while not password: password = getpass('Please enter your github password for {0}: ' .format(user)) # Compute token note = 'Fab release by N3' note_url = 'http://numericube.com' scopes = ['user', 'repo'] try: auth = authorize(user, password, scopes, note, note_url, two_factor_callback=my_two_factor_function) with open(os.path.join(self.local_dir, self.credentials_file), 'w') as fdgit: fdgit.write(auth.token + '\n') # fd.write(auth.id) except GitHubError as exception: if exception.message == "Bad credentials": print red("ERROR: Invalid GitHub credentials") exit(0) elif exception.message == 'Validation Failed': # We probably already have an auth, find it back, # delete it and start again gith = github3.login(user, password) for auth in gith.iter_authorizations(): if (auth.note == note) and (auth.note_url == note_url): auth.delete() return self.get_git_token(user, password) # If we reach here, we just raise raise # Just return our token return auth.token
def authorize_token(user): config = read_config() if config.get('GitHub', 'token'): print("The token already exists.") sys.exit() password = getpass('Password for {0}: '.format(user)) note = 'OCA (odoo community association) Maintainers Tools' note_url = 'https://github.com/OCA/maintainers-tools' scopes = ['repo', 'read:org', 'write:org', 'admin:org'] try: # Python 2 prompt = raw_input except NameError: # Python 3 prompt = input def two_factor_prompt(): code = '' while not code: # The user could accidentally press Enter before being ready, # let's protect them from doing that. code = prompt('Enter 2FA code: ') return code try: auth = github3.authorize(user, password, scopes, note, note_url, two_factor_callback=two_factor_prompt) except github3.GitHubError as err: if err.code == 422: for error in err.errors: if error['code'] == 'already_exists': msg = ("The 'OCA (odoo community association) Maintainers " "Tools' token already exists. You will find it at " "https://github.com/settings/applications and can " "revoke it or set the token manually in the " "configuration file.") sys.exit(msg) raise config.set("GitHub", "token", auth.token) write_config(config) print("Token stored in configuration file")
def repo_token(self): if self._repo_token is not None: return self._repo_token token_note = "automatic releases for {} {}".format( self.repo_id,datetime.datetime.utcnow().isoformat() ) token = github3.authorize( config.data['gh_user'], config.data['gh_password'], scopes=('public_repo'), note=token_note ) self._repo_token = token.token return self._repo_token
def authorize(): username = input('Username: '******'s " % username) password = getpass(stream=sys.stderr) note = 'prs-since.py' note_url = 'http://github.com/rmcgibbo/prs-since' scopes = [] auth = github3.authorize( username, password, scopes, note, note_url, two_factor_callback=tfa_callback) store_token(auth) return load_token()
def login(): user = raw_input('Username: '******'' while not password: password = getpass('Password for {0}: '.format(user)) note = 'Ohj2710 autobuild uploader' note_url = 'https://github.com/Deraen/ohj2710' scopes = ['user', 'repo'] auth = github3.authorize(user, password, scopes, note, note_url) print(auth) with open(CREDENTIALS_FILE, 'w') as fd: fd.write(auth.token)
def get_github(): config_path = os.path.expanduser('~/.lbry-release-tool.json') if os.path.exists(config_path): with open(config_path, 'r') as config_file: config = json.load(config_file) return github3.login(token=config['token']) print('GitHub Credentials') username = input('username: '******'password: '******'repo'], 'lbry release tool', two_factor_callback=lambda: input('Enter 2FA: ') ) with open(config_path, 'w') as config_file: json.dump({'token': gh.token}, config_file) return github3.login(token=gh.token)
def get_gh_token(args): user = args.user password = '' while not password: password = getpass('Password for {}: '.format(user)) note = "Github Classroom Repo Downloader" note_url = "http://classroom.github.com" scopes = ['user', 'repo'] auth = authorize(user, password, scopes, note, note_url, two_factor_callback=twofac_callback) with open(CREDENTIALS_FILE, 'w') as fd: fd.write(auth.as_json()) return auth
def create_token(id = None, user=None, password=None): from github3 import authorize from getpass import getuser, getpass if not user: user = getuser() print "Enter github username [%s]:"%user, tmp = raw_input() if tmp: user = tmp password = '' while not password: password = getpass('Password for {0}: '.format(user)) scopes = ['user', 'repo'] auth = authorize(user, password, scopes, id, 'http://nsclient.org') return auth.token
def login(): token = get_token() if not token: user = raw_input("Github login: "******"" while not password: password = getpass("Password for {0}: ".format(user)) note = "SDLMetricsCollector" note_url = "https://github.com/LuxoftAKutsan/SDLMetricsCollector" scopes = ["user", "repo"] auth = github3.authorize(user, password, scopes, note, note_url) with open(CREDENTIALS_FILE, "w") as fd: print(auth) fd.write(auth.token + "\n") fd.write(auth.id) fd.close() return login() return github3.login(token=token)
def github(self): url = self.config.get("github", "url") # TODO: This is only used to create the key, but we shall add support # github enterprise as well key = "lancet+{}".format(url) username = self.config.get("github", "username") token = keyring.get_password(key, username) if not token: def two_factor_callback(): with taskstatus.suspend(): return click.prompt("2-factor auth code") with taskstatus.suspend(): while True: click.echo("Please provide your authentication information for {}".format(url)) if not username: username = click.prompt("Username") else: click.echo("Username: {}".format(username)) password = click.prompt("Password", hide_input=True) with taskstatus("Getting authorization token") as ts: scopes = ["user", "repo"] try: auth = github3.authorize( username, password, scopes, "Lancet", __url__, two_factor_callback=two_factor_callback ) except github3.GitHubError as e: ts.fail("Login failed ({})", e) username, password = None, None continue else: ts.ok("New token correctly generated") break token = "{}:{}".format(auth.id, auth.token) keyring.set_password(key, username, token) id, token = token.split(":", 1) gh = github3.login(token=token) self.call_on_close(gh._session.close) return gh
def authorize(credentials_file, scopes, note, note_url): if os.path.exists(credentials_file): token = id = "" with open(credentials_file, "r") as fd: token = fd.readline().strip() id = fd.readline().strip() else: from getpass import getpass username = input("Username: "******"" while not password: password = getpass("Password for {0}: ".format(username)) auth = github3.authorize(username, password, scopes, note, note_url, two_factor_callback=two_factor_function) with open(credentials_file, "w") as fd: fd.write(auth.token + "\n" + str(auth.id)) token = auth.token id = str(auth.id) gh = github3.login(token=token) return gh
def login(): token, id = get_token() if not token: user = raw_input("Github login: "******"SDLMetricsCollector_hash" + randomword(10) note_url = "https://github.com/LuxoftAKutsan/SDLMetricsCollector" scopes = ['user', 'repo'] auth = github3.authorize(user, password, scopes, note, note_url) with open(CREDENTIALS_FILE, 'w') as fd: print("token %s" %auth.token) print("id %s" %auth.id) fd.write(str(auth.token) + '\n') fd.write(str(auth.id)) fd.close() return login() return github3.login(token=token)