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},
}
+11 -6
View File
@@ -88,25 +88,30 @@ function getLevelColor(level: string) {
<PopoverTrigger asChild>
<Button variant="ghost" size="icon" class="relative">
<Bell class="h-5 w-5" />
<span v-if="unreadCount > 0" class="absolute top-1 right-1 h-2 w-2 rounded-full bg-red-500 animate-pulse"></span>
<span v-if="unreadCount > 0"
class="absolute top-1 right-1 h-2 w-2 rounded-full bg-red-500 animate-pulse"></span>
</Button>
</PopoverTrigger>
<PopoverContent class="w-80 p-0" align="end">
<div class="flex items-center justify-between px-4 py-3 border-b">
<span class="font-medium text-sm">系统通知 <span class="text-xs text-muted-foreground ml-1" v-if="unreadCount">({{ unreadCount }})</span></span>
<Button variant="ghost" size="sm" class="h-auto p-0 text-xs text-muted-foreground hover:text-foreground" :disabled="loading || unreadCount === 0" @click="markAllAsRead">
<span class="font-medium text-sm">系统通知 <span class="text-xs text-muted-foreground ml-1" v-if="unreadCount">({{
unreadCount }})</span></span>
<Button variant="ghost" size="sm" class="h-auto p-0 text-xs text-muted-foreground hover:text-foreground"
:disabled="loading || unreadCount === 0" @click="markAllAsRead">
<Check class="h-3 w-3 mr-1" />
全标已读
</Button>
</div>
<ScrollArea class="h-[300px]" v-if="notices.length > 0">
<div class="flex flex-col">
<div v-for="notice in notices" :key="notice.id" class="p-4 border-b last:border-0 hover:bg-muted/50 transition-colors group relative">
<div v-for="notice in notices" :key="notice.id"
class="p-4 border-b last:border-0 hover:bg-muted/50 transition-colors group relative">
<div class="flex items-start justify-between gap-2 mb-1 cursor-pointer" @click="markAsRead(notice.id)">
<div class="flex-1 min-w-0">
<div class="flex items-center gap-2 mb-1">
<Badge :variant="getLevelColor(notice.level) as any" class="px-1.5 py-0 text-[10px]">{{ notice.level || 'info' }}</Badge>
<Badge :variant="getLevelColor(notice.level) as any" class="px-1.5 py-0 text-[10px]">{{ notice.level
|| 'info' }}</Badge>
<span class="text-sm font-medium truncate">{{ notice.title }}</span>
</div>
<p class="text-xs text-muted-foreground line-clamp-2">{{ notice.content }}</p>
+1 -1
View File
@@ -62,7 +62,7 @@ const navItems = [
{ to: '/languages', icon: Globe, label: '语言依赖', exact: true },
{ to: '/terminal', icon: Terminal, label: '终端命令', exact: true },
{ to: '/notify', icon: Bell, label: '消息推送', exact: true },
{ to: '/loginlogs', icon: KeyRound, label: '登录日志', exact: true },
{ to: '/logs', icon: KeyRound, label: '消息日志', exact: true },
{ to: '/settings', icon: Settings, label: '系统设置', exact: true },
]
+1 -1
View File
@@ -45,7 +45,7 @@ const router = createRouter({
{ path: 'languages', name: 'languages', component: () => import('@/views/languages/Languages.vue') },
{ path: 'agents', name: 'agents', component: () => import('@/views/agents/Agents.vue') },
{ path: 'history', name: 'history', component: () => import('@/views/history/History.vue') },
{ path: 'loginlogs', name: 'loginlogs', component: () => import('@/views/loginlogs/LoginLogs.vue') },
{ path: 'logs', name: 'logs', component: () => import('@/views/loginlogs/LoginLogs.vue') },
{ path: 'terminal', name: 'terminal', component: () => import('@/views/terminal/Terminal.vue') },
{ path: 'notify', name: 'notify', component: () => import('@/views/notify/Notify.vue') },
{ path: 'settings', name: 'settings', component: () => import('@/views/settings/Settings.vue') }
+30 -182
View File
@@ -1,194 +1,42 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import Pagination from '@/components/Pagination.vue'
import { RefreshCw, Search, Loader2 } from 'lucide-vue-next'
import TextOverflow from '@/components/TextOverflow.vue'
import { api } from '@/api'
import { toast } from 'vue-sonner'
import { useSiteSettings } from '@/composables/useSiteSettings'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription
} from '@/components/ui/dialog'
import { ref } from 'vue'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import LoginLogTab from './tabs/LoginLogTab.vue'
import SystemEventTab from './tabs/SystemEventTab.vue'
import PushLog from '@/views/notify/components/PushLog.vue'
const { pageSize } = useSiteSettings()
interface LoginLog {
id: string
username: string
ip: string
user_agent: string
status: string
message: string
created_at: string
}
interface IpGeoInfo {
ip: string
country: string
country_code: string
organization: string
isp: string
asn: number
asn_organization: string
timezone: string
latitude: number
longitude: number
continent_code: string
offset: number
}
const logs = ref<LoginLog[]>([])
const filterUsername = ref('')
const currentPage = ref(1)
const total = ref(0)
const loading = ref(false)
let searchTimer: ReturnType<typeof setTimeout> | null = null
// IP 地理位置弹窗
const ipDialogOpen = ref(false)
const ipGeoInfo = ref<IpGeoInfo | null>(null)
const ipGeoLoading = ref(false)
const selectedIp = ref('')
async function showIpInfo(ip: string) {
selectedIp.value = ip
ipDialogOpen.value = true
ipGeoLoading.value = true
ipGeoInfo.value = null
try {
const res = await fetch(`https://api.ip.sb/geoip/${ip}`)
if (!res.ok) throw new Error('请求失败')
ipGeoInfo.value = await res.json()
} catch {
toast.error('获取 IP 信息失败')
} finally {
ipGeoLoading.value = false
}
}
async function loadLogs() {
loading.value = true
try {
const res = await api.settings.getLoginLogs({
page: currentPage.value,
page_size: pageSize.value,
username: filterUsername.value || undefined
})
logs.value = res.data
total.value = res.total
} catch {
toast.error('加载登录日志失败')
} finally {
loading.value = false
}
}
function handleSearch() {
if (searchTimer) clearTimeout(searchTimer)
searchTimer = setTimeout(() => {
currentPage.value = 1
loadLogs()
}, 300)
}
function handlePageChange(page: number) {
currentPage.value = page
loadLogs()
}
onMounted(loadLogs)
const activeTab = ref('system')
</script>
<template>
<div class="space-y-6">
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<h2 class="text-xl sm:text-2xl font-bold tracking-tight">登录日志</h2>
<p class="text-muted-foreground text-sm">查看系统登录记录</p>
</div>
<div class="flex items-center gap-2">
<div class="relative flex-1 sm:flex-none">
<Search class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input v-model="filterUsername" placeholder="搜索用户名..." class="h-9 pl-9 w-full sm:w-56 text-sm"
@input="handleSearch" />
<Tabs v-model="activeTab" class="w-full">
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
<div>
<h2 class="text-xl sm:text-2xl font-bold tracking-tight">消息日志</h2>
<p class="text-muted-foreground text-sm">
{{ activeTab === 'system' ? '查看系统重要运行事件' :
activeTab === 'push' ? '查看消息推送历史记录' : '查看系统用户登录记录' }}
</p>
</div>
<Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="loadLogs" :disabled="loading">
<RefreshCw class="h-4 w-4" :class="{ 'animate-spin': loading }" />
</Button>
<TabsList class="grid grid-cols-3 w-full sm:w-auto min-w-[300px]">
<TabsTrigger value="system">系统事件</TabsTrigger>
<TabsTrigger value="push">推送日志</TabsTrigger>
<TabsTrigger value="login">登录日志</TabsTrigger>
</TabsList>
</div>
</div>
<div class="rounded-lg border bg-card overflow-x-auto">
<!-- 表头 -->
<div
class="flex items-center gap-2 sm:gap-4 px-3 sm:px-4 py-2 border-b bg-muted/50 text-xs sm:text-sm text-muted-foreground font-medium sm:min-w-[500px]">
<span class="w-16 sm:w-24 shrink-0">用户名</span>
<span class="w-20 sm:w-32 shrink-0">IP 地址</span>
<span class="w-10 sm:w-16 shrink-0 text-center">状态</span>
<span class="hidden sm:flex sm:flex-1">User Agent</span>
<span class="shrink-0 sm:w-40 sm:text-right">时间</span>
</div>
<!-- 列表 -->
<div class="divide-y sm:min-w-[500px]">
<div v-if="logs.length === 0" class="text-sm text-muted-foreground text-center py-8">
暂无登录日志
</div>
<div v-for="log in logs" :key="log.id"
class="flex items-center gap-2 sm:gap-4 px-3 sm:px-4 py-2 hover:bg-muted/50 transition-colors">
<span class="w-16 sm:w-24 shrink-0 font-medium text-xs sm:text-sm truncate">{{ log.username }}</span>
<code
class="w-20 sm:w-32 shrink-0 text-xs text-muted-foreground bg-muted px-1 sm:px-2 py-0.5 sm:py-1 rounded truncate cursor-pointer hover:bg-muted/80 transition-colors"
@click="showIpInfo(log.ip)">{{ log.ip }}</code>
<span class="w-10 sm:w-16 shrink-0 flex justify-center">
<span :class="['h-2 w-2 rounded-full', log.status === 'success' ? 'bg-green-500' : 'bg-red-500']"></span>
</span>
<span class="hidden sm:flex sm:flex-1 text-xs text-muted-foreground truncate">
<TextOverflow :text="log.user_agent || '-'" title="User Agent" />
</span>
<span class="shrink-0 sm:w-40 sm:text-right text-xs text-muted-foreground">{{ log.created_at }}</span>
</div>
</div>
<!-- 分页 -->
<Pagination :total="total" :page="currentPage" @update:page="handlePageChange" />
</div>
<TabsContent value="system" class="mt-0">
<SystemEventTab />
</TabsContent>
<!-- IP 地理位置弹窗 -->
<Dialog v-model:open="ipDialogOpen">
<DialogContent class="max-w-[90vw] sm:max-w-md">
<DialogHeader>
<DialogTitle>IP 详情</DialogTitle>
<DialogDescription>
<code class="text-xs bg-muted px-2 py-0.5 rounded">{{ selectedIp }}</code>
</DialogDescription>
</DialogHeader>
<div v-if="ipGeoLoading" class="flex items-center justify-center py-8">
<Loader2 class="h-6 w-6 animate-spin text-muted-foreground" />
</div>
<div v-else-if="ipGeoInfo" class="grid grid-cols-[auto_1fr] gap-x-4 gap-y-2 text-xs sm:text-sm">
<div class="text-muted-foreground">国家</div>
<div class="font-medium">{{ ipGeoInfo.country }} ({{ ipGeoInfo.country_code }})</div>
<div class="text-muted-foreground">运营商</div>
<div class="font-medium truncate">{{ ipGeoInfo.isp || '-' }}</div>
<div class="text-muted-foreground">组织</div>
<div class="font-medium truncate">{{ ipGeoInfo.organization || '-' }}</div>
<div class="text-muted-foreground">ASN</div>
<div class="font-medium truncate">{{ ipGeoInfo.asn }} - {{ ipGeoInfo.asn_organization || '-' }}</div>
<div class="text-muted-foreground">时区</div>
<div class="font-medium">{{ ipGeoInfo.timezone || '-' }}</div>
<div class="text-muted-foreground">坐标</div>
<div class="font-medium">{{ ipGeoInfo.latitude }}, {{ ipGeoInfo.longitude }}</div>
</div>
<div v-else class="text-center text-muted-foreground py-4">
无法获取 IP 信息
</div>
</DialogContent>
</Dialog>
<TabsContent value="push" class="mt-0">
<PushLog />
</TabsContent>
<TabsContent value="login" class="mt-0">
<LoginLogTab />
</TabsContent>
</Tabs>
</div>
</template>
@@ -0,0 +1,194 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import Pagination from '@/components/Pagination.vue'
import { RefreshCw, Search, Loader2 } from 'lucide-vue-next'
import TextOverflow from '@/components/TextOverflow.vue'
import { api } from '@/api'
import { toast } from 'vue-sonner'
import { useSiteSettings } from '@/composables/useSiteSettings'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription
} from '@/components/ui/dialog'
const { pageSize } = useSiteSettings()
interface LoginLog {
id: string
username: string
ip: string
user_agent: string
status: string
message: string
created_at: string
}
interface IpGeoInfo {
ip: string
country: string
country_code: string
organization: string
isp: string
asn: number
asn_organization: string
timezone: string
latitude: number
longitude: number
continent_code: string
offset: number
}
const logs = ref<LoginLog[]>([])
const filterUsername = ref('')
const currentPage = ref(1)
const total = ref(0)
const loading = ref(false)
let searchTimer: ReturnType<typeof setTimeout> | null = null
// IP 地理位置弹窗
const ipDialogOpen = ref(false)
const ipGeoInfo = ref<IpGeoInfo | null>(null)
const ipGeoLoading = ref(false)
const selectedIp = ref('')
async function showIpInfo(ip: string) {
selectedIp.value = ip
ipDialogOpen.value = true
ipGeoLoading.value = true
ipGeoInfo.value = null
try {
const res = await fetch(`https://api.ip.sb/geoip/${ip}`)
if (!res.ok) throw new Error('请求失败')
ipGeoInfo.value = await res.json()
} catch {
toast.error('获取 IP 信息失败')
} finally {
ipGeoLoading.value = false
}
}
async function loadLogs() {
loading.value = true
try {
const res = await api.settings.getLoginLogs({
page: currentPage.value,
page_size: pageSize.value,
username: filterUsername.value || undefined
})
logs.value = res.data
total.value = res.total
} catch {
toast.error('加载登录日志失败')
} finally {
loading.value = false
}
}
function handleSearch() {
if (searchTimer) clearTimeout(searchTimer)
searchTimer = setTimeout(() => {
currentPage.value = 1
loadLogs()
}, 300)
}
function handlePageChange(page: number) {
currentPage.value = page
loadLogs()
}
onMounted(loadLogs)
</script>
<template>
<div class="space-y-4">
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div class="flex items-center gap-2">
<div class="relative flex-1 sm:flex-none">
<Search class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input v-model="filterUsername" placeholder="搜索用户名..." class="h-9 pl-9 w-full sm:w-56 text-sm"
@input="handleSearch" />
</div>
<Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="loadLogs" :disabled="loading">
<RefreshCw class="h-4 w-4" :class="{ 'animate-spin': loading }" />
</Button>
</div>
</div>
<div class="rounded-lg border bg-card overflow-x-auto">
<!-- 表头 -->
<div
class="flex items-center gap-2 sm:gap-4 px-3 sm:px-4 py-2 border-b bg-muted/50 text-xs sm:text-sm text-muted-foreground font-medium sm:min-w-[500px]">
<span class="w-16 sm:w-24 shrink-0">用户名</span>
<span class="w-20 sm:w-32 shrink-0">IP 地址</span>
<span class="w-10 sm:w-16 shrink-0 text-center">状态</span>
<span class="hidden sm:flex sm:flex-1">User Agent</span>
<span class="shrink-0 sm:w-40 sm:text-right">时间</span>
</div>
<!-- 列表 -->
<div class="divide-y sm:min-w-[500px]">
<div v-if="logs.length === 0" class="text-sm text-muted-foreground text-center py-8">
暂无登录日志
</div>
<div v-for="log in logs" :key="log.id"
class="flex items-center gap-2 sm:gap-4 px-3 sm:px-4 py-2 hover:bg-muted/50 transition-colors">
<span class="w-16 sm:w-24 shrink-0 font-medium text-xs sm:text-sm truncate">{{ log.username
}}</span>
<code
class="w-20 sm:w-32 shrink-0 text-xs text-muted-foreground bg-muted px-1 sm:px-2 py-0.5 sm:py-1 rounded truncate cursor-pointer hover:bg-muted/80 transition-colors"
@click="showIpInfo(log.ip)">{{ log.ip }}</code>
<span class="w-10 sm:w-16 shrink-0 flex justify-center">
<span
:class="['h-2 w-2 rounded-full', log.status === 'success' ? 'bg-green-500' : 'bg-red-500']"></span>
</span>
<span class="hidden sm:flex sm:flex-1 text-xs text-muted-foreground truncate">
<TextOverflow :text="log.user_agent || '-'" title="User Agent" />
</span>
<span class="shrink-0 sm:w-40 sm:text-right text-xs text-muted-foreground">{{ log.created_at
}}</span>
</div>
</div>
<!-- 分页 -->
<Pagination :total="total" :page="currentPage" @update:page="handlePageChange" />
</div>
<!-- IP 地理位置弹窗 -->
<Dialog v-model:open="ipDialogOpen">
<DialogContent class="max-w-[90vw] sm:max-w-md">
<DialogHeader>
<DialogTitle>IP 详情</DialogTitle>
<DialogDescription>
<code class="text-xs bg-muted px-2 py-0.5 rounded">{{ selectedIp }}</code>
</DialogDescription>
</DialogHeader>
<div v-if="ipGeoLoading" class="flex items-center justify-center py-8">
<Loader2 class="h-6 w-6 animate-spin text-muted-foreground" />
</div>
<div v-else-if="ipGeoInfo" class="grid grid-cols-[auto_1fr] gap-x-4 gap-y-2 text-xs sm:text-sm">
<div class="text-muted-foreground">国家</div>
<div class="font-medium">{{ ipGeoInfo.country }} ({{ ipGeoInfo.country_code }})</div>
<div class="text-muted-foreground">运营商</div>
<div class="font-medium truncate">{{ ipGeoInfo.isp || '-' }}</div>
<div class="text-muted-foreground">组织</div>
<div class="font-medium truncate">{{ ipGeoInfo.organization || '-' }}</div>
<div class="text-muted-foreground">ASN</div>
<div class="font-medium truncate">{{ ipGeoInfo.asn }} - {{ ipGeoInfo.asn_organization || '-' }}
</div>
<div class="text-muted-foreground">时区</div>
<div class="font-medium">{{ ipGeoInfo.timezone || '-' }}</div>
<div class="text-muted-foreground">坐标</div>
<div class="font-medium">{{ ipGeoInfo.latitude }}, {{ ipGeoInfo.longitude }}</div>
</div>
<div v-else class="text-center text-muted-foreground py-4">
无法获取 IP 信息
</div>
</DialogContent>
</Dialog>
</div>
</template>
@@ -0,0 +1,284 @@
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { api, type AppLog, LOG_CATEGORY, LOG_LEVEL } from '@/api'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import Pagination from '@/components/Pagination.vue'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { toast } from 'vue-sonner'
import { format } from 'date-fns'
import {
RefreshCw, Trash2, Search, Info, AlertTriangle, AlertCircle
} from 'lucide-vue-next'
import { useSiteSettings } from '@/composables/useSiteSettings'
const { pageSize } = useSiteSettings()
const logs = ref<AppLog[]>([])
const selectedLogId = ref<string | null>(null)
const total = ref(0)
const loading = ref(false)
const filters = ref({
level: 'all',
keyword: '',
page: 1
})
let searchTimer: ReturnType<typeof setTimeout> | null = null
const detailDialogProps = ref({
open: false,
title: '',
content: '',
error: ''
})
async function fetchLogs() {
loading.value = true
try {
const res = await api.appLogs.list({
category: LOG_CATEGORY.SYSTEM_NOTICE,
level: filters.value.level === 'all' ? undefined : filters.value.level,
keyword: filters.value.keyword || undefined,
page: filters.value.page,
page_size: pageSize.value
})
logs.value = res.data || []
total.value = res.total || 0
} catch (e: any) {
toast.error(e.message || '获取系统事件失败')
} finally {
loading.value = false
}
}
function handleSearch() {
if (searchTimer) clearTimeout(searchTimer)
searchTimer = setTimeout(() => {
filters.value.page = 1
fetchLogs()
}, 300)
}
function handlePageChange(page: number) {
filters.value.page = page
fetchLogs()
}
function handleLevelChange(val: any) {
if (val === null || val === undefined) return
filters.value.level = String(val)
filters.value.page = 1
fetchLogs()
}
function showDetail(log: AppLog) {
selectedLogId.value = log.id
detailDialogProps.value = {
open: true,
title: log.title,
content: log.content,
error: log.error_msg
}
}
async function handleClear() {
try {
await api.appLogs.clear(LOG_CATEGORY.SYSTEM_NOTICE)
toast.success('清空成功')
filters.value.page = 1
fetchLogs()
} catch (e: any) {
toast.error('清空失败: ' + (e.message || ''))
}
}
onMounted(() => {
fetchLogs()
})
const selectedLog = computed(() => logs.value.find((l: AppLog) => l.id === selectedLogId.value))
function getLevelBadgeClass(level: string) {
switch (level) {
case LOG_LEVEL.INFO:
return 'bg-blue-500/10 text-blue-700 border-blue-200/50'
case LOG_LEVEL.WARNING:
return 'bg-yellow-500/10 text-yellow-700 border-yellow-200/50'
case LOG_LEVEL.ERROR:
return 'bg-red-500/10 text-red-700 border-red-200/50'
default:
return 'bg-secondary text-secondary-foreground border-transparent'
}
}
function getLevelIcon(level: string) {
switch (level) {
case LOG_LEVEL.INFO:
return Info
case LOG_LEVEL.WARNING:
return AlertTriangle
case LOG_LEVEL.ERROR:
return AlertCircle
default:
return Info
}
}
function formatDate(dateStr: string) {
if (!dateStr) return '-'
try {
return format(new Date(dateStr), 'yyyy-MM-dd HH:mm:ss')
} catch {
return dateStr
}
}
function onDialogClose(open: boolean) {
if (!open) {
selectedLogId.value = null
}
}
</script>
<template>
<div class="space-y-4">
<div class="flex items-center justify-between gap-2">
<div class="flex items-center gap-2">
<div class="relative flex-1 sm:flex-none">
<Search class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input v-model="filters.keyword" placeholder="搜索标题或内容..." class="h-9 pl-9 w-full sm:w-56 text-sm"
@input="handleSearch" />
</div>
<div class="relative flex-1 sm:flex-none">
<Select :model-value="filters.level" @update:model-value="handleLevelChange">
<SelectTrigger class="h-9 w-full sm:w-28 text-sm">
<SelectValue placeholder="级别" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">所有级别</SelectItem>
<SelectItem :value="LOG_LEVEL.INFO">信息</SelectItem>
<SelectItem :value="LOG_LEVEL.WARNING">警告</SelectItem>
<SelectItem :value="LOG_LEVEL.ERROR">错误</SelectItem>
</SelectContent>
</Select>
</div>
<Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="fetchLogs" :disabled="loading"
title="刷新">
<RefreshCw class="h-4 w-4" :class="{ 'animate-spin': loading }" />
</Button>
</div>
<Button variant="outline"
class="h-9 px-4 shrink-0 text-sm text-destructive hover:bg-destructive/10 hover:text-destructive border-destructive/20"
@click="handleClear">
<Trash2 class="h-4 w-4 sm:mr-2" /> <span class="hidden sm:inline" style="padding-left: 2px;">清空记录</span>
</Button>
</div>
<div class="rounded-lg border bg-card overflow-x-auto">
<div
class="flex items-center gap-2 sm:gap-4 px-3 sm:px-4 py-2 border-b bg-muted/50 text-xs sm:text-sm text-muted-foreground font-medium sm:min-w-[700px]">
<span class="w-12 sm:w-16 shrink-0">级别</span>
<span class="w-40 sm:w-56 shrink-0">事件标题</span>
<span class="hidden sm:flex sm:flex-1">详情内容</span>
<span class="shrink-0 w-24 sm:w-40 sm:text-right">发生时间</span>
</div>
<div class="divide-y sm:min-w-[700px]">
<div v-if="logs.length === 0 && !loading" class="text-sm text-muted-foreground text-center py-8">
暂无系统事件
</div>
<div v-for="log in logs" :key="log.id"
class="flex items-center gap-2 sm:gap-4 px-3 sm:px-4 py-2 hover:bg-muted/50 transition-colors cursor-pointer group"
:class="[selectedLogId === log.id && 'bg-accent/50']" @click="showDetail(log)">
<span class="w-12 sm:w-16 shrink-0 flex justify-center">
<component :is="getLevelIcon(log.level)" :class="['h-4 w-4',
log.level === LOG_LEVEL.INFO ? 'text-blue-500' :
log.level === LOG_LEVEL.WARNING ? 'text-yellow-500' : 'text-red-500']" />
</span>
<span class="w-40 sm:w-56 shrink-0 font-medium text-xs sm:text-sm truncate" :title="log.title">{{
log.title }}</span>
<span class="hidden sm:flex sm:flex-1 text-xs sm:text-sm text-muted-foreground truncate"
:title="log.content">
{{ log.content || '-' }}
</span>
<span class="shrink-0 w-24 sm:w-40 sm:text-right text-xs text-muted-foreground">
{{ formatDate(log.created_at) }}
</span>
</div>
</div>
<Pagination :total="total" :page="filters.page" @update:page="handlePageChange" />
</div>
<Dialog v-model:open="detailDialogProps.open" @update:open="onDialogClose">
<DialogContent class="sm:max-w-2xl max-h-[90vh] flex flex-col p-0 overflow-hidden">
<DialogHeader class="px-6 py-4 border-b bg-muted/20">
<div class="flex items-center justify-between pr-8">
<DialogTitle>事件详情</DialogTitle>
<Badge variant="outline" :class="[
'px-2 py-0.5 text-[10px] font-bold rounded-full border shadow-sm',
selectedLog ? getLevelBadgeClass(selectedLog.level) : ''
]">
<div class="flex items-center gap-1.5 uppercase tracking-wider">
<component :is="getLevelIcon(selectedLog?.level || 'info')" class="h-3 w-3" />
<span>{{ selectedLog?.level || 'INFO' }}</span>
</div>
</Badge>
</div>
</DialogHeader>
<div class="flex-1 overflow-y-auto">
<div class="px-6 py-4 border-b space-y-3 bg-card">
<div class="flex justify-between items-center text-sm">
<span class="text-muted-foreground">标题</span>
<span class="font-medium text-foreground">{{ detailDialogProps.title }}</span>
</div>
<div class="flex justify-between items-center text-sm">
<span class="text-muted-foreground">发生时间</span>
<span class="font-mono text-xs text-muted-foreground">{{ selectedLog ?
formatDate(selectedLog.created_at) : '-' }}</span>
</div>
</div>
<div class="flex flex-col min-h-0 bg-muted/5">
<div
class="px-6 py-2.5 text-xs font-semibold text-muted-foreground border-b bg-muted/10 uppercase tracking-wider">
内容详情
</div>
<div class="p-6">
<pre v-if="detailDialogProps.content"
class="text-xs font-mono bg-muted/30 p-4 rounded-lg border border-muted/50 whitespace-pre-wrap break-all leading-relaxed shadow-inner">{{ detailDialogProps.content }}</pre>
<div v-else class="text-xs text-muted-foreground italic py-2">无内容</div>
</div>
<template v-if="detailDialogProps.error">
<div
class="px-6 py-2.5 text-xs font-semibold text-red-500 border-y bg-red-500/5 uppercase tracking-wider">
错误信息
</div>
<div class="p-6">
<pre
class="text-xs font-mono bg-red-500/5 text-red-600/90 p-4 rounded-lg border border-red-500/20 whitespace-pre-wrap break-all leading-relaxed shadow-inner">{{ detailDialogProps.error }}</pre>
</div>
</template>
</div>
</div>
</DialogContent>
</Dialog>
</div>
</template>
+5 -10
View File
@@ -17,7 +17,6 @@ import ChannelList from './components/ChannelList.vue'
import EventBinding from './components/EventBinding.vue'
import ApiUsage from './components/ApiUsage.vue'
import ChannelDialog from './components/ChannelDialog.vue'
import PushLog from './components/PushLog.vue'
const activeTab = ref('channels')
@@ -323,11 +322,10 @@ onMounted(() => {
<h2 class="text-xl sm:text-2xl font-bold tracking-tight">消息推送</h2>
<p class="text-muted-foreground text-sm">配置通知渠道绑定系统事件实现自动推送</p>
</div>
<TabsList class="w-full sm:w-auto grid grid-cols-4 sm:inline-flex h-9 gap-1 p-1">
<TabsTrigger value="channels" class="text-xs px-3 py-1">渠道管理</TabsTrigger>
<TabsTrigger value="events" class="text-xs px-3 py-1">事件绑定</TabsTrigger>
<TabsTrigger value="logs" class="text-xs px-3 py-1">推送日志</TabsTrigger>
<TabsTrigger value="api" class="text-xs px-3 py-1">脚本调用</TabsTrigger>
<TabsList class="grid grid-cols-3 w-full sm:w-auto min-w-[300px]">
<TabsTrigger value="channels">渠道管理</TabsTrigger>
<TabsTrigger value="events">事件绑定</TabsTrigger>
<TabsTrigger value="api">脚本调用</TabsTrigger>
</TabsList>
</div>
@@ -349,10 +347,7 @@ onMounted(() => {
@generate-token="generateApiToken" @copy-token="copyApiToken" @copy-example="copyApiExample" />
</TabsContent>
<!-- 推送日志 -->
<TabsContent value="logs">
<PushLog />
</TabsContent>
</Tabs>
<!-- 添加/编辑渠道弹窗 -->
+19 -13
View File
@@ -167,7 +167,8 @@ function onDialogClose(open: boolean) {
</SelectContent>
</Select>
</div>
<Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="fetchLogs" :disabled="loading" title="刷新">
<Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="fetchLogs" :disabled="loading"
title="刷新">
<RefreshCw class="h-4 w-4" :class="{ 'animate-spin': loading }" />
</Button>
</div>
@@ -188,7 +189,7 @@ function onDialogClose(open: boolean) {
<span class="w-10 sm:w-16 shrink-0 text-center">状态</span>
<span class="shrink-0 w-24 sm:w-40 sm:text-right">发送时间</span>
</div>
<!-- 列表 -->
<div class="divide-y sm:min-w-[700px]">
<div v-if="logs.length === 0 && !loading" class="text-sm text-muted-foreground text-center py-8">
@@ -196,22 +197,23 @@ function onDialogClose(open: boolean) {
</div>
<div v-for="(log, index) in logs" :key="log.id"
class="flex items-center gap-2 sm:gap-4 px-3 sm:px-4 py-2 hover:bg-muted/50 transition-colors cursor-pointer group"
:class="[selectedLogId === log.id && 'bg-accent/50']"
@click="showDetail(log)">
:class="[selectedLogId === log.id && 'bg-accent/50']" @click="showDetail(log)">
<span class="w-12 sm:w-16 shrink-0 text-muted-foreground text-xs sm:text-sm">#{{ getLogIndex(index) }}</span>
<span class="w-40 sm:w-56 shrink-0 font-medium text-xs sm:text-sm truncate" :title="log.title">{{ log.title }}</span>
<span class="w-40 sm:w-56 shrink-0 font-medium text-xs sm:text-sm truncate" :title="log.title">{{ log.title
}}</span>
<span class="hidden sm:flex sm:flex-1 text-xs sm:text-sm text-muted-foreground truncate" :title="log.content">
{{ log.content || '-' }}
</span>
<span class="w-10 sm:w-16 shrink-0 flex justify-center">
<span :class="['h-2 w-2 rounded-full', log.status === LOG_STATUS.SUCCESS ? 'bg-green-500' : 'bg-red-500']"></span>
<span
:class="['h-2 w-2 rounded-full', log.status === LOG_STATUS.SUCCESS ? 'bg-green-500' : 'bg-red-500']"></span>
</span>
<span class="shrink-0 w-24 sm:w-40 sm:text-right text-xs text-muted-foreground">
{{ formatDate(log.created_at) }}
</span>
</div>
</div>
<!-- 分页 -->
<Pagination :total="total" :page="filters.page" @update:page="handlePageChange" />
</div>
@@ -233,7 +235,7 @@ function onDialogClose(open: boolean) {
</Badge>
</div>
</DialogHeader>
<div class="flex-1 overflow-y-auto">
<!-- 基础信息区 -->
<div class="px-6 py-4 border-b space-y-3 bg-card">
@@ -243,27 +245,31 @@ function onDialogClose(open: boolean) {
</div>
<div class="flex justify-between items-center text-sm">
<span class="text-muted-foreground">发生时间</span>
<span class="font-mono text-xs text-muted-foreground">{{ selectedLog ? formatDate(selectedLog.created_at) : '-' }}</span>
<span class="font-mono text-xs text-muted-foreground">{{ selectedLog ? formatDate(selectedLog.created_at)
: '-' }}</span>
</div>
</div>
<!-- 内容输出区 -->
<div class="flex flex-col min-h-0 bg-muted/5">
<div class="px-6 py-2.5 text-xs font-semibold text-muted-foreground border-b bg-muted/10 uppercase tracking-wider">
<div
class="px-6 py-2.5 text-xs font-semibold text-muted-foreground border-b bg-muted/10 uppercase tracking-wider">
推送内容
</div>
<div class="p-6">
<pre v-if="detailDialogProps.content"
<pre v-if="detailDialogProps.content"
class="text-xs font-mono bg-muted/30 p-4 rounded-lg border border-muted/50 whitespace-pre-wrap break-all leading-relaxed shadow-inner">{{ detailDialogProps.content }}</pre>
<div v-else class="text-xs text-muted-foreground italic py-2">无推送内容</div>
</div>
<template v-if="detailDialogProps.error">
<div class="px-6 py-2.5 text-xs font-semibold text-red-500 border-y bg-red-500/5 uppercase tracking-wider">
<div
class="px-6 py-2.5 text-xs font-semibold text-red-500 border-y bg-red-500/5 uppercase tracking-wider">
错误信息
</div>
<div class="p-6">
<pre class="text-xs font-mono bg-red-500/5 text-red-600/90 p-4 rounded-lg border border-red-500/20 whitespace-pre-wrap break-all leading-relaxed shadow-inner">{{ detailDialogProps.error }}</pre>
<pre
class="text-xs font-mono bg-red-500/5 text-red-600/90 p-4 rounded-lg border border-red-500/20 whitespace-pre-wrap break-all leading-relaxed shadow-inner">{{ detailDialogProps.error }}</pre>
</div>
</template>
</div>