Python github3.authorize() Examples

The following are 10 code examples of github3.authorize(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module github3 , or try the search function .
Example #1
Source File: release.py    From lbry-sdk with MIT License 6 votes vote down vote up
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'])

    token = os.environ.get("GH_TOKEN")
    if not token:
        print('GitHub Credentials')
        username = input('username: ')
        password = getpass('password: ')
        gh = github3.authorize(
            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)
        token = gh.token
    return github3.login(token=token) 
Example #2
Source File: helpers.py    From farcy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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) 
Example #3
Source File: __init__.py    From CaveJohnson with MIT License 5 votes vote down vote up
def github_auth():
    if os.path.exists(CREDENTIALS_FILE):
        with open(CREDENTIALS_FILE) as f:
            token = f.read().strip()
            return token

    from github3 import authorize
    from getpass import getpass
    user = ''
    while not user:
        user = input("Username: ")
    password = ''
    while not password:
        password = getpass('Password for {0}: '.format(user))
    note = 'cavejohnson, teaching Xcode 6 CI new tricks'
    note_url = 'http://sealedabstract.com'
    scopes = ['repo:status', 'repo']
    auth = authorize(user, password, scopes, note, note_url)

    with open(CREDENTIALS_FILE, "w") as f:
        f.write(auth.token)

    return auth.token


# rdar://17923022 
Example #4
Source File: gitconsensus.py    From GitConsensusCLI with MIT License 5 votes vote down vote up
def auth():
    username = click.prompt('Username')
    password = click.prompt('Password', hide_input=True)
    def twofacallback(*args):
        return click.prompt('2fa Code')

    hostid = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8))
    note = 'gitconsensus - %s' % (hostid,)
    note_url = 'https://github.com/tedivm/GitConsensus'
    scopes = ['repo']
    auth = github3.authorize(username, password, scopes, note, note_url, two_factor_callback=twofacallback)

    with open("%s/%s" % (os.getcwd(), '/.gitcredentials'), 'w') as fd:
        fd.write(str(auth.id) + '\n')
        fd.write(auth.token + '\n') 
Example #5
Source File: github_login.py    From maintainer-tools with GNU Affero General Public License v3.0 4 votes vote down vote up
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/tokens 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") 
Example #6
Source File: get_year_commits.py    From scraper with MIT License 4 votes vote down vote up
def login(self, username="", password=""):
        """
        Performs a login and sets the Github object via given credentials. If
        credentials are empty or incorrect then prompts user for credentials.
        Stores the authentication token in a CREDENTIALS_FILE used for future
        logins. Handles Two Factor Authentication.
        """
        try:

            token = ""
            id = ""
            if not os.path.isfile("CREDENTIALS_FILE"):
                if username == "" or password == "":
                    username = raw_input("Username: ")
                    password = getpass.getpass("Password: ")
                note = "GitHub Organization Stats App"
                note_url = "http://software.llnl.gov/"
                scopes = ["user", "repo"]
                auth = github3.authorize(
                    username,
                    password,
                    scopes,
                    note,
                    note_url,
                    two_factor_callback=self.prompt_2fa,
                )
                token = auth.token
                id = auth.id
                with open("CREDENTIALS_FILE", "w+") as fd:
                    fd.write(token + "\n")
                    fd.write(str(id))
                fd.close()
            else:
                with open("CREDENTIALS_FILE", "r") as fd:
                    token = fd.readline().strip()
                    id = fd.readline().strip()
                fd.close()
            print("Logging in.")
            self.logged_in_gh = github3.login(
                token=token, two_factor_callback=self.prompt_2fa
            )
            self.logged_in_gh.user().to_json()
        except (ValueError, AttributeError, github3.models.GitHubError):
            print("Bad credentials. Try again.")
            self.login() 
Example #7
Source File: get_users_emails.py    From scraper with MIT License 4 votes vote down vote up
def login(self, username="", password=""):
        """
        Performs a login and sets the Github object via given credentials. If
        credentials are empty or incorrect then prompts user for credentials.
        Stores the authentication token in a CREDENTIALS_FILE used for future
        logins. Handles Two Factor Authentication.
        """
        try:

            token = ""
            id = ""
            if not os.path.isfile("CREDENTIALS_FILE"):
                if username == "" or password == "":
                    username = raw_input("Username: ")
                    password = getpass.getpass("Password: ")
                note = "GitHub Organization Stats App"
                note_url = "http://software.llnl.gov/"
                scopes = ["user", "repo"]
                auth = github3.authorize(
                    username,
                    password,
                    scopes,
                    note,
                    note_url,
                    two_factor_callback=self.prompt_2fa,
                )
                token = auth.token
                id = auth.id
                with open("CREDENTIALS_FILE", "w+") as fd:
                    fd.write(token + "\n")
                    fd.write(str(id))
                fd.close()
            else:
                with open("CREDENTIALS_FILE", "r") as fd:
                    token = fd.readline().strip()
                    id = fd.readline().strip()
                fd.close()
            print("Logging in.")
            self.logged_in_gh = github3.login(
                token=token, two_factor_callback=self.prompt_2fa
            )
            self.logged_in_gh.user().to_json()
        except (ValueError, AttributeError, github3.models.GitHubError):
            print("Bad credentials. Try again.")
            self.login() 
