Sign in with an transfer token, only available for Podio
487916
def authenticate_with_transfer_token(transfer_token)
      response = @oauth_connection.post do |req|
        req.url '/oauth/token'
        req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
        req.body = {:grant_type => 'transfer_token', :client_id => api_key, :client_secret => api_secret, :transfer_token => transfer_token}
      end

      @oauth_token = OAuthToken.new(response.body)
      configure_oauth
      @oauth_token
    end
1143087
def authenticate
      begin
        @backend.transaction(true){
          raise NotInitializedError.new(@backend.path.path) unless @backend[:user] && @backend[:system] && @backend[:system][:created]
          check_salt!
        }
      rescue OpenSSL::Cipher::CipherError
        raise WrongMasterPasswordError
      end
    end
345032
def sign(self, consumer_secret, method, url, oauth_token_secret=None,
             **params):
        """"""
        # build the url the same way aiohttp will build the query later on
        # cf https://github.com/KeepSafe/aiohttp/blob/master/aiohttp/client.py#L151
        # and https://github.com/KeepSafe/aiohttp/blob/master/aiohttp/client_reqrep.py#L81
        url = yarl.URL(url).with_query(sorted(params.items()))
        url, params = str(url).split('?', 1)
        method = method.upper()

        signature = b"&".join(map(self._escape, (method, url, params)))

        key = self._escape(consumer_secret) + b"&"
        if oauth_token_secret:
            key += self._escape(oauth_token_secret)

        hashed = hmac.new(key, signature, sha1)
        return base64.b64encode(hashed.digest()).decode()
151006
public TransactionInput addSignedInput(TransactionOutput output, ECKey signingKey, SigHash sigHash, boolean anyoneCanPay) {
        return addSignedInput(output.getOutPointFor(), output.getScriptPubKey(), signingKey, sigHash, anyoneCanPay);
    }
548135
def _auth(profile=None, api_version=1, **connection_args):
    '''
    
    '''

    if profile:
        prefix = profile + ':keystone.'
    else:
        prefix = 'keystone.'

    def get(key, default=None):
        '''
        Checks connection_args, then salt-minion config,
        falls back to specified default value.
        '''
        return connection_args.get('connection_' + key,
                                   __salt__['config.get'](prefix + key, default))

    user = get('user', 'admin')
    password = get('password', None)
    tenant = get('tenant', 'admin')
    tenant_id = get('tenant_id')
    auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0')
    insecure = get('insecure', False)
    admin_token = get('token')
    region_name = get('region_name', None)

    if admin_token and api_version != 1 and not password:
        # If we had a password we could just
        # ignore the admin-token and move on...
        raise SaltInvocationError('Only can use keystone admin token ' +
                                  'with Heat API v1')
    elif password:
        # Can't use the admin-token anyway
        kwargs = {'username': user,
                  'password': password,
                  'tenant_id': tenant_id,
                  'auth_url': auth_url,
                  'region_name': region_name,
                  'tenant_name': tenant}
        # 'insecure' keyword not supported by all v2.0 keystone clients
        #   this ensures it's only passed in when defined
        if insecure:
            kwargs['insecure'] = True
    elif api_version == 1 and admin_token:
        kwargs = {'token': admin_token,
                  'auth_url': auth_url}
    else:
        raise SaltInvocationError('No credentials to authenticate with.')

    token = __salt__['keystone.token_get'](profile)
    kwargs['token'] = token['id']
    # This doesn't realy prevent the password to show up
    # in the minion log as keystoneclient.session is
    # logging it anyway when in debug-mode
    kwargs.pop('password')
    try:
        heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['url']
    except KeyError:
        heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['publicurl']
    heat_endpoint = heat_endpoint % token
    log.debug('Calling heatclient.client.Client(%s, %s, **%s)',
              api_version, heat_endpoint, kwargs)
    # may raise exc.HTTPUnauthorized, exc.HTTPNotFound
    # but we deal with those elsewhere
    return heatclient.client.Client(api_version, endpoint=heat_endpoint, **kwargs)
