// OAuth2TokenRevocationFactory creates an OAuth2 token revocation handler.
352770
func OAuth2TokenRevocationFactory(config *Config, storage interface{}, strategy interface{}) interface{} {
	return &oauth2.TokenRevocationHandler{
		TokenRevocationStorage: storage.(oauth2.TokenRevocationStorage),
		AccessTokenStrategy:    strategy.(oauth2.AccessTokenStrategy),
		RefreshTokenStrategy:   strategy.(oauth2.RefreshTokenStrategy),
	}
}
595065
func (c *Client) OAuthTokenCreate(grant OAuthTokenCreateGrant, client OAuthTokenCreateClient, refreshToken OAuthTokenCreateRefreshToken) (*OAuthToken, error) {
	params := struct {
		Grant        OAuthTokenCreateGrant        `json:"grant"`
		Client       OAuthTokenCreateClient       `json:"client"`
		RefreshToken OAuthTokenCreateRefreshToken `json:"refresh_token"`
	}{
		Grant:        grant,
		Client:       client,
		RefreshToken: refreshToken,
	}
	var oauthTokenRes OAuthToken
	return &oauthTokenRes, c.Post(&oauthTokenRes, "/oauth/tokens", params)
}
326199
func NewAuthTokenHandler(tokenStorage session.Storage) func(http.Handler) http.Handler {
	return func(h http.Handler) http.Handler {
		return &authHandler{
			handler:    h,
			backend:    tokenStorage,
			contextKey: tokenKey,
			headerKey:  TokenHeader,
			mustAuth:   true,
		}
	}
}
801809
func (a Authenticator) Token(state string, r *http.Request) (*oauth2.Token, error) {
	values := r.URL.Query()
	if e := values.Get("error"); e != "" {
		return nil, errors.New("spotify: auth failed - " + e)
	}
	code := values.Get("code")
	if code == "" {
		return nil, errors.New("spotify: didn't get access code")
	}
	actualState := values.Get("state")
	if actualState != state {
		return nil, errors.New("spotify: redirect state parameter doesn't match")
	}
	return a.config.Exchange(a.context, code)
}
159425
func (ts *TokenStore) handleUpdateRevokeAccessor(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	accessor := data.Get("accessor").(string)
	if accessor == "" {
		return nil, &logical.StatusBadRequest{Err: "missing accessor"}
	}

	aEntry, err := ts.lookupByAccessor(ctx, accessor, false, true)
	if err != nil {
		return nil, err
	}

	te, err := ts.Lookup(ctx, aEntry.TokenID)
	if err != nil {
		return nil, err
	}
	if te == nil {
		return logical.ErrorResponse("token not found"), logical.ErrInvalidRequest
	}

	tokenNS, err := NamespaceByID(ctx, te.NamespaceID, ts.core)
	if err != nil {
		return nil, err
	}
	if tokenNS == nil {
		return nil, namespace.ErrNoNamespace
	}

	revokeCtx := namespace.ContextWithNamespace(ts.quitContext, tokenNS)
	leaseID, err := ts.expiration.CreateOrFetchRevocationLeaseByToken(revokeCtx, te)
	if err != nil {
		return nil, err
	}

	err = ts.expiration.Revoke(revokeCtx, leaseID)
	if err != nil {
		return nil, err
	}

	return nil, nil
}
947107
func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) {
	token := &oauth2.Token{RefreshToken: refreshToken}
	ctx := context.WithValue(goth.ContextForClient(p.Client()), oauth2.HTTPClient, goth.HTTPClientWithFallBack(p.Client()))
	ts := p.config.TokenSource(ctx, token)
	newToken, err := ts.Token()
	if err != nil {
		return nil, err
	}
	return newToken, err
}
787453
func OAuth2(code, message string, query url.Values) Error {
	return WrapWithMessage(&OAuth2Error{
		Code:    code,
		Message: message,
		Query:   query,
	}, message)
}
872638
func (e *engineImpl) allocateInvocations(c context.Context, job *Job, req []task.Request) ([]*Invocation, error) {
	wg := sync.WaitGroup{}
	wg.Add(len(req))

	invs := make([]*Invocation, len(req))
	merr := errors.NewLazyMultiError(len(req))
	for i := range req {
		go func(i int) {
			defer wg.Done()
			inv, err := e.allocateInvocation(c, job, req[i])
			invs[i] = inv
			merr.Assign(i, err)
			if err != nil {
				logging.WithError(err).Errorf(c, "Failed to create invocation with %d triggers", len(req[i].IncomingTriggers))
			}
		}(i)
	}

	wg.Wait()

	// Bail if any of them failed. Try best effort cleanup.
	if err := merr.Get(); err != nil {
		cleanupUnreferencedInvocations(c, invs)
		return nil, transient.Tag.Apply(err)
	}

	return invs, nil
}
343036
func (cfg *ApplicationConfigEnv) LoadToken() (*oauth2.Token, error) {
	tok, err := NewTokenPassword(
		cfg.ApplicationCredentials(),
		cfg.PasswordCredentials())
	if err == nil {
		cfg.AccessToken = tok.AccessToken
	}
	return tok, err
}
119948
func appEngineTokenSource(ctx context.Context, scope ...string) oauth2.TokenSource {
	scopes := append([]string{}, scope...)
	sort.Strings(scopes)
	return &gaeTokenSource{
		ctx:    ctx,
		scopes: scopes,
		key:    strings.Join(scopes, " "),
	}
}
159212
func (ccc ClientCredentialsConfig) Authorizer() (autorest.Authorizer, error) {
	spToken, err := ccc.ServicePrincipalToken()
	if err != nil {
		return nil, fmt.Errorf("failed to get oauth token from client credentials: %v", err)
	}
	return autorest.NewBearerAuthorizer(spToken), nil
}
350099
func (c *tokenSource) Token() (*oauth2.Token, error) {
	v := url.Values{
		"grant_type": {"client_credentials"},
	}
	if len(c.conf.Scopes) > 0 {
		v.Set("scope", strings.Join(c.conf.Scopes, " "))
	}
	for k, p := range c.conf.EndpointParams {
		// Allow grant_type to be overridden to allow interoperability with
		// non-compliant implementations.
		if _, ok := v[k]; ok && k != "grant_type" {
			return nil, fmt.Errorf("oauth2: cannot overwrite parameter %q", k)
		}
		v[k] = p
	}

	tk, err := internal.RetrieveToken(c.ctx, c.conf.ClientID, c.conf.ClientSecret, c.conf.TokenURL, v, internal.AuthStyle(c.conf.AuthStyle))
	if err != nil {
		if rErr, ok := err.(*internal.RetrieveError); ok {
			return nil, (*oauth2.RetrieveError)(rErr)
		}
		return nil, err
	}
	t := &oauth2.Token{
		AccessToken:  tk.AccessToken,
		TokenType:    tk.TokenType,
		RefreshToken: tk.RefreshToken,
		Expiry:       tk.Expiry,
	}
	return t.WithExtra(tk.Raw), nil
}
160061
func NewAuthorizeAuthenticator(request authenticator.Request, handler AuthenticationHandler, errorHandler AuthenticationErrorHandler) osinserver.AuthorizeHandler {
	return &authorizeAuthenticator{request: request, handler: handler, errorHandler: errorHandler}
}
578045
func (spt *ServicePrincipalToken) OAuthToken() string {
	spt.refreshLock.RLock()
	defer spt.refreshLock.RUnlock()
	return spt.inner.Token.OAuthToken()
}
1060126
func (c *Config) TokenSource(token *oauth2.Token) oauth2.TokenSource {
	config := c.getConfig()
	return config.TokenSource(c.getContext(), token)
}
777204
func NewRevocationProducerFromBytes(data []byte) (*RevocationProducer, error) {
	root, err := chainhash.NewHash(data)
	if err != nil {
		return nil, err
	}

	return &RevocationProducer{
		root: &element{
			index: rootIndex,
			hash:  *root,
		},
	}, nil
}
1046298
func oauth2Login(ctx context.Context, port int, oauth2conf *oauth2.Config, provider *oidc.Provider) (string, string) {
	oauth2conf.RedirectURL = fmt.Sprintf("http://localhost:%d/auth/callback", port)
	oidcConf, err := oidcutil.ParseConfig(provider)
	errors.CheckError(err)
	log.Debug("OIDC Configuration:")
	log.Debugf("  supported_scopes: %v", oidcConf.ScopesSupported)
	log.Debugf("  response_types_supported: %v", oidcConf.ResponseTypesSupported)

	// handledRequests ensures we do not handle more requests than necessary
	handledRequests := 0
	// completionChan is to signal flow completed. Non-empty string indicates error
	completionChan := make(chan string)
	// stateNonce is an OAuth2 state nonce
	stateNonce := rand.RandString(10)
	var tokenString string
	var refreshToken string

	handleErr := func(w http.ResponseWriter, errMsg string) {
		http.Error(w, errMsg, http.StatusBadRequest)
		completionChan <- errMsg
	}

	// Authorization redirect callback from OAuth2 auth flow.
	// Handles both implicit and authorization code flow
	callbackHandler := func(w http.ResponseWriter, r *http.Request) {
		log.Debugf("Callback: %s", r.URL)

		if formErr := r.FormValue("error"); formErr != "" {
			handleErr(w, formErr+": "+r.FormValue("error_description"))
			return
		}

		handledRequests++
		if handledRequests > 2 {
			// Since implicit flow will redirect back to ourselves, this counter ensures we do not
			// fallinto a redirect loop (e.g. user visits the page by hand)
			handleErr(w, "Unable to complete login flow: too many redirects")
			return
		}

		if len(r.Form) == 0 {
			// If we get here, no form data was set. We presume to be performing an implicit login
			// flow where the id_token is contained in a URL fragment, making it inaccessible to be
			// read from the request. This javascript will redirect the browser to send the
			// fragments as query parameters so our callback handler can read and return token.
			fmt.Fprintf(w, `<script>window.location.search = window.location.hash.substring(1)</script>`)
			return
		}

		if state := r.FormValue("state"); state != stateNonce {
			handleErr(w, "Unknown state nonce")
			return
		}

		tokenString = r.FormValue("id_token")
		if tokenString == "" {
			code := r.FormValue("code")
			if code == "" {
				handleErr(w, fmt.Sprintf("no code in request: %q", r.Form))
				return
			}
			tok, err := oauth2conf.Exchange(ctx, code)
			if err != nil {
				handleErr(w, err.Error())
				return
			}
			var ok bool
			tokenString, ok = tok.Extra("id_token").(string)
			if !ok {
				handleErr(w, "no id_token in token response")
				return
			}
			refreshToken, _ = tok.Extra("refresh_token").(string)
		}
		successPage := `
		<div style="height:100px; width:100%!; display:flex; flex-direction: column; justify-content: center; align-items:center; background-color:#2ecc71; color:white; font-size:22"><div>Authentication successful!</div></div>
		<p style="margin-top:20px; font-size:18; text-align:center">Authentication was successful, you can now return to CLI. This page will close automatically</p>
		<script>window.onload=function(){setTimeout(this.close, 4000)}</script>
		`
		fmt.Fprint(w, successPage)
		completionChan <- ""
	}
	srv := &http.Server{Addr: "localhost:" + strconv.Itoa(port)}
	http.HandleFunc("/auth/callback", callbackHandler)

	// Redirect user to login & consent page to ask for permission for the scopes specified above.
	fmt.Printf("Opening browser for authentication\n")

	var url string
	grantType := oidcutil.InferGrantType(oauth2conf, oidcConf)
	switch grantType {
	case oidcutil.GrantTypeAuthorizationCode:
		url = oauth2conf.AuthCodeURL(stateNonce, oauth2.AccessTypeOffline)
	case oidcutil.GrantTypeImplicit:
		url = oidcutil.ImplicitFlowURL(oauth2conf, stateNonce, oauth2.AccessTypeOffline)
	default:
		log.Fatalf("Unsupported grant type: %v", grantType)
	}
	fmt.Printf("Performing %s flow login: %s\n", grantType, url)
	time.Sleep(1 * time.Second)
	err = open.Run(url)
	errors.CheckError(err)
	go func() {
		if err := srv.ListenAndServe(); err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()
	errMsg := <-completionChan
	if errMsg != "" {
		log.Fatal(errMsg)
	}
	fmt.Printf("Authentication successful\n")
	ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
	defer cancel()
	_ = srv.Shutdown(ctx)
	log.Debugf("Token: %s", tokenString)
	log.Debugf("Refresh Token: %s", refreshToken)
	return tokenString, refreshToken
}