87 lines
1.9 KiB
Go
87 lines
1.9 KiB
Go
package services
|
|
|
|
import (
|
|
"cmii-uav-watchdog/config"
|
|
"log"
|
|
"time"
|
|
|
|
otp "cmii-uav-watchdog-otp"
|
|
"cmii-uav-watchdog-otp/totp"
|
|
)
|
|
|
|
var tierTwoTOTPSecretOpts = totp.GenerateOpts{
|
|
SecretSize: 32,
|
|
Issuer: "cmii-uav-watchdog",
|
|
AccountName: "cmii-uav-watchdog",
|
|
Period: 30,
|
|
Secret: []byte{},
|
|
Digits: otp.DigitsSix,
|
|
Algorithm: otp.AlgorithmSHA1,
|
|
Rand: nil,
|
|
}
|
|
|
|
// TOTPService TOTP服务
|
|
type TOTPService struct {
|
|
secret string
|
|
}
|
|
|
|
// NewTOTPService 创建TOTP服务
|
|
func NewTOTPService() *TOTPService {
|
|
return &TOTPService{
|
|
secret: config.GetConfig().Auth.Secret,
|
|
}
|
|
}
|
|
|
|
// GenerateTierOneTOTP 生成一级TOTP验证码
|
|
func (ts *TOTPService) GenerateTierOneTOTP() (string, error) {
|
|
// 使用当前时间生成TOTP
|
|
code, err := totp.GenerateCode(ts.secret, time.Now())
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return code, nil
|
|
}
|
|
|
|
// VerifyTierOneTOTP 验证一级TOTP验证码
|
|
func (ts *TOTPService) VerifyTierOneTOTP(code string) bool {
|
|
// 验证TOTP
|
|
valid := totp.Validate(code, ts.secret)
|
|
if !valid {
|
|
return false
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
// GenerateTierTwoTOTPSecret 生成二级TOTP密钥
|
|
func (ts *TOTPService) GenerateTierTwoTOTPSecret() (string, error) {
|
|
secret, err := totp.Generate(tierTwoTOTPSecretOpts)
|
|
if err != nil {
|
|
log.Printf("生成TOTP密钥失败: %v", err)
|
|
return "", err
|
|
}
|
|
|
|
return secret.Secret(), nil
|
|
}
|
|
|
|
// GenerateTierTwoTOTPCode 生成二级TOTP验证码
|
|
func (ts *TOTPService) GenerateTierTwoTOTPCode(secret string) (string, error) {
|
|
code, err := totp.GenerateCode(secret, time.Now())
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return code, nil
|
|
}
|
|
|
|
// VerifyTierTwoTOTPCode 验证二级TOTP验证码
|
|
func (ts *TOTPService) VerifyTierTwoTOTPCode(code string, secret string) bool {
|
|
validateOpts := totp.ValidateOpts{}
|
|
validateOpts.ConvertToValidateOpts(tierTwoTOTPSecretOpts)
|
|
valid, err := totp.ValidateCustom(code, secret, time.Now(), validateOpts)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return valid
|
|
}
|