feat: opt message logs page

This commit is contained in:
engigu
2026-03-09 21:31:54 +08:00
parent ca1bcf289c
commit 77ceef7616
17 changed files with 630 additions and 330 deletions
+1
View File
@@ -119,6 +119,7 @@ const (
LogCategoryDefault = "default"
LogCategorySystemNotice = "system_notice"
LogCategoryPushLog = "push_log"
LogCategoryLoginLog = "login_log"
// AppLog 级别
LogLevelInfo = "info"
+28 -13
View File
@@ -10,6 +10,7 @@ import (
"os"
"strings"
"time"
"github.com/engigu/baihu-panel/internal/constant"
"github.com/engigu/baihu-panel/internal/database"
"github.com/engigu/baihu-panel/internal/eventbus"
@@ -143,18 +144,18 @@ func (sc *SettingsController) GetPublicSiteSettings(c *gin.Context) {
// UpdateSiteSettings 更新站点设置
func (sc *SettingsController) UpdateSiteSettings(c *gin.Context) {
var req struct {
Title string `json:"title"`
Subtitle string `json:"subtitle"`
Icon string `json:"icon"`
PageSize string `json:"page_size"`
CookieDays string `json:"cookie_days"`
OpenapiEnabled bool `json:"openapi_enabled"`
OpenapiToken string `json:"openapi_token"`
OpenapiTokenExpire string `json:"openapi_token_expire"`
SystemNoticeDays int `json:"system_notice_days"`
SystemNoticeMaxCount int `json:"system_notice_max_count"`
PushLogDays int `json:"push_log_days"`
PushLogMaxCount int `json:"push_log_max_count"`
Title string `json:"title"`
Subtitle string `json:"subtitle"`
Icon string `json:"icon"`
PageSize string `json:"page_size"`
CookieDays string `json:"cookie_days"`
OpenapiEnabled bool `json:"openapi_enabled"`
OpenapiToken string `json:"openapi_token"`
OpenapiTokenExpire string `json:"openapi_token_expire"`
SystemNoticeDays int `json:"system_notice_days"`
SystemNoticeMaxCount int `json:"system_notice_max_count"`
PushLogDays int `json:"push_log_days"`
PushLogMaxCount int `json:"push_log_max_count"`
}
if err := c.ShouldBindJSON(&req); err != nil {
@@ -341,8 +342,22 @@ func (sc *SettingsController) GetLoginLogs(c *gin.Context) {
return
}
// 将 AppLog 转换为 LoginLogVO 返回,保持前端兼容性
vos := make([]*vo.LoginLogVO, len(logs))
for i, log := range logs {
vos[i] = &vo.LoginLogVO{
ID: log.ID,
Username: log.Title,
IP: log.RefID,
UserAgent: string(log.Content),
Status: log.Status,
Message: string(log.ErrorMsg),
CreatedAt: log.CreatedAt,
}
}
utils.Success(c, utils.PaginationData{
Data: vo.ToLoginLogVOListFromModels(logs),
Data: vos,
Total: total,
Page: page,
PageSize: pageSize,
-1
View File
@@ -21,7 +21,6 @@ func Migrate() error {
&models.Script{},
&models.EnvironmentVariable{},
&models.Setting{},
&models.LoginLog{},
&models.SendStats{},
&models.Dependency{},
&models.Agent{},
-20
View File
@@ -1,20 +0,0 @@
package models
import (
"github.com/engigu/baihu-panel/internal/constant"
)
// LoginLog 登录日志
type LoginLog struct {
ID string `json:"id" gorm:"primaryKey;size:20"`
Username string `json:"username" gorm:"size:100;index;not null"`
IP string `json:"ip" gorm:"size:50"`
UserAgent string `json:"user_agent" gorm:"size:500"`
Status string `json:"status" gorm:"size:20;index"` // success, failed
Message string `json:"message" gorm:"size:255"`
CreatedAt LocalTime `json:"created_at" gorm:"index"`
}
func (LoginLog) TableName() string {
return constant.TablePrefix + "login_logs"
}
-37
View File
@@ -88,43 +88,6 @@ type LoginLogVO struct {
CreatedAt models.LocalTime `json:"created_at"`
}
// ToLoginLogVO 将 LoginLog 模型转换为 LoginLogVO
func ToLoginLogVO(log *models.LoginLog) *LoginLogVO {
if log == nil {
return nil
}
return &LoginLogVO{
ID: log.ID,
Username: log.Username,
IP: log.IP,
UserAgent: log.UserAgent,
Status: log.Status,
Message: log.Message,
CreatedAt: log.CreatedAt,
}
}
// ToLoginLogVOList 将 LoginLog 模型列表转换为 LoginLogVO 列表
func ToLoginLogVOList(logs []*models.LoginLog) []*LoginLogVO {
if logs == nil {
return nil
}
vos := make([]*LoginLogVO, len(logs))
for i, l := range logs {
vos[i] = ToLoginLogVO(l)
}
return vos
}
// ToLoginLogVOListFromModels 将 LoginLog 模型列表转换为 LoginLogVO 列表
func ToLoginLogVOListFromModels(logs []models.LoginLog) []*LoginLogVO {
vos := make([]*LoginLogVO, len(logs))
for i := range logs {
vos[i] = ToLoginLogVO(&logs[i])
}
return vos
}
// TokenConfig Token 配置结构体
type TokenConfig struct {
Enabled bool `json:"enabled"`
+32 -29
View File
@@ -5,6 +5,7 @@ import (
"time"
"fmt"
"github.com/engigu/baihu-panel/internal/constant"
"github.com/engigu/baihu-panel/internal/database"
"github.com/engigu/baihu-panel/internal/eventbus"
@@ -185,40 +186,42 @@ func (s *AppLogService) SubscribeEvents(bus *eventbus.EventBus) {
})
// 3. 将某些业务事件转化为系统内部通知 (自动出现在小铃铛)
bus.Subscribe(constant.EventTaskFailed, func(e eventbus.Event) {
payload, ok := e.Payload.(map[string]interface{})
if !ok {
return
}
taskName, _ := payload["task_name"].(string)
errMsg, _ := payload["error"].(string)
/*
bus.Subscribe(constant.EventTaskFailed, func(e eventbus.Event) {
payload, ok := e.Payload.(map[string]interface{})
if !ok {
return
}
taskName, _ := payload["task_name"].(string)
errMsg, _ := payload["error"].(string)
bus.Publish(eventbus.Event{
Type: constant.EventSystemNotice,
Payload: map[string]interface{}{
"title": fmt.Sprintf("任务 [%s] 执行失败", taskName),
"content": fmt.Sprintf("错误详情: %s", errMsg),
"level": constant.LogLevelError,
},
bus.Publish(eventbus.Event{
Type: constant.EventSystemNotice,
Payload: map[string]interface{}{
"title": fmt.Sprintf("任务 [%s] 执行失败", taskName),
"content": fmt.Sprintf("错误详情: %s", errMsg),
"level": constant.LogLevelError,
},
})
})
})
bus.Subscribe(constant.EventTaskTimeout, func(e eventbus.Event) {
payload, ok := e.Payload.(map[string]interface{})
if !ok {
return
}
taskName, _ := payload["task_name"].(string)
bus.Subscribe(constant.EventTaskTimeout, func(e eventbus.Event) {
payload, ok := e.Payload.(map[string]interface{})
if !ok {
return
}
taskName, _ := payload["task_name"].(string)
bus.Publish(eventbus.Event{
Type: constant.EventSystemNotice,
Payload: map[string]interface{}{
"title": fmt.Sprintf("任务 [%s] 执行超时", taskName),
"content": "任务已经超过预设的运行时间并被系统强制中止。",
"level": constant.LogLevelWarning,
},
bus.Publish(eventbus.Event{
Type: constant.EventSystemNotice,
Payload: map[string]interface{}{
"title": fmt.Sprintf("任务 [%s] 执行超时", taskName),
"content": "任务已经超过预设的运行时间并被系统强制中止。",
"level": constant.LogLevelWarning,
},
})
})
})
*/
bus.Subscribe(constant.EventPasswordChanged, func(e eventbus.Event) {
payload, ok := e.Payload.(map[string]interface{})
+3 -4
View File
@@ -50,7 +50,7 @@ func (s *BackupService) getTableConfigs() []tableConfig {
{"scripts.json", s.exportTable(&[]models.Script{}, true), s.restoreTable(&[]models.Script{}, true)},
{"settings.json", s.exportSettings, s.restoreSettings},
{"send_stats.json", s.exportTable(&[]models.SendStats{}, false), s.restoreTable(&[]models.SendStats{}, false)},
{"login_logs.json", s.exportTable(&[]models.LoginLog{}, false), s.restoreTable(&[]models.LoginLog{}, false)},
{"agents.json", s.exportTable(&[]models.Agent{}, true), s.restoreTable(&[]models.Agent{}, true)},
{"tokens.json", s.exportTable(&[]models.AgentToken{}, true), s.restoreTable(&[]models.AgentToken{}, true)},
{"languages.json", s.exportTable(&[]models.Language{}, true), s.restoreTable(&[]models.Language{}, true)},
@@ -229,7 +229,7 @@ func (s *BackupService) Restore(zipPath string) error {
tx.Unscoped().Where("1=1").Delete(&models.Script{})
tx.Unscoped().Where("section != ?", BackupSection).Delete(&models.Setting{})
tx.Unscoped().Where("1=1").Delete(&models.SendStats{})
tx.Unscoped().Where("1=1").Delete(&models.LoginLog{})
tx.Unscoped().Where("1=1").Delete(&models.Agent{})
tx.Unscoped().Where("1=1").Delete(&models.AgentToken{})
tx.Unscoped().Where("1=1").Delete(&models.Language{})
@@ -328,8 +328,7 @@ func (s *BackupService) restoreFromZipFile(tx *gorm.DB, f *zip.File, filename st
return restoreStreamBatch[models.Script](tx, decoder)
case "send_stats.json":
return restoreStreamBatch[models.SendStats](tx, decoder)
case "login_logs.json":
return restoreStreamBatch[models.LoginLog](tx, decoder)
case "agents.json":
return restoreStreamBatch[models.Agent](tx, decoder)
case "tokens.json":
+21 -12
View File
@@ -2,6 +2,8 @@ package services
import (
"fmt"
"time"
"github.com/engigu/baihu-panel/internal/constant"
"github.com/engigu/baihu-panel/internal/database"
"github.com/engigu/baihu-panel/internal/eventbus"
@@ -17,13 +19,19 @@ func NewLoginLogService() *LoginLogService {
// Create 创建登录日志
func (s *LoginLogService) Create(username, ip, userAgent, status, message string) error {
log := &models.LoginLog{
ID: utils.GenerateID(),
Username: username,
IP: ip,
UserAgent: userAgent,
Status: status,
Message: message,
level := constant.LogLevelInfo
if status != "success" {
level = constant.LogLevelWarning
}
log := &models.AppLog{
ID: utils.GenerateID(),
Category: constant.LogCategoryLoginLog,
Title: username,
Content: models.BigText(userAgent),
Level: level,
Status: status,
RefID: ip,
ErrorMsg: models.BigText(message),
}
return database.DB.Create(log).Error
}
@@ -84,13 +92,13 @@ func (s *LoginLogService) SubscribeEvents(bus *eventbus.EventBus) {
}
// List 获取登录日志列表
func (s *LoginLogService) List(page, pageSize int, username string) ([]models.LoginLog, int64, error) {
var logs []models.LoginLog
func (s *LoginLogService) List(page, pageSize int, username string) ([]models.AppLog, int64, error) {
var logs []models.AppLog
var total int64
query := database.DB.Model(&models.LoginLog{})
query := database.DB.Model(&models.AppLog{}).Where("category = ?", constant.LogCategoryLoginLog)
if username != "" {
query = query.Where("username LIKE ?", "%"+username+"%")
query = query.Where("title LIKE ?", "%"+username+"%")
}
if err := query.Count(&total).Error; err != nil {
@@ -107,6 +115,7 @@ func (s *LoginLogService) List(page, pageSize int, username string) ([]models.Lo
// CleanOldLogs 清理指定天数前的日志
func (s *LoginLogService) CleanOldLogs(days int) (int64, error) {
result := database.DB.Exec("DELETE FROM "+models.LoginLog{}.TableName()+" WHERE created_at < datetime('now', ?)", "-"+string(rune(days))+" days")
deadline := time.Now().AddDate(0, 0, -days)
result := database.DB.Unscoped().Where("category = ? AND created_at < ?", constant.LogCategoryLoginLog, deadline).Delete(&models.AppLog{})
return result.RowsAffected, result.Error
}
-1
View File
@@ -32,7 +32,6 @@ func getMigrationTables() []MigrationTable {
{&models.Script{}, "scripts", map[string]string{"UserID": "users"}, nil},
{&models.Setting{}, "settings", nil, nil},
{&models.SendStats{}, "send_stats", map[string]string{"TaskID": "tasks"}, nil},
{&models.LoginLog{}, "login_logs", nil, nil},
{&models.Language{}, "languages", nil, nil},
{&models.Dependency{}, "deps", nil, nil},
}