guard/internal/logic/tokenservice/validation_token_logic.go

69 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/gen_result/pb/permission"
"ark-permission/internal/svc"
2024-08-12 14:19:34 +00:00
ers "code.30cm.net/wanderland/library-go/errors"
"context"
2024-08-10 01:52:23 +00:00
"github.com/zeromicro/go-zero/core/logx"
)
2024-08-10 01:52:23 +00:00
type ValidationTokenLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
2024-08-10 01:52:23 +00:00
func NewValidationTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ValidationTokenLogic {
return &ValidationTokenLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
2024-08-10 01:52:23 +00:00
type refreshTokenReq struct {
2024-08-08 03:02:13 +00:00
Token string `json:"token" validate:"required"`
}
2024-08-10 01:52:23 +00:00
// ValidationToken 驗證這個 Token 有沒有效
func (l *ValidationTokenLogic) ValidationToken(in *permission.ValidationTokenReq) (*permission.ValidationTokenResp, 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-11 12:21:42 +00:00
claims, err := parseClaims(in.GetToken(), l.svcCtx.Config.Token.Secret, true)
2024-08-08 08:10:38 +00:00
if err != nil {
logx.WithCallerSkip(1).WithFields(
logx.Field("func", "parseClaims"),
2024-08-12 14:19:34 +00:00
).Info(err.Error())
2024-08-08 08:10:38 +00:00
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-10 01:52:23 +00:00
return &permission.ValidationTokenResp{
Token: &permission.Token{
Id: token.ID,
Uid: token.UID,
DeviceId: token.DeviceID,
AccessCreateAt: token.AccessCreateAt.Unix(),
AccessToken: token.AccessToken,
ExpiresIn: int32(token.ExpiresIn),
RefreshToken: token.RefreshToken,
RefreshExpiresIn: int32(token.RefreshExpiresIn),
RefreshCreateAt: token.RefreshCreateAt.Unix(),
},
Data: claims,
}, nil
}