Builds a client config dictionary used in the OAuth 2.0 flow.
762139
def Build(self):
    """"""
    if all((self.client_type, self.client_id, self.client_secret,
            self.auth_uri, self.token_uri)):
      client_config = {
          self.client_type: {
              'client_id': self.client_id,
              'client_secret': self.client_secret,
              'auth_uri': self.auth_uri,
              'token_uri': self.token_uri
          }
      }
    else:
      raise ValueError('Required field is missing.')

    return client_config
604238
def _client_data(self, client):
        
        data = {}
        if client:
            data['obj'] = client
            data['id'] = client.id
            data['url'] = client.absolute_url()
            data['name'] = to_utf8(client.getName())
        return data
111431
def build_attributes(cls, attributes, namespace):
        
        config_path = attributes.get('config_path')
        tokens = {}

        def build_config_key(value_def, config_key):
            key = value_def.config_key or config_key
            return '%s.%s' % (config_path, key) if config_path else key

        def build_token(name, value_def):
            config_key = build_config_key(value_def, name)
            value_token = ValueToken.from_definition(
                                            value_def, namespace, config_key)
            getters.register_value_proxy(namespace, value_token, value_def.help)
            tokens[name] = value_token
            return name, build_property(value_token)

        def build_attr(name, attribute):
            if not isinstance(attribute, ValueTypeDefinition):
                return name, attribute
            return build_token(name, attribute)

        attributes = dict(build_attr(*item)
                          for item in six.iteritems(attributes))
        attributes['_tokens'] = tokens
        return attributes
1010259
def init_config(self, app):
        """"""
        for k in dir(config):
            if k.startswith('OAUTHCLIENT_'):
                app.config.setdefault(k, getattr(config, k))

        @app.before_first_request
        def override_template_configuration():
            """Override template configuration."""
            template_key = app.config.get(
                'OAUTHCLIENT_TEMPLATE_KEY',
                'SECURITY_LOGIN_USER_TEMPLATE'  # default template key
            )
            if template_key is not None:
                template = app.config[template_key]  # keep the old value
                app.config['OAUTHCLIENT_LOGIN_USER_TEMPLATE_PARENT'] = template
                app.config[template_key] = app.config.get(
                    'OAUTHCLIENT_LOGIN_USER_TEMPLATE',
                    'invenio_oauthclient/login_user.html'
                )
163310
def create_uber_client(credentials):
    
    oauth2credential = OAuth2Credential(
        client_id=credentials.get('client_id'),
        access_token=credentials.get('access_token'),
        expires_in_seconds=credentials.get('expires_in_seconds'),
        scopes=credentials.get('scopes'),
        grant_type=credentials.get('grant_type'),
        redirect_url=credentials.get('redirect_url'),
        client_secret=credentials.get('client_secret'),
        refresh_token=credentials.get('refresh_token'),
    )
    session = Session(oauth2credential=oauth2credential)
    return UberRidesClient(session, sandbox_mode=True)
1018173
public OAuthFlow build() {
        if(httpClient == null){
            httpClient = new DefaultHttpClient();
        }

        if(tokenURL == null){
            tokenURL = DEFAULT_TOKEN_URL;
        }

        if(authorizationURL == null){
            authorizationURL = DEFAULT_AUTHORIZATION_URL;
        }

        if(jsonSerializer == null){
            jsonSerializer = new JacksonJsonSerializer();
        }

        if(clientId == null || clientSecret == null || redirectURL == null){
            throw new IllegalStateException();
        }

        return new OAuthFlowImpl(clientId, clientSecret, redirectURL, authorizationURL, tokenURL, httpClient,
                jsonSerializer);
    }
943601
def config_cred(config, providers):
    """"""
    expected = ['aws', 'azure', 'gcp', 'alicloud']
    cred = {}
    to_remove = []
    for item in providers:
        if any(item.startswith(itemb) for itemb in expected):
            try:
                cred[item] = dict(list(config[item].items()))
            except KeyError as e:
                print("No credentials section in config file for {} -"
                      " provider will be skipped.".format(e))
                to_remove.append(item)
        else:
            print("Unsupported provider: '{}' listed in config - ignoring"
                  .format(item))
            to_remove.append(item)
    return cred, to_remove
49897
def build_from_developer_settings(api_name: str, api_version: str):
        
        developer_settings = read_developer_settings()

        api_host = "http://" + api_name + ".apis.devision.io"
        return ApiClient(
            host=api_host,
            api_version=api_version,
            access_token=None,
            refresh_token=developer_settings['refreshToken'],
            client_id=developer_settings['clientId'],
            client_secret=developer_settings['clientSecret'],
        )
1103089
def create_client(self, name):
        ''''''
        client = {'client':{
            'name': name,
        }}
        response = self.post_request('clients/', client, follow = True)
        if response:
            return Client(self, response['client'])
1054575
def _config_from_url(self):
        
        config = {
            "name": self._blk.name,
            "options": {}
        }
        for key, value in six.iteritems(request.args):
            if isinstance(value, list) and len(value) == 1:
                config["options"][key] = value[0]
            else:
                config["options"][key] = value
        return config
787229
def config(config_dict: typing.Mapping) -> Config:
    
    logger.debug(f"Updating with {config_dict}")
    _cfg.update(config_dict)
    return _cfg
