2022-10-04 00:36:01 +08:00
|
|
|
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 {
|
2024-01-07 15:13:35 +08:00
|
|
|
res.UnLogin()
|
2022-10-04 00:36:01 +08:00
|
|
|
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 {
|
2024-01-07 15:13:35 +08:00
|
|
|
tokenRow := entity.Token{}
|
|
|
|
tx := dao.DB().Where("token=?", token).Last(&tokenRow)
|
2022-10-04 00:36:01 +08:00
|
|
|
if tx.Error == gorm.ErrRecordNotFound {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return &tokenRow
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *TokenService) getTokenByUsername(username string) *entity.Token {
|
2024-01-07 15:13:35 +08:00
|
|
|
tokenRow := entity.Token{}
|
|
|
|
tx := dao.DB().Where("grant_to=?", username).Last(&tokenRow)
|
2022-10-04 00:36:01 +08:00
|
|
|
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
|
|
|
|
}
|