auth_test.go 1.2 KB
Newer Older
liming6's avatar
liming6 committed
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package auth

import (
	"encoding/base64"
	"testing"
	"time"

	"github.com/pquerna/otp"
	"github.com/pquerna/otp/totp"
)

func TestOTP(t *testing.T) {
	key, err := totp.Generate(totp.GenerateOpts{

		Issuer:      "System",
		AccountName: "Opsflow",
	})
	if err != nil {
		t.Error(err)
	}
	t.Log(key.Secret())
}

// OA5BDGLJ2DYGAWNCLJYSNZFAESPQ7BRL

func verify(sec, input string) bool {
	return totp.Validate(input, sec)
}

func TestAuth(t *testing.T) {
	sec := "OA5BDGLJ2DYGAWNCLJYSNZFAESPQ7BRL"
	out, err := totp.GenerateCode(sec, time.Now())
	if err != nil {
		t.Error(err)
	}
	t.Log(out)

	if verify(sec, out) {
		t.Log("auth ok")
	} else {
		t.Log("auth fail")
	}

	ok, err := totp.ValidateCustom(out, sec, time.Now(), totp.ValidateOpts{
		Period:    30, // 每 30 秒更新一次
		Skew:      1,  // 允许前后偏移 1 个周期(即允许 30 秒的时间误差)
		Digits:    otp.DigitsSix,
		Algorithm: otp.AlgorithmSHA1,
	})
	if err != nil {
		t.Error(err)
	}
	t.Logf("auth result: %v\n", ok)
}

func TestGetCode(t *testing.T) {
	sec := "OA5BDGLJ2DYGAWNCLJYSNZFAESPQ7BRL"
	out, err := totp.GenerateCode(sec, time.Now())
	if err != nil {
		t.Error(err)
	}
	t.Log(base64.StdEncoding.EncodeToString([]byte(out)))
}