Files
cmii-uav-watchdog-project/cmii-uav-watchdog/services/heartbeat_service.go

70 lines
1.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
}