更新项目配置,修改 Go 版本至 1.24,添加依赖项,重构主程序以加载配置和初始化服务,删除不再使用的远程目标配置文件。
This commit is contained in:
69
cmii-uav-watchdog/services/heartbeat_service.go
Normal file
69
cmii-uav-watchdog/services/heartbeat_service.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"cmii-uav-watchdog-common/models"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// HeartbeatService 心跳服务
|
||||
type HeartbeatService struct {
|
||||
authService *AuthService
|
||||
totpService *TOTPService
|
||||
}
|
||||
|
||||
// NewHeartbeatService 创建心跳服务
|
||||
func NewHeartbeatService() *HeartbeatService {
|
||||
return &HeartbeatService{
|
||||
authService: NewAuthService(),
|
||||
totpService: NewTOTPService(),
|
||||
}
|
||||
}
|
||||
|
||||
// ProcessHeartbeat 处理心跳请求
|
||||
func (hs *HeartbeatService) ProcessHeartbeat(req models.HeartbeatRequest) (*models.HeartbeatResponse, error) {
|
||||
// 检查时间戳是否有效
|
||||
if !hs.isTimestampValid(req.Timestamp) {
|
||||
return nil, errors.New("无效的时间戳")
|
||||
}
|
||||
|
||||
// 添加主机信息到集合
|
||||
hs.authService.AddHostInfo(req.HostInfo)
|
||||
|
||||
// 检查是否携带totp,如果为空立即返回
|
||||
if req.TOTPCode == "" {
|
||||
return &models.HeartbeatResponse{
|
||||
Authorized: false,
|
||||
TOTPCode: "",
|
||||
Timestamp: time.Now().Unix(),
|
||||
SecondTOTPSecret: "",
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 检查totp密码是都有效
|
||||
|
||||
// 检查主机是否已授权
|
||||
authorized := hs.authService.IsHostAuthorized(req.HostInfo)
|
||||
|
||||
// 生成TOTP验证码
|
||||
totpCode, err := hs.totpService.GenerateTOTP()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 返回心跳响应
|
||||
return &models.HeartbeatResponse{
|
||||
Authorized: authorized,
|
||||
TOTPCode: totpCode,
|
||||
Timestamp: time.Now().Unix(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// isTimestampValid 检查时间戳是否有效
|
||||
func (hs *HeartbeatService) isTimestampValid(timestamp int64) bool {
|
||||
now := time.Now().Unix()
|
||||
diff := now - timestamp
|
||||
|
||||
// 允许5分钟的时间偏差
|
||||
return diff < 300 && diff > -300
|
||||
}
|
||||
Reference in New Issue
Block a user