Store and fetch a GitHub access token
197287
def token(config, token):
    """"""
    if not token:
        info_out(
            "To generate a personal API token, go to:\n\n\t"
            "https://github.com/settings/tokens\n\n"
            "To read more about it, go to:\n\n\t"
            "https://help.github.com/articles/creating-an-access"
            "-token-for-command-line-use/\n\n"
            'Remember to enable "repo" in the scopes.'
        )
        token = getpass.getpass("GitHub API Token: ").strip()
    url = urllib.parse.urljoin(config.github_url, "/user")
    assert url.startswith("https://"), url
    response = requests.get(url, headers={"Authorization": "token {}".format(token)})
    if response.status_code == 200:
        update(
            config.configfile,
            {
                "GITHUB": {
                    "github_url": config.github_url,
                    "token": token,
                    "login": response.json()["login"],
                }
            },
        )
        name = response.json()["name"] or response.json()["login"]
        success_out("Hi! {}".format(name))
    else:
        error_out("Failed - {} ({})".format(response.status_code, response.content))
99329
def _get_api_content(self):
        """"""

        if GITHUB_TOKEN is not None:
            self.add_params_to_url({
                "access_token": GITHUB_TOKEN
            })

        api_content_response = requests.get(self.api_url)
        self.api_content = json.loads(
            api_content_response.text
        )
743398
def github_setup(self):
        """"""
        github_auth = self.authenticate()
        github_username = github_auth[0]

        expt_name = self.config.get('name', self.expt.name)
        expt_description = self.expt.config.get('description')
        if not expt_description:
            expt_description = input('Briefly describe the experiment: ')
            assert isinstance(expt_description, str)
        expt_private = self.config.get('private', False)

        # 1. Create the organisation if needed
        github_api_url = 'https://api.github.com'
        org_name = self.config.get('organization')
        if org_name:
            repo_target = org_name

            # Check if org exists
            org_query_url = os.path.join(github_api_url, 'orgs', org_name)
            org_req = requests.get(org_query_url)

            if org_req.status_code == 404:
                # NOTE: Orgs cannot be created via the API
                print('payu: github organization {org} does not exist.'
                      ''.format(org=org_name))
                print('      You must first create this on the website.')

            elif org_req.status_code == 200:
                # TODO: Confirm that the user can interact with the repo
                pass

            else:
                # TODO: Exit with grace
                print('payu: abort!')
                sys.exit(-1)

            repo_query_url = os.path.join(github_api_url, 'orgs', org_name,
                                          'repos')
            repo_api_url = os.path.join(github_api_url, 'repos', org_name,
                                        expt_name)
        else:
            repo_target = github_username

            # Create repo in user account
            repo_query_url = os.path.join(github_api_url, 'user', 'repos')
            repo_api_url = os.path.join(github_api_url, 'repos',
                                        github_username, expt_name)

        # 2. Create the remote repository
        user_repos = []
        page = 1
        while True:
            repo_params = {'page': page, 'per_page': 100}
            repo_query = requests.get(repo_query_url, auth=github_auth,
                                      params=repo_params)
            assert repo_query.status_code == 200
            if repo_query.json():
                user_repos.extend(list(r['name'] for r in repo_query.json()))
                page += 1
            else:
                break

        if expt_name not in user_repos:
            repo_config = {
                'name': expt_name,
                'description': expt_description,
                'private': expt_private,
                'has_issues': True,
                'has_downloads': True,
                'has_wiki': False
            }

            repo_gen = requests.post(repo_query_url, json.dumps(repo_config),
                                     auth=github_auth)

            assert repo_gen.status_code == 201

        # 3. Check if remote is set
        git_remote_out = subprocess.check_output(shlex.split('git remote -v'),
                                                 cwd=self.expt.control_path)

        git_remotes = dict([(r.split()[0], r.split()[1])
                            for r in git_remote_out.split('\n') if r])

        remote_name = self.config.get('remote', 'payu')
        remote_url = os.path.join('ssh://git@github.com', repo_target,
                                  self.expt.name + '.git')

        if remote_name not in git_remotes:
            cmd = ('git remote add {name} {url}'
                   ''.format(name=remote_name, url=remote_url))
            subprocess.check_call(shlex.split(cmd), cwd=self.expt.control_path)
        elif git_remotes[remote_name] != remote_url:
            print('payu: error: Existing remote URL does not match '
                  'the proposed URL.')
            print('payu: error: To delete the old remote, type '
                  '`git remote rm {name}`.'.format(name=remote_name))
            sys.exit(-1)

        # 4. Generate a payu-specific SSH key
        default_ssh_key = 'id_rsa_payu_' + expt_name
        ssh_key = self.config.get('sshid', default_ssh_key)
        ssh_dir = os.path.join(os.path.expanduser('~'), '.ssh', 'payu')
        mkdir_p(ssh_dir)

        ssh_keypath = os.path.join(ssh_dir, ssh_key)
        if not os.path.isfile(ssh_keypath):
            cmd = 'ssh-keygen -t rsa -f {key} -q -P ""'.format(key=ssh_key)
            subprocess.check_call(shlex.split(cmd), cwd=ssh_dir)

        # 5. Deploy key to repo
        with open(ssh_keypath + '.pub') as keyfile:
            pubkey = ' '.join(keyfile.read().split()[:-1])

        # TODO: Get this from github?
        repo_keys_url = os.path.join(repo_api_url, 'keys')
        keys_req = requests.get(repo_keys_url, auth=github_auth)
        assert keys_req.status_code == 200

        if not any(k['key'] == pubkey for k in keys_req.json()):
            add_key_param = {'title': 'payu', 'key': pubkey}
            add_key_req = requests.post(repo_keys_url, auth=github_auth,
                                        json=add_key_param)
            assert add_key_req.status_code == 201
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)
830845
def _dev_api(cls):
        """"""
        gh = github3.GitHub()
        gh.set_client_id(cls.remote.consumer_key, cls.remote.consumer_secret)
        return gh