Example #8
Source File: get_traffic.py    From scraper with MIT License 4 votes vote down vote up
def login(self, username="", password=""):
        """
        Performs a login and sets the Github object via given credentials. If
        credentials are empty or incorrect then prompts user for credentials.
        Stores the authentication token in a CREDENTIALS_FILE used for future
        logins. Handles Two Factor Authentication.
        """
        try:

            self.token = ""
            id = ""
            if not os.path.isfile("CREDENTIALS_FILE_ADMIN"):
                if username == "" or password == "":
                    username = raw_input("Username: ")
                    password = getpass.getpass("Password: ")
                note = "GitHub Organization Stats App"
                note_url = "http://software.llnl.gov/"
                scopes = ["user", "repo"]
                auth = github3.authorize(
                    username,
                    password,
                    scopes,
                    note,
                    note_url,
                    two_factor_callback=self.prompt_2fa,
                )
                self.token = auth.token
                id = auth.id
                with open("CREDENTIALS_FILE_ADMIN", "w+") as fd:
                    fd.write(self.token + "\n")
                    fd.write(str(id))
                fd.close()
            else:
                with open("CREDENTIALS_FILE_ADMIN", "r") as fd:
                    self.token = fd.readline().strip()
                    id = fd.readline().strip()
                fd.close()
            print("Logging in.")
            self.logged_in_gh = github3.login(
                token=self.token, two_factor_callback=self.prompt_2fa
            )
            self.logged_in_gh.user().to_json()
        except (ValueError, AttributeError, github3.models.GitHubError):
            print("Bad credentials. Try again.")
            self.login() 
Example #9
Source File: get_stargazers.py    From scraper with MIT License 4 votes vote down vote up
def login(self, username="", password=""):
        """
        Performs a login and sets the Github object via given credentials. If
        credentials are empty or incorrect then prompts user for credentials.
        Stores the authentication token in a CREDENTIALS_FILE used for future
        logins. Handles Two Factor Authentication.
        """
        try:

            self.token = ""
            id = ""
            if not os.path.isfile("CREDENTIALS_FILE"):
                if username == "" or password == "":
                    username = raw_input("Username: ")
                    password = getpass.getpass("Password: ")
                note = "GitHub Organization Stats App"
                note_url = "http://software.llnl.gov/"
                scopes = ["user", "repo"]
                auth = github3.authorize(
                    username,
                    password,
                    scopes,
                    note,
                    note_url,
                    two_factor_callback=self.prompt_2fa,
                )
                self.token = auth.token
                id = auth.id
                with open("CREDENTIALS_FILE", "w+") as fd:
                    fd.write(self.token + "\n")
                    fd.write(str(id))
                fd.close()
            else:
                with open("CREDENTIALS_FILE", "r") as fd:
                    self.token = fd.readline().strip()
                    id = fd.readline().strip()
                fd.close()
            print("Logging in.")
            self.logged_in_gh = github3.login(
                token=self.token, two_factor_callback=self.prompt_2fa
            )
            self.logged_in_gh.user().to_json()
        except (ValueError, AttributeError, github3.models.GitHubError):
            print("Bad credentials. Try again.")
            self.login() 
Example #10
Source File: github_stats.py    From scraper with MIT License 4 votes vote down vote up
def login(self, username="", password=""):
        """
        Performs a login and sets the Github object via given credentials. If
        credentials are empty or incorrect then prompts user for credentials.
        Stores the authentication token in a CREDENTIALS_FILE used for future
        logins. Handles Two Factor Authentication.
        """
        try:

            self.token = ""
            id = ""
            if not os.path.isfile("CREDENTIALS_FILE"):
                if username == "" or password == "":
                    username = raw_input("Username: ")
                    password = getpass.getpass("Password: ")
                note = "GitHub Organization Stats App"
                note_url = "http://software.llnl.gov/"
                scopes = ["user", "repo"]
                auth = github3.authorize(
                    username,
                    password,
                    scopes,
                    note,
                    note_url,
                    two_factor_callback=self.prompt_2fa,
                )
                self.token = auth.token
                id = auth.id
                with open("CREDENTIALS_FILE", "w+") as fd:
                    fd.write(self.token + "\n")
                    fd.write(str(id))
                fd.close()
            else:
                with open("CREDENTIALS_FILE", "r") as fd:
                    self.token = fd.readline().strip()
                    id = fd.readline().strip()
                fd.close()
            print("Logging in.")
            self.logged_in_gh = github3.login(
                token=self.token, two_factor_callback=self.prompt_2fa
            )
            self.logged_in_gh.user().to_json()
        except (ValueError, AttributeError, github3.models.GitHubError):
            print("Bad credentials. Try again.")
            self.login()