Authenticate GitHub user.
160639
public function githubAuth()
    {
        if ($this->hasAuth()) {
            $this->io()->warning(
                'A personal GitHub access token has already been setup.'
            );

            return;
        }
        $this->io()->note("A personal GitHub access token is required.\n\n" .
            'If you need help setting up a access token follow the GitHub guide:' .
            ' https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/');

        $user = $this->ask('GitHub username:');
        $pass = $this->askHidden('GitHub token (hidden):');

        $status = $this->gitHubUserAuth()
            ->setUser($user)
            ->setToken($pass)
            ->save();

        if (!$status) {
            $this->io()->success(
                "You've successfully added your personal GitHub access token."
            );
        }
    }
842732
def GitHub_post(data, url, *, auth, headers):
    
    r = requests.post(url, auth=auth, headers=headers, data=json.dumps(data))
    GitHub_raise_for_status(r)
    return r.json()
662405
function getUser (argv, next) {
  if (argv.user) return next()

  const conf = rc('npm')
  if (!conf) return next('no npm config found')

  const github = conf['init.author.github']
  if (!github) return next('no init.author.github set')

  const name = conf['init.author.name']
  if (!name) return next('no init.author.name set')

  argv.user = github
  argv.realName = name
  next()
}
1261258
def account_setup(remote, token, resp):
    
    gh = github3.login(token=resp['access_token'])
    with db.session.begin_nested():
        me = gh.me()

        token.remote_account.extra_data = {'login': me.login, 'id': me.id}

        # Create user <-> external id link.
        oauth_link_external_id(
            token.remote_account.user, dict(
                id=str(me.id),
                method='github')
        )
1243386
def _authenticate(self):
        """"""
        if not self._get_provider_option(
                'auth_username') or not self._get_provider_option('auth_password'):
            raise Exception(
                'No valid authentication data passed, expected: auth-username and auth-password')
        response = self._request_login(self._get_provider_option('auth_username'),
                                       self._get_provider_option('auth_password'))
        if 'ssid' in response:
            self.ssid = response['ssid']
            domains = self.domains_list()
            if any((domain['name'] == self.domain for domain in domains)):
                self.domain_id = self.domain
            else:
                raise Exception("Unknown domain {}".format(self.domain))
        else:
            raise Exception("No SSID provided by server")
220959
def construct_auth (self):
        """"""
        if self.auth:
            return
        _user, _password = self.get_user_password()
        if _user is not None and _password is not None:
            self.auth = (_user, _password)
1249986
def _authenticate_https(org):
    """"""
    _CREDENTIAL_SOCKET.parent.mkdir(mode=0o700, exist_ok=True)
    try:
        Git.cache = f"-c credential.helper= -c credential.helper='cache --socket {_CREDENTIAL_SOCKET}'"
        git = Git(Git.cache)

        # Get credentials from cache if possible
        with _spawn(git("credential fill"), quiet=True) as child:
            child.sendline("protocol=https")
            child.sendline("host=github.com")
            child.sendline("")
            i = child.expect(["Username for '.+'", "Password for '.+'",
                              "username=([^\r]+)\r\npassword=([^\r]+)\r\n"])
            if i == 2:
                username, password = child.match.groups()
            else:
                username = password = None
                child.close()
                child.exitstatus = 0

        # No credentials found, need to ask user
        if password is None:
            username = _prompt_username(_("GitHub username: "))
            password = _prompt_password(_("GitHub password: "))

        # Check if credentials are correct
        res = requests.get("https://api.github.com/user", auth=(username, password))

        # Check for 2-factor authentication https://developer.github.com/v3/auth/#working-with-two-factor-authentication
        if "X-GitHub-OTP" in res.headers:
            raise Error("Looks like you have two-factor authentication enabled!"
                        " Please generate a personal access token and use it as your password."
                        " See https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line for more info.")

        if res.status_code != 200:
            logger.info(res.headers)
            logger.info(res.text)
            raise Error(_("Invalid username and/or password.") if res.status_code ==
                        401 else _("Could not authenticate user."))

        # Canonicalize (capitalization of) username,
        # Especially if user logged in via email address
        username = res.json()["login"]

        # Credentials are correct, best cache them
        with _spawn(git("-c credentialcache.ignoresighup=true credential approve"), quiet=True) as child:
            child.sendline("protocol=https")
            child.sendline("host=github.com")
            child.sendline(f"path={org}/{username}")
            child.sendline(f"username={username}")
            child.sendline(f"password={password}")
            child.sendline("")

        yield User(name=username,
                   repo=f"https://{username}@github.com/{org}/{username}")
    except BaseException:
        # Some error occured while this context manager is active, best forget credentials.
        logout()
        raise
356275
def authenticate(username, password, permission=None):
    
    try:
        author = Author.objects.get(
            **{'%s__exact' % Author.USERNAME_FIELD: username})
    except Author.DoesNotExist:
        raise Fault(LOGIN_ERROR, _('Username is incorrect.'))
    if not author.check_password(password):
        raise Fault(LOGIN_ERROR, _('Password is invalid.'))
    if not author.is_staff or not author.is_active:
        raise Fault(PERMISSION_DENIED, _('User account unavailable.'))
    if permission:
        if not author.has_perm(permission):
            raise Fault(PERMISSION_DENIED, _('User cannot %s.') % permission)
    return author
1026034
def create(cls, user_id, github_id=None, name=None, **kwargs):
        """"""
        with db.session.begin_nested():
            obj = cls(user_id=user_id, github_id=github_id, name=name,
                      **kwargs)
            db.session.add(obj)
        return obj
