2024-08-24 07:14:58 +00:00
|
|
|
|
package tokenservicelogic
|
|
|
|
|
|
|
|
|
|
import (
|
2024-08-24 14:40:09 +00:00
|
|
|
|
"app-cloudep-permission-server/internal/domain"
|
|
|
|
|
"app-cloudep-permission-server/internal/entity"
|
|
|
|
|
ers "code.30cm.net/digimon/library-go/errors"
|
2024-08-24 07:14:58 +00:00
|
|
|
|
"context"
|
2024-08-24 14:40:09 +00:00
|
|
|
|
"github.com/google/uuid"
|
|
|
|
|
"time"
|
2024-08-24 07:14:58 +00:00
|
|
|
|
|
|
|
|
|
"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) {
|
2024-08-24 14:40:09 +00:00
|
|
|
|
// 驗證所需
|
|
|
|
|
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
|
|
|
|
|
}
|
2024-08-24 07:14:58 +00:00
|
|
|
|
|
2024-08-24 14:40:09 +00:00
|
|
|
|
return &permission.CreateOneTimeTokenResp{
|
|
|
|
|
OneTimeToken: oneTimeToken,
|
|
|
|
|
}, nil
|
2024-08-24 07:14:58 +00:00
|
|
|
|
}
|