919877
async function cappedSTO_launch(stoConfig, factoryAddress) {
  console.log(chalk.blue('Launch STO - Capped STO in No. of Tokens'));

  let cappedSTOFactoryABI = abis.cappedSTOFactory();
  let cappedSTOFactory = new web3.eth.Contract(cappedSTOFactoryABI, factoryAddress);
  cappedSTOFactory.setProvider(web3.currentProvider);
  let stoFee = new web3.utils.BN(await cappedSTOFactory.methods.getSetupCost().call());

  let contractBalance = new web3.utils.BN(await polyToken.methods.balanceOf(securityToken._address).call());
  if (contractBalance.lt(stoFee)) {
    let transferAmount = stoFee.sub(contractBalance);
    let ownerBalance = new web3.utils.BN(await polyToken.methods.balanceOf(Issuer.address).call());
    if (ownerBalance.lt(transferAmount)) {
      console.log(chalk.red(`\n**************************************************************************************************************************************************`));
      console.log(chalk.red(`Not enough balance to pay the CappedSTO fee, Requires ${web3.utils.fromWei(transferAmount)} POLY but have ${web3.utils.fromWei(ownerBalance)} POLY. Access POLY faucet to get the POLY to complete this txn`));
      console.log(chalk.red(`**************************************************************************************************************************************************\n`));
      return;
    } else {
      let transferAction = polyToken.methods.transfer(securityToken._address, transferAmount);
      let receipt = await common.sendTransaction(transferAction, { factor: 2 });
      let event = common.getEventFromLogs(polyToken._jsonInterface, receipt.logs, 'Transfer');
      console.log(`Number of POLY sent: ${web3.utils.fromWei(new web3.utils.BN(event._value))}`)
    }
  }

  let oneMinuteFromNow = new web3.utils.BN((Math.floor(Date.now() / 1000) + 60));
  let oneMonthFromNow = new web3.utils.BN((Math.floor(Date.now() / 1000) + (30 * 24 * 60 * 60)));

  let cappedSTOconfig = {};
  let useConfigFile = typeof stoConfig !== 'undefined';
  if (!useConfigFile) {
    cappedSTOconfig.cap = readlineSync.question('How many tokens do you plan to sell on the STO? (500.000): ');
    if (cappedSTOconfig.cap == "") cappedSTOconfig.cap = 500000;

    cappedSTOconfig.raiseType = readlineSync.question('Enter' + chalk.green(` P `) + 'for POLY raise or leave empty for Ether raise (E): ');
    if (cappedSTOconfig.raiseType.toUpperCase() == 'P') {
      cappedSTOconfig.raiseType = [gbl.constants.FUND_RAISE_TYPES.POLY];
    } else {
      cappedSTOconfig.raiseType = [gbl.constants.FUND_RAISE_TYPES.ETH];
    }

    cappedSTOconfig.rate = readlineSync.question(`Enter the rate (1 ${cappedSTOconfig.raiseType == gbl.constants.FUND_RAISE_TYPES.POLY ? 'POLY' : 'ETH'} = X ${tokenSymbol}) for the STO (1000): `);
    if (cappedSTOconfig.rate == "") cappedSTOconfig.rate = 1000;

    cappedSTOconfig.wallet = readlineSync.question('Enter the address that will receive the funds from the STO (' + Issuer.address + '): ');
    if (cappedSTOconfig.wallet == "") cappedSTOconfig.wallet = Issuer.address;

    cappedSTOconfig.startTime = readlineSync.question('Enter the start time for the STO (Unix Epoch time)\n(1 minutes from now = ' + oneMinuteFromNow + ' ): ');

    cappedSTOconfig.endTime = readlineSync.question('Enter the end time for the STO (Unix Epoch time)\n(1 month from now = ' + oneMonthFromNow + ' ): ');
  } else {
    cappedSTOconfig = stoConfig;
  }

  if (cappedSTOconfig.startTime == "") cappedSTOconfig.startTime = oneMinuteFromNow;
  if (cappedSTOconfig.endTime == "") cappedSTOconfig.endTime = oneMonthFromNow;

  let cappedSTOABI = abis.cappedSTO();
  let configureFunction = cappedSTOABI.find(o => o.name === 'configure' && o.type === 'function');
  let bytesSTO = web3.eth.abi.encodeFunctionCall(configureFunction,
    [cappedSTOconfig.startTime,
    cappedSTOconfig.endTime,
    web3.utils.toWei(cappedSTOconfig.cap.toString()),
    web3.utils.toWei(cappedSTOconfig.rate.toString()),
    cappedSTOconfig.raiseType,
    cappedSTOconfig.wallet]
  );

  let addModuleAction = securityToken.methods.addModule(cappedSTOFactory.options.address, bytesSTO, stoFee, 0);
  let receipt = await common.sendTransaction(addModuleAction);
  let event = common.getEventFromLogs(securityToken._jsonInterface, receipt.logs, 'ModuleAdded');
  console.log(`STO deployed at address: ${event._module}`);

  let cappedSTO = new web3.eth.Contract(cappedSTOABI, event._module);
  cappedSTO.setProvider(web3.currentProvider);

  return cappedSTO;
}
745348
def _save_token_on_disk(self):
        """"""
        token = self._token.copy()

        # Client secret is needed for token refreshing and isn't returned
        # as a pared of OAuth token by default
        token.update(client_secret=self._client_secret)

        with codecs.open(config.TOKEN_FILE_PATH, 'w', 'utf8') as f:
            json.dump(
                token, f,
                ensure_ascii=False,
                sort_keys=True,
                indent=4,
            )