801955
def _construct_config(self, basedir, port, name=None, isreplset=False):
        """"""
        if isreplset:
            return self._construct_replset(basedir=basedir, portstart=port,
                                           name=name,
                                           num_nodes=list(range(
                                               self.args['config'])),
                                           arbiter=False, extra='--configsvr')
        else:
            datapath = self._create_paths(basedir, name)
            self._construct_mongod(os.path.join(datapath, 'db'),
                                   os.path.join(datapath, 'mongod.log'),
                                   port, replset=None, extra='--configsvr')
672629
def GetClientConfig(filename):
  """"""
  config_lib.SetPlatformArchContext()
  config_lib.ParseConfigCommandLine()
  context = list(grr_config.CONFIG.context)
  context.append("Client Context")
  deployer = build.ClientRepacker()
  # Disable timestamping so we can get a reproducible and cachable config file.
  config_data = deployer.GetClientConfig(
      context, validate=True, deploy_timestamp=False)
  builder = build.ClientBuilder()
  with open(filename, "w") as fd:
    fd.write(config_data)
    builder.WriteBuildYaml(fd, build_timestamp=False)
729322
def get_new_user_credentials(self):
        
        # OAuth2.0 authorization flow
        flow = client.flow_from_clientsecrets(self.app_secrets, self.scope)
        flow.user_agent = self.app_name
        return tools.run_flow(flow, self.store)
322798
def GetClientConfig(self, context, validate=True, deploy_timestamp=True):
    """"""
    with utils.TempDirectory() as tmp_dir:
      # Make sure we write the file in yaml format.
      filename = os.path.join(
          tmp_dir,
          config.CONFIG.Get("ClientBuilder.config_filename", context=context))

      new_config = config.CONFIG.MakeNewConfig()
      new_config.Initialize(reset=True, data="")
      new_config.SetWriteBack(filename)

      # Only copy certain sections to the client. We enumerate all
      # defined options and then resolve those from the config in the
      # client's context. The result is the raw option as if the
      # client read our config file.
      client_context = context[:]
      while contexts.CLIENT_BUILD_CONTEXT in client_context:
        client_context.remove(contexts.CLIENT_BUILD_CONTEXT)
      for descriptor in sorted(config.CONFIG.type_infos, key=lambda x: x.name):
        if descriptor.name in self.SKIP_OPTION_LIST:
          continue

        if descriptor.section in self.CONFIG_SECTIONS:
          value = config.CONFIG.GetRaw(
              descriptor.name, context=client_context, default=None)

          if value is not None:
            logging.debug("Copying config option to client: %s",
                          descriptor.name)

            new_config.SetRaw(descriptor.name, value)

      if deploy_timestamp:
        deploy_time_string = str(rdfvalue.RDFDatetime.Now())
        new_config.Set("Client.deploy_time", deploy_time_string)
      new_config.Write()

      if validate:
        self.ValidateEndConfig(new_config)

      private_validator = config.CONFIG.Get(
          "ClientBuilder.private_config_validator_class", context=context)
      if private_validator:
        try:
          validator = config_validator_base.PrivateConfigValidator.classes[
              private_validator]()
        except KeyError:
          logging.error(
              "Couldn't find config validator class %s, "
              "you probably need to copy it into lib/local", private_validator)
          raise
        validator.ValidateEndConfig(new_config, self.context)

      return io.open(filename, "r").read()
1160080
def authenticate(self):
        
        settings_dict = self.settings_dict
        url = ''.join([settings_dict['HOST'], '/services/oauth2/token'])

        log.info("attempting authentication to %s", settings_dict['HOST'])
        self._session.mount(settings_dict['HOST'], HTTPAdapter(max_retries=get_max_retries()))
        auth_params = {
            'grant_type':    'password',
            'client_id':     settings_dict['CONSUMER_KEY'],
            'client_secret': settings_dict['CONSUMER_SECRET'],
            'username':      settings_dict['USER'],
            'password':      settings_dict['PASSWORD'],
        }
        response = self._session.post(url, data=auth_params)
        if response.status_code == 200:
            # prefer str in Python 2 due to other API
            response_data = {str(k): str(v) for k, v in response.json().items()}
            # Verify signature (not important for this auth mechanism)
            calc_signature = (
                base64.b64encode(
                    hmac.new(
                        key=settings_dict['CONSUMER_SECRET'].encode('ascii'),
                        msg=(response_data['id'] + response_data['issued_at']).encode('ascii'),
                        digestmod=hashlib.sha256
                    ).digest()
                )
            ).decode('ascii')
            if calc_signature == response_data['signature']:
                log.info("successfully authenticated %s", settings_dict['USER'])
            else:
                raise IntegrityError('Invalid auth signature received')
        else:
            raise LookupError("oauth failed: %s: %s" % (settings_dict['USER'], response.text))
        return response_data
1335924
def init_app(self, app, **kwargs):
        
        self.init_config(app)

        allowed_urlencode_chars = app.config.get(
            'OAUTH2SERVER_ALLOWED_URLENCODE_CHARACTERS')
        if allowed_urlencode_chars:
            InvenioOAuth2ServerREST.monkeypatch_oauthlib_urlencode_chars(
                allowed_urlencode_chars)
        app.before_request(verify_oauth_token_and_set_current_user)