mc-client-updater-server/internal/service/token.go

58 lines
1.3 KiB
Go

package service
import (
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"mc-client-updater-server/pkg/dao"
"mc-client-updater-server/pkg/dao/entity"
"mc-client-updater-server/pkg/result"
"time"
)
type TokenService struct {
ctx *gin.Context
}
func NewTokenService(c *gin.Context) *TokenService {
return &TokenService{ctx: c}
}
func (s *TokenService) VerifyToken(token string) (*entity.Token, bool) {
res := result.NewResult(s.ctx)
// 是否存在
tokenRow := s.getToken(token)
if tokenRow == nil {
res.Unauthorized()
return nil, false
}
// 是否过期
if tokenRow.TTL != 0 && int(time.Since(tokenRow.CreatedAt).Seconds()) > tokenRow.TTL {
res.LoginExpired()
return tokenRow, false
}
return tokenRow, true
}
func (s *TokenService) getToken(token string) *entity.Token {
tokenRow := entity.Token{Token: token}
tx := dao.DB().Last(&tokenRow)
if tx.Error == gorm.ErrRecordNotFound {
return nil
}
return &tokenRow
}
func (s *TokenService) getTokenByUsername(username string) *entity.Token {
tokenRow := entity.Token{GrantTo: username}
tx := dao.DB().First(&tokenRow)
if tx.Error == gorm.ErrRecordNotFound {
return nil
}
return &tokenRow
}
func (s *TokenService) AddToken(tokenObj *entity.Token) error {
tx := dao.DB().Create(tokenObj)
return tx.Error
}