-
Notifications
You must be signed in to change notification settings - Fork 0
/
totp.go
74 lines (62 loc) · 1.37 KB
/
totp.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package otp
import (
"fmt"
"time"
"github.com/pquerna/otp"
"github.com/pquerna/otp/totp"
)
type TOTP interface {
Generate(ttime time.Time, digits Digits, seconds ...uint) (string, error)
Validate(code string, digits Digits, seconds ...uint) (bool, error)
ToURL() string
QRCode() QRCode
}
type pTOTP struct {
opts *Options
}
func (t *pTOTP) Generate(ttime time.Time, digits Digits, seconds ...uint) (string, error) {
if len(seconds) == 0 {
seconds = append(seconds, 30)
}
return totp.GenerateCodeCustom(t.opts.Secret, ttime, totp.ValidateOpts{
Period: seconds[0],
Skew: 1,
Digits: otp.Digits(digits),
Algorithm: otp.AlgorithmSHA1,
})
}
func (t *pTOTP) Validate(code string, digits Digits, seconds ...uint) (bool, error) {
if len(seconds) == 0 {
seconds = append(seconds, 30)
}
return totp.ValidateCustom(
code,
t.opts.Secret,
time.Now().UTC(),
totp.ValidateOpts{
Period: seconds[0],
Skew: 1,
Digits: otp.Digits(digits),
Algorithm: otp.AlgorithmSHA1,
},
)
}
func (t *pTOTP) ToURL() string {
return fmt.Sprintf(
"otpauth://%s/%s:%s?secret=%s&issuer=%s",
"totp",
t.opts.Issuer,
t.opts.Account,
t.opts.Secret,
t.opts.Issuer,
)
}
func (t *pTOTP) QRCode() QRCode {
return NewQR(t.ToURL())
}
/*********************************************/
func NewTOTP(opts Options) TOTP {
return &pTOTP{
opts: &opts,
}
}