701446
function GithubAuth() {

  var opts = {
    version: '3.0.0',
    timeout: 30000
  };

  var proxy = bag.proxy();
  if (proxy) {
    proxy = url.parse(proxy);
    opts.proxy = {
      host: proxy.hostname,
      port: proxy.port
    };
  }

  this.gh = new github(opts);
}
455542
def authenticate(self, api_key):
        """"""
        self._api_key = api_key

        # Attach auth to session.
        self._session.auth = ('', self._api_key)

        return self._verify_api_key()
506848
def _authenticate_client(self, client):
        """"""
        if self.login and not self.restart_required:
            try:
                db = client[self.auth_source]
                if self.x509_extra_user:
                    db.authenticate(
                        DEFAULT_SUBJECT,
                        mechanism='MONGODB-X509'
                    )
                else:
                    db.authenticate(
                        self.login, self.password)
            except Exception:
                logger.exception(
                    "Could not authenticate to %r as %s/%s"
                    % (client, self.login, self.password))
                raise
214869
def _get_github(self):
        
        from github import Github
        vms("Querying github with user '{}'.".format(self.username))
        g = Github(self.username, self.apikey)
        self._user = g.get_user()
        if self._user is None:
            raise ValueError("Can't authenticate to github with '{}'.".format(self.username))
        #The github user authenticating always has to be specified; however the user
        #may not be able to see the repo, even if it has access to it. We may need
        #to check the organization repos.
        if self.organization is not None:
            self._org = g.get_organization(self.organization)
            vms("Found github organization '{}'.".format(self._org.name), 2)

            #Next we need to find this repository in the lists available to both
            #the user *and* the organization. If they specified an organization, then we
            #should check that first/exclusively.
            for repo in self._org.get_repos():
                if repo.full_name.lower() == self.name.lower():
                    self._repo = repo
                    vms("Found organization repository '{}'.".format(self._repo.full_name), 2)
                    break
        else:
            for repo in self._user.get_repos():
                if repo.full_name.lower() == self.name.lower():
                    self._repo = repo
                    vms("Found user repository '{}'.".format(self._repo.full_name), 2)
                    break
479736
def run():
    """"""
    args = parse_args()

    appname = sys.argv[0]
    hostname = platform.node()

    codetools.setup_logging(args.debug)

    password = ''

    if args.token_path is None and args.delete_role is True:
        cred_path = os.path.expanduser('~/.sq_github_token_delete')
    elif args.token_path is None and args.delete_role is False:
        cred_path = os.path.expanduser('~/.sq_github_token')
    else:
        cred_path = os.path.expandvars(os.path.expanduser(args.token_path))

    if not os.path.isfile(cred_path):
        print("""
        Type in your password to get an auth token from github
        It will be stored in {0}
        and used in subsequent occasions.
        """.format(cred_path))

        while not password:
            password = getpass('Password for {0}: '.format(args.user))

        note = textwrap.dedent("""\
            {app} via bored^H^H^H^H^H terrified opossums[1]
            on {host}
            by {user} {creds}
            [1] https://youtu.be/ZtLrn2zPTxQ?t=1m10s
            """).format(
            app=appname,
            host=hostname,
            user=args.user,
            creds=cred_path
        )
        note_url = 'https://www.youtube.com/watch?v=cFvijBpzD_Y'

        if args.delete_role:
            scopes = ['repo', 'user', 'delete_repo', 'admin:org']
        else:
            scopes = ['repo', 'user']

        global g
        g = github.Github(args.user, password)
        u = g.get_user()

        try:
            auth = u.create_authorization(
                scopes=scopes,
                note=note,
                note_url=note_url,
            )
        except github.TwoFactorException:
            auth = u.create_authorization(
                scopes=scopes,
                note=note,
                note_url=note_url,
                # not a callback
                onetime_password=codetools.github_2fa_callback()
            )
        g = github.Github(auth.token)

        with open(cred_path, 'w') as fdo:
            fdo.write(auth.token + '\n')
            fdo.write(str(auth.id))

        print('Token written to {0}'.format(cred_path))

    else:
        print("You already have an auth file: {0} ".format(cred_path))
        print("Delete it if you want a new one and run again")
        print("Remember to also remove the corresponding token on Github")
356376
def _authenticate(self):
        """"""
        data = {'username': self.username,
                'password': self.password}
        url = '{base}/client/login'.format(base=self.base_url)
        response = self._session.get(url, params=data)
        print(response.text)
        data = response.json()
        if not data.get('success'):
            raise InvalidCredentials(data.get('reason', None))
        self._populate_info(data)
214026
def get_user(self, login=github.GithubObject.NotSet):
        
        assert login is github.GithubObject.NotSet or isinstance(login, (str, unicode)), login
        if login is github.GithubObject.NotSet:
            return AuthenticatedUser.AuthenticatedUser(self.__requester, {}, {"url": "/user"}, completed=False)
        else:
            headers, data = self.__requester.requestJsonAndCheck(
                "GET",
                "/users/" + login
            )
            return github.NamedUser.NamedUser(self.__requester, headers, data, completed=True)
990960
def authenticate_user(self, response, **kwargs):
        """"""

        host = urlparse(response.url).hostname

        try:
            auth_header = self.generate_request_header(response, host)
        except KerberosExchangeError:
            # GSS Failure, return existing response
            return response

        log.debug("authenticate_user(): Authorization header: {0}".format(
            auth_header))
        response.request.headers['Authorization'] = auth_header

        # Consume the content so we can reuse the connection for the next
        # request.
        response.content
        response.raw.release_conn()

        _r = response.connection.send(response.request, **kwargs)
        _r.history.append(response)

        log.debug("authenticate_user(): returning {0}".format(_r))
        return _r