// Exchange is like Token, except it allows you to manually specify the access
// code instead of pulling it out of an HTTP request.
511683
func (a Authenticator) Exchange(code string) (*oauth2.Token, error) {
	return a.config.Exchange(a.context, code)
}
1136000
func (c *Client) ListExchangesIn(vhost string) (rec []ExchangeInfo, err error) {
	req, err := newGETRequest(c, "exchanges/"+PathEscape(vhost))
	if err != nil {
		return []ExchangeInfo{}, err
	}

	if err = executeAndParseRequest(c, req, &rec); err != nil {
		return []ExchangeInfo{}, err
	}

	return rec, nil
}
1151467
func (ex *dohExchanger) exchangeWireformat(msg []byte) ([]byte, error) {
	req, err := http.NewRequest("POST", ex.endpoint.String(), bytes.NewBuffer(msg))
	if err != nil {
		return nil, fmt.Errorf("failed to create an HTTPS request: %s", err)
	}

	req.Header.Add("Content-Type", "application/dns-udpwireformat")
	req.Host = ex.endpoint.Hostname()

	resp, err := ex.client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("failed to perform an HTTPS request: %s", err)
	}

	// Check response status code
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("returned status code %d", resp.StatusCode)
	}

	// Read wireformat response from the body
	buf, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("failed to read the response body: %s", err)
	}

	return buf, nil
}
579004
func (s *authenticationProviderServiceImpl) ExchangeAuthorizationCodeForUserToken(ctx context.Context, code string, clientID string, redirectURL *url.URL) (*string, *app.OauthToken, error) {
	// Default value of this public client id is set to "740650a2-9c44-4db5-b067-a3d1b2cd2d01"
	if clientID != s.config.GetPublicOAuthClientID() {
		log.Error(ctx, map[string]interface{}{
			"client_id": clientID,
		}, "unknown oauth client id")
		return nil, nil, autherrors.NewUnauthorizedError("invalid oauth client id")
	}

	// Exchange the authorization code for an access token with the identity provider
	providerToken, err := s.ExchangeCodeWithProvider(ctx, code, redirectURL.String())
	if err != nil {
		return nil, nil, err
	}

	notApprovedRedirectURL, userToken, err := s.CreateOrUpdateIdentityAndUser(ctx, redirectURL, providerToken)
	if err != nil {
		return nil, nil, err
	}

	var token *app.OauthToken

	if userToken != nil {
		// Convert expiry to expire_in
		expiry := userToken.Expiry
		var expireIn *string
		if expiry != *new(time.Time) {
			exp := expiry.Sub(time.Now())
			if exp > 0 {
				seconds := strconv.FormatInt(int64(exp/time.Second), 10)
				expireIn = &seconds
			}
		}

		token = &app.OauthToken{
			AccessToken:  &userToken.AccessToken,
			ExpiresIn:    expireIn,
			RefreshToken: &userToken.RefreshToken,
			TokenType:    &userToken.TokenType,
		}
	}

	return notApprovedRedirectURL, token, nil
}
307391
func Decorate(ex Exchanger, ds ...Decorator) Exchanger {
	decorated := ex
	for _, decorate := range ds {
		decorated = decorate(decorated)
	}
	return decorated
}
188668
func (c *Component) ExchangeAppKeyForToken(appID, key string) (string, error) {
	issuerID := keys.KeyIssuer(key)
	if issuerID == "" {
		// Take the first configured auth server
		for k := range c.Config.AuthServers {
			issuerID = k
			break
		}
		key = fmt.Sprintf("%s.%s", issuerID, key)
	}
	issuer, ok := c.Config.AuthServers[issuerID]
	if !ok {
		return "", fmt.Errorf("Auth server \"%s\" not registered", issuerID)
	}

	token, err := getTokenFromCache(oauthCache, appID, key)
	if err != nil {
		return "", err
	}

	if token != nil {
		return token.AccessToken, nil
	}

	srv, _ := parseAuthServer(issuer)
	acc := account.New(srv.url)

	if srv.username != "" {
		acc = acc.WithAuth(auth.BasicAuth(srv.username, srv.password))
	} else {
		acc = acc.WithAuth(auth.AccessToken(c.AccessToken))
	}

	token, err = acc.ExchangeAppKeyForToken(appID, key)
	if err != nil {
		return "", err
	}

	saveTokenToCache(oauthCache, appID, key, token)

	return token.AccessToken, nil
}
430871
func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error {
	if debugHandshake {
		log.Printf("%s entered key exchange", t.id())
	}
	myInit, myInitPacket, err := t.sendKexInit()
	if err != nil {
		return err
	}

	otherInit := &kexInitMsg{}
	if err := Unmarshal(otherInitPacket, otherInit); err != nil {
		return err
	}

	magics := handshakeMagics{
		clientVersion: t.clientVersion,
		serverVersion: t.serverVersion,
		clientKexInit: otherInitPacket,
		serverKexInit: myInitPacket,
	}

	clientInit := otherInit
	serverInit := myInit
	if len(t.hostKeys) == 0 {
		clientInit = myInit
		serverInit = otherInit

		magics.clientKexInit = myInitPacket
		magics.serverKexInit = otherInitPacket
	}

	algs, err := findAgreedAlgorithms(clientInit, serverInit)
	if err != nil {
		return err
	}

	// We don't send FirstKexFollows, but we handle receiving it.
	if otherInit.FirstKexFollows && algs.kex != otherInit.KexAlgos[0] {
		// other side sent a kex message for the wrong algorithm,
		// which we have to ignore.
		if _, err := t.conn.readPacket(); err != nil {
			return err
		}
	}

	kex, ok := kexAlgoMap[algs.kex]
	if !ok {
		return fmt.Errorf("ssh: unexpected key exchange algorithm %v", algs.kex)
	}

	var result *kexResult
	if len(t.hostKeys) > 0 {
		result, err = t.server(kex, algs, &magics)
	} else {
		result, err = t.client(kex, algs, &magics)
	}

	if err != nil {
		return err
	}

	t.conn.prepareKeyChange(algs, result)
	if err = t.conn.writePacket([]byte{msgNewKeys}); err != nil {
		return err
	}
	if packet, err := t.conn.readPacket(); err != nil {
		return err
	} else if packet[0] != msgNewKeys {
		return unexpectedMessageError(msgNewKeys, packet[0])
	}
	return nil
}
1087732
func New() *Exchange {
	mu := new(sync.RWMutex)
	return &Exchange{
		trie:           patricia.NewTrie(),
		topicForHandle: make(map[Handle]Topic),
		mu:             mu,
		cond:           sync.NewCond(mu),
		nextHandle:     1,
	}
}
99613
func (r *ExchangeAuthorizationError) Error() string {
	return fmt.Sprintf("%v %v: %v %v",
		r.HttpResponse.Request.Method, r.HttpResponse.Request.URL,
		r.ErrorCode, r.ErrorDescription)
}
1210738
func (bot *ExchangeBot) Indices(token string) FiatIndices {
	bot.mtx.RLock()
	defer bot.mtx.RUnlock()
	indices := make(FiatIndices)
	for code, price := range bot.indexMap[token] {
		indices[code] = price
	}
	return indices
}
659936
func (c *Client) ListExchangeBindingsWithSource(vhost, exchange string) (rec []BindingInfo, err error) {
	return c.ListExchangeBindings(vhost, exchange, BindingSource)
}
1116267
func (p Standard) Token(req []byte) (token []byte, err error) {
	h := hmac.New(sha256.New, p.key)
	h.Write(req)
	h.Write(p.ad)
	return h.Sum(nil), nil
}
734900
func (bot *ExchangeBot) updateExchange(update *ExchangeUpdate) error {
	bot.mtx.Lock()
	defer bot.mtx.Unlock()
	if update.State.Candlesticks != nil {
		for bin := range update.State.Candlesticks {
			bot.incrementChart(genCacheID(update.Token, string(bin)))
		}
	}
	if update.State.Depth != nil {
		bot.incrementChart(genCacheID(update.Token, "depth"))
	}
	bot.currentState.DcrBtc[update.Token] = update.State
	return bot.updateState()
}
821916
func (d *dnsEx) Exchange(ctx context.Context, addr string, state request.Request) (*dns.Msg, error) {
	proto := state.Proto()
	if d.Options.ForceTCP {
		proto = "tcp"
	}
	co, err := net.DialTimeout(proto, addr, d.Timeout)
	if err != nil {
		return nil, err
	}

	reply, _, err := d.ExchangeConn(state.Req, co)

	co.Close()

	if reply != nil && reply.Truncated {
		// Suppress proxy error for truncated responses
		err = nil
	}

	if err != nil {
		return nil, err
	}
	// Make sure it fits in the DNS response.
	reply, _ = state.Scrub(reply)
	reply.Compress = true
	reply.Id = state.Req.Id

	return reply, nil
}
904662
func (c *UserConfig) GetToken() (string, string) {
	if c.AccessTokenKey != "" {
		return c.AccessTokenKey, c.AccessTokenSecret
	}
	if c.RequestTokenKey != "" {
		return c.RequestTokenKey, c.RequestTokenSecret
	}
	return "", ""
}
423909
func KeyExchange(pub *rsa.PublicKey) []byte {
	asn1, err := x509.MarshalPKIXPublicKey(pub)
	if err != nil {
		return nil
	}
	return asn1
}
363790
func (t *TokenSource) Token() (*oauth2.Token, error) {
	token := &oauth2.Token{
		AccessToken: t.AccessToken,
	}
	return token, nil
}