Files
EdgeAPI/internal/db/models/api_token_dao.go

98 lines
2.1 KiB
Go
Raw Normal View History

2020-07-22 22:17:53 +08:00
package models
import (
_ "github.com/go-sql-driver/mysql"
"github.com/iwind/TeaGo/Tea"
"github.com/iwind/TeaGo/dbs"
)
const (
ApiTokenStateEnabled = 1 // 已启用
ApiTokenStateDisabled = 0 // 已禁用
)
type ApiTokenDAO dbs.DAO
func NewApiTokenDAO() *ApiTokenDAO {
return dbs.NewDAO(&ApiTokenDAO{
DAOObject: dbs.DAOObject{
DB: Tea.Env,
2020-09-23 10:12:57 +08:00
Table: "edgeAPITokens",
2020-07-22 22:17:53 +08:00
Model: new(ApiToken),
PkName: "id",
},
}).(*ApiTokenDAO)
}
2020-10-13 20:05:13 +08:00
var SharedApiTokenDAO *ApiTokenDAO
func init() {
dbs.OnReady(func() {
SharedApiTokenDAO = NewApiTokenDAO()
})
}
2020-07-22 22:17:53 +08:00
// 启用条目
func (this *ApiTokenDAO) EnableApiToken(tx *dbs.Tx, id uint32) (rowsAffected int64, err error) {
return this.Query(tx).
2020-07-22 22:17:53 +08:00
Pk(id).
Set("state", ApiTokenStateEnabled).
Update()
}
// 禁用条目
func (this *ApiTokenDAO) DisableApiToken(tx *dbs.Tx, id uint32) (rowsAffected int64, err error) {
return this.Query(tx).
2020-07-22 22:17:53 +08:00
Pk(id).
Set("state", ApiTokenStateDisabled).
Update()
}
// 查找启用中的条目
func (this *ApiTokenDAO) FindEnabledApiToken(tx *dbs.Tx, id uint32) (*ApiToken, error) {
result, err := this.Query(tx).
2020-07-22 22:17:53 +08:00
Pk(id).
Attr("state", ApiTokenStateEnabled).
Find()
if result == nil {
return nil, err
}
return result.(*ApiToken), err
}
// 获取节点Token信息
// TODO 需要添加缓存
func (this *ApiTokenDAO) FindEnabledTokenWithNode(tx *dbs.Tx, nodeId string) (*ApiToken, error) {
one, err := this.Query(tx).
2020-07-22 22:17:53 +08:00
Attr("nodeId", nodeId).
State(ApiTokenStateEnabled).
Find()
if one != nil {
return one.(*ApiToken), nil
}
return nil, err
}
2020-09-06 16:19:54 +08:00
2020-10-13 20:05:13 +08:00
// 根据角色获取节点
func (this *ApiTokenDAO) FindEnabledTokenWithRole(tx *dbs.Tx, role string) (*ApiToken, error) {
one, err := this.Query(tx).
2020-10-13 20:05:13 +08:00
Attr("role", role).
State(ApiTokenStateEnabled).
Find()
if one != nil {
return one.(*ApiToken), nil
}
return nil, err
}
2020-09-06 16:19:54 +08:00
// 保存API Token
func (this *ApiTokenDAO) CreateAPIToken(tx *dbs.Tx, nodeId string, secret string, role NodeRole) error {
2020-09-06 16:19:54 +08:00
op := NewApiTokenOperator()
op.NodeId = nodeId
op.Secret = secret
op.Role = role
op.State = ApiTokenStateEnabled
err := this.Save(tx, op)
2020-09-06 16:19:54 +08:00
return err
}