// ExchangeRefreshToken exchanges refreshToken for a new user token
173545
func (s *tokenServiceImpl) ExchangeRefreshToken(ctx context.Context, refreshToken string, rptToken string) (*manager.TokenSet, error) {

	tkn, err := s.tokenManager.Parse(ctx, refreshToken)
	if err != nil {
		return nil, errors.NewUnauthorizedError(err.Error())
	}

	err = s.ValidateToken(ctx, tkn)
	if err != nil {
		return nil, errors.NewUnauthorizedError(err.Error())
	}

	claims := tkn.Claims.(jwt.MapClaims)
	sub := claims["sub"]
	if sub == nil {
		return nil, errors.NewUnauthorizedError("missing 'sub' claim in the refresh token")
	}
	identityID, err := uuid.FromString(fmt.Sprintf("%s", sub))
	if err != nil {
		return nil, errors.NewUnauthorizedError(err.Error())
	}

	identity, err := s.Repositories().Identities().LoadWithUser(ctx, identityID)

	if err != nil {
		if unauth, _ := errors.IsUnauthorizedError(err); unauth {
			return nil, err
		}
		// It's OK if we didn't find the identity, if the token was issued for an API client
		// Just log it and proceed.
		log.Warn(ctx, map[string]interface{}{
			"err": err,
		}, "failed to load identity when refreshing token; it's OK if the token was issued for an API client")
	}

	if identity != nil && identity.User.Banned {
		log.Warn(ctx, map[string]interface{}{
			"identity_id": identity.ID,
			"user_name":   identity.Username,
		}, "banned user tried to refresh token")
		return nil, errors.NewUnauthorizedError("unauthorized access")
	}

	// Initialize an array of permission objects that *may* be included in the token
	permissions := []manager.Permissions{}

	// Initialize an array of TokenPrivilege objects so that we can persist a record of the token's privileges to the database
	tokenPrivs := []tokenrepo.TokenPrivilege{}

	var generatedToken *oauth2.Token

	err = s.ExecuteInTransaction(func() error {

		// if an RPT token is provided, then use it to generate a permissions claim for the refreshed token
		if identity != nil && rptToken != "" {

			// Parse the claims from the provided token string
			tokenClaims, err := s.tokenManager.ParseToken(ctx, rptToken)
			if err != nil {
				log.Error(ctx, map[string]interface{}{"error": err, "rptToken": rptToken}, "invalid RPT token could not be parsed")
				return errors.NewUnauthorizedError("invalid RPT token could not be parsed")
			}

			// Extract the id from the refresh token
			tokenID, err := uuid.FromString(tokenClaims.Id)
			if err != nil {
				log.Error(ctx, map[string]interface{}{"error": err, "rptToken": rptToken}, "could not extract token ID from RPT token")
				return errors.NewUnauthorizedError("could not extract token ID from RPT token")
			}

			loadedToken, err := s.Repositories().TokenRepository().Load(ctx, tokenID)
			if err != nil {
				// This is not an error per se, so we'll just log an informational message
				log.Info(ctx, map[string]interface{}{
					"token_id": tokenID,
				}, "token with specified id not found")
			}

			// check if the token is still valid
			if loadedToken != nil {
				// Confirm that the token belongs to the current identity
				if loadedToken.IdentityID != identity.ID {
					return errors.NewUnauthorizedError("invalid token for identity")
				}
				// We now process the various token status codes in order of priority, starting with DEPROVISIONED
				if loadedToken.HasStatus(authtoken.TOKEN_STATUS_DEPROVISIONED) {
					return errors.NewUnauthorizedErrorWithCode("token banned", errors.UNAUTHORIZED_CODE_TOKEN_DEPROVISIONED)
				}
				// If the token has been revoked or the user is logged out, we respond in the same way
				if loadedToken.HasStatus(authtoken.TOKEN_STATUS_REVOKED) || loadedToken.HasStatus(authtoken.TOKEN_STATUS_LOGGED_OUT) {
					return errors.NewUnauthorizedErrorWithCode("token revoked or logged out", errors.UNAUTHORIZED_CODE_TOKEN_REVOKED)
				}
			}

			// If we've gotten this far, it means that either no existing token was found, or the token that was found
			// has been marked with status STALE and its privileges have changed, in either case we must generate a new token

			// If an existing RPT token is being replaced with a new token, then populate it with the privileges from the
			// existing token.  HOWEVER, don't exceed the maximum configured permissions for the token
			if loadedToken != nil {
				oldTokenPrivs, err := s.Repositories().TokenRepository().ListPrivileges(ctx, loadedToken.TokenID)
				if err != nil {
					return errors.NewInternalError(ctx, err)
				}
				// Sort the old token privileges by expiry time, from latest to earliest
				sort.Slice(oldTokenPrivs, func(i, j int) bool {
					return oldTokenPrivs[i].ExpiryTime.After(oldTokenPrivs[j].ExpiryTime)
				})
				// Loop through the privileges stored in the previous token, and add them to the permissions of the
				// new token, breaking once the maximum permission limit has been hit
				for _, oldPriv := range oldTokenPrivs {
					// If we have hit the maximum permissions limit then break
					if len(permissions) >= s.config.GetRPTTokenMaxPermissions() {
						break
					}
					oldPrivResourceID := oldPriv.ResourceID
					if loadedToken.HasStatus(authtoken.TOKEN_STATUS_STALE) || oldPriv.Stale {
						privilegeCache, err := s.Services().PrivilegeCacheService().CachedPrivileges(ctx, identity.ID, oldPrivResourceID)
						if err != nil {
							return errors.NewInternalError(ctx, err)
						}

						log.Debug(ctx, map[string]interface{}{"resource_id": oldPrivResourceID,
							"new_scopes": privilegeCache.ScopesAsArray(), "old_scopes": oldPriv.ScopesAsArray()},
							"old privileges are stale")

						perm := &manager.Permissions{
							ResourceSetID: &oldPrivResourceID,
							Scopes:        privilegeCache.ScopesAsArray(),
							Expiry:        privilegeCache.ExpiryTime.Unix(),
						}
						permissions = append(permissions, *perm)
					} else {
						// Create a new permissions object for the RPT token and store it in the array
						perm := &manager.Permissions{
							ResourceSetID: &oldPrivResourceID,
							Scopes:        oldPriv.ScopesAsArray(),
							Expiry:        oldPriv.ExpiryTime.Unix(),
						}
						permissions = append(permissions, *perm)
					}
					// Create a token privilege object to store in the database
					tokenPriv := &tokenrepo.TokenPrivilege{
						PrivilegeCacheID: oldPriv.PrivilegeCacheID,
					}
					tokenPrivs = append(tokenPrivs, *tokenPriv)
				}
			}
		}

		// Generate the new user token
		generatedToken, err = s.tokenManager.GenerateUserTokenUsingRefreshToken(ctx, refreshToken, identity, permissions)
		if err != nil {
			return err
		}

		// Register the new token - if it has permission it's an RPT token, otherwise it's a standard access token
		if len(permissions) > 0 {
			_, err = s.RegisterToken(ctx, identity.ID, generatedToken.AccessToken, authtoken.TOKEN_TYPE_RPT, tokenPrivs)
		} else {
			_, err = s.RegisterToken(ctx, identity.ID, generatedToken.AccessToken, authtoken.TOKEN_TYPE_ACCESS, nil)
		}

		if err != nil {
			log.Error(ctx, map[string]interface{}{"error": err}, "could not register token")
			return errors.NewInternalError(ctx, err)
		}

		// Register the refresh token
		_, err = s.RegisterToken(ctx, identity.ID, generatedToken.RefreshToken, authtoken.TOKEN_TYPE_REFRESH, nil)
		if err != nil {
			log.Error(ctx, map[string]interface{}{"error": err}, "could not register token")
			return errors.NewInternalError(ctx, err)
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	return s.tokenManager.ConvertToken(*generatedToken)
}
1305355
func (tracker *VoteTracker) refreshRCI() (*dcrjson.GetVoteInfoResult, error) {
	oldVersion := tracker.Version()
	v := oldVersion
	var err error
	var voteInfo, vinfo *dcrjson.GetVoteInfoResult

	// Retrieves the voteinfo for the last stake version supported.
	for {
		vinfo, err = tracker.node.GetVoteInfo(v)
		if err != nil {
			break
		}
		voteInfo = vinfo
		v++
	}

	if voteInfo == nil {
		return nil, fmt.Errorf("Vote information not found: %v", err)
	}
	if v > oldVersion+1 {
		tracker.mtx.Lock()
		tracker.version = v
		tracker.mtx.Unlock()
	}
	return voteInfo, nil
}
1248996
func (s *ReindexService) Refresh(refresh string) *ReindexService {
	s.refresh = refresh
	return s
}
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
}
1283931
func (s *AuthenticationResultType) SetRefreshToken(v string) *AuthenticationResultType {
	s.RefreshToken = &v
	return s
}
1217608
func (m *tokenManager) GenerateUserTokenUsingRefreshToken(ctx context.Context, refreshTokenString string,
	identity *repository.Identity, permissions []Permissions) (*oauth2.Token, error) {

	nowTime := time.Now().Unix()
	unsignedAccessToken, err := m.GenerateUnsignedUserAccessTokenFromRefreshToken(ctx, refreshTokenString, identity)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	if permissions != nil && len(permissions) > 0 {
		claims := unsignedAccessToken.Claims.(jwt.MapClaims)
		claims["permissions"] = permissions
	}

	accessToken, err := unsignedAccessToken.SignedString(m.userAccountPrivateKey.Key)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	unsignedRefreshToken, err := m.GenerateUnsignedUserRefreshToken(ctx, refreshTokenString, identity)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	refreshToken, err := unsignedRefreshToken.SignedString(m.userAccountPrivateKey.Key)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	var nbf int64

	token := &oauth2.Token{
		AccessToken:  accessToken,
		RefreshToken: refreshToken,
		Expiry:       time.Unix(nowTime+m.config.GetAccessTokenExpiresIn(), 0),
		TokenType:    "Bearer",
	}

	// Derivative OAuth2 claims "expires_in" and "refresh_expires_in"
	extra := make(map[string]interface{})
	extra["expires_in"] = m.config.GetAccessTokenExpiresIn()
	extra["refresh_expires_in"] = m.config.GetRefreshTokenExpiresIn()
	extra["not_before_policy"] = nbf

	token = token.WithExtra(extra)

	return token, nil
}
1176324
func (s *ClusterPairServer) ResetToken(
	ctx context.Context,
	req *api.SdkClusterPairResetTokenRequest,
) (*api.SdkClusterPairResetTokenResponse, error) {
	if s.cluster() == nil {
		return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
	}

	resp, err := s.cluster().GetPairToken(true)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "Cannot generate token: %v", err)
	}
	return &api.SdkClusterPairResetTokenResponse{
		Result: resp,
	}, nil
}
953515
func (m *Registry) SchemaRefresh(name string) error {
	m.mu.RLock()
	s, ok := m.schemas[name]
	m.mu.RUnlock()
	if !ok {
		return ErrNotFound
	}
	return m.applyer.AddOrUpdateOnSchema(s, s)
}
723244
func (s *Server) handleRefreshToken(w http.ResponseWriter, r *http.Request, client storage.Client) {
	code := r.PostFormValue("refresh_token")
	scope := r.PostFormValue("scope")
	if code == "" {
		s.tokenErrHelper(w, errInvalidRequest, "No refresh token in request.", http.StatusBadRequest)
		return
	}

	token := new(internal.RefreshToken)
	if err := internal.Unmarshal(code, token); err != nil {
		// For backward compatibility, assume the refresh_token is a raw refresh token ID
		// if it fails to decode.
		//
		// Because refresh_token values that aren't unmarshable were generated by servers
		// that don't have a Token value, we'll still reject any attempts to claim a
		// refresh_token twice.
		token = &internal.RefreshToken{RefreshId: code, Token: ""}
	}

	refresh, err := s.storage.GetRefresh(token.RefreshId)
	if err != nil {
		s.logger.Errorf("failed to get refresh token: %v", err)
		if err == storage.ErrNotFound {
			s.tokenErrHelper(w, errInvalidRequest, "Refresh token is invalid or has already been claimed by another client.", http.StatusBadRequest)
		} else {
			s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
		}
		return
	}
	if refresh.ClientID != client.ID {
		s.logger.Errorf("client %s trying to claim token for client %s", client.ID, refresh.ClientID)
		s.tokenErrHelper(w, errInvalidRequest, "Refresh token is invalid or has already been claimed by another client.", http.StatusBadRequest)
		return
	}
	if refresh.Token != token.Token {
		s.logger.Errorf("refresh token with id %s claimed twice", refresh.ID)
		s.tokenErrHelper(w, errInvalidRequest, "Refresh token is invalid or has already been claimed by another client.", http.StatusBadRequest)
		return
	}

	// Per the OAuth2 spec, if the client has omitted the scopes, default to the original
	// authorized scopes.
	//
	// https://tools.ietf.org/html/rfc6749#section-6
	scopes := refresh.Scopes
	if scope != "" {
		requestedScopes := strings.Fields(scope)
		var unauthorizedScopes []string

		for _, s := range requestedScopes {
			contains := func() bool {
				for _, scope := range refresh.Scopes {
					if s == scope {
						return true
					}
				}
				return false
			}()
			if !contains {
				unauthorizedScopes = append(unauthorizedScopes, s)
			}
		}

		if len(unauthorizedScopes) > 0 {
			msg := fmt.Sprintf("Requested scopes contain unauthorized scope(s): %q.", unauthorizedScopes)
			s.tokenErrHelper(w, errInvalidRequest, msg, http.StatusBadRequest)
			return
		}
		scopes = requestedScopes
	}

	conn, err := s.getConnector(refresh.ConnectorID)
	if err != nil {
		s.logger.Errorf("connector with ID %q not found: %v", refresh.ConnectorID, err)
		s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
		return
	}
	ident := connector.Identity{
		UserID:        refresh.Claims.UserID,
		Username:      refresh.Claims.Username,
		Email:         refresh.Claims.Email,
		EmailVerified: refresh.Claims.EmailVerified,
		Groups:        refresh.Claims.Groups,
		ConnectorData: refresh.ConnectorData,
	}

	// Can the connector refresh the identity? If so, attempt to refresh the data
	// in the connector.
	//
	// TODO(ericchiang): We may want a strict mode where connectors that don't implement
	// this interface can't perform refreshing.
	if refreshConn, ok := conn.Connector.(connector.RefreshConnector); ok {
		newIdent, err := refreshConn.Refresh(r.Context(), parseScopes(scopes), ident)
		if err != nil {
			s.logger.Errorf("failed to refresh identity: %v", err)
			s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
			return
		}
		ident = newIdent
	}

	claims := storage.Claims{
		UserID:        ident.UserID,
		Username:      ident.Username,
		Email:         ident.Email,
		EmailVerified: ident.EmailVerified,
		Groups:        ident.Groups,
	}

	accessToken := storage.NewID()
	idToken, expiry, err := s.newIDToken(client.ID, claims, scopes, refresh.Nonce, accessToken, refresh.ConnectorID)
	if err != nil {
		s.logger.Errorf("failed to create ID token: %v", err)
		s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
		return
	}

	newToken := &internal.RefreshToken{
		RefreshId: refresh.ID,
		Token:     storage.NewID(),
	}
	rawNewToken, err := internal.Marshal(newToken)
	if err != nil {
		s.logger.Errorf("failed to marshal refresh token: %v", err)
		s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
		return
	}

	lastUsed := s.now()
	updater := func(old storage.RefreshToken) (storage.RefreshToken, error) {
		if old.Token != refresh.Token {
			return old, errors.New("refresh token claimed twice")
		}
		old.Token = newToken.Token
		// Update the claims of the refresh token.
		//
		// UserID intentionally ignored for now.
		old.Claims.Username = ident.Username
		old.Claims.Email = ident.Email
		old.Claims.EmailVerified = ident.EmailVerified
		old.Claims.Groups = ident.Groups
		old.ConnectorData = ident.ConnectorData
		old.LastUsed = lastUsed
		return old, nil
	}

	// Update LastUsed time stamp in refresh token reference object
	// in offline session for the user.
	if err := s.storage.UpdateOfflineSessions(refresh.Claims.UserID, refresh.ConnectorID, func(old storage.OfflineSessions) (storage.OfflineSessions, error) {
		if old.Refresh[refresh.ClientID].ID != refresh.ID {
			return old, errors.New("refresh token invalid")
		}
		old.Refresh[refresh.ClientID].LastUsed = lastUsed
		return old, nil
	}); err != nil {
		s.logger.Errorf("failed to update offline session: %v", err)
		s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
		return
	}

	// Update refresh token in the storage.
	if err := s.storage.UpdateRefreshToken(refresh.ID, updater); err != nil {
		s.logger.Errorf("failed to update refresh token: %v", err)
		s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
		return
	}

	s.writeAccessToken(w, idToken, accessToken, rawNewToken, expiry)
}
691656
func (conn *Connection) Refresh() (err error) {
	urlValues := url.Values{}

	urlValues.Set("grant_type", "password")
	urlValues.Set("client_id", conn.ConsumerKey)
	urlValues.Set("client_secret", conn.ConsumerSecret)
	urlValues.Set("username", conn.Username)
	urlValues.Set("password", conn.Password)

	resp, err := http.PostForm(conn.InstanceUrl+"/services/oauth2/token", urlValues)

	if err != nil {
		return err
	}

	body, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()

	if err != nil {
		return err
	}

	result := OAuthResponse{}

	err = json.Unmarshal(body, &result)

	if err != nil {
		return err
	}

	conn.AccessToken = result.AccessToken
	conn.InstanceUrl = result.InstanceUrl

	return nil
}
144861
func (u *modelUserEntity) Refresh() error {
	if u.user == nil {
		return nil
	}
	return u.user.Refresh()
}
882894
func (p *Provider) RefreshOAuth1Token(session *Session) error {
	newAccessToken, err := p.consumer.RefreshToken(session.AccessToken)
	if err != nil {
		return err
	}
	session.AccessToken = newAccessToken
	session.AccessTokenExpires = time.Now().UTC().Add(30 * time.Minute)
	return nil
}
845589
func (s *Credentials) SetRefreshToken(v string) *Credentials {
	s.RefreshToken = &v
	return s
}
390195
func (spt *ServicePrincipalToken) RefreshExchangeWithContext(ctx context.Context, resource string) error {
	spt.refreshLock.Lock()
	defer spt.refreshLock.Unlock()
	return spt.refreshInternal(ctx, resource)
}
250536
func (t *tokenWithProvider) refreshTokenWithRetries(ctx context.Context, prev, base *internal.Token) (tok *internal.Token, err error) {
	err = retry.Retry(ctx, transient.Only(retryParams), func() error {
		tok, err = t.provider.RefreshToken(ctx, prev, base)
		return err
	}, nil)
	return
}
1158643
func (b *blockServerRemoteClientHandler) RefreshAuthToken(
	ctx context.Context) {
	if v := ctx.Value(ctxBServerResetKey); v == b.name {
		b.log.CDebugf(ctx, "Avoiding resetAuth recursion")
		return
	}

	if err := b.resetAuth(ctx, b.client); err != nil {
		b.log.CDebugf(ctx, "%s: error refreshing auth token: %v", b.name, err)
	}
}
412633
func (u *User) Refresh() error {
	var udoc userDoc
	if err := u.st.getUser(u.Name(), &udoc); err != nil {
		return err
	}
	u.doc = udoc
	return nil
}