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

66 lines
1.3 KiB
Go

package services
import (
"cmii-uav-watchdog/config"
"errors"
"log"
"time"
otp "cmii-uav-watchdog-otp"
"cmii-uav-watchdog-otp/totp"
)
// TOTPService TOTP服务
type TOTPService struct {
secret string
}
// NewTOTPService 创建TOTP服务
func NewTOTPService() *TOTPService {
return &TOTPService{
secret: config.GetConfig().Auth.Secret,
}
}
// GenerateTOTP 生成TOTP验证码
func (ts *TOTPService) GenerateTOTP() (string, error) {
// 使用当前时间生成TOTP
code, err := totp.GenerateCode(ts.secret, time.Now())
if err != nil {
return "", err
}
return code, nil
}
// VerifyTOTP 验证TOTP验证码
func (ts *TOTPService) VerifyTOTP(code string) error {
// 验证TOTP
valid := totp.Validate(code, ts.secret)
if !valid {
return errors.New("无效的TOTP验证码")
}
return nil
}
// GenerateTOTPSecret 生成TOTP密钥
func (ts *TOTPService) GenerateTOTPSecret() (string, error) {
secret, err := totp.Generate(totp.GenerateOpts{
SecretSize: 32,
Issuer: "cmii-uav-watchdog",
AccountName: "cmii-uav-watchdog",
Period: 30,
Secret: []byte{},
Digits: otp.DigitsSix,
Algorithm: otp.AlgorithmSHA1,
Rand: nil,
})
if err != nil {
log.Printf("生成TOTP密钥失败: %v", err)
return "", err
}
return secret.Secret(), nil
}