81249
def token_cli(self, eauth, load):
        '''
        
        '''
        load['cmd'] = 'mk_token'
        load['eauth'] = eauth
        tdata = self._send_token_request(load)
        if 'token' not in tdata:
            return tdata
        try:
            with salt.utils.files.set_umask(0o177):
                with salt.utils.files.fopen(self.opts['token_file'], 'w+') as fp_:
                    fp_.write(tdata['token'])
        except (IOError, OSError):
            pass
        return tdata
310840
def broadcast_signed_transaction(unsigned_tx, signatures, pubkeys, coin_symbol='btc', api_key=None):
    '''
    
    '''

    assert 'errors' not in unsigned_tx, unsigned_tx
    assert api_key, 'api_key required'

    url = make_url(coin_symbol, **dict(txs='send'))

    data = unsigned_tx.copy()
    data['signatures'] = signatures
    data['pubkeys'] = pubkeys

    params = {'token': api_key}

    r = requests.post(url, params=params, json=data, verify=True, timeout=TIMEOUT_IN_SECONDS)
    response_dict = get_valid_json(r)

    if response_dict.get('tx') and response_dict.get('received'):
        response_dict['tx']['received'] = parser.parse(response_dict['tx']['received'])

    return response_dict
1027847
function sign($pairs)
    {
        $kv = Auth_OpenID_KVForm::fromArray($pairs);

        /* Invalid association types should be caught at constructor */
        $callback = $this->_macs[$this->assoc_type];

        return call_user_func_array($callback, array($this->secret, $kv));
    }
871292
def login(un, pw)
      response_body = Helper.auth_request un, pw
      auth_token = Hash[*response_body.split.collect { |i| i.split('=') }.flatten]['Auth']
      raise InoreaderApi::InoreaderApiError.new 'Bad Authentication' if auth_token.nil?
      auth_token
    rescue => e
      raise InoreaderApi::InoreaderApiError.new e.message if auth_token.nil?
    end
58012
def make_send_to_address_tx(recipient_address, amount, private_key,
        blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE,
        change_address=None):
    
    # get out the private key object, sending address, and inputs
    private_key_obj, from_address, inputs = analyze_private_key(private_key,
        blockchain_client)
    # get the change address
    if not change_address:
        change_address = from_address
    # create the outputs
    outputs = make_pay_to_address_outputs(recipient_address, amount, inputs,
                                          change_address, fee=fee)
    # serialize the transaction
    unsigned_tx = serialize_transaction(inputs, outputs)

    # generate a scriptSig for each input
    for i in xrange(0, len(inputs)):
        signed_tx = sign_transaction(unsigned_tx, i, private_key_obj.to_hex())
        unsigned_tx = signed_tx

    # return the signed tx
    return signed_tx
1063476
def GET_account_tokens(self, path_info, account_addr):
        
        if not check_account_address(account_addr):
            return self._reply_json({'error': 'Invalid address'}, status_code=400)

        blockstackd_url = get_blockstackd_url()
        res = blockstackd_client.get_account_tokens(account_addr, hostport=blockstackd_url)
        if json_is_error(res):
            log.error("Failed to load tokens for {}: {}".format(account_addr, res['error']))
            return self._reply_json({'error': 'Failed to load tokens for {}: {}'.format(account_addr, res['error'])}, status_code=res.get('http_status', 500))

        self._reply_json({'tokens': res})
        return
1127285
function SignInputPacket(tx, index, coin, ring, type) {
  Packet.call(this);
  this.tx = tx || null;
  this.index = index;
  this.coin = coin || null;
  this.ring = ring || null;
  this.type = type != null ? type : 1;
}
270145
def sign_jwt(data, secret_key, expires_in, salt=None, **kw):
    
    s = itsdangerous.TimedJSONWebSignatureSerializer(secret_key=secret_key,
                                                     expires_in=expires_in,
                                                     salt=salt,
                                                      **kw)
    return s.dumps(data)
216598
def express_endpoint_for_token(token, commit=False):
    
    pp_params = dict(token=token)
    if commit:
        pp_params['useraction'] = 'commit'
    return express_endpoint() % urlencode(pp_params)
565847
def sign(self, pkt, key):
        
        if not self.mac:
            return pkt

        mac = self.new_mac(key)

        if pkt.haslayer(ESP):
            mac.update(raw(pkt[ESP]))
            pkt[ESP].data += mac.finalize()[:self.icv_size]

        elif pkt.haslayer(AH):
            clone = zero_mutable_fields(pkt.copy(), sending=True)
            mac.update(raw(clone))
            pkt[AH].icv = mac.finalize()[:self.icv_size]

        return pkt