package tokenservicelogic import ( "app-cloudep-permission-server/internal/domain" "app-cloudep-permission-server/internal/entity" "context" "time" ers "code.30cm.net/digimon/library-go/errors" "github.com/google/uuid" "app-cloudep-permission-server/gen_result/pb/permission" "app-cloudep-permission-server/internal/svc" "github.com/zeromicro/go-zero/core/logx" ) type NewOneTimeTokenLogic struct { ctx context.Context svcCtx *svc.ServiceContext logx.Logger } func NewNewOneTimeTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NewOneTimeTokenLogic { return &NewOneTimeTokenLogic{ ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx), } } // NewOneTimeToken 建立一次性使用,例如:RefreshToken func (l *NewOneTimeTokenLogic) NewOneTimeToken(in *permission.CreateOneTimeTokenReq) (*permission.CreateOneTimeTokenResp, error) { // 驗證所需 if err := l.svcCtx.Validate.ValidateAll(&refreshTokenReq{ Token: in.GetToken(), }); err != nil { return nil, ers.InvalidFormat(err.Error()) } // 驗證Token claims, err := parseClaims(in.GetToken(), l.svcCtx.Config.Token.Secret, false) if err != nil { logx.WithCallerSkip(1).WithFields( logx.Field("func", "parseClaims"), ).Error(err.Error()) return nil, err } token, err := l.svcCtx.TokenRedisRepo.GetAccessTokenByID(l.ctx, claims.ID()) if err != nil { logx.WithCallerSkip(1).WithFields( logx.Field("func", "TokenRedisRepo.GetByAccess"), logx.Field("claims", claims), ).Error(err.Error()) return nil, err } oneTimeToken := generateRefreshToken(uuid.Must(uuid.NewRandom()).String()) key := domain.TicketKeyPrefix + oneTimeToken if err = l.svcCtx.TokenRedisRepo.CreateOneTimeToken(l.ctx, key, entity.Ticket{ Data: claims, Token: token, }, time.Minute); err != nil { return &permission.CreateOneTimeTokenResp{}, err } return &permission.CreateOneTimeTokenResp{ OneTimeToken: oneTimeToken, }, nil }