完成重构数据库操作代码
This commit is contained in:
@ -1,9 +1,5 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"next-terminal/server/global"
|
||||
)
|
||||
|
||||
type AccessSecurity struct {
|
||||
ID string `json:"id"`
|
||||
Rule string `json:"rule"`
|
||||
@ -15,69 +11,3 @@ type AccessSecurity struct {
|
||||
func (r *AccessSecurity) TableName() string {
|
||||
return "access_securities"
|
||||
}
|
||||
|
||||
func FindAllAccessSecurities() (o []AccessSecurity, err error) {
|
||||
db := global.DB
|
||||
err = db.Order("priority asc").Find(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func FindPageSecurity(pageIndex, pageSize int, ip, rule, order, field string) (o []AccessSecurity, total int64, err error) {
|
||||
t := AccessSecurity{}
|
||||
db := global.DB.Table(t.TableName())
|
||||
dbCounter := global.DB.Table(t.TableName())
|
||||
|
||||
if len(ip) > 0 {
|
||||
db = db.Where("ip like ?", "%"+ip+"%")
|
||||
dbCounter = dbCounter.Where("ip like ?", "%"+ip+"%")
|
||||
}
|
||||
|
||||
if len(rule) > 0 {
|
||||
db = db.Where("rule = ?", rule)
|
||||
dbCounter = dbCounter.Where("rule = ?", rule)
|
||||
}
|
||||
|
||||
err = dbCounter.Count(&total).Error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if order == "descend" {
|
||||
order = "desc"
|
||||
} else {
|
||||
order = "asc"
|
||||
}
|
||||
|
||||
if field == "ip" {
|
||||
field = "ip"
|
||||
} else if field == "rule" {
|
||||
field = "rule"
|
||||
} else {
|
||||
field = "priority"
|
||||
}
|
||||
|
||||
err = db.Order(field + " " + order).Find(&o).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Error
|
||||
if o == nil {
|
||||
o = make([]AccessSecurity, 0)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func CreateNewSecurity(o *AccessSecurity) error {
|
||||
return global.DB.Create(o).Error
|
||||
}
|
||||
|
||||
func UpdateSecurityById(o *AccessSecurity, id string) error {
|
||||
o.ID = id
|
||||
return global.DB.Updates(o).Error
|
||||
}
|
||||
|
||||
func DeleteSecurityById(id string) error {
|
||||
|
||||
return global.DB.Where("id = ?", id).Delete(AccessSecurity{}).Error
|
||||
}
|
||||
|
||||
func FindSecurityById(id string) (o *AccessSecurity, err error) {
|
||||
err = global.DB.Where("id = ?", id).First(&o).Error
|
||||
return
|
||||
}
|
||||
|
@ -1,10 +1,6 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"next-terminal/server/constant"
|
||||
"next-terminal/server/global"
|
||||
"next-terminal/server/utils"
|
||||
)
|
||||
|
||||
@ -45,195 +41,13 @@ func (r *Asset) TableName() string {
|
||||
return "assets"
|
||||
}
|
||||
|
||||
func FindAllAsset() (o []Asset, err error) {
|
||||
err = global.DB.Find(&o).Error
|
||||
return
|
||||
type AssetAttribute struct {
|
||||
Id string `gorm:"index" json:"id"`
|
||||
AssetId string `gorm:"index" json:"assetId"`
|
||||
Name string `gorm:"index" json:"name"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
func FindAssetByIds(assetIds []string) (o []Asset, err error) {
|
||||
err = global.DB.Where("id in ?", assetIds).Find(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func FindAssetByProtocol(protocol string) (o []Asset, err error) {
|
||||
err = global.DB.Where("protocol = ?", protocol).Find(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func FindAssetByProtocolAndIds(protocol string, assetIds []string) (o []Asset, err error) {
|
||||
err = global.DB.Where("protocol = ? and id in ?", protocol, assetIds).Find(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func FindAssetByConditions(protocol string, account User) (o []Asset, err error) {
|
||||
db := global.DB.Table("assets").Select("assets.id,assets.name,assets.ip,assets.port,assets.protocol,assets.active,assets.owner,assets.created, users.nickname as owner_name,COUNT(resource_sharers.user_id) as sharer_count").Joins("left join users on assets.owner = users.id").Joins("left join resource_sharers on assets.id = resource_sharers.resource_id").Group("assets.id")
|
||||
|
||||
if constant.TypeUser == account.Type {
|
||||
owner := account.ID
|
||||
db = db.Where("assets.owner = ? or resource_sharers.user_id = ?", owner, owner)
|
||||
}
|
||||
|
||||
if len(protocol) > 0 {
|
||||
db = db.Where("assets.protocol = ?", protocol)
|
||||
}
|
||||
err = db.Find(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func FindPageAsset(pageIndex, pageSize int, name, protocol, tags string, account User, owner, sharer, userGroupId, ip, order, field string) (o []AssetVo, total int64, err error) {
|
||||
db := global.DB.Table("assets").Select("assets.id,assets.name,assets.ip,assets.port,assets.protocol,assets.active,assets.owner,assets.created,assets.tags, users.nickname as owner_name,COUNT(resource_sharers.user_id) as sharer_count").Joins("left join users on assets.owner = users.id").Joins("left join resource_sharers on assets.id = resource_sharers.resource_id").Group("assets.id")
|
||||
dbCounter := global.DB.Table("assets").Select("DISTINCT assets.id").Joins("left join resource_sharers on assets.id = resource_sharers.resource_id").Group("assets.id")
|
||||
|
||||
if constant.TypeUser == account.Type {
|
||||
owner := account.ID
|
||||
db = db.Where("assets.owner = ? or resource_sharers.user_id = ?", owner, owner)
|
||||
dbCounter = dbCounter.Where("assets.owner = ? or resource_sharers.user_id = ?", owner, owner)
|
||||
|
||||
// 查询用户所在用户组列表
|
||||
userGroupIds, err := FindUserGroupIdsByUserId(account.ID)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if len(userGroupIds) > 0 {
|
||||
db = db.Or("resource_sharers.user_group_id in ?", userGroupIds)
|
||||
dbCounter = dbCounter.Or("resource_sharers.user_group_id in ?", userGroupIds)
|
||||
}
|
||||
} else {
|
||||
if len(owner) > 0 {
|
||||
db = db.Where("assets.owner = ?", owner)
|
||||
dbCounter = dbCounter.Where("assets.owner = ?", owner)
|
||||
}
|
||||
if len(sharer) > 0 {
|
||||
db = db.Where("resource_sharers.user_id = ?", sharer)
|
||||
dbCounter = dbCounter.Where("resource_sharers.user_id = ?", sharer)
|
||||
}
|
||||
|
||||
if len(userGroupId) > 0 {
|
||||
db = db.Where("resource_sharers.user_group_id = ?", userGroupId)
|
||||
dbCounter = dbCounter.Where("resource_sharers.user_group_id = ?", userGroupId)
|
||||
}
|
||||
}
|
||||
|
||||
if len(name) > 0 {
|
||||
db = db.Where("assets.name like ?", "%"+name+"%")
|
||||
dbCounter = dbCounter.Where("assets.name like ?", "%"+name+"%")
|
||||
}
|
||||
|
||||
if len(ip) > 0 {
|
||||
db = db.Where("assets.ip like ?", "%"+ip+"%")
|
||||
dbCounter = dbCounter.Where("assets.ip like ?", "%"+ip+"%")
|
||||
}
|
||||
|
||||
if len(protocol) > 0 {
|
||||
db = db.Where("assets.protocol = ?", protocol)
|
||||
dbCounter = dbCounter.Where("assets.protocol = ?", protocol)
|
||||
}
|
||||
|
||||
if len(tags) > 0 {
|
||||
tagArr := strings.Split(tags, ",")
|
||||
for i := range tagArr {
|
||||
if global.Config.DB == "sqlite" {
|
||||
db = db.Where("(',' || assets.tags || ',') LIKE ?", "%,"+tagArr[i]+",%")
|
||||
dbCounter = dbCounter.Where("(',' || assets.tags || ',') LIKE ?", "%,"+tagArr[i]+",%")
|
||||
} else {
|
||||
db = db.Where("find_in_set(?, assets.tags)", tagArr[i])
|
||||
dbCounter = dbCounter.Where("find_in_set(?, assets.tags)", tagArr[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
err = dbCounter.Count(&total).Error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if order == "ascend" {
|
||||
order = "asc"
|
||||
} else {
|
||||
order = "desc"
|
||||
}
|
||||
|
||||
if field == "name" {
|
||||
field = "name"
|
||||
} else {
|
||||
field = "created"
|
||||
}
|
||||
|
||||
err = db.Order("assets." + field + " " + order).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&o).Error
|
||||
|
||||
if o == nil {
|
||||
o = make([]AssetVo, 0)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func CreateNewAsset(o *Asset) (err error) {
|
||||
if err = global.DB.Create(o).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func FindAssetById(id string) (o Asset, err error) {
|
||||
err = global.DB.Where("id = ?", id).First(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func UpdateAssetById(o *Asset, id string) {
|
||||
o.ID = id
|
||||
global.DB.Updates(o)
|
||||
}
|
||||
|
||||
func UpdateAssetActiveById(active bool, id string) {
|
||||
sql := "update assets set active = ? where id = ?"
|
||||
global.DB.Exec(sql, active, id)
|
||||
}
|
||||
|
||||
func DeleteAssetById(id string) error {
|
||||
return global.DB.Where("id = ?", id).Delete(&Asset{}).Error
|
||||
}
|
||||
|
||||
func CountAsset() (total int64, err error) {
|
||||
err = global.DB.Find(&Asset{}).Count(&total).Error
|
||||
return
|
||||
}
|
||||
|
||||
func CountAssetByUserId(userId string) (total int64, err error) {
|
||||
db := global.DB.Joins("left join resource_sharers on assets.id = resource_sharers.resource_id")
|
||||
|
||||
db = db.Where("assets.owner = ? or resource_sharers.user_id = ?", userId, userId)
|
||||
|
||||
// 查询用户所在用户组列表
|
||||
userGroupIds, err := FindUserGroupIdsByUserId(userId)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if len(userGroupIds) > 0 {
|
||||
db = db.Or("resource_sharers.user_group_id in ?", userGroupIds)
|
||||
}
|
||||
err = db.Find(&Asset{}).Count(&total).Error
|
||||
return
|
||||
}
|
||||
|
||||
func FindAssetTags() (o []string, err error) {
|
||||
var assets []Asset
|
||||
err = global.DB.Not("tags = ?", "").Find(&assets).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
o = make([]string, 0)
|
||||
|
||||
for i := range assets {
|
||||
if len(assets[i].Tags) == 0 {
|
||||
continue
|
||||
}
|
||||
split := strings.Split(assets[i].Tags, ",")
|
||||
|
||||
o = append(o, split...)
|
||||
}
|
||||
|
||||
return utils.Distinct(o), nil
|
||||
func (r *AssetAttribute) TableName() string {
|
||||
return "asset_attributes"
|
||||
}
|
||||
|
@ -1,119 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"next-terminal/server/constant"
|
||||
"next-terminal/server/global"
|
||||
"next-terminal/server/guacd"
|
||||
"next-terminal/server/utils"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type AssetAttribute struct {
|
||||
Id string `gorm:"index" json:"id"`
|
||||
AssetId string `gorm:"index" json:"assetId"`
|
||||
Name string `gorm:"index" json:"name"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
func (r *AssetAttribute) TableName() string {
|
||||
return "asset_attributes"
|
||||
}
|
||||
|
||||
var SSHParameterNames = []string{guacd.FontName, guacd.FontSize, guacd.ColorScheme, guacd.Backspace, guacd.TerminalType, constant.SshMode}
|
||||
var RDPParameterNames = []string{guacd.Domain, guacd.RemoteApp, guacd.RemoteAppDir, guacd.RemoteAppArgs}
|
||||
var VNCParameterNames = []string{guacd.ColorDepth, guacd.Cursor, guacd.SwapRedBlue, guacd.DestHost, guacd.DestPort}
|
||||
var TelnetParameterNames = []string{guacd.FontName, guacd.FontSize, guacd.ColorScheme, guacd.Backspace, guacd.TerminalType, guacd.UsernameRegex, guacd.PasswordRegex, guacd.LoginSuccessRegex, guacd.LoginFailureRegex}
|
||||
var KubernetesParameterNames = []string{guacd.FontName, guacd.FontSize, guacd.ColorScheme, guacd.Backspace, guacd.TerminalType, guacd.Namespace, guacd.Pod, guacd.Container, guacd.UesSSL, guacd.ClientCert, guacd.ClientKey, guacd.CaCert, guacd.IgnoreCert}
|
||||
|
||||
func UpdateAssetAttributes(assetId, protocol string, m echo.Map) error {
|
||||
var data []AssetAttribute
|
||||
var parameterNames []string
|
||||
switch protocol {
|
||||
case "ssh":
|
||||
parameterNames = SSHParameterNames
|
||||
case "rdp":
|
||||
parameterNames = RDPParameterNames
|
||||
case "vnc":
|
||||
parameterNames = VNCParameterNames
|
||||
case "telnet":
|
||||
parameterNames = TelnetParameterNames
|
||||
case "kubernetes":
|
||||
parameterNames = KubernetesParameterNames
|
||||
|
||||
}
|
||||
|
||||
for i := range parameterNames {
|
||||
name := parameterNames[i]
|
||||
if m[name] != nil && m[name] != "" {
|
||||
data = append(data, genAttribute(assetId, name, m))
|
||||
}
|
||||
}
|
||||
|
||||
return global.DB.Transaction(func(tx *gorm.DB) error {
|
||||
err := tx.Where("asset_id = ?", assetId).Delete(&AssetAttribute{}).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.CreateInBatches(&data, len(data)).Error
|
||||
})
|
||||
}
|
||||
|
||||
func genAttribute(assetId, name string, m echo.Map) AssetAttribute {
|
||||
value := fmt.Sprintf("%v", m[name])
|
||||
attribute := AssetAttribute{
|
||||
Id: utils.Sign([]string{assetId, name}),
|
||||
AssetId: assetId,
|
||||
Name: name,
|
||||
Value: value,
|
||||
}
|
||||
return attribute
|
||||
}
|
||||
|
||||
func FindAssetAttributeByAssetId(assetId string) (o []AssetAttribute, err error) {
|
||||
err = global.DB.Where("asset_id = ?", assetId).Find(&o).Error
|
||||
if o == nil {
|
||||
o = make([]AssetAttribute, 0)
|
||||
}
|
||||
return o, err
|
||||
}
|
||||
|
||||
func FindAssetAttrMapByAssetId(assetId string) (map[string]interface{}, error) {
|
||||
asset, err := FindAssetById(assetId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
attributes, err := FindAssetAttributeByAssetId(assetId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var parameterNames []string
|
||||
switch asset.Protocol {
|
||||
case "ssh":
|
||||
parameterNames = SSHParameterNames
|
||||
case "rdp":
|
||||
parameterNames = RDPParameterNames
|
||||
case "vnc":
|
||||
parameterNames = VNCParameterNames
|
||||
case "telnet":
|
||||
parameterNames = TelnetParameterNames
|
||||
case "kubernetes":
|
||||
parameterNames = KubernetesParameterNames
|
||||
}
|
||||
propertiesMap := FindAllPropertiesMap()
|
||||
var attributeMap = make(map[string]interface{})
|
||||
for name := range propertiesMap {
|
||||
if utils.Contains(parameterNames, name) {
|
||||
attributeMap[name] = propertiesMap[name]
|
||||
}
|
||||
}
|
||||
|
||||
for i := range attributes {
|
||||
attributeMap[attributes[i].Name] = attributes[i].Value
|
||||
}
|
||||
return attributeMap, nil
|
||||
}
|
@ -1,8 +1,6 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"next-terminal/server/constant"
|
||||
"next-terminal/server/global"
|
||||
"next-terminal/server/utils"
|
||||
)
|
||||
|
||||
@ -27,69 +25,3 @@ type CommandVo struct {
|
||||
func (r *Command) TableName() string {
|
||||
return "commands"
|
||||
}
|
||||
|
||||
func FindPageCommand(pageIndex, pageSize int, name, content, order, field string, account User) (o []CommandVo, total int64, err error) {
|
||||
|
||||
db := global.DB.Table("commands").Select("commands.id,commands.name,commands.content,commands.owner,commands.created, users.nickname as owner_name,COUNT(resource_sharers.user_id) as sharer_count").Joins("left join users on commands.owner = users.id").Joins("left join resource_sharers on commands.id = resource_sharers.resource_id").Group("commands.id")
|
||||
dbCounter := global.DB.Table("commands").Select("DISTINCT commands.id").Joins("left join resource_sharers on commands.id = resource_sharers.resource_id").Group("commands.id")
|
||||
|
||||
if constant.TypeUser == account.Type {
|
||||
owner := account.ID
|
||||
db = db.Where("commands.owner = ? or resource_sharers.user_id = ?", owner, owner)
|
||||
dbCounter = dbCounter.Where("commands.owner = ? or resource_sharers.user_id = ?", owner, owner)
|
||||
}
|
||||
|
||||
if len(name) > 0 {
|
||||
db = db.Where("commands.name like ?", "%"+name+"%")
|
||||
dbCounter = dbCounter.Where("commands.name like ?", "%"+name+"%")
|
||||
}
|
||||
|
||||
if len(content) > 0 {
|
||||
db = db.Where("commands.content like ?", "%"+content+"%")
|
||||
dbCounter = dbCounter.Where("commands.content like ?", "%"+content+"%")
|
||||
}
|
||||
|
||||
err = dbCounter.Count(&total).Error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if order == "ascend" {
|
||||
order = "asc"
|
||||
} else {
|
||||
order = "desc"
|
||||
}
|
||||
|
||||
if field == "name" {
|
||||
field = "name"
|
||||
} else {
|
||||
field = "created"
|
||||
}
|
||||
|
||||
err = db.Order("commands." + field + " " + order).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&o).Error
|
||||
if o == nil {
|
||||
o = make([]CommandVo, 0)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func CreateNewCommand(o *Command) (err error) {
|
||||
if err = global.DB.Create(o).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func FindCommandById(id string) (o Command, err error) {
|
||||
err = global.DB.Where("id = ?", id).First(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func UpdateCommandById(o *Command, id string) {
|
||||
o.ID = id
|
||||
global.DB.Updates(o)
|
||||
}
|
||||
|
||||
func DeleteCommandById(id string) error {
|
||||
return global.DB.Where("id = ?", id).Delete(&Command{}).Error
|
||||
}
|
||||
|
@ -1,8 +1,6 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"next-terminal/server/constant"
|
||||
"next-terminal/server/global"
|
||||
"next-terminal/server/utils"
|
||||
)
|
||||
|
||||
@ -37,95 +35,3 @@ type CredentialSimpleVo struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
func FindAllCredential(account User) (o []CredentialSimpleVo, err error) {
|
||||
db := global.DB.Table("credentials").Select("DISTINCT credentials.id,credentials.name").Joins("left join resource_sharers on credentials.id = resource_sharers.resource_id")
|
||||
if account.Type == constant.TypeUser {
|
||||
db = db.Where("credentials.owner = ? or resource_sharers.user_id = ?", account.ID, account.ID)
|
||||
}
|
||||
err = db.Find(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func FindPageCredential(pageIndex, pageSize int, name, order, field string, account User) (o []CredentialVo, total int64, err error) {
|
||||
db := global.DB.Table("credentials").Select("credentials.id,credentials.name,credentials.type,credentials.username,credentials.owner,credentials.created,users.nickname as owner_name,COUNT(resource_sharers.user_id) as sharer_count").Joins("left join users on credentials.owner = users.id").Joins("left join resource_sharers on credentials.id = resource_sharers.resource_id").Group("credentials.id")
|
||||
dbCounter := global.DB.Table("credentials").Select("DISTINCT credentials.id").Joins("left join resource_sharers on credentials.id = resource_sharers.resource_id").Group("credentials.id")
|
||||
|
||||
if constant.TypeUser == account.Type {
|
||||
owner := account.ID
|
||||
db = db.Where("credentials.owner = ? or resource_sharers.user_id = ?", owner, owner)
|
||||
dbCounter = dbCounter.Where("credentials.owner = ? or resource_sharers.user_id = ?", owner, owner)
|
||||
}
|
||||
|
||||
if len(name) > 0 {
|
||||
db = db.Where("credentials.name like ?", "%"+name+"%")
|
||||
dbCounter = dbCounter.Where("credentials.name like ?", "%"+name+"%")
|
||||
}
|
||||
|
||||
err = dbCounter.Count(&total).Error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if order == "ascend" {
|
||||
order = "asc"
|
||||
} else {
|
||||
order = "desc"
|
||||
}
|
||||
|
||||
if field == "name" {
|
||||
field = "name"
|
||||
} else {
|
||||
field = "created"
|
||||
}
|
||||
|
||||
err = db.Order("credentials." + field + " " + order).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&o).Error
|
||||
if o == nil {
|
||||
o = make([]CredentialVo, 0)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func CreateNewCredential(o *Credential) (err error) {
|
||||
if err = global.DB.Create(o).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func FindCredentialById(id string) (o Credential, err error) {
|
||||
err = global.DB.Where("id = ?", id).First(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func UpdateCredentialById(o *Credential, id string) {
|
||||
o.ID = id
|
||||
global.DB.Updates(o)
|
||||
}
|
||||
|
||||
func DeleteCredentialById(id string) error {
|
||||
return global.DB.Where("id = ?", id).Delete(&Credential{}).Error
|
||||
}
|
||||
|
||||
func CountCredential() (total int64, err error) {
|
||||
err = global.DB.Find(&Credential{}).Count(&total).Error
|
||||
return
|
||||
}
|
||||
|
||||
func CountCredentialByUserId(userId string) (total int64, err error) {
|
||||
db := global.DB.Joins("left join resource_sharers on credentials.id = resource_sharers.resource_id")
|
||||
|
||||
db = db.Where("credentials.owner = ? or resource_sharers.user_id = ?", userId, userId)
|
||||
|
||||
// 查询用户所在用户组列表
|
||||
userGroupIds, err := FindUserGroupIdsByUserId(userId)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if len(userGroupIds) > 0 {
|
||||
db = db.Or("resource_sharers.user_group_id in ?", userGroupIds)
|
||||
}
|
||||
err = db.Find(&Credential{}).Count(&total).Error
|
||||
return
|
||||
}
|
||||
|
@ -1,19 +1,7 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"next-terminal/server/constant"
|
||||
"next-terminal/server/global"
|
||||
"next-terminal/server/term"
|
||||
"next-terminal/server/utils"
|
||||
|
||||
"github.com/robfig/cron/v3"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type Job struct {
|
||||
@ -34,323 +22,13 @@ func (r *Job) TableName() string {
|
||||
return "jobs"
|
||||
}
|
||||
|
||||
func FindPageJob(pageIndex, pageSize int, name, status, order, field string) (o []Job, total int64, err error) {
|
||||
job := Job{}
|
||||
db := global.DB.Table(job.TableName())
|
||||
dbCounter := global.DB.Table(job.TableName())
|
||||
|
||||
if len(name) > 0 {
|
||||
db = db.Where("name like ?", "%"+name+"%")
|
||||
dbCounter = dbCounter.Where("name like ?", "%"+name+"%")
|
||||
}
|
||||
|
||||
if len(status) > 0 {
|
||||
db = db.Where("status = ?", status)
|
||||
dbCounter = dbCounter.Where("status = ?", status)
|
||||
}
|
||||
|
||||
err = dbCounter.Count(&total).Error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if order == "ascend" {
|
||||
order = "asc"
|
||||
} else {
|
||||
order = "desc"
|
||||
}
|
||||
|
||||
if field == "name" {
|
||||
field = "name"
|
||||
} else if field == "created" {
|
||||
field = "created"
|
||||
} else {
|
||||
field = "updated"
|
||||
}
|
||||
|
||||
err = db.Order(field + " " + order).Find(&o).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Error
|
||||
if o == nil {
|
||||
o = make([]Job, 0)
|
||||
}
|
||||
return
|
||||
type JobLog struct {
|
||||
ID string `json:"id"`
|
||||
Timestamp utils.JsonTime `json:"timestamp"`
|
||||
JobId string `json:"jobId"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func FindJobByFunc(function string) (o []Job, err error) {
|
||||
db := global.DB
|
||||
err = db.Where("func = ?", function).Find(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func CreateNewJob(o *Job) (err error) {
|
||||
|
||||
if o.Status == constant.JobStatusRunning {
|
||||
j, err := getJob(o)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
jobId, err := global.Cron.AddJob(o.Cron, j)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
o.CronJobId = int(jobId)
|
||||
}
|
||||
|
||||
return global.DB.Create(o).Error
|
||||
}
|
||||
|
||||
func UpdateJobById(o *Job, id string) (err error) {
|
||||
if o.Status == constant.JobStatusRunning {
|
||||
return errors.New("请先停止定时任务后再修改")
|
||||
}
|
||||
|
||||
o.ID = id
|
||||
return global.DB.Updates(o).Error
|
||||
}
|
||||
|
||||
func UpdateJonUpdatedById(id string) (err error) {
|
||||
err = global.DB.Updates(Job{ID: id, Updated: utils.NowJsonTime()}).Error
|
||||
return
|
||||
}
|
||||
|
||||
func ChangeJobStatusById(id, status string) (err error) {
|
||||
var job Job
|
||||
err = global.DB.Where("id = ?", id).First(&job).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if status == constant.JobStatusRunning {
|
||||
j, err := getJob(&job)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
entryID, err := global.Cron.AddJob(job.Cron, j)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logrus.Debugf("开启计划任务「%v」,运行中计划任务数量「%v」", job.Name, len(global.Cron.Entries()))
|
||||
|
||||
return global.DB.Updates(Job{ID: id, Status: constant.JobStatusRunning, CronJobId: int(entryID)}).Error
|
||||
} else {
|
||||
global.Cron.Remove(cron.EntryID(job.CronJobId))
|
||||
logrus.Debugf("关闭计划任务「%v」,运行中计划任务数量「%v」", job.Name, len(global.Cron.Entries()))
|
||||
return global.DB.Updates(Job{ID: id, Status: constant.JobStatusNotRunning}).Error
|
||||
}
|
||||
}
|
||||
|
||||
func ExecJobById(id string) (err error) {
|
||||
job, err := FindJobById(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
j, err := getJob(&job)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
j.Run()
|
||||
return nil
|
||||
}
|
||||
|
||||
func FindJobById(id string) (o Job, err error) {
|
||||
err = global.DB.Where("id = ?", id).First(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func DeleteJobById(id string) error {
|
||||
job, err := FindJobById(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if job.Status == constant.JobStatusRunning {
|
||||
if err := ChangeJobStatusById(id, constant.JobStatusNotRunning); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return global.DB.Where("id = ?", id).Delete(Job{}).Error
|
||||
}
|
||||
|
||||
func getJob(j *Job) (job cron.Job, err error) {
|
||||
switch j.Func {
|
||||
case constant.FuncCheckAssetStatusJob:
|
||||
job = CheckAssetStatusJob{ID: j.ID, Mode: j.Mode, ResourceIds: j.ResourceIds, Metadata: j.Metadata}
|
||||
case constant.FuncShellJob:
|
||||
job = ShellJob{ID: j.ID, Mode: j.Mode, ResourceIds: j.ResourceIds, Metadata: j.Metadata}
|
||||
default:
|
||||
return nil, errors.New("未识别的任务")
|
||||
}
|
||||
return job, err
|
||||
}
|
||||
|
||||
type CheckAssetStatusJob struct {
|
||||
ID string
|
||||
Mode string
|
||||
ResourceIds string
|
||||
Metadata string
|
||||
}
|
||||
|
||||
func (r CheckAssetStatusJob) Run() {
|
||||
if r.ID == "" {
|
||||
return
|
||||
}
|
||||
|
||||
var assets []Asset
|
||||
if r.Mode == constant.JobModeAll {
|
||||
assets, _ = FindAllAsset()
|
||||
} else {
|
||||
assets, _ = FindAssetByIds(strings.Split(r.ResourceIds, ","))
|
||||
}
|
||||
|
||||
if len(assets) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
msgChan := make(chan string)
|
||||
for i := range assets {
|
||||
asset := assets[i]
|
||||
go func() {
|
||||
t1 := time.Now()
|
||||
active := utils.Tcping(asset.IP, asset.Port)
|
||||
elapsed := time.Since(t1)
|
||||
msg := fmt.Sprintf("资产「%v」存活状态检测完成,存活「%v」,耗时「%v」", asset.Name, active, elapsed)
|
||||
|
||||
UpdateAssetActiveById(active, asset.ID)
|
||||
logrus.Infof(msg)
|
||||
msgChan <- msg
|
||||
}()
|
||||
}
|
||||
|
||||
var message = ""
|
||||
for i := 0; i < len(assets); i++ {
|
||||
message += <-msgChan + "\n"
|
||||
}
|
||||
|
||||
_ = UpdateJonUpdatedById(r.ID)
|
||||
jobLog := JobLog{
|
||||
ID: utils.UUID(),
|
||||
JobId: r.ID,
|
||||
Timestamp: utils.NowJsonTime(),
|
||||
Message: message,
|
||||
}
|
||||
|
||||
_ = CreateNewJobLog(&jobLog)
|
||||
}
|
||||
|
||||
type ShellJob struct {
|
||||
ID string
|
||||
Mode string
|
||||
ResourceIds string
|
||||
Metadata string
|
||||
}
|
||||
|
||||
type MetadataShell struct {
|
||||
Shell string
|
||||
}
|
||||
|
||||
func (r ShellJob) Run() {
|
||||
if r.ID == "" {
|
||||
return
|
||||
}
|
||||
|
||||
var assets []Asset
|
||||
if r.Mode == constant.JobModeAll {
|
||||
assets, _ = FindAssetByProtocol("ssh")
|
||||
} else {
|
||||
assets, _ = FindAssetByProtocolAndIds("ssh", strings.Split(r.ResourceIds, ","))
|
||||
}
|
||||
|
||||
if len(assets) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
var metadataShell MetadataShell
|
||||
err := json.Unmarshal([]byte(r.Metadata), &metadataShell)
|
||||
if err != nil {
|
||||
logrus.Errorf("JSON数据解析失败 %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
msgChan := make(chan string)
|
||||
for i := range assets {
|
||||
asset, err := FindAssetById(assets[i].ID)
|
||||
if err != nil {
|
||||
msgChan <- fmt.Sprintf("资产「%v」Shell执行失败,查询数据异常「%v」", assets[i].Name, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
username = asset.Username
|
||||
password = asset.Password
|
||||
privateKey = asset.PrivateKey
|
||||
passphrase = asset.Passphrase
|
||||
ip = asset.IP
|
||||
port = asset.Port
|
||||
)
|
||||
|
||||
if asset.AccountType == "credential" {
|
||||
credential, err := FindCredentialById(asset.CredentialId)
|
||||
if err != nil {
|
||||
msgChan <- fmt.Sprintf("资产「%v」Shell执行失败,查询授权凭证数据异常「%v」", assets[i].Name, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if credential.Type == constant.Custom {
|
||||
username = credential.Username
|
||||
password = credential.Password
|
||||
} else {
|
||||
username = credential.Username
|
||||
privateKey = credential.PrivateKey
|
||||
passphrase = credential.Passphrase
|
||||
}
|
||||
}
|
||||
|
||||
go func() {
|
||||
|
||||
t1 := time.Now()
|
||||
result, err := ExecCommandBySSH(metadataShell.Shell, ip, port, username, password, privateKey, passphrase)
|
||||
elapsed := time.Since(t1)
|
||||
var msg string
|
||||
if err != nil {
|
||||
msg = fmt.Sprintf("资产「%v」Shell执行失败,返回值「%v」,耗时「%v」", asset.Name, err.Error(), elapsed)
|
||||
logrus.Infof(msg)
|
||||
} else {
|
||||
msg = fmt.Sprintf("资产「%v」Shell执行成功,返回值「%v」,耗时「%v」", asset.Name, result, elapsed)
|
||||
logrus.Infof(msg)
|
||||
}
|
||||
|
||||
msgChan <- msg
|
||||
}()
|
||||
}
|
||||
|
||||
var message = ""
|
||||
for i := 0; i < len(assets); i++ {
|
||||
message += <-msgChan + "\n"
|
||||
}
|
||||
|
||||
_ = UpdateJonUpdatedById(r.ID)
|
||||
jobLog := JobLog{
|
||||
ID: utils.UUID(),
|
||||
JobId: r.ID,
|
||||
Timestamp: utils.NowJsonTime(),
|
||||
Message: message,
|
||||
}
|
||||
|
||||
_ = CreateNewJobLog(&jobLog)
|
||||
}
|
||||
|
||||
func ExecCommandBySSH(cmd, ip string, port int, username, password, privateKey, passphrase string) (result string, err error) {
|
||||
sshClient, err := term.NewSshClient(ip, port, username, password, privateKey, passphrase)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
session, err := sshClient.NewSession()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer session.Close()
|
||||
//执行远程命令
|
||||
combo, err := session.CombinedOutput(cmd)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(combo), nil
|
||||
func (r *JobLog) TableName() string {
|
||||
return "job_logs"
|
||||
}
|
||||
|
@ -1,30 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"next-terminal/server/global"
|
||||
"next-terminal/server/utils"
|
||||
)
|
||||
|
||||
type JobLog struct {
|
||||
ID string `json:"id"`
|
||||
Timestamp utils.JsonTime `json:"timestamp"`
|
||||
JobId string `json:"jobId"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func (r *JobLog) TableName() string {
|
||||
return "job_logs"
|
||||
}
|
||||
|
||||
func CreateNewJobLog(o *JobLog) error {
|
||||
return global.DB.Create(o).Error
|
||||
}
|
||||
|
||||
func FindJobLogs(jobId string) (o []JobLog, err error) {
|
||||
err = global.DB.Where("job_id = ?", jobId).Order("timestamp asc").Find(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func DeleteJobLogByJobId(jobId string) error {
|
||||
return global.DB.Where("job_id = ?", jobId).Delete(JobLog{}).Error
|
||||
}
|
@ -1,7 +1,6 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"next-terminal/server/global"
|
||||
"next-terminal/server/utils"
|
||||
)
|
||||
|
||||
@ -29,78 +28,3 @@ type LoginLogVo struct {
|
||||
func (r *LoginLog) TableName() string {
|
||||
return "login_logs"
|
||||
}
|
||||
|
||||
func FindPageLoginLog(pageIndex, pageSize int, userId, clientIp string) (o []LoginLogVo, total int64, err error) {
|
||||
|
||||
db := global.DB.Table("login_logs").Select("login_logs.id,login_logs.user_id,login_logs.client_ip,login_logs.client_user_agent,login_logs.login_time, login_logs.logout_time, users.nickname as user_name").Joins("left join users on login_logs.user_id = users.id")
|
||||
dbCounter := global.DB.Table("login_logs").Select("DISTINCT login_logs.id")
|
||||
|
||||
if userId != "" {
|
||||
db = db.Where("login_logs.user_id = ?", userId)
|
||||
dbCounter = dbCounter.Where("login_logs.user_id = ?", userId)
|
||||
}
|
||||
|
||||
if clientIp != "" {
|
||||
db = db.Where("login_logs.client_ip like ?", "%"+clientIp+"%")
|
||||
dbCounter = dbCounter.Where("login_logs.client_ip like ?", "%"+clientIp+"%")
|
||||
}
|
||||
|
||||
err = dbCounter.Count(&total).Error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
err = db.Order("login_logs.login_time desc").Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&o).Error
|
||||
if o == nil {
|
||||
o = make([]LoginLogVo, 0)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func FindAliveLoginLogs() (o []LoginLog, err error) {
|
||||
err = global.DB.Where("logout_time is null").Find(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func FindAliveLoginLogsByUserId(userId string) (o []LoginLog, err error) {
|
||||
err = global.DB.Where("logout_time is null and user_id = ?", userId).Find(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func CreateNewLoginLog(o *LoginLog) (err error) {
|
||||
return global.DB.Create(o).Error
|
||||
}
|
||||
|
||||
func DeleteLoginLogByIdIn(ids []string) (err error) {
|
||||
return global.DB.Where("id in ?", ids).Delete(&LoginLog{}).Error
|
||||
}
|
||||
|
||||
func FindLoginLogById(id string) (o LoginLog, err error) {
|
||||
err = global.DB.Where("id = ?", id).First(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func Logout(token string) (err error) {
|
||||
//
|
||||
//loginLog, err := FindLoginLogById(token)
|
||||
//if err != nil {
|
||||
// logrus.Warnf("登录日志「%v」获取失败", token)
|
||||
// return
|
||||
//}
|
||||
//
|
||||
//err = global.DB.Updates(&LoginLog{LogoutTime: utils.NowJsonTime(), ID: token}).Error
|
||||
//if err != nil {
|
||||
// return err
|
||||
//}
|
||||
//
|
||||
//loginLogs, err := FindAliveLoginLogsByUserId(loginLog.UserId)
|
||||
//if err != nil {
|
||||
// return
|
||||
//}
|
||||
//
|
||||
//if len(loginLogs) == 0 {
|
||||
// // TODO
|
||||
// err = UpdateUserOnline(false, loginLog.UserId)
|
||||
//}
|
||||
return
|
||||
}
|
||||
|
@ -1,9 +1,5 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"next-terminal/server/global"
|
||||
)
|
||||
|
||||
type Num struct {
|
||||
I string `gorm:"primary_key" json:"i"`
|
||||
}
|
||||
@ -11,15 +7,3 @@ type Num struct {
|
||||
func (r *Num) TableName() string {
|
||||
return "nums"
|
||||
}
|
||||
|
||||
func FindAllTemp() (o []Num) {
|
||||
if global.DB.Find(&o).Error != nil {
|
||||
return nil
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func CreateNewTemp(o *Num) (err error) {
|
||||
err = global.DB.Create(o).Error
|
||||
return
|
||||
}
|
||||
|
@ -1,16 +1,5 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"net/smtp"
|
||||
|
||||
"next-terminal/server/constant"
|
||||
"next-terminal/server/global"
|
||||
"next-terminal/server/guacd"
|
||||
|
||||
"github.com/jordan-wright/email"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type Property struct {
|
||||
Name string `gorm:"primary_key" json:"name"`
|
||||
Value string `json:"value"`
|
||||
@ -19,73 +8,3 @@ type Property struct {
|
||||
func (r *Property) TableName() string {
|
||||
return "properties"
|
||||
}
|
||||
|
||||
func FindAllProperties() (o []Property) {
|
||||
if global.DB.Find(&o).Error != nil {
|
||||
return nil
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func CreateNewProperty(o *Property) (err error) {
|
||||
err = global.DB.Create(o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func UpdatePropertyByName(o *Property, name string) {
|
||||
o.Name = name
|
||||
global.DB.Updates(o)
|
||||
}
|
||||
|
||||
func FindPropertyByName(name string) (o Property, err error) {
|
||||
err = global.DB.Where("name = ?", name).First(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func FindAllPropertiesMap() map[string]string {
|
||||
properties := FindAllProperties()
|
||||
propertyMap := make(map[string]string)
|
||||
for i := range properties {
|
||||
propertyMap[properties[i].Name] = properties[i].Value
|
||||
}
|
||||
return propertyMap
|
||||
}
|
||||
|
||||
func GetDrivePath() (string, error) {
|
||||
property, err := FindPropertyByName(guacd.DrivePath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return property.Value, nil
|
||||
}
|
||||
|
||||
func GetRecordingPath() (string, error) {
|
||||
property, err := FindPropertyByName(guacd.RecordingPath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return property.Value, nil
|
||||
}
|
||||
|
||||
func SendMail(to, subject, text string) {
|
||||
propertiesMap := FindAllPropertiesMap()
|
||||
host := propertiesMap[constant.MailHost]
|
||||
port := propertiesMap[constant.MailPort]
|
||||
username := propertiesMap[constant.MailUsername]
|
||||
password := propertiesMap[constant.MailPassword]
|
||||
|
||||
if host == "" || port == "" || username == "" || password == "" {
|
||||
logrus.Debugf("邮箱信息不完整,跳过发送邮件。")
|
||||
return
|
||||
}
|
||||
|
||||
e := email.NewEmail()
|
||||
e.From = "Next Terminal <" + username + ">"
|
||||
e.To = []string{to}
|
||||
e.Subject = subject
|
||||
e.Text = []byte(text)
|
||||
err := e.Send(host+":"+port, smtp.PlainAuth("", username, password, host))
|
||||
if err != nil {
|
||||
logrus.Errorf("邮件发送失败: %v", err.Error())
|
||||
}
|
||||
}
|
||||
|
@ -1,14 +1,5 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"next-terminal/server/global"
|
||||
"next-terminal/server/utils"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ResourceSharer struct {
|
||||
ID string `gorm:"primary_key" json:"id"`
|
||||
ResourceId string `gorm:"index" json:"resourceId"`
|
||||
@ -20,179 +11,3 @@ type ResourceSharer struct {
|
||||
func (r *ResourceSharer) TableName() string {
|
||||
return "resource_sharers"
|
||||
}
|
||||
|
||||
func FindUserIdsByResourceId(resourceId string) (r []string, err error) {
|
||||
db := global.DB
|
||||
err = db.Table("resource_sharers").Select("user_id").Where("resource_id = ?", resourceId).Find(&r).Error
|
||||
if r == nil {
|
||||
r = make([]string, 0)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func OverwriteUserIdsByResourceId(resourceId, resourceType string, userIds []string) (err error) {
|
||||
db := global.DB.Begin()
|
||||
|
||||
var owner string
|
||||
// 检查资产是否存在
|
||||
switch resourceType {
|
||||
case "asset":
|
||||
resource := Asset{}
|
||||
err = db.Where("id = ?", resourceId).First(&resource).Error
|
||||
owner = resource.Owner
|
||||
case "command":
|
||||
resource := Command{}
|
||||
err = db.Where("id = ?", resourceId).First(&resource).Error
|
||||
owner = resource.Owner
|
||||
case "credential":
|
||||
resource := Credential{}
|
||||
err = db.Where("id = ?", resourceId).First(&resource).Error
|
||||
owner = resource.Owner
|
||||
}
|
||||
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return echo.NewHTTPError(404, "资源「"+resourceId+"」不存在")
|
||||
}
|
||||
|
||||
for i := range userIds {
|
||||
if owner == userIds[i] {
|
||||
return echo.NewHTTPError(400, "参数错误")
|
||||
}
|
||||
}
|
||||
|
||||
db.Where("resource_id = ?", resourceId).Delete(&ResourceSharer{})
|
||||
|
||||
for i := range userIds {
|
||||
userId := userIds[i]
|
||||
if len(userId) == 0 {
|
||||
continue
|
||||
}
|
||||
id := utils.Sign([]string{resourceId, resourceType, userId})
|
||||
resource := &ResourceSharer{
|
||||
ID: id,
|
||||
ResourceId: resourceId,
|
||||
ResourceType: resourceType,
|
||||
UserId: userId,
|
||||
}
|
||||
err = db.Create(resource).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
db.Commit()
|
||||
return nil
|
||||
}
|
||||
|
||||
func DeleteByUserIdAndResourceTypeAndResourceIdIn(userGroupId, userId, resourceType string, resourceIds []string) error {
|
||||
db := global.DB
|
||||
if userGroupId != "" {
|
||||
db = db.Where("user_group_id = ?", userGroupId)
|
||||
}
|
||||
|
||||
if userId != "" {
|
||||
db = db.Where("user_id = ?", userId)
|
||||
}
|
||||
|
||||
if resourceType != "" {
|
||||
db = db.Where("resource_type = ?", resourceType)
|
||||
}
|
||||
|
||||
if resourceIds != nil {
|
||||
db = db.Where("resource_id in ?", resourceIds)
|
||||
}
|
||||
|
||||
return db.Delete(&ResourceSharer{}).Error
|
||||
}
|
||||
|
||||
func DeleteResourceSharerByResourceId(resourceId string) error {
|
||||
return global.DB.Where("resource_id = ?", resourceId).Delete(&ResourceSharer{}).Error
|
||||
}
|
||||
|
||||
func AddSharerResources(userGroupId, userId, resourceType string, resourceIds []string) error {
|
||||
return global.DB.Transaction(func(tx *gorm.DB) (err error) {
|
||||
|
||||
for i := range resourceIds {
|
||||
resourceId := resourceIds[i]
|
||||
|
||||
var owner string
|
||||
// 检查资产是否存在
|
||||
switch resourceType {
|
||||
case "asset":
|
||||
resource := Asset{}
|
||||
if err = tx.Where("id = ?", resourceId).First(&resource).Error; err != nil {
|
||||
return errors.Wrap(err, "find asset fail")
|
||||
}
|
||||
owner = resource.Owner
|
||||
case "command":
|
||||
resource := Command{}
|
||||
if err = tx.Where("id = ?", resourceId).First(&resource).Error; err != nil {
|
||||
return errors.Wrap(err, "find command fail")
|
||||
}
|
||||
owner = resource.Owner
|
||||
case "credential":
|
||||
resource := Credential{}
|
||||
if err = tx.Where("id = ?", resourceId).First(&resource).Error; err != nil {
|
||||
return errors.Wrap(err, "find credential fail")
|
||||
|
||||
}
|
||||
owner = resource.Owner
|
||||
}
|
||||
|
||||
if owner == userId {
|
||||
return echo.NewHTTPError(400, "参数错误")
|
||||
}
|
||||
|
||||
id := utils.Sign([]string{resourceId, resourceType, userId, userGroupId})
|
||||
resource := &ResourceSharer{
|
||||
ID: id,
|
||||
ResourceId: resourceId,
|
||||
ResourceType: resourceType,
|
||||
UserId: userId,
|
||||
UserGroupId: userGroupId,
|
||||
}
|
||||
err = tx.Create(resource).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func FindAssetIdsByUserId(userId string) (assetIds []string, err error) {
|
||||
// 查询当前用户创建的资产
|
||||
var ownerAssetIds, sharerAssetIds []string
|
||||
asset := Asset{}
|
||||
err = global.DB.Table(asset.TableName()).Select("id").Where("owner = ?", userId).Find(&ownerAssetIds).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 查询其他用户授权给该用户的资产
|
||||
groupIds, err := FindUserGroupIdsByUserId(userId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
db := global.DB.Table("resource_sharers").Select("resource_id").Where("user_id = ?", userId)
|
||||
if len(groupIds) > 0 {
|
||||
db = db.Or("user_group_id in ?", groupIds)
|
||||
}
|
||||
err = db.Find(&sharerAssetIds).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 合并查询到的资产ID
|
||||
assetIds = make([]string, 0)
|
||||
|
||||
if ownerAssetIds != nil {
|
||||
assetIds = append(assetIds, ownerAssetIds...)
|
||||
}
|
||||
|
||||
if sharerAssetIds != nil {
|
||||
assetIds = append(assetIds, sharerAssetIds...)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
@ -1,12 +1,6 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path"
|
||||
"time"
|
||||
|
||||
"next-terminal/server/constant"
|
||||
"next-terminal/server/global"
|
||||
"next-terminal/server/utils"
|
||||
)
|
||||
|
||||
@ -60,151 +54,3 @@ type SessionVo struct {
|
||||
Message string `json:"message"`
|
||||
Mode string `json:"mode"`
|
||||
}
|
||||
|
||||
func FindPageSession(pageIndex, pageSize int, status, userId, clientIp, assetId, protocol string) (results []SessionVo, total int64, err error) {
|
||||
|
||||
db := global.DB
|
||||
var params []interface{}
|
||||
|
||||
params = append(params, status)
|
||||
|
||||
itemSql := "SELECT s.id,s.mode, s.protocol,s.recording, s.connection_id, s.asset_id, s.creator, s.client_ip, s.width, s.height, s.ip, s.port, s.username, s.status, s.connected_time, s.disconnected_time,s.code, s.message, a.name AS asset_name, u.nickname AS creator_name FROM sessions s LEFT JOIN assets a ON s.asset_id = a.id LEFT JOIN users u ON s.creator = u.id WHERE s.STATUS = ? "
|
||||
countSql := "select count(*) from sessions as s where s.status = ? "
|
||||
|
||||
if len(userId) > 0 {
|
||||
itemSql += " and s.creator = ?"
|
||||
countSql += " and s.creator = ?"
|
||||
params = append(params, userId)
|
||||
}
|
||||
|
||||
if len(clientIp) > 0 {
|
||||
itemSql += " and s.client_ip like ?"
|
||||
countSql += " and s.client_ip like ?"
|
||||
params = append(params, "%"+clientIp+"%")
|
||||
}
|
||||
|
||||
if len(assetId) > 0 {
|
||||
itemSql += " and s.asset_id = ?"
|
||||
countSql += " and s.asset_id = ?"
|
||||
params = append(params, assetId)
|
||||
}
|
||||
|
||||
if len(protocol) > 0 {
|
||||
itemSql += " and s.protocol = ?"
|
||||
countSql += " and s.protocol = ?"
|
||||
params = append(params, protocol)
|
||||
}
|
||||
|
||||
params = append(params, (pageIndex-1)*pageSize, pageSize)
|
||||
itemSql += " order by s.connected_time desc LIMIT ?, ?"
|
||||
|
||||
db.Raw(countSql, params...).Scan(&total)
|
||||
|
||||
err = db.Raw(itemSql, params...).Scan(&results).Error
|
||||
|
||||
if results == nil {
|
||||
results = make([]SessionVo, 0)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func FindSessionByStatus(status string) (o []Session, err error) {
|
||||
err = global.DB.Where("status = ?", status).Find(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func FindSessionByStatusIn(statuses []string) (o []Session, err error) {
|
||||
err = global.DB.Where("status in ?", statuses).Find(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func FindOutTimeSessions(dayLimit int) (o []Session, err error) {
|
||||
limitTime := time.Now().Add(time.Duration(-dayLimit*24) * time.Hour)
|
||||
err = global.DB.Where("status = ? and connected_time < ?", constant.Disconnected, limitTime).Find(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func CreateNewSession(o *Session) (err error) {
|
||||
err = global.DB.Create(o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func FindSessionById(id string) (o Session, err error) {
|
||||
err = global.DB.Where("id = ?", id).First(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func FindSessionByConnectionId(connectionId string) (o Session, err error) {
|
||||
err = global.DB.Where("connection_id = ?", connectionId).First(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func UpdateSessionById(o *Session, id string) error {
|
||||
o.ID = id
|
||||
return global.DB.Updates(o).Error
|
||||
}
|
||||
|
||||
func UpdateSessionWindowSizeById(width, height int, id string) error {
|
||||
session := Session{}
|
||||
session.Width = width
|
||||
session.Height = height
|
||||
|
||||
return UpdateSessionById(&session, id)
|
||||
}
|
||||
|
||||
func DeleteSessionById(id string) error {
|
||||
return global.DB.Where("id = ?", id).Delete(&Session{}).Error
|
||||
}
|
||||
|
||||
func DeleteSessionByIds(sessionIds []string) error {
|
||||
drivePath, err := GetRecordingPath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for i := range sessionIds {
|
||||
if err := os.RemoveAll(path.Join(drivePath, sessionIds[i])); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := DeleteSessionById(sessionIds[i]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func DeleteSessionByStatus(status string) {
|
||||
global.DB.Where("status = ?", status).Delete(&Session{})
|
||||
}
|
||||
|
||||
func CountOnlineSession() (total int64, err error) {
|
||||
err = global.DB.Where("status = ?", constant.Connected).Find(&Session{}).Count(&total).Error
|
||||
return
|
||||
}
|
||||
|
||||
type D struct {
|
||||
Day string `json:"day"`
|
||||
Count int `json:"count"`
|
||||
Protocol string `json:"protocol"`
|
||||
}
|
||||
|
||||
func CountSessionByDay(day int) (results []D, err error) {
|
||||
|
||||
today := time.Now().Format("20060102")
|
||||
sql := "select t1.`day`, count(t2.id) as count\nfrom (\n SELECT @date := DATE_ADD(@date, INTERVAL - 1 DAY) day\n FROM (SELECT @date := DATE_ADD('" + today + "', INTERVAL + 1 DAY) FROM nums) as t0\n LIMIT ?\n )\n as t1\n left join\n (\n select DATE(s.connected_time) as day, s.id\n from sessions as s\n WHERE protocol = ? and DATE(connected_time) <= '" + today + "'\n AND DATE(connected_time) > DATE_SUB('" + today + "', INTERVAL ? DAY)\n ) as t2 on t1.day = t2.day\ngroup by t1.day"
|
||||
|
||||
protocols := []string{"rdp", "ssh", "vnc", "telnet"}
|
||||
|
||||
for i := range protocols {
|
||||
var result []D
|
||||
err = global.DB.Raw(sql, day, protocols[i], day).Scan(&result).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for j := range result {
|
||||
result[j].Protocol = protocols[i]
|
||||
}
|
||||
results = append(results, result...)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
@ -1,23 +0,0 @@
|
||||
package model
|
||||
|
||||
import "next-terminal/server/global"
|
||||
|
||||
type UserAttribute struct {
|
||||
Id string `gorm:"index" json:"id"`
|
||||
UserId string `gorm:"index" json:"userId"`
|
||||
Name string `gorm:"index" json:"name"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
func (r *UserAttribute) TableName() string {
|
||||
return "user_attributes"
|
||||
}
|
||||
|
||||
func CreateUserAttribute(o *UserAttribute) error {
|
||||
return global.DB.Create(o).Error
|
||||
}
|
||||
|
||||
func FindUserAttributeByUserId(userId string) (o []UserAttribute, err error) {
|
||||
err = global.DB.Where("user_id = ?", userId).Find(&o).Error
|
||||
return o, err
|
||||
}
|
@ -1,18 +0,0 @@
|
||||
package model
|
||||
|
||||
import "next-terminal/server/global"
|
||||
|
||||
type UserGroupMember struct {
|
||||
ID string `gorm:"primary_key" json:"name"`
|
||||
UserId string `gorm:"index" json:"userId"`
|
||||
UserGroupId string `gorm:"index" json:"userGroupId"`
|
||||
}
|
||||
|
||||
func (r *UserGroupMember) TableName() string {
|
||||
return "user_group_members"
|
||||
}
|
||||
|
||||
func FindUserGroupMembersByUserGroupId(id string) (o []string, err error) {
|
||||
err = global.DB.Table("user_group_members").Select("user_id").Where("user_group_id = ?", id).Find(&o).Error
|
||||
return
|
||||
}
|
@ -1,137 +1,26 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"next-terminal/server/global"
|
||||
"next-terminal/server/utils"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UserGroup struct {
|
||||
ID string `gorm:"primary_key" json:"id"`
|
||||
Name string `json:"name"`
|
||||
Created utils.JsonTime `json:"created"`
|
||||
}
|
||||
|
||||
type UserGroupVo struct {
|
||||
ID string `json:"id"`
|
||||
ID string `gorm:"primary_key" json:"id"`
|
||||
Name string `json:"name"`
|
||||
Created utils.JsonTime `json:"created"`
|
||||
AssetCount int64 `json:"assetCount"`
|
||||
AssetCount int64 `gorm:"-" json:"assetCount"`
|
||||
}
|
||||
|
||||
func (r *UserGroup) TableName() string {
|
||||
return "user_groups"
|
||||
}
|
||||
|
||||
func FindPageUserGroup(pageIndex, pageSize int, name, order, field string) (o []UserGroupVo, total int64, err error) {
|
||||
db := global.DB.Table("user_groups").Select("user_groups.id, user_groups.name, user_groups.created, count(resource_sharers.user_group_id) as asset_count").Joins("left join resource_sharers on user_groups.id = resource_sharers.user_group_id and resource_sharers.resource_type = 'asset'").Group("user_groups.id")
|
||||
dbCounter := global.DB.Table("user_groups")
|
||||
if len(name) > 0 {
|
||||
db = db.Where("user_groups.name like ?", "%"+name+"%")
|
||||
dbCounter = dbCounter.Where("name like ?", "%"+name+"%")
|
||||
}
|
||||
|
||||
err = dbCounter.Count(&total).Error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if order == "ascend" {
|
||||
order = "asc"
|
||||
} else {
|
||||
order = "desc"
|
||||
}
|
||||
|
||||
if field == "name" {
|
||||
field = "name"
|
||||
} else {
|
||||
field = "created"
|
||||
}
|
||||
|
||||
err = db.Order("user_groups." + field + " " + order).Find(&o).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Error
|
||||
if o == nil {
|
||||
o = make([]UserGroupVo, 0)
|
||||
}
|
||||
return
|
||||
type UserGroupMember struct {
|
||||
ID string `gorm:"primary_key" json:"name"`
|
||||
UserId string `gorm:"index" json:"userId"`
|
||||
UserGroupId string `gorm:"index" json:"userGroupId"`
|
||||
}
|
||||
|
||||
func CreateNewUserGroup(o *UserGroup, members []string) (err error) {
|
||||
return global.DB.Transaction(func(tx *gorm.DB) error {
|
||||
err = tx.Create(o).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if members != nil {
|
||||
userGroupId := o.ID
|
||||
err = AddUserGroupMembers(tx, members, userGroupId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
func AddUserGroupMembers(tx *gorm.DB, userIds []string, userGroupId string) error {
|
||||
//for i := range userIds {
|
||||
// userId := userIds[i]
|
||||
// // TODO
|
||||
// _, err := FindUserById(userId)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
//
|
||||
// userGroupMember := UserGroupMember{
|
||||
// ID: utils.Sign([]string{userGroupId, userId}),
|
||||
// UserId: userId,
|
||||
// UserGroupId: userGroupId,
|
||||
// }
|
||||
// err = tx.Create(&userGroupMember).Error
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
//}
|
||||
return nil
|
||||
}
|
||||
|
||||
func FindUserGroupById(id string) (o UserGroup, err error) {
|
||||
err = global.DB.Where("id = ?", id).First(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func FindUserGroupIdsByUserId(userId string) (o []string, err error) {
|
||||
// 先查询用户所在的用户
|
||||
err = global.DB.Table("user_group_members").Select("user_group_id").Where("user_id = ?", userId).Find(&o).Error
|
||||
return
|
||||
}
|
||||
|
||||
func UpdateUserGroupById(o *UserGroup, members []string, id string) error {
|
||||
return global.DB.Transaction(func(tx *gorm.DB) error {
|
||||
o.ID = id
|
||||
err := tx.Updates(o).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Where("user_group_id = ?", id).Delete(&UserGroupMember{}).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if members != nil {
|
||||
userGroupId := o.ID
|
||||
err = AddUserGroupMembers(tx, members, userGroupId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return err
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func DeleteUserGroupById(id string) {
|
||||
global.DB.Where("id = ?", id).Delete(&UserGroup{})
|
||||
global.DB.Where("user_group_id = ?", id).Delete(&UserGroupMember{})
|
||||
func (r *UserGroupMember) TableName() string {
|
||||
return "user_group_members"
|
||||
}
|
||||
|
Reference in New Issue
Block a user