2022-09-14 23:27:17 +08:00
|
|
|
package mfa
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/base64"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
|
2023-06-25 17:52:13 +08:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/global"
|
2022-09-14 23:27:17 +08:00
|
|
|
"github.com/skip2/go-qrcode"
|
|
|
|
"github.com/xlzd/gotp"
|
|
|
|
)
|
|
|
|
|
|
|
|
const secretLength = 16
|
|
|
|
|
|
|
|
type Otp struct {
|
|
|
|
Secret string `json:"secret"`
|
|
|
|
QrImage string `json:"qrImage"`
|
|
|
|
}
|
|
|
|
|
2023-09-28 15:46:18 +08:00
|
|
|
func GetOtp(username, title string, interval int) (otp Otp, err error) {
|
2022-09-14 23:27:17 +08:00
|
|
|
secret := gotp.RandomSecret(secretLength)
|
|
|
|
otp.Secret = secret
|
2023-06-25 17:52:13 +08:00
|
|
|
totp := gotp.NewTOTP(secret, 6, interval, nil)
|
2023-09-28 15:46:18 +08:00
|
|
|
uri := totp.ProvisioningUri(username, title)
|
2022-09-14 23:27:17 +08:00
|
|
|
subImg, err := qrcode.Encode(uri, qrcode.Medium, 256)
|
|
|
|
dist := make([]byte, 3000)
|
|
|
|
base64.StdEncoding.Encode(dist, subImg)
|
|
|
|
index := bytes.IndexByte(dist, 0)
|
|
|
|
baseImage := dist[0:index]
|
|
|
|
otp.QrImage = "data:image/png;base64," + string(baseImage)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-06-25 17:52:13 +08:00
|
|
|
func ValidCode(code, intervalStr, secret string) bool {
|
|
|
|
interval, err := strconv.Atoi(intervalStr)
|
|
|
|
if err != nil {
|
|
|
|
global.LOG.Errorf("type conversion failed, err: %v", err)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
totp := gotp.NewTOTP(secret, 6, interval, nil)
|
2022-09-14 23:27:17 +08:00
|
|
|
now := time.Now().Unix()
|
|
|
|
strInt64 := strconv.FormatInt(now, 10)
|
|
|
|
id16, _ := strconv.Atoi(strInt64)
|
|
|
|
return totp.Verify(code, int64(id16))
|
|
|
|
}
|