fix: agent page and agent cmd
This commit is contained in:
@@ -519,16 +519,16 @@ func (c *AgentController) NotifyTaskUpdate(agentID uint) {
|
|||||||
c.wsManager.BroadcastTasks(agentID)
|
c.wsManager.BroadcastTasks(agentID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ========== 注册码管理 ==========
|
// ========== 令牌管理 ==========
|
||||||
|
|
||||||
// ListRegCodes 获取注册码列表
|
// ListTokens 获取令牌列表
|
||||||
func (c *AgentController) ListRegCodes(ctx *gin.Context) {
|
func (c *AgentController) ListTokens(ctx *gin.Context) {
|
||||||
codes := c.agentService.ListRegCodes()
|
tokens := c.agentService.ListTokens()
|
||||||
utils.Success(ctx, codes)
|
utils.Success(ctx, tokens)
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateRegCode 创建注册码
|
// CreateToken 创建令牌
|
||||||
func (c *AgentController) CreateRegCode(ctx *gin.Context) {
|
func (c *AgentController) CreateToken(ctx *gin.Context) {
|
||||||
var req struct {
|
var req struct {
|
||||||
Remark string `json:"remark"`
|
Remark string `json:"remark"`
|
||||||
MaxUses int `json:"max_uses"`
|
MaxUses int `json:"max_uses"`
|
||||||
@@ -550,24 +550,24 @@ func (c *AgentController) CreateRegCode(ctx *gin.Context) {
|
|||||||
expiresAt = &t
|
expiresAt = &t
|
||||||
}
|
}
|
||||||
|
|
||||||
code, err := c.agentService.CreateRegCode(req.Remark, req.MaxUses, expiresAt)
|
token, err := c.agentService.CreateToken(req.Remark, req.MaxUses, expiresAt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.ServerError(ctx, err.Error())
|
utils.ServerError(ctx, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
utils.Success(ctx, code)
|
utils.Success(ctx, token)
|
||||||
}
|
}
|
||||||
|
|
||||||
// DeleteRegCode 删除注册码
|
// DeleteToken 删除令牌
|
||||||
func (c *AgentController) DeleteRegCode(ctx *gin.Context) {
|
func (c *AgentController) DeleteToken(ctx *gin.Context) {
|
||||||
id, err := strconv.ParseUint(ctx.Param("id"), 10, 32)
|
id, err := strconv.ParseUint(ctx.Param("id"), 10, 32)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.BadRequest(ctx, "无效的 ID")
|
utils.BadRequest(ctx, "无效的 ID")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := c.agentService.DeleteRegCode(uint(id)); err != nil {
|
if err := c.agentService.DeleteToken(uint(id)); err != nil {
|
||||||
utils.ServerError(ctx, err.Error())
|
utils.ServerError(ctx, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,18 +22,19 @@ func Migrate() error {
|
|||||||
&models.SendStats{},
|
&models.SendStats{},
|
||||||
&models.Dependency{},
|
&models.Dependency{},
|
||||||
&models.Agent{},
|
&models.Agent{},
|
||||||
&models.AgentRegCode{},
|
&models.AgentToken{},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// customMigrations 自定义迁移(处理 AutoMigrate 无法自动完成的变更)
|
// customMigrations 自定义迁移(处理 AutoMigrate 无法自动完成的变更)
|
||||||
func customMigrations() error {
|
func customMigrations() error {
|
||||||
// 检查 ql_tokens 表是否存在,如果存在则修改 code 列大小为 64
|
// 检查 ql_tokens 表是否存在
|
||||||
if DB.Migrator().HasTable("ql_tokens") {
|
if DB.Migrator().HasTable("ql_tokens") {
|
||||||
// MySQL: 修改 code 列大小
|
// 将 code 列重命名为 token(如果 code 列存在)
|
||||||
if err := DB.Exec("ALTER TABLE ql_tokens MODIFY COLUMN code VARCHAR(64)").Error; err != nil {
|
if DB.Migrator().HasColumn(&models.AgentToken{}, "code") {
|
||||||
// 忽略错误(可能是 SQLite 或列已经是正确大小)
|
if err := DB.Migrator().RenameColumn(&models.AgentToken{}, "code", "token"); err != nil {
|
||||||
logger.Debugf("[Database] 修改 ql_tokens.code 列: %v", err)
|
logger.Debugf("[Database] 重命名 ql_tokens.code 列: %v", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -32,21 +32,21 @@ func (Agent) TableName() string {
|
|||||||
return constant.TablePrefix + "agents"
|
return constant.TablePrefix + "agents"
|
||||||
}
|
}
|
||||||
|
|
||||||
// AgentRegCode 注册码
|
// AgentToken Agent 令牌
|
||||||
type AgentRegCode struct {
|
type AgentToken struct {
|
||||||
ID uint `json:"id" gorm:"primaryKey"`
|
ID uint `json:"id" gorm:"primaryKey"`
|
||||||
Code string `json:"code" gorm:"size:64;uniqueIndex;not null"` // 令牌
|
Token string `json:"token" gorm:"size:64;uniqueIndex;not null"` // 令牌
|
||||||
Remark string `json:"remark" gorm:"size:255"` // 备注
|
Remark string `json:"remark" gorm:"size:255"` // 备注
|
||||||
MaxUses int `json:"max_uses" gorm:"default:0"` // 最大使用次数,0 表示无限制
|
MaxUses int `json:"max_uses" gorm:"default:0"` // 最大使用次数,0 表示无限制
|
||||||
UsedCount int `json:"used_count" gorm:"default:0"` // 已使用次数
|
UsedCount int `json:"used_count" gorm:"default:0"` // 已使用次数
|
||||||
ExpiresAt *LocalTime `json:"expires_at"` // 过期时间,null 表示永不过期
|
ExpiresAt *LocalTime `json:"expires_at"` // 过期时间,null 表示永不过期
|
||||||
Enabled bool `json:"enabled" gorm:"default:true"` // 是否启用
|
Enabled bool `json:"enabled" gorm:"default:true"` // 是否启用
|
||||||
CreatedAt LocalTime `json:"created_at"`
|
CreatedAt LocalTime `json:"created_at"`
|
||||||
UpdatedAt LocalTime `json:"updated_at"`
|
UpdatedAt LocalTime `json:"updated_at"`
|
||||||
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
|
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (AgentRegCode) TableName() string {
|
func (AgentToken) TableName() string {
|
||||||
return constant.TablePrefix + "tokens"
|
return constant.TablePrefix + "tokens"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -209,9 +209,9 @@ func Setup(c *Controllers) *gin.Engine {
|
|||||||
agents.POST("/:id/token", c.Agent.RegenerateToken)
|
agents.POST("/:id/token", c.Agent.RegenerateToken)
|
||||||
agents.POST("/:id/update", c.Agent.ForceUpdate)
|
agents.POST("/:id/update", c.Agent.ForceUpdate)
|
||||||
// 令牌管理
|
// 令牌管理
|
||||||
agents.GET("/regcodes", c.Agent.ListRegCodes)
|
agents.GET("/tokens", c.Agent.ListTokens)
|
||||||
agents.POST("/regcodes", c.Agent.CreateRegCode)
|
agents.POST("/tokens", c.Agent.CreateToken)
|
||||||
agents.DELETE("/regcodes/:id", c.Agent.DeleteRegCode)
|
agents.DELETE("/tokens/:id", c.Agent.DeleteToken)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -24,87 +24,80 @@ func NewAgentService() *AgentService {
|
|||||||
return &AgentService{}
|
return &AgentService{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// generateToken 生成随机 Token
|
// generateToken 生成随机 Token(64位十六进制)
|
||||||
func generateToken() string {
|
func generateToken() string {
|
||||||
bytes := make([]byte, 32)
|
bytes := make([]byte, 32)
|
||||||
rand.Read(bytes)
|
rand.Read(bytes)
|
||||||
return hex.EncodeToString(bytes)
|
return hex.EncodeToString(bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
// generateRegCode 生成令牌(64位,与认证 Token 相同)
|
// ========== 令牌管理 ==========
|
||||||
func generateRegCode() string {
|
|
||||||
bytes := make([]byte, 32)
|
|
||||||
rand.Read(bytes)
|
|
||||||
return hex.EncodeToString(bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ========== 注册码管理 ==========
|
// CreateToken 创建令牌
|
||||||
|
func (s *AgentService) CreateToken(remark string, maxUses int, expiresAt *time.Time) (*models.AgentToken, error) {
|
||||||
// CreateRegCode 创建令牌(同时创建 Agent 记录)
|
|
||||||
func (s *AgentService) CreateRegCode(remark string, maxUses int, expiresAt *time.Time) (*models.AgentRegCode, error) {
|
|
||||||
var expires *models.LocalTime
|
var expires *models.LocalTime
|
||||||
if expiresAt != nil {
|
if expiresAt != nil {
|
||||||
t := models.LocalTime(*expiresAt)
|
t := models.LocalTime(*expiresAt)
|
||||||
expires = &t
|
expires = &t
|
||||||
}
|
}
|
||||||
|
|
||||||
token := generateRegCode()
|
token := generateToken()
|
||||||
|
|
||||||
regCode := &models.AgentRegCode{
|
agentToken := &models.AgentToken{
|
||||||
Code: token,
|
Token: token,
|
||||||
Remark: remark,
|
Remark: remark,
|
||||||
MaxUses: maxUses,
|
MaxUses: maxUses,
|
||||||
ExpiresAt: expires,
|
ExpiresAt: expires,
|
||||||
Enabled: true,
|
Enabled: true,
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := database.DB.Create(regCode).Error; err != nil {
|
if err := database.DB.Create(agentToken).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.Infof("[Agent] 创建令牌: %s (max_uses=%d)", token[:8]+"...", maxUses)
|
logger.Infof("[Agent] 创建令牌: %s (max_uses=%d)", token[:8]+"...", maxUses)
|
||||||
return regCode, nil
|
return agentToken, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListRegCodes 获取注册码列表
|
// ListTokens 获取令牌列表
|
||||||
func (s *AgentService) ListRegCodes() []models.AgentRegCode {
|
func (s *AgentService) ListTokens() []models.AgentToken {
|
||||||
var codes []models.AgentRegCode
|
var tokens []models.AgentToken
|
||||||
database.DB.Order("id DESC").Find(&codes)
|
database.DB.Order("id DESC").Find(&tokens)
|
||||||
return codes
|
return tokens
|
||||||
}
|
}
|
||||||
|
|
||||||
// DeleteRegCode 删除注册码
|
// DeleteToken 删除令牌
|
||||||
func (s *AgentService) DeleteRegCode(id uint) error {
|
func (s *AgentService) DeleteToken(id uint) error {
|
||||||
return database.DB.Delete(&models.AgentRegCode{}, id).Error
|
return database.DB.Delete(&models.AgentToken{}, id).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
// ValidateRegCode 验证注册码
|
// ValidateToken 验证令牌
|
||||||
func (s *AgentService) ValidateRegCode(code string) (*models.AgentRegCode, error) {
|
func (s *AgentService) ValidateToken(token string) (*models.AgentToken, error) {
|
||||||
var regCode models.AgentRegCode
|
var agentToken models.AgentToken
|
||||||
if err := database.DB.Where("code = ?", code).First(®Code).Error; err != nil {
|
if err := database.DB.Where("token = ?", token).First(&agentToken).Error; err != nil {
|
||||||
return nil, &ServiceError{Message: "无效的注册码"}
|
return nil, &ServiceError{Message: "无效的令牌"}
|
||||||
}
|
}
|
||||||
|
|
||||||
if !regCode.Enabled {
|
if !agentToken.Enabled {
|
||||||
return nil, &ServiceError{Message: "注册码已禁用"}
|
return nil, &ServiceError{Message: "令牌已禁用"}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查使用次数
|
// 检查使用次数
|
||||||
if regCode.MaxUses > 0 && regCode.UsedCount >= regCode.MaxUses {
|
if agentToken.MaxUses > 0 && agentToken.UsedCount >= agentToken.MaxUses {
|
||||||
return nil, &ServiceError{Message: "注册码已达到使用上限"}
|
return nil, &ServiceError{Message: "令牌已达到使用上限"}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查过期时间
|
// 检查过期时间
|
||||||
if regCode.ExpiresAt != nil && time.Time(*regCode.ExpiresAt).Before(time.Now()) {
|
if agentToken.ExpiresAt != nil && time.Time(*agentToken.ExpiresAt).Before(time.Now()) {
|
||||||
return nil, &ServiceError{Message: "注册码已过期"}
|
return nil, &ServiceError{Message: "令牌已过期"}
|
||||||
}
|
}
|
||||||
|
|
||||||
return ®Code, nil
|
return &agentToken, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// UseRegCode 使用注册码(增加使用计数)
|
// UseToken 使用令牌(增加使用计数)
|
||||||
func (s *AgentService) UseRegCode(id uint) {
|
func (s *AgentService) UseToken(id uint) {
|
||||||
database.DB.Model(&models.AgentRegCode{}).Where("id = ?", id).UpdateColumn("used_count", gorm.Expr("used_count + 1"))
|
database.DB.Model(&models.AgentToken{}).Where("id = ?", id).UpdateColumn("used_count", gorm.Expr("used_count + 1"))
|
||||||
}
|
}
|
||||||
|
|
||||||
// ========== Agent 注册 ==========
|
// ========== Agent 注册 ==========
|
||||||
@@ -113,7 +106,7 @@ func (s *AgentService) UseRegCode(id uint) {
|
|||||||
// 返回: agent, isNewAgent, error
|
// 返回: agent, isNewAgent, error
|
||||||
func (s *AgentService) RegisterByToken(token string, machineID string, ip string) (*models.Agent, bool, error) {
|
func (s *AgentService) RegisterByToken(token string, machineID string, ip string) (*models.Agent, bool, error) {
|
||||||
// 验证令牌
|
// 验证令牌
|
||||||
regCode, err := s.ValidateRegCode(token)
|
agentToken, err := s.ValidateToken(token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, false, err
|
return nil, false, err
|
||||||
}
|
}
|
||||||
@@ -125,12 +118,12 @@ func (s *AgentService) RegisterByToken(token string, machineID string, ip string
|
|||||||
// 已存在,更新 token 和状态,复用已有 Agent
|
// 已存在,更新 token 和状态,复用已有 Agent
|
||||||
now := models.LocalTime(time.Now())
|
now := models.LocalTime(time.Now())
|
||||||
database.DB.Model(&existing).Updates(map[string]interface{}{
|
database.DB.Model(&existing).Updates(map[string]interface{}{
|
||||||
"token": token,
|
"token": token,
|
||||||
"ip": ip,
|
"ip": ip,
|
||||||
"status": "online",
|
"status": "online",
|
||||||
"last_seen": now,
|
"last_seen": now,
|
||||||
})
|
})
|
||||||
s.UseRegCode(regCode.ID)
|
s.UseToken(agentToken.ID)
|
||||||
logger.Infof("[Agent] Agent #%d 通过 machine_id 复用 (%s)", existing.ID, machineID[:8]+"...")
|
logger.Infof("[Agent] Agent #%d 通过 machine_id 复用 (%s)", existing.ID, machineID[:8]+"...")
|
||||||
return &existing, false, nil
|
return &existing, false, nil
|
||||||
}
|
}
|
||||||
@@ -152,7 +145,7 @@ func (s *AgentService) RegisterByToken(token string, machineID string, ip string
|
|||||||
return nil, false, err
|
return nil, false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
s.UseRegCode(regCode.ID)
|
s.UseToken(agentToken.ID)
|
||||||
logger.Infof("[Agent] Agent 通过令牌注册: #%d (%s)", agent.ID, ip)
|
logger.Infof("[Agent] Agent 通过令牌注册: #%d (%s)", agent.ID, ip)
|
||||||
return agent, true, nil
|
return agent, true, nil
|
||||||
}
|
}
|
||||||
@@ -161,10 +154,10 @@ func (s *AgentService) RegisterByToken(token string, machineID string, ip string
|
|||||||
func (s *AgentService) Register(req *models.AgentRegisterRequest, ip string) (*models.Agent, string, error) {
|
func (s *AgentService) Register(req *models.AgentRegisterRequest, ip string) (*models.Agent, string, error) {
|
||||||
// 必须提供令牌
|
// 必须提供令牌
|
||||||
if req.Token == "" {
|
if req.Token == "" {
|
||||||
return nil, "", &ServiceError{Message: "缺少注册令牌"}
|
return nil, "", &ServiceError{Message: "缺少令牌"}
|
||||||
}
|
}
|
||||||
|
|
||||||
regCode, err := s.ValidateRegCode(req.Token)
|
agentToken, err := s.ValidateToken(req.Token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "", err
|
return nil, "", err
|
||||||
}
|
}
|
||||||
@@ -193,7 +186,7 @@ func (s *AgentService) Register(req *models.AgentRegisterRequest, ip string) (*m
|
|||||||
return nil, "", err
|
return nil, "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
s.UseRegCode(regCode.ID)
|
s.UseToken(agentToken.ID)
|
||||||
logger.Infof("[Agent] Agent 注册成功: %s (%s)", req.Name, ip)
|
logger.Infof("[Agent] Agent 注册成功: %s (%s)", req.Name, ip)
|
||||||
return agent, req.Token, nil
|
return agent, req.Token, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -217,10 +217,10 @@ export const api = {
|
|||||||
forceUpdate: (id: number) => request('/agents/' + id + '/update', { method: 'POST' }),
|
forceUpdate: (id: number) => request('/agents/' + id + '/update', { method: 'POST' }),
|
||||||
downloadUrl: (os: string, arch: string) => `${BASE_URL}/agent/download?os=${os}&arch=${arch}`,
|
downloadUrl: (os: string, arch: string) => `${BASE_URL}/agent/download?os=${os}&arch=${arch}`,
|
||||||
// 令牌管理
|
// 令牌管理
|
||||||
listRegCodes: () => request<AgentRegCode[]>('/agents/regcodes'),
|
listTokens: () => request<AgentToken[]>('/agents/tokens'),
|
||||||
createRegCode: (data: { remark?: string; max_uses?: number; expires_at?: string }) =>
|
createToken: (data: { remark?: string; max_uses?: number; expires_at?: string }) =>
|
||||||
request<AgentRegCode>('/agents/regcodes', { method: 'POST', body: JSON.stringify(data) }),
|
request<AgentToken>('/agents/tokens', { method: 'POST', body: JSON.stringify(data) }),
|
||||||
deleteRegCode: (id: number) => request('/agents/regcodes/' + id, { method: 'DELETE' })
|
deleteToken: (id: number) => request('/agents/tokens/' + id, { method: 'DELETE' })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -411,9 +411,9 @@ export interface Agent {
|
|||||||
updated_at: string
|
updated_at: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AgentRegCode {
|
export interface AgentToken {
|
||||||
id: number
|
id: number
|
||||||
code: string
|
token: string
|
||||||
remark: string
|
remark: string
|
||||||
max_uses: number
|
max_uses: number
|
||||||
used_count: number
|
used_count: number
|
||||||
|
|||||||
@@ -7,14 +7,14 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogD
|
|||||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'
|
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||||
import { RefreshCw, Trash2, Edit, Copy, Server, Search, Download, RotateCw, Plus, Ticket, Power, PowerOff, ListTodo, Eye } from 'lucide-vue-next'
|
import { RefreshCw, Trash2, Edit, Copy, Server, Search, Download, RotateCw, Plus, Ticket, Power, PowerOff, ListTodo, Eye } from 'lucide-vue-next'
|
||||||
import { api, type Agent, type AgentRegCode } from '@/api'
|
import { api, type Agent, type AgentToken } from '@/api'
|
||||||
import { toast } from 'vue-sonner'
|
import { toast } from 'vue-sonner'
|
||||||
import { useRouter } from 'vue-router'
|
import { useRouter } from 'vue-router'
|
||||||
|
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
|
||||||
const agents = ref<Agent[]>([])
|
const agents = ref<Agent[]>([])
|
||||||
const regCodes = ref<AgentRegCode[]>([])
|
const tokens = ref<AgentToken[]>([])
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const searchQuery = ref('')
|
const searchQuery = ref('')
|
||||||
const activeTab = ref('agents')
|
const activeTab = ref('agents')
|
||||||
@@ -23,10 +23,10 @@ const platforms = ref<{ os: string; arch: string; filename: string }[]>([])
|
|||||||
const showEditDialog = ref(false)
|
const showEditDialog = ref(false)
|
||||||
const showDeleteDialog = ref(false)
|
const showDeleteDialog = ref(false)
|
||||||
const showDownloadDialog = ref(false)
|
const showDownloadDialog = ref(false)
|
||||||
const showRegCodeDialog = ref(false)
|
const showTokenDialog = ref(false)
|
||||||
const showDetailDialog = ref(false)
|
const showDetailDialog = ref(false)
|
||||||
const formData = ref({ name: '', description: '' })
|
const formData = ref({ name: '', description: '' })
|
||||||
const regCodeForm = ref({ remark: '', max_uses: 0, expires_at: '' })
|
const tokenForm = ref({ remark: '', max_uses: 0, expires_at: '' })
|
||||||
const editingAgent = ref<Agent | null>(null)
|
const editingAgent = ref<Agent | null>(null)
|
||||||
const deletingAgent = ref<Agent | null>(null)
|
const deletingAgent = ref<Agent | null>(null)
|
||||||
const viewingAgent = ref<Agent | null>(null)
|
const viewingAgent = ref<Agent | null>(null)
|
||||||
@@ -53,15 +53,15 @@ function isOnline(agent: Agent): boolean {
|
|||||||
async function loadAgents() {
|
async function loadAgents() {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
try {
|
try {
|
||||||
const [agentList, versionInfo, codeList] = await Promise.all([
|
const [agentList, versionInfo, tokenList] = await Promise.all([
|
||||||
api.agents.list(),
|
api.agents.list(),
|
||||||
api.agents.getVersion(),
|
api.agents.getVersion(),
|
||||||
api.agents.listRegCodes()
|
api.agents.listTokens()
|
||||||
])
|
])
|
||||||
agents.value = agentList
|
agents.value = agentList
|
||||||
agentVersion.value = versionInfo.version || ''
|
agentVersion.value = versionInfo.version || ''
|
||||||
platforms.value = versionInfo.platforms || []
|
platforms.value = versionInfo.platforms || []
|
||||||
regCodes.value = codeList
|
tokens.value = tokenList
|
||||||
} catch {
|
} catch {
|
||||||
toast.error('加载失败')
|
toast.error('加载失败')
|
||||||
} finally {
|
} finally {
|
||||||
@@ -133,20 +133,20 @@ function viewTasks(agent: Agent) {
|
|||||||
router.push({ path: '/tasks', query: { agent_id: String(agent.id) } })
|
router.push({ path: '/tasks', query: { agent_id: String(agent.id) } })
|
||||||
}
|
}
|
||||||
|
|
||||||
function copyRegCode(code: string) {
|
function copyToken(token: string) {
|
||||||
navigator.clipboard.writeText(code)
|
navigator.clipboard.writeText(token)
|
||||||
toast.success('已复制')
|
toast.success('已复制')
|
||||||
}
|
}
|
||||||
|
|
||||||
async function createRegCode() {
|
async function createToken() {
|
||||||
try {
|
try {
|
||||||
await api.agents.createRegCode({
|
await api.agents.createToken({
|
||||||
remark: regCodeForm.value.remark,
|
remark: tokenForm.value.remark,
|
||||||
max_uses: regCodeForm.value.max_uses,
|
max_uses: tokenForm.value.max_uses,
|
||||||
expires_at: regCodeForm.value.expires_at || undefined
|
expires_at: tokenForm.value.expires_at || undefined
|
||||||
})
|
})
|
||||||
showRegCodeDialog.value = false
|
showTokenDialog.value = false
|
||||||
regCodeForm.value = { remark: '', max_uses: 0, expires_at: '' }
|
tokenForm.value = { remark: '', max_uses: 0, expires_at: '' }
|
||||||
await loadAgents()
|
await loadAgents()
|
||||||
toast.success('创建成功')
|
toast.success('创建成功')
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
@@ -154,9 +154,9 @@ async function createRegCode() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function deleteRegCode(id: number) {
|
async function deleteToken(id: number) {
|
||||||
try {
|
try {
|
||||||
await api.agents.deleteRegCode(id)
|
await api.agents.deleteToken(id)
|
||||||
await loadAgents()
|
await loadAgents()
|
||||||
toast.success('删除成功')
|
toast.success('删除成功')
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
@@ -164,13 +164,13 @@ async function deleteRegCode(id: number) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function isRegCodeExpired(code: AgentRegCode) {
|
function isTokenExpired(token: AgentToken) {
|
||||||
if (!code.expires_at) return false
|
if (!token.expires_at) return false
|
||||||
return new Date(code.expires_at) < new Date()
|
return new Date(token.expires_at) < new Date()
|
||||||
}
|
}
|
||||||
|
|
||||||
function isRegCodeExhausted(code: AgentRegCode) {
|
function isTokenExhausted(token: AgentToken) {
|
||||||
return code.max_uses > 0 && code.used_count >= code.max_uses
|
return token.max_uses > 0 && token.used_count >= token.max_uses
|
||||||
}
|
}
|
||||||
|
|
||||||
function downloadAgent(os: string, arch: string) {
|
function downloadAgent(os: string, arch: string) {
|
||||||
@@ -290,35 +290,35 @@ onUnmounted(() => {
|
|||||||
<span class="w-16 sm:w-20 shrink-0 text-center">使用次数</span>
|
<span class="w-16 sm:w-20 shrink-0 text-center">使用次数</span>
|
||||||
<span class="w-28 sm:w-36 shrink-0 hidden sm:block">过期时间</span>
|
<span class="w-28 sm:w-36 shrink-0 hidden sm:block">过期时间</span>
|
||||||
<span class="w-20 shrink-0 flex justify-center">
|
<span class="w-20 shrink-0 flex justify-center">
|
||||||
<Button size="sm" class="h-7" @click="showRegCodeDialog = true">
|
<Button size="sm" class="h-7" @click="showTokenDialog = true">
|
||||||
<Plus class="h-3.5 w-3.5 mr-1" />生成
|
<Plus class="h-3.5 w-3.5 mr-1" />生成
|
||||||
</Button>
|
</Button>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="divide-y min-w-[500px]">
|
<div class="divide-y min-w-[500px]">
|
||||||
<div v-if="regCodes.length === 0" class="text-center py-8 text-muted-foreground">
|
<div v-if="tokens.length === 0" class="text-center py-8 text-muted-foreground">
|
||||||
<Ticket class="h-8 w-8 mx-auto mb-2 opacity-50" />暂无令牌
|
<Ticket class="h-8 w-8 mx-auto mb-2 opacity-50" />暂无令牌
|
||||||
</div>
|
</div>
|
||||||
<div v-for="code in regCodes" :key="code.id" class="flex items-center gap-2 sm:gap-4 px-3 sm:px-4 py-2 hover:bg-muted/50 transition-colors">
|
<div v-for="token in tokens" :key="token.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-6 shrink-0 flex justify-center">
|
<span class="w-6 shrink-0 flex justify-center">
|
||||||
<span class="relative flex h-2.5 w-2.5">
|
<span class="relative flex h-2.5 w-2.5">
|
||||||
<span v-if="!isRegCodeExpired(code) && !isRegCodeExhausted(code)" class="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
|
<span v-if="!isTokenExpired(token) && !isTokenExhausted(token)" class="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
|
||||||
<span :class="!isRegCodeExpired(code) && !isRegCodeExhausted(code) ? 'bg-green-500' : 'bg-gray-400'" class="relative inline-flex rounded-full h-2.5 w-2.5"></span>
|
<span :class="!isTokenExpired(token) && !isTokenExhausted(token) ? 'bg-green-500' : 'bg-gray-400'" class="relative inline-flex rounded-full h-2.5 w-2.5"></span>
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
<code class="flex-1 min-w-[200px] font-mono text-xs bg-muted px-2 py-0.5 rounded truncate">{{ code.code }}</code>
|
<code class="flex-1 min-w-[200px] font-mono text-xs bg-muted px-2 py-0.5 rounded truncate">{{ token.token }}</code>
|
||||||
<span class="w-24 sm:w-32 shrink-0 text-xs sm:text-sm text-muted-foreground truncate">{{ code.remark || '-' }}</span>
|
<span class="w-24 sm:w-32 shrink-0 text-xs sm:text-sm text-muted-foreground truncate">{{ token.remark || '-' }}</span>
|
||||||
<span class="w-16 sm:w-20 shrink-0 text-xs sm:text-sm text-muted-foreground text-center">
|
<span class="w-16 sm:w-20 shrink-0 text-xs sm:text-sm text-muted-foreground text-center">
|
||||||
{{ code.used_count }}/{{ code.max_uses === 0 ? '∞' : code.max_uses }}
|
{{ token.used_count }}/{{ token.max_uses === 0 ? '∞' : token.max_uses }}
|
||||||
</span>
|
</span>
|
||||||
<span class="w-28 sm:w-36 shrink-0 text-xs sm:text-sm text-muted-foreground hidden sm:block truncate">
|
<span class="w-28 sm:w-36 shrink-0 text-xs sm:text-sm text-muted-foreground hidden sm:block truncate">
|
||||||
{{ code.expires_at || '永不过期' }}
|
{{ token.expires_at || '永不过期' }}
|
||||||
</span>
|
</span>
|
||||||
<span class="w-20 shrink-0 flex justify-center gap-1">
|
<span class="w-20 shrink-0 flex justify-center gap-1">
|
||||||
<Button variant="ghost" size="icon" class="h-7 w-7" @click="copyRegCode(code.code)" title="复制">
|
<Button variant="ghost" size="icon" class="h-7 w-7" @click="copyToken(token.token)" title="复制">
|
||||||
<Copy class="h-3.5 w-3.5" />
|
<Copy class="h-3.5 w-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="ghost" size="icon" class="h-7 w-7 text-destructive" @click="deleteRegCode(code.id)" title="删除">
|
<Button variant="ghost" size="icon" class="h-7 w-7 text-destructive" @click="deleteToken(token.id)" title="删除">
|
||||||
<Trash2 class="h-3.5 w-3.5" />
|
<Trash2 class="h-3.5 w-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
</span>
|
</span>
|
||||||
@@ -478,28 +478,28 @@ onUnmounted(() => {
|
|||||||
</Dialog>
|
</Dialog>
|
||||||
|
|
||||||
<!-- 创建令牌对话框 -->
|
<!-- 创建令牌对话框 -->
|
||||||
<Dialog v-model:open="showRegCodeDialog">
|
<Dialog v-model:open="showTokenDialog">
|
||||||
<DialogContent>
|
<DialogContent>
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>生成注册令牌</DialogTitle>
|
<DialogTitle>生成令牌</DialogTitle>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<div class="space-y-4">
|
<div class="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
<Label>备注</Label>
|
<Label>备注</Label>
|
||||||
<Input v-model="regCodeForm.remark" placeholder="备注信息(可选)" />
|
<Input v-model="tokenForm.remark" placeholder="备注信息(可选)" />
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<Label>最大使用次数</Label>
|
<Label>最大使用次数</Label>
|
||||||
<Input v-model.number="regCodeForm.max_uses" type="number" placeholder="0 表示无限制" />
|
<Input v-model.number="tokenForm.max_uses" type="number" placeholder="0 表示无限制" />
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<Label>过期时间</Label>
|
<Label>过期时间</Label>
|
||||||
<Input v-model="regCodeForm.expires_at" type="datetime-local" />
|
<Input v-model="tokenForm.expires_at" type="datetime-local" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button variant="outline" @click="showRegCodeDialog = false">取消</Button>
|
<Button variant="outline" @click="showTokenDialog = false">取消</Button>
|
||||||
<Button @click="createRegCode">生成</Button>
|
<Button @click="createToken">生成</Button>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|||||||
Reference in New Issue
Block a user