-
Notifications
You must be signed in to change notification settings - Fork 2k
/
mfa.go
46 lines (40 loc) · 1.13 KB
/
mfa.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package mfa
import (
"bytes"
"encoding/base64"
"strconv"
"time"
"github.com/1Panel-dev/1Panel/backend/global"
"github.com/skip2/go-qrcode"
"github.com/xlzd/gotp"
)
const secretLength = 16
type Otp struct {
Secret string `json:"secret"`
QrImage string `json:"qrImage"`
}
func GetOtp(username, title string, interval int) (otp Otp, err error) {
secret := gotp.RandomSecret(secretLength)
otp.Secret = secret
totp := gotp.NewTOTP(secret, 6, interval, nil)
uri := totp.ProvisioningUri(username, title)
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
}
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)
now := time.Now().Unix()
strInt64 := strconv.FormatInt(now, 10)
id16, _ := strconv.Atoi(strInt64)
return totp.Verify(code, int64(id16))
}