// LoadToken loads and returns an OAuth token.
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
}
1177897
func (s *CreateCacheClusterInput) SetAuthToken(v string) *CreateCacheClusterInput {
	s.AuthToken = &v
	return s
}
180514
func RequestToken(clientCfg *restclient.Config, reader io.Reader, defaultUsername string, defaultPassword string) (string, error) {
	return NewRequestTokenOptions(clientCfg, reader, defaultUsername, defaultPassword, false).RequestToken()
}
45727
func (user *User) OAuthToken() string {
	// todo: oauthtoken per host?
	/*
		host := user.ctx.ServiceBaseURL.Host

		if host == "" {
			host = user.ctx.Service().DefaultBaseURL.Host
		}
	*/
	ps, _ := user.protectedSettings()

	if ps != nil {
		if ps.OAuthExpireDate != nil && ps.OAuthExpireDate.Before(time.Now().Add(time.Second*5)) {
			token, err := user.ctx.OAuthProvider().OAuth2Client(user.ctx).TokenSource(oauth2.NoContext, &oauth2.Token{AccessToken: ps.OAuthToken, Expiry: *ps.OAuthExpireDate, RefreshToken: ps.OAuthRefreshToken}).Token()

			if err != nil {
				if strings.Contains(err.Error(), "revoked") || strings.Contains(err.Error(), "invalid_grant") {
					//remove stored OAuthToken
					//todo: provide revoked callback
					ps.OAuthToken = ""
					ps.OAuthExpireDate = nil
					user.saveProtectedSettings()
				}
				user.ctx.Log().WithError(err).Error("OAuth token refresh failed")
				return ""
			}

			if token != nil {
				ps.OAuthToken = token.AccessToken
				if token.RefreshToken != "" {
					ps.OAuthRefreshToken = token.RefreshToken
				}
				ps.OAuthExpireDate = &token.Expiry
				user.saveProtectedSettings()

			}

		}
		return ps.OAuthToken
	}

	return ""
}
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
}
8502
func (s *service) AuthorizeToken(ctx context.Context, hostname, path, token string) (*sessions.Session, error) {
	resourceCh, resourceErrCh := make(chan *resources.Resource, 1), make(chan error, 1)
	sessionCh, sessionErrCh := make(chan *sessions.Session, 1), make(chan error, 1)
	go func() {
		session, err := s.sessionRepo.FindByToken(ctx, token)
		if err != nil {
			sessionErrCh <- err
			close(sessionCh)
			return
		}
		sessionCh <- session
		close(sessionErrCh)
	}()
	go func() {
		resource, err := s.resourceRepo.FindByHostname(ctx, hostname)
		if err != nil {
			resourceErrCh <- err
			close(resourceCh)
			return
		}
		resourceCh <- resource
		close(resourceErrCh)
	}()
	// If we can't find a resource, we deny the access
	// Otherwise, the access is denied with an error
	if err := <-resourceErrCh; err != nil {
		if isErrNotFound(err) {
			return nil, withErrDeniedAccess(err)
		}
		return nil, err

	}
	resource := <-resourceCh
	// If the found resource is marked as public, we allow the access without condition
	if resource.Public != nil && *resource.Public {
		return nil, nil
	}
	// If no session is found for the token, we initiate a guest session
	// Otherwise, the access is denied with an error
	if err := <-sessionErrCh; err != nil {
		if isErrNotFound(err) {
			return s.authorizeGuestSession(ctx, path, resource.Name)
		}
		return nil, err
	}
	foundSession := <-sessionCh
	// If a session is found, we try to authorize it
	session, err := s.authorizeSession(ctx, path, resource.Name, foundSession)
	if err != nil {
		// If denied, we at least try to authorize as guest
		if isErrDeniedAccess(err) {
			if _, err := s.authorizeGuestSession(ctx, path, resource.Name); err != nil {
				return nil, err
			}
			return foundSession, nil
		}
		return nil, err
	}
	// If found, we return it
	return session, nil
}
221355
func (a *Authorization) GetToken() string {
	if a == nil || a.Token == nil {
		return ""
	}
	return *a.Token
}
595554
func (c *UserConfig) GetRequestToken(service *Service, client *http.Client) error {
	data := url.Values{}
	if service.ClientConfig.CallbackURL != "" {
		data.Set("oauth_callback", service.ClientConfig.CallbackURL)
	}
	body := strings.NewReader(data.Encode())
	request, err := http.NewRequest("POST", service.RequestURL, body)
	if err != nil {
		return err
	}
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	response, err := c.send(request, service, client)
	if err != nil {
		return err
	}
	err = c.parseRequestToken(response)
	return err
}
300305
func MustAuthToken(ctx context.Context) *types.AuthToken {
	return ctx.Value(AuthTokenKey).(*types.AuthToken)
}
547628
func (m *manager) GetToken(opts *auth.Options) (string, error) {
	signature, err := auth.NewSignatureSharedSecret(m.config.SharedSecret)
	if err != nil {
		return "", err
	}

	return auth.Token(m.claims, signature, opts)
}
1022797
func (us UsersService) GetToken(username, password string, client Client) (string, error) {
	req := network.Request{
		Method:        "POST",
		Path:          "/oauth/token",
		Authorization: network.NewBasicAuthorization(client.ID, ""),
		Body: network.NewFormRequestBody(url.Values{
			"username":      []string{username},
			"password":      []string{password},
			"grant_type":    []string{"password"},
			"response_type": []string{"token"},
		}),
		AcceptableStatusCodes: []int{http.StatusOK},
	}

	resp, err := newNetworkClient(us.config).MakeRequest(req)
	if err != nil {
		return "", translateError(err)
	}

	var responseBody struct {
		AccessToken string `json:"access_token"`
	}
	err = json.Unmarshal(resp.Body, &responseBody)
	if err != nil {
		return "", MalformedResponseError{err}
	}

	return responseBody.AccessToken, nil
}
478974
func (s *OAuth2Storage) LoadAuthorize(code string) (*osin.AuthorizeData, error) {
	authorize := new(OAuth2AuthorizeData)
	e := Db().Model(OAuth2AuthorizeData{}).Where(&OAuth2AuthorizeData{Code: code}).Scan(authorize)
	if e != nil {
		return nil, e
	}
	if code != authorize.Code {
		return nil, errors.New("Authorization data not found")
	}

	authData := &osin.AuthorizeData{
		Code:        code,
		CreatedAt:   authorize.CreatedAt.Round(time.Second),
		ExpiresIn:   int32(authorize.ExpiresIn),
		RedirectUri: authorize.RedirectURI,
		Scope:       authorize.Scope,
		//State:       authorize.State,
		UserData: authorize.UserID}

	if authData.IsExpired() {
		return nil, errors.New("Authorization data expired")
	}

	if client, err := s.GetClient(strconv.FormatUint(authorize.ClientID, 10)); err == nil {
		authData.Client = client
		return authData, nil
	}
	return nil, errors.New("LoadAuthorize: Client not found")
}
271790
func (d *Decoder) RawToken() (Token, error) {
	if d.unmarshalDepth > 0 {
		return nil, errRawToken
	}
	return d.rawToken()
}
1174835
func GoogleToken(file, clientID, clientSecret, scope string) (*oauth.Transport, error) {
	cfg := &oauth.Config{
		ClientId:     clientID,
		ClientSecret: clientSecret,
		Scope:        scope,
		AuthURL:      "https://accounts.google.com/o/oauth2/auth",
		TokenURL:     "https://accounts.google.com/o/oauth2/token",
	}
	return Token(file, cfg)
}
1172764
func (i *InstallationToken) GetToken() string {
	if i == nil || i.Token == nil {
		return ""
	}
	return *i.Token
}
394789
func (ts *tokenServer) getToken(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	dcontext.GetLogger(ctx).Info("getToken")

	params := r.URL.Query()
	service := params.Get("service")
	scopeSpecifiers := params["scope"]
	var offline bool
	if offlineStr := params.Get("offline_token"); offlineStr != "" {
		var err error
		offline, err = strconv.ParseBool(offlineStr)
		if err != nil {
			handleError(ctx, ErrorBadTokenOption.WithDetail(err), w)
			return
		}
	}

	requestedAccessList := ResolveScopeSpecifiers(ctx, scopeSpecifiers)

	authorizedCtx, err := ts.accessController.Authorized(ctx, requestedAccessList...)
	if err != nil {
		challenge, ok := err.(auth.Challenge)
		if !ok {
			handleError(ctx, err, w)
			return
		}

		// Get response context.
		ctx, w = dcontext.WithResponseWriter(ctx, w)

		challenge.SetHeaders(r, w)
		handleError(ctx, errcode.ErrorCodeUnauthorized.WithDetail(challenge.Error()), w)

		dcontext.GetResponseLogger(ctx).Info("get token authentication challenge")

		return
	}
	ctx = authorizedCtx

	username := dcontext.GetStringValue(ctx, "auth.user.name")

	ctx = context.WithValue(ctx, acctSubject{}, username)
	ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, acctSubject{}))

	dcontext.GetLogger(ctx).Info("authenticated client")

	ctx = context.WithValue(ctx, requestedAccess{}, requestedAccessList)
	ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, requestedAccess{}))

	grantedAccessList := filterAccessList(ctx, username, requestedAccessList)
	ctx = context.WithValue(ctx, grantedAccess{}, grantedAccessList)
	ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, grantedAccess{}))

	token, err := ts.issuer.CreateJWT(username, service, grantedAccessList)
	if err != nil {
		handleError(ctx, err, w)
		return
	}

	dcontext.GetLogger(ctx).Info("authorized client")

	response := tokenResponse{
		Token:     token,
		ExpiresIn: int(ts.issuer.Expiration.Seconds()),
	}

	if offline {
		response.RefreshToken = newRefreshToken()
		ts.refreshCache[response.RefreshToken] = refreshToken{
			subject: username,
			service: service,
		}
	}

	ctx, w = dcontext.WithResponseWriter(ctx, w)

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)

	dcontext.GetResponseLogger(ctx).Info("get token complete")
}
330708
func (l *Loader) LoadedWallet() (*Wallet, bool) {
	l.mu.Lock()
	w := l.wallet
	l.mu.Unlock()
	return w, w != nil
}