forked from gopasspw/gopass
-
Notifications
You must be signed in to change notification settings - Fork 0
/
totp.go
75 lines (62 loc) · 1.55 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
75
package action
import (
"errors"
"fmt"
"strings"
"time"
"github.com/fatih/color"
"github.com/pquerna/otp"
"github.com/pquerna/otp/totp"
"github.com/urfave/cli"
)
const (
totpPeriod = 30 // seconds
)
// TOTP implements time-based OTP token handling
func (s *Action) TOTP(c *cli.Context) error {
name := c.Args().First()
if name == "" {
return errors.New("provide a password name")
}
content, err := s.Store.Get(name)
if err != nil {
return err
}
key, err := otp.NewKeyFromURL(string(content))
if err != nil {
return err
}
now := time.Now()
code, err := printCode(key.Secret(), now)
if err != nil {
return err
}
_, err = printCode(key.Secret(), now.Add(totpPeriod*time.Second))
if err != nil {
return err
}
if c.Bool("clip") {
return s.copyToClipboard(fmt.Sprintf("time based token for %s", name), []byte(code))
}
return nil
}
func printCode(secret string, t time.Time) (string, error) {
secret = strings.TrimSpace(secret)
secret = strings.ToUpper(secret)
code, err := totp.GenerateCodeCustom(secret, t, totp.ValidateOpts{
Period: totpPeriod,
Digits: otp.DigitsSix,
Algorithm: otp.AlgorithmSHA1,
})
if err != nil {
return "", err
}
expiresAt := time.Unix(t.Unix()+totpPeriod-(t.Unix()%totpPeriod), 0)
secondsLeft := int(time.Until(expiresAt).Seconds())
if secondsLeft <= totpPeriod {
color.Yellow("%s lasts %ds \t|%s%s|", code, secondsLeft, strings.Repeat("=", totpPeriod-secondsLeft), strings.Repeat("-", secondsLeft))
} else {
color.Yellow("%s expires in %ds", code, secondsLeft)
}
return code, nil
}