forked from xlzd/gotp
/
generate.go
218 lines (185 loc) · 4.62 KB
/
generate.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package otp
import (
"fmt"
"os"
"time"
"github.com/atotto/clipboard"
"github.com/charmbracelet/bubbles/table"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/ganboonhong/gotp/pkg/config"
"github.com/ganboonhong/gotp/pkg/crypto"
errMsg "github.com/ganboonhong/gotp/pkg/error"
"github.com/ganboonhong/gotp/pkg/orm"
"github.com/ganboonhong/gotp/pkg/otp"
"github.com/ganboonhong/gotp/pkg/parameter"
"github.com/ganboonhong/gotp/pkg/user"
"github.com/spf13/cobra"
)
type TickMsg time.Time
type model struct {
table table.Model
parameters []parameter.Parameter
lastCursor int
remainingSec int
}
var helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#626262")).Render
// NewGenerateCmd returns command to generate OTP
func NewGenerateCmd(c *config.Config) *cobra.Command {
var cmd = &cobra.Command{
Use: "gen",
Short: "Generate an OPT",
RunE: func(cmd *cobra.Command, args []string) error {
generate(c)
return nil
},
}
return cmd
}
func generate(c *config.Config) {
if c.UserID == 0 {
fmt.Fprintf(os.Stderr, errMsg.NoAccount())
os.Exit(1)
}
newModel(otpParameters(c))
}
func newModel(parameters []parameter.Parameter) {
t := newTable(parameters)
m := model{
table: t,
parameters: parameters,
lastCursor: -1,
remainingSec: -1,
}
if err := tea.NewProgram(m).Start(); err != nil {
fmt.Println("Error running program:", err)
os.Exit(1)
}
}
func otpParameters(c *config.Config) []parameter.Parameter {
var parameters []parameter.Parameter
orm := orm.New(c)
u := &user.User{}
orm.Find(c.UserID, u)
orm.DB.Model(&u).Association("Parameters").Find(¶meters)
if len(parameters) == 0 {
fmt.Fprintf(os.Stderr, errMsg.NoParameter())
os.Exit(1)
}
return parameters
}
func newTable(parameters []parameter.Parameter) table.Model {
columns := tableColumns()
rows := tableRows(parameters)
height := tableHeight(len(parameters))
style := tableStyle()
t := table.New(
table.WithColumns(columns),
table.WithRows(rows),
table.WithFocused(true),
table.WithHeight(height),
table.WithStyles(style),
)
return t
}
func tableColumns() []table.Column {
return []table.Column{
{Title: "Issuer", Width: 20},
{Title: "Account", Width: 25},
{Title: "OTP", Width: 15},
{Title: "Expires in", Width: 10},
}
}
func tableRows(parameters []parameter.Parameter) []table.Row {
var rows []table.Row
for _, p := range parameters {
rows = append(rows, table.Row{p.Issuer, p.Account, "******", "-"})
}
return rows
}
func tableHeight(rowCount int) int {
if rowCount > 10 {
return 10
}
return rowCount
}
func tableStyle() table.Styles {
s := table.DefaultStyles()
s.Header = s.Header.
BorderStyle(lipgloss.NormalBorder()).
BorderForeground(lipgloss.Color("240")).
BorderBottom(true).
Bold(false)
s.Selected = s.Selected.
Foreground(lipgloss.Color("229")).
Background(lipgloss.Color("57")).
Bold(false)
return s
}
func (m model) Init() tea.Cmd { return tickEvery(m) }
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
switch msg := msg.(type) {
case TickMsg:
m.remainingSec--
m = m.reloadTable()
return m, tickEvery(m)
case tea.KeyMsg:
switch msg.String() {
case "esc":
if m.table.Focused() {
m.table.Blur()
} else {
m.table.Focus()
}
case "q", "ctrl+c":
return m, tea.Quit
case "enter":
// 29: there about 1 second difference after user hitting enter
m.remainingSec = int(29 - (time.Now().Unix() % parameter.DefaultInterval))
m.lastCursor = m.table.Cursor()
m = m.reloadTable()
return m, nil
}
}
m.table, cmd = m.table.Update(msg)
return m, cmd
}
func (m model) View() string {
baseStyle := lipgloss.NewStyle().
BorderStyle(lipgloss.NormalBorder()).
BorderForeground(lipgloss.Color("240"))
return baseStyle.Render(m.table.View()) + "\n" +
helpStyle("Press 'q' to quit")
}
func (m model) reloadTable() model {
if m.remainingSec < 0 {
return m
}
var rows []table.Row
for i, p := range m.parameters {
OTP := "******"
expiresIn := "-"
if i == m.lastCursor {
code := m.calculateOTP()
OTP = fmt.Sprintf("%s (copied)", code)
expiresIn = fmt.Sprintf("%ds", m.remainingSec)
}
rows = append(rows, table.Row{p.Issuer, p.Account, OTP, expiresIn})
}
m.table.SetRows(rows)
return m
}
func (m model) calculateOTP() string {
encrytpedSecret := m.parameters[m.lastCursor].Secret
secret := crypto.Decrypt(encrytpedSecret, config.Key)
otp := otp.NewDefaultTOTP(secret)
code := otp.Now()
clipboard.WriteAll(code)
return code
}
func tickEvery(m model) tea.Cmd {
return tea.Every(time.Second, func(t time.Time) tea.Msg {
return TickMsg(t)
})
}