388123
function getUserCredentials() {
  return new Promise((resolve) => {
    print(clc.bold('Sign in to authorize this app to find open pull-requests'), true);
    gitUser.email((err, email) => {
      prompt.message = '';
      prompt.delimiter = '';
      prompt.start();
      prompt.get({
        properties: {
          username: {
            description: 'Github username',
            default: email,
            message: 'Name must be only letters, spaces, or dashes',
            required: true
          },
          password: {
            description: 'Github password',
            hidden: true
          }
        }
      }, (err, result) => {
        resolve(result);
      });
    });
  });
}
733620
def get_auth():
    """"""
    import getpass
    user = input("User Name: ")  # noqa
    pswd = getpass.getpass('Password: ')
    return Github(user, pswd)
547802
def get_json(uri):
    
    response = requests.get(API + uri, headers=HEADERS)

    limit = int(response.headers.get("x-ratelimit-remaining"))
    if limit == 0:
        sys.stdout.write("\n")
        message = "You have run out of GitHub request tokens. "

        if int(response.headers.get("x-ratelimit-limit")) == 60:
            message += "Set a GITHUB_TOKEN to increase your limit to 5000/hour. "

        wait_seconds = int(response.headers.get("x-ratelimit-reset")) - int(time.time())
        wait_minutes = math.ceil(wait_seconds / 60)
        message += "Try again in ~%d minutes. " % wait_minutes

        if "--wait-for-reset" in sys.argv:
            progress_message(message.replace("Try ", "Trying "))
            time.sleep(wait_seconds + 1)
            progress_message("Resuming")
            return get_json(uri)
        else:
            raise ValueError(message)

    progress()
    return response.json()
439171
def get_access_token(self, request, callback=None):
        ""
        raw_token = request.session.get(self.session_key, None)
        verifier = request.GET.get('oauth_verifier', None)
        if raw_token is not None and verifier is not None:
            data = {'oauth_verifier': verifier}
            callback = request.build_absolute_uri(callback or request.path)
            callback = force_text(callback)
            try:
                response = self.request('post', self.provider.access_token_url,
                                        token=raw_token, data=data, oauth_callback=callback)
                response.raise_for_status()
            except RequestException as e:
                logger.error('Unable to fetch access token: {0}'.format(e))
                return None
            else:
                return response.text
        return None
723577
def get_access_token(self, code):
        """"""
        try:
            self._token = super().fetch_token(
                MINUT_TOKEN_URL,
                client_id=self._client_id,
                client_secret=self._client_secret,
                code=code,
            )
        # except Exception as e:
        except MissingTokenError as error:
            _LOGGER.debug("Token issues: %s", error)
        return self._token
469257
function (req, res, next) {
    if (!req.headers[authHeader]) {
      next();
      return;
    }
    var profile = req.profile;
    User.find({ where: { github: profile.id }}, function(err, users) {
      var user = users[0];
      if (user) {
        res.status(409).send({ message: 'There is already a GitHub account that belongs to you' });
        return;
      }
      var token = req.headers[authHeader].split(' ')[1];
      var payload = jwt.decode(token, config.TOKEN_SECRET);
      User.findById(payload.sub, function(err, user) {
        if (!user) {
          res.status(400).send({ message: 'User not found' });
          return;
        }
        user.github = profile.id;
        user.displayName = user.displayName || profile.name;
        user.save(function() {
          res.send({ 
            token: createToken(user),
            user: user
          });
        });
      });
    });
  }
424666
def get_auth_token(self):
        """"""
        data = [str(self.id), hash_data(self.password)]
        return _security.remember_token_serializer.dumps(data)
115957
function getUser(req, result, cb) {
    if (!result || !result.access_token) return process.nextTick(cb);
    request.get(
      'https://api.github.com/user/emails?access_token=' + result.access_token,
      { headers:{ 'Accept':'application/vnd.github.v3+json' } },
      function(err, resp, body) {
        if (err) { debug(err); return cb(err); }
        var list = JSON.parse(body); debug(list);
        var email = u.find(list, function(entry) { return entry.primary; });
        if (email) {
          email = email.email;
          if (req.session && !req.session.user) { req.session.user = email; }
          result.user = email;
        }
        cb();
    });
  }
601422
def create_github_client(self, project):
        """"""
        token = self._get_installation_key(project=project)
        if not token:
            LOGGER.warning(
                "Could not find an authentication token for '%s'. Do you "
                "have access to this repository?",
                project,
            )
            return
        gh = github3.GitHubEnterprise(self.base_url)
        gh.login(token=token)
        return gh
1315180
def get_app_token(self, scope):
        """"""

        app_token = self.__get_app_token(scope)

        if app_token:
            return app_token

        if self.__cache is not None:
            token = self.__cache.get(self.__app_token_cache_key(scope))
            if token:
                return token

        self.__app_token = None

        payload = {
            'grant_type': 'client_credentials',
            'scope': scope
        }

        url = settings.AUTH_ENDPOINT + '/token'
        r = post(url, data=payload, auth=HTTPBasicAuth(self.__client_id, self.__client_secret), verify=self.__verify_cert)
        if r.status_code == 200:
            data = r.json()
            self.__set_app_token(scope, data[u'access_token'])
            if self.__cache is not None:
                self.__cache.set(self.__app_token_cache_key(scope), str(data[u'access_token']),
                                 data[u'expires_in'] - 300)

        app_token = self.__get_app_token(scope)

        if not app_token:
            raise MxitAPIException("Failed to retrieve app token for '%s' scope" % scope)

        return app_token
1179874
def get_access_token(self, request, callback=None):
        """"""
        callback = request.build_absolute_uri(callback or request.path)
        if not self.check_application_state(request):
            logger.error('Application state check failed.')
            return None
        if 'code' in request.GET:
            args = {
                'client_id': self.consumer_key,
                'redirect_uri': callback,
                'client_secret': self.consumer_secret,
                'code': request.GET['code'],
                'grant_type': 'authorization_code',
            }
        else:
            logger.error('No code returned by the provider')
            return None
        try:
            response = self.request('post', self.access_token_url, data=args)
            response.raise_for_status()
        except RequestException as e:
            logger.error('Unable to fetch access token: {0}'.format(e))
            return None
        else:
            return response.text
909970
def fetch(method, uri, params_prefix=None, **params):
    """"""
    params = urlencode(_prepare_params(params, params_prefix))
    binary_params = params.encode('ASCII')

    # build the HTTP request
    url = "https://%s/%s.xml" % (CHALLONGE_API_URL, uri)
    req = Request(url, binary_params)
    req.get_method = lambda: method

    # use basic authentication
    user, api_key = get_credentials()
    auth_handler = HTTPBasicAuthHandler()
    auth_handler.add_password(
        realm="Application",
        uri=req.get_full_url(),
        user=user,
        passwd=api_key
    )
    opener = build_opener(auth_handler)

    try:
        response = opener.open(req)
    except HTTPError as e:
        if e.code != 422:
            raise
        # wrap up application-level errors
        doc = ElementTree.parse(e).getroot()
        if doc.tag != "errors":
            raise
        errors = [e.text for e in doc]
        raise ChallongeException(*errors)

    return response