/
selfGenerateTOTPCodes.go
90 lines (70 loc) · 2.39 KB
/
selfGenerateTOTPCodes.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package cmd
import (
"fmt"
"os/exec"
"strings"
"github.com/inpher/sb/internal/commands"
"github.com/inpher/sb/internal/helpers"
"github.com/inpher/sb/internal/models"
)
// SelfGenerateTOTPCodes describes the SelfGenerateTOTPCodes command
type SelfGenerateTOTPCodes struct{}
func init() {
commands.RegisterCommand("self totp emergency-codes generate", func() (c commands.Command, r models.Right, helper helpers.Helper, args map[string]commands.Argument) {
return new(SelfGenerateTOTPCodes), models.Public, helpers.Helper{
Header: "generate TOTP emergency codes",
Usage: "self totp emergency-codes generate",
Description: "generate TOTP emergency codes",
Aliases: []string{"selfGenerateTOTPCodes"},
}, map[string]commands.Argument{}
})
}
// Checks checks whether or not the user can execute this method
func (c *SelfGenerateTOTPCodes) Checks(ct *commands.Context) error {
// We're building on top of pam_google_authenticator, let's check the server is setup correctly
_, err := exec.LookPath("google-authenticator")
if err != nil {
return fmt.Errorf("the server is not configured for TOTP")
}
// Check that TOTP is enabled for current account
enabled, _, _ := ct.User.GetTOTP()
if !enabled {
return fmt.Errorf("TOTP is disabled on this account")
}
return nil
}
// Execute executes the command
func (c *SelfGenerateTOTPCodes) Execute(ct *commands.Context) (repl models.ReplicationData, cmdError error, err error) {
_, currentSecret, _ := ct.User.GetTOTP()
random := helpers.GetRandomStrings(5, 8)
repl = models.ReplicationData{
"account": ct.User.User.Username,
"secret": currentSecret,
"random-codes": strings.Join(random, ";"),
}
err = c.Replicate(repl)
if err != nil {
return
}
fmt.Printf("Here are your %d emergency codes:\n", len(random))
for _, str := range random {
fmt.Printf("%s", str)
}
fmt.Printf("Be sure to store them in a secure place, they will never be displayed again\n")
return
}
func (c *SelfGenerateTOTPCodes) PostExecute(repl models.ReplicationData) (err error) {
return
}
func (c *SelfGenerateTOTPCodes) Replicate(repl models.ReplicationData) (err error) {
user, err := models.LoadUser(repl["account"])
if err != nil {
return
}
// Store the secrets (and thus, enable the TOTP on the account)
err = user.SetTOTPSecret(repl["secret"], strings.Split(repl["random-codes"], ";"))
if err != nil {
return
}
return
}