guard/internal/logic/tokenservice/new_one_time_token_logic.go

71 lines
1.9 KiB
Go
Raw Normal View History

2024-08-10 01:52:23 +00:00
package tokenservicelogic
import (
2024-08-10 01:52:23 +00:00
"ark-permission/internal/domain"
"ark-permission/internal/entity"
2024-08-08 08:10:38 +00:00
ers "code.30cm.net/wanderland/library-go/errors"
2024-08-08 03:02:13 +00:00
"context"
2024-08-11 12:21:42 +00:00
"github.com/google/uuid"
2024-08-10 01:52:23 +00:00
"time"
"ark-permission/gen_result/pb/permission"
"ark-permission/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
2024-08-10 01:52:23 +00:00
type NewOneTimeTokenLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
2024-08-10 01:52:23 +00:00
func NewNewOneTimeTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NewOneTimeTokenLogic {
return &NewOneTimeTokenLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
2024-08-12 14:19:34 +00:00
// NewOneTimeToken 建立一次性使用例如RefreshToken TODO 目前並無後續操作
2024-08-10 01:52:23 +00:00
func (l *NewOneTimeTokenLogic) NewOneTimeToken(in *permission.CreateOneTimeTokenReq) (*permission.CreateOneTimeTokenResp, error) {
2024-08-08 08:10:38 +00:00
// 驗證所需
2024-08-10 01:52:23 +00:00
if err := l.svcCtx.Validate.ValidateAll(&refreshTokenReq{
2024-08-08 08:10:38 +00:00
Token: in.GetToken(),
}); err != nil {
return nil, ers.InvalidFormat(err.Error())
}
2024-08-10 01:52:23 +00:00
// 驗證Token
2024-08-11 12:21:42 +00:00
claims, err := parseClaims(in.GetToken(), l.svcCtx.Config.Token.Secret, false)
2024-08-08 08:10:38 +00:00
if err != nil {
logx.WithCallerSkip(1).WithFields(
logx.Field("func", "parseClaims"),
).Error(err.Error())
return nil, err
}
2024-08-11 12:21:42 +00:00
token, err := l.svcCtx.TokenRedisRepo.GetAccessTokenByID(l.ctx, claims.ID())
2024-08-08 08:10:38 +00:00
if err != nil {
logx.WithCallerSkip(1).WithFields(
logx.Field("func", "TokenRedisRepo.GetByAccess"),
logx.Field("claims", claims),
).Error(err.Error())
return nil, err
}
2024-08-11 12:21:42 +00:00
oneTimeToken := generateRefreshToken(uuid.Must(uuid.NewRandom()).String())
2024-08-10 01:52:23 +00:00
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-08 08:10:38 +00:00
}
2024-08-10 01:52:23 +00:00
return &permission.CreateOneTimeTokenResp{
OneTimeToken: oneTimeToken,
}, nil
}