给出了这个 golang 代码,因为我的 golang 生锈了,所以很难自由批评。基本的刷新令牌流,但是我们将函数包装在 TX 函数中,以便在刷新流出现问题时允许回滚。我们需要返回该newToken值,但是refresh当它返回 refreshToken 时它只保存函数期间我们需要的值,具体取决于我传递给它的对象或指针是否分别返回新的空标记或 nil。package serviceimport ( "context" "database/sql" "errors" "strings" "github.com/api-oauth/pkg/models" "github.com/api-oauth/pkg/repository" "golang.org/x/oauth2")const minParts = 2type OAuthAPI interface { Exchange(context.Context, string) (*oauth2.Token, error) Refresh(context.Context, string) (*oauth2.Token, error)}type Service struct { repo repository.RepoInterface oauthAPI OAuthAPI}func New(api OAuthAPI, repo repository.RepoInterface) *Service { return &Service{repo: repo, oauthAPI: api}}var ( ErrNoRefreshTokenFound = errors.New("no refresh token found") errNoScopesReturn = errors.New("no scopes returned") errNoProfileFound = errors.New("no profile found"))func (s *Service) RefreshToken(ctx context.Context, clientID string, userID int64) (*oauth2.Token, error) { var newToken *oauth2.Token err := s.repo.InTx(s.refresh(ctx, clientID, userID, newToken)) if err != nil { return nil, err } return newToken, nil}func (s *Service) refresh(ctx context.Context, clientID string, userID int64, newToken *oauth2.Token) func(repo repository.Auth) error { return func(repo repository.Auth) error { oldToken, err := repo.GetToken(ctx, userID, clientID) if err != nil && err != sql.ErrNoRows { return err } if oldToken == nil { return ErrNoRefreshTokenFound } newToken, err = s.oauthAPI.Refresh(ctx, oldToken.Refresh) if err != nil { return err } }}试图RefreshToken返回更新的令牌信息
1 回答
慕婉清6462132
TA贡献1804条经验 获得超2个赞
通过地址newToken:
func (s *Service) RefreshToken(ctx context.Context, clientID string, userID int64) (*oauth2.Token, error) {
var newToken *oauth2.Token
err := s.repo.InTx(s.refresh(ctx, clientID, userID, &newToken))
...
并且,将refresh函数更改为:
func (s *Service) refresh(ctx context.Context, clientID string, userID int64, newToken **oauth2.Token) func(repo repository.Auth) error {
...
*newToken, err=...
- 1 回答
- 0 关注
- 77 浏览
添加回答
举报
0/150
提交
取消