登录与授权等

This commit is contained in:
2024-01-07 15:13:35 +08:00
parent 968eab9b06
commit ec548f4256
22 changed files with 248 additions and 53 deletions

View File

@@ -0,0 +1,54 @@
package service
import (
"github.com/gin-gonic/gin"
"mc-client-updater-server/pkg/dao"
"mc-client-updater-server/pkg/dao/entity"
"mc-client-updater-server/pkg/util"
)
type InstanceService struct {
ctx *gin.Context
}
func NewInstanceService(c *gin.Context) *InstanceService {
return &InstanceService{ctx: c}
}
func (s *InstanceService) AddInstance(name, updateURL string) (*entity.Instance, error) {
instEntity := entity.Instance{
Name: name,
UpdateURL: updateURL,
}
tx := dao.DB().Create(&instEntity)
if tx.Error != nil {
return nil, tx.Error
}
tx = dao.DB().Where(&instEntity).Last(&instEntity)
return &instEntity, tx.Error
}
func (s *InstanceService) GetInstanceByName(name string) (*entity.Instance, error) {
instEntity := entity.Instance{}
tx := dao.DB().Where("name=?", name).Last(&instEntity)
return &instEntity, tx.Error
}
func (s *InstanceService) NewGrantToken(instName string, expireStr string) (*entity.Grant, error) {
expireAt := util.MustParseSQLTime(expireStr)
grantEntity := entity.Grant{GrantTo: instName, ExpireAt: expireAt, Token: util.RandStr(32)}
tx := dao.DB().Create(&grantEntity)
if tx.Error != nil {
return nil, tx.Error
}
tx = dao.DB().Where(&grantEntity).Last(&grantEntity)
return &grantEntity, tx.Error
}
func (s *InstanceService) GetGrantByToken(token string) (*entity.Grant, error) {
grantEntity := entity.Grant{}
tx := dao.DB().Where("token=?", token).Last(&grantEntity)
return &grantEntity, tx.Error
}

View File

@@ -22,7 +22,7 @@ func (s *TokenService) VerifyToken(token string) (*entity.Token, bool) {
// 是否存在
tokenRow := s.getToken(token)
if tokenRow == nil {
res.Unauthorized()
res.UnLogin()
return nil, false
}
// 是否过期
@@ -34,8 +34,8 @@ func (s *TokenService) VerifyToken(token string) (*entity.Token, bool) {
}
func (s *TokenService) getToken(token string) *entity.Token {
tokenRow := entity.Token{Token: token}
tx := dao.DB().Last(&tokenRow)
tokenRow := entity.Token{}
tx := dao.DB().Where("token=?", token).Last(&tokenRow)
if tx.Error == gorm.ErrRecordNotFound {
return nil
}
@@ -43,8 +43,8 @@ func (s *TokenService) getToken(token string) *entity.Token {
}
func (s *TokenService) getTokenByUsername(username string) *entity.Token {
tokenRow := entity.Token{GrantTo: username}
tx := dao.DB().First(&tokenRow)
tokenRow := entity.Token{}
tx := dao.DB().Where("grant_to=?", username).Last(&tokenRow)
if tx.Error == gorm.ErrRecordNotFound {
return nil
}

View File

@@ -64,8 +64,8 @@ func (s *UserService) hasRole(role string, user *entity.User) bool {
}
func (s *UserService) getUserByUsername(name string) *entity.User {
user := entity.User{Username: name}
tx := dao.DB().First(&user)
user := entity.User{}
tx := dao.DB().Where("username=?", name).First(&user)
if tx.Error != nil {
return nil
}