vaulterm/server/app/hosts/repository.go

70 lines
1.4 KiB
Go
Raw Normal View History

2024-11-07 19:07:41 +00:00
package hosts
import (
"gorm.io/gorm"
2024-11-16 02:34:07 +07:00
"rul.sh/vaulterm/server/db"
"rul.sh/vaulterm/server/models"
"rul.sh/vaulterm/server/utils"
2024-11-07 19:07:41 +00:00
)
type Hosts struct {
db *gorm.DB
User *utils.UserContext
}
2024-11-07 19:07:41 +00:00
func NewRepository(r *Hosts) *Hosts {
if r == nil {
r = &Hosts{}
}
r.db = db.Get()
return r
2024-11-07 19:07:41 +00:00
}
2024-11-12 17:17:10 +00:00
func (r *Hosts) GetAll(opt GetAllOpt) ([]*models.Host, error) {
query := r.db.Order("id DESC")
if opt.TeamID != "" {
query = query.Where("hosts.team_id = ?", opt.TeamID)
} else {
query = query.Where("hosts.owner_id = ? AND hosts.team_id IS NULL", r.User.ID)
}
2024-11-07 19:07:41 +00:00
var rows []*models.Host
ret := query.Find(&rows)
2024-11-07 19:07:41 +00:00
return rows, ret.Error
}
2024-11-09 14:37:09 +00:00
func (r *Hosts) Get(id string) (*models.HostDecrypted, error) {
var host models.Host
2024-11-12 17:17:10 +00:00
ret := r.db.Joins("Key").Joins("AltKey").Where("hosts.id = ?", id).First(&host)
2024-11-07 19:07:41 +00:00
if ret.Error != nil {
return nil, ret.Error
}
2024-11-09 14:37:09 +00:00
res, err := host.DecryptKeys()
if err != nil {
return nil, err
2024-11-07 19:07:41 +00:00
}
return res, ret.Error
}
2024-11-09 10:33:07 +00:00
func (r *Hosts) Exists(id string) (bool, error) {
var count int64
2024-11-12 17:17:10 +00:00
ret := r.db.Model(&models.Host{}).Where("id = ?", id).Count(&count)
2024-11-09 10:33:07 +00:00
return count > 0, ret.Error
}
2024-11-07 19:07:41 +00:00
func (r *Hosts) Create(item *models.Host) error {
return r.db.Create(item).Error
}
2024-11-09 10:33:07 +00:00
2024-11-09 18:57:36 +00:00
func (r *Hosts) Update(id string, item *models.Host) error {
2024-11-12 17:17:10 +00:00
return r.db.Where("id = ?", id).Updates(item).Error
2024-11-09 10:33:07 +00:00
}
2024-11-14 17:58:19 +07:00
func (r *Hosts) Delete(id string) error {
return r.db.Delete(&models.Host{Model: models.Model{ID: id}}).Error
}