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.UnLogin() 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{} tx := dao.DB().Where("token=?", token).Last(&tokenRow) if tx.Error == gorm.ErrRecordNotFound { return nil } return &tokenRow } func (s *TokenService) getTokenByUsername(username string) *entity.Token { tokenRow := entity.Token{} tx := dao.DB().Where("grant_to=?", username).Last(&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 }