-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_model.go
More file actions
124 lines (111 loc) · 2.49 KB
/
auth_model.go
File metadata and controls
124 lines (111 loc) · 2.49 KB
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
package main
import (
"fmt"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/huh"
)
type authState int
const (
authIdle authState = iota
authPrompt
)
type authModel struct {
form *huh.Form
state authState
width int
height int
}
type authenticated struct{}
type needSecretsMsg struct{}
func (m authModel) Init() tea.Cmd {
if cfg.AccessToken == "" {
return func() tea.Msg { return needSecretsMsg{} }
}
return func() tea.Msg { return authenticated{} }
}
func (m authModel) View() string {
if m.form != nil {
return m.form.View()
}
return "Input required"
}
func (m authModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
var cmds []tea.Cmd
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width, m.height = msg.Width, msg.Height
case tea.KeyMsg:
switch msg.String() {
case "ctrl+c":
return m, tea.Quit
}
if m.form != nil {
var f tea.Model
f, cmd = m.form.Update(msg)
if form, ok := f.(*huh.Form); ok {
m.form = form
}
cmds = append(cmds, cmd)
return m, tea.Batch(cmds...)
}
case needSecretsMsg:
m.state = authPrompt
m.form = huh.NewForm(
huh.NewGroup(
huh.NewInput().
Title("Github Personal Token").
Value(&cfg.AccessToken).
Key("access_token").
Validate(func(s string) error {
if s == "" {
return fmt.Errorf("client id required")
}
return nil
}),
),
)
if m.width > 0 && m.height > 0 {
var f tea.Model
f, _ = m.form.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
if form, ok := f.(*huh.Form); ok {
m.form = form
}
}
return m, m.form.Init()
case infoMsg:
if msg.variant == info_error {
log.Errorln(msg.msg)
}
return m, nil
default:
// only run this block of code when we're submitting the form
if m.state == authPrompt && m.form != nil {
var f tea.Model
f, cmd = m.form.Update(msg)
if form, ok := f.(*huh.Form); ok {
m.form = form
}
cmds = append(cmds, cmd)
if m.form.State == huh.StateCompleted {
access_token := m.form.GetString("access_token")
if err := cfg.set("AccessToken", access_token); err != nil {
panic(err)
}
client, err := createGhClient()
if err != nil {
panic(err)
}
githubClient = client
if err := preloadGists(); err != nil {
panic(err)
}
cmds = append(cmds, func() tea.Msg { return authenticated{} })
m.state = authIdle
return m, tea.Batch(cmds...)
}
}
}
cmds = append(cmds, cmd)
return m, tea.Batch(cmds...)
}