新增审计日志的搜索功能

This commit is contained in:
lanrenwo
2022-07-25 09:23:58 +08:00
parent e761c1e111
commit b8c3d33f2e
5 changed files with 218 additions and 5 deletions

51
server/dbdata/audit.go Normal file
View File

@@ -0,0 +1,51 @@
package dbdata
import (
"encoding/json"
"xorm.io/xorm"
)
type SearchCon struct {
Username string `json:"username"`
Src string `json:"src"`
Dst string `json:"dst"`
DstPort string `json:"dst_port"`
AccessProto string `json:"access_proto"`
Date []string `json:"date"`
Info string `json:"info"`
}
func GetAuditSession(search string) *xorm.Session {
session := xdb.Where("1=1")
if search == "" {
return session
}
var searchData SearchCon
err := json.Unmarshal([]byte(search), &searchData)
if err != nil {
return session
}
if searchData.Username != "" {
session.And("username = ?", searchData.Username)
}
if searchData.Src != "" {
session.And("src = ?", searchData.Src)
}
if searchData.Dst != "" {
session.And("dst = ?", searchData.Dst)
}
if searchData.DstPort != "" {
session.And("dst_port = ?", searchData.DstPort)
}
if searchData.AccessProto != "" {
session.And("access_proto = ?", searchData.AccessProto)
}
if len(searchData.Date) > 0 && searchData.Date[0] != "" {
session.And("created_at BETWEEN ? AND ?", searchData.Date[0], searchData.Date[1])
}
if searchData.Info != "" {
session.And("info LIKE ?", "%"+searchData.Info+"%")
}
return session
}

View File

@@ -0,0 +1,43 @@
package dbdata
import (
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestSearchAudit(t *testing.T) {
ast := assert.New(t)
preIpData()
defer closeIpdata()
currDateVal := "2022-07-24 00:00:00"
CreatedAt, _ := time.Parse("2006-01-02 15:04:05", currDateVal)
dataTest := AccessAudit{
Username: "Test",
Protocol: 6,
Src: "10.10.1.5",
SrcPort: 0,
Dst: "172.217.160.68",
DstPort: 80,
AccessProto: 4,
Info: "www.google.com",
CreatedAt: CreatedAt,
}
err := Add(dataTest)
ast.Nil(err)
var datas []AccessAudit
searchFormat := `{"username": "%s", "src":"%s", "dst": "%s", "dst_port":"%d","access_proto":"%d","info":"%s","date":["%s","%s"]}`
search := fmt.Sprintf(searchFormat, dataTest.Username, dataTest.Src, dataTest.Dst, dataTest.DstPort, dataTest.AccessProto, dataTest.Info, currDateVal, currDateVal)
session := GetAuditSession(search)
count, _ := FindAndCount(session, &datas, PageSize, 0)
ast.Equal(count, int64(1))
ast.Equal(datas[0].Username, dataTest.Username)
ast.Equal(datas[0].Dst, dataTest.Dst)
}

View File

@@ -3,6 +3,8 @@ package dbdata
import (
"errors"
"reflect"
"xorm.io/xorm"
)
const PageSize = 10
@@ -82,3 +84,12 @@ func Prefix(fieldName string, prefix string, data interface{}, limit, page int)
start := (page - 1) * limit
return where.Limit(limit, start).Find(data)
}
func FindAndCount(session *xorm.Session, data interface{}, limit, page int) (int64, error) {
if limit == 0 {
return session.FindAndCount(data)
}
start := (page - 1) * limit
totalCount, err := session.Limit(limit, start).FindAndCount(data)
return totalCount, err
}