// renewToken is called to mint a new token or update existing one.
//
// It is called from non-interactive 'refreshToken' method, and thus it can't
// use interactive login flow.
326796
func (t *tokenWithProvider) renewToken(ctx context.Context, prev, base *internal.Token) (*internal.Token, error) {
	if prev == nil {
		if t.provider.RequiresInteraction() {
			return nil, ErrLoginRequired
		}
		logging.Debugf(ctx, "Minting a new token")
		tok, err := t.mintTokenWithRetries(ctx, base)
		if err != nil {
			logging.Warningf(ctx, "Failed to mint a token: %s", err)
			return nil, err
		}
		return tok, nil
	}

	logging.Debugf(ctx, "Refreshing the token")
	tok, err := t.refreshTokenWithRetries(ctx, prev, base)
	if err != nil {
		logging.Warningf(ctx, "Failed to refresh the token: %s", err)
		return nil, err
	}
	return tok, nil
}
1056204
func NewAuthToken(signer Signer, tokenType string, expireIn int,
	submoduleName, version string, rh AuthTokenRefreshHandler) *AuthToken {
	clientName := fmt.Sprintf("go %s %s %s",
		submoduleName, libkb.GetPlatformString(), runtime.GOARCH)
	authToken := &AuthToken{
		signer:         signer,
		tokenType:      tokenType,
		expireIn:       expireIn,
		clientName:     clientName,
		clientVersion:  version,
		refreshHandler: rh,
	}
	return authToken
}
1226222
func (client *Client) RefreshAccessToken(refreshToken string) (RefreshedTokens, error) {
	var values url.Values

	switch client.config.UAAGrantType() {
	case string(constant.GrantTypeClientCredentials):
		values = client.clientCredentialRefreshBody()
	case "", string(constant.GrantTypePassword): // CLI used to write empty string for grant type in the case of password; preserve compatibility with old config.json files
		values = client.refreshTokenBody(refreshToken)
	}

	body := strings.NewReader(values.Encode())

	request, err := client.newRequest(requestOptions{
		RequestName: internal.PostOAuthTokenRequest,
		Header:      http.Header{"Content-Type": {"application/x-www-form-urlencoded"}},
		Body:        body,
	})
	if err != nil {
		return RefreshedTokens{}, err
	}

	if client.config.UAAGrantType() != string(constant.GrantTypeClientCredentials) {
		request.SetBasicAuth(client.config.UAAOAuthClient(), client.config.UAAOAuthClientSecret())
	}

	var refreshResponse RefreshedTokens
	response := Response{
		Result: &refreshResponse,
	}

	err = client.connection.Make(request, &response)
	if err != nil {
		return RefreshedTokens{}, err
	}

	return refreshResponse, nil
}
800469
func (tf *tokenRefresher) Token() (*Token, error) {
	if tf.refreshToken == "" {
		return nil, errors.New("oauth2: token expired and refresh token is not set")
	}

	tk, err := retrieveToken(tf.ctx, tf.conf, url.Values{
		"grant_type":    {"refresh_token"},
		"refresh_token": {tf.refreshToken},
	})

	if err != nil {
		return nil, err
	}
	if tf.refreshToken != tk.RefreshToken {
		tf.refreshToken = tk.RefreshToken
	}
	return tk, err
}
1022233
func (c *client) refreshAuthToken(localCfg *localconfig.LocalConfig, ctxName, configPath string) error {
	if c.RefreshToken == "" {
		// If we have no refresh token, there's no point in doing anything
		return nil
	}
	configCtx, err := localCfg.ResolveContext(ctxName)
	if err != nil {
		return err
	}
	parser := &jwt.Parser{
		SkipClaimsValidation: true,
	}
	var claims jwt.StandardClaims
	_, _, err = parser.ParseUnverified(configCtx.User.AuthToken, &claims)
	if err != nil {
		return err
	}
	if claims.Valid() == nil {
		// token is still valid
		return nil
	}

	log.Debug("Auth token no longer valid. Refreshing")
	rawIDToken, refreshToken, err := c.redeemRefreshToken()
	if err != nil {
		return err
	}
	c.AuthToken = rawIDToken
	c.RefreshToken = refreshToken
	localCfg.UpsertUser(localconfig.User{
		Name:         ctxName,
		AuthToken:    c.AuthToken,
		RefreshToken: c.RefreshToken,
	})
	err = localconfig.WriteLocalConfig(*localCfg, configPath)
	if err != nil {
		return err
	}
	return nil
}
102669
func (t *UAAAuthentication) refreshToken() error {
	var expiresIn time.Duration

	tokenStr := strings.TrimPrefix(t.cache.AccessToken(), "bearer ")
	token, err := jws.ParseJWT([]byte(tokenStr))
	if err != nil {
		// if the JWT could not be parsed, force a refresh
		expiresIn = 0
	} else {
		expiration, _ := token.Claims().Expiration()
		expiresIn = time.Until(expiration)
	}

	if expiresIn < accessTokenExpirationMargin {
		tokens, err := t.client.RefreshAccessToken(t.cache.RefreshToken())
		if err != nil {
			return err
		}
		t.cache.SetAccessToken(tokens.AuthorizationToken())
		t.cache.SetRefreshToken(tokens.RefreshToken)
	}
	return nil
}
208514
func (s *Service) RenewSession(ctx context.Context, session *platform.Session, newExpiration time.Time) error {
	if session == nil {
		return &platform.Error{
			Msg: "session is nil",
		}
	}
	session.ExpiresAt = newExpiration
	return s.PutSession(ctx, session)
}
894207
func (m *Manager) Renew(w http.ResponseWriter, s *Session) error {
	s.data = make(Data)
	return m.Regenerate(w, s)
}
848225
func (kv *consulKV) renewSession(
	pair *api.KVPair,
	ttl uint64,
	noCreate bool,
) (string, error) {
	// Check if there is any previous session with an active TTL
	session, err := kv.getActiveSession(pair.Key)
	if err != nil {
		logrus.Infof("Failed to find session: %v", err)
		return "", err
	}

	if session != "" {
		if noCreate {
			// Do not create new session for the key
			return "", kvdb.ErrModified
		}
		// Destroy the existing session associated with the key
		kv.client.Destroy(session, nil)
	}

	durationTTL := time.Duration(int64(ttl)) * time.Second

	entry := &api.SessionEntry{
		Behavior:  api.SessionBehaviorDelete, // Delete the key when the session expires
		TTL:       durationTTL.String(),
		LockDelay: 0, // Virtually disable lock delay
	}

	// Create the key session
	session, _, err = kv.client.Create(entry, nil)

	// Session timer is started after a call to "Renew"
	kv.client.Renew(session, nil)

	return session, err
}
1283931
func (s *AuthenticationResultType) SetRefreshToken(v string) *AuthenticationResultType {
	s.RefreshToken = &v
	return s
}
504271
func (m *MongoDB) RenewUser(ctx context.Context, statements dbplugin.Statements, username string, expiration time.Time) error {
	// NOOP
	return nil
}
229707
func (c *client) redeemRefreshToken() (string, string, error) {
	setConn, setIf, err := c.NewSettingsClient()
	if err != nil {
		return "", "", err
	}
	defer func() { _ = setConn.Close() }()
	httpClient, err := c.HTTPClient()
	if err != nil {
		return "", "", err
	}
	ctx := oidc.ClientContext(context.Background(), httpClient)
	acdSet, err := setIf.Get(ctx, &settings.SettingsQuery{})
	if err != nil {
		return "", "", err
	}
	oauth2conf, _, err := c.OIDCConfig(ctx, acdSet)
	if err != nil {
		return "", "", err
	}
	t := &oauth2.Token{
		RefreshToken: c.RefreshToken,
	}
	token, err := oauth2conf.TokenSource(ctx, t).Token()
	if err != nil {
		return "", "", err
	}
	rawIDToken, ok := token.Extra("id_token").(string)
	if !ok {
		return "", "", errors.New("no id_token in token response")
	}
	refreshToken, _ := token.Extra("refresh_token").(string)
	return rawIDToken, refreshToken, nil
}
399767
func (cp *ConsulClient) renewService(keyName, ttl, sessionID string, jsonVal []byte, stopChan chan struct{}) {
	for {
		err := cp.client.Session().RenewPeriodic(ttl, sessionID, nil, stopChan)
		if err == nil {
			log.Infof("Stoping renew on %s", keyName)
			return
		}
		log.Infof("RenewPeriodic for session %s exited with error: %v. Retrying..", keyName, err)

		// session configuration
		sessCfg := api.SessionEntry{
			Name:      keyName,
			Behavior:  "delete",
			LockDelay: 10 * time.Millisecond,
			TTL:       ttl,
		}

		// Create consul session
		sessionID, _, err = cp.client.Session().CreateNoChecks(&sessCfg, nil)
		if err != nil {
			log.Errorf("Error Creating session for lock %s. Err: %v", keyName, err)
		}

		// Delete the old key if it exists..
		log.Infof("Deleting old service entry for key %s", keyName)
		_, err = cp.client.KV().Delete(keyName, nil)
		if err != nil {
			log.Errorf("Error deleting key %s. Err: %v", keyName, err)
		}

		// Set it via consul client
		succ, _, err := cp.client.KV().Acquire(&api.KVPair{Key: keyName, Value: jsonVal, Session: sessionID}, nil)
		if err != nil {
			log.Errorf("Error setting key %s, Err: %v", keyName, err)
		} else if !succ {
			log.Errorf("Failed to acquire key %s. Already acquired", keyName)
		}
	}
}
1155766
func (auth *Auth) ResetUserToken(user *User) {
	user.Token = RandomKey()
	user.TokenSetAt = time.Now()

	// Update the user before generating an email
	stmt := Users.Update().Values(
		sol.Values{"token": user.Token, "token_set_at": user.TokenSetAt},
	).Where(Users.C("id").Equals(user.ID))
	auth.conn.Query(stmt)
}
155800
func (r *Renewer) Renew() {
	var result error
	if r.secret.Auth != nil {
		result = r.renewAuth()
	} else {
		result = r.renewLease()
	}

	r.doneCh <- result
}
714721
func NewTokenRefresher(uaaClient UAAClient, cache TokenCache) *TokenRefresher {
	return &TokenRefresher{
		uaaClient: uaaClient,
		cache:     cache,
	}
}
990069
func RefreshToken(f TokenFunc, filename string) (int64, error) {
	log.Debug("Refreshing authentication token")
	token, expires, err := f()
	if err != nil {
		return 0, err
	}
	updateToken(token, time.Unix(expires, 0), filename)
	log.WithField("expiration", expires).Info("Received new authentication token")
	return expires, err
}