This repository has been archived by the owner on Aug 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
device.go
301 lines (246 loc) · 6.66 KB
/
device.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package service
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/alexzorin/authy"
homedir "github.com/mitchellh/go-homedir"
)
const (
configFileName = ".authy.json"
cacheFileName = ".authycache.json"
)
// DeviceRegistration device register info
type DeviceRegistration struct {
UserID uint64 `json:"user_id,omitempty"`
DeviceID uint64 `json:"device_id,omitempty"`
Seed string `json:"seed,omitempty"`
APIKey string `json:"api_key,omitempty"`
MainPassword string `json:"main_password,omitempty"`
}
// NewDeviceConfig new device config
type NewDeviceConfig struct {
CountryCode string
Mobile string
Password string
ConfigFilePath string
ConfigFileName string
CacheFileName string
}
// Device ..
type Device struct {
conf NewDeviceConfig
registration DeviceRegistration
tokenMap map[string]*Token
tokens []*Token
}
// NewDevice ..
func NewDevice(conf NewDeviceConfig) *Device {
if len(conf.ConfigFileName) == 0 {
conf.ConfigFileName = configFileName
}
if len(conf.CacheFileName) == 0 {
conf.CacheFileName = cacheFileName
}
d := &Device{
conf: conf,
}
d.RegisterOrGetDeviceInfo()
return d
}
// RegisterOrGetDeviceInfo get device info from local cache, if not exist register a new device
func (d *Device) RegisterOrGetDeviceInfo() (devInfo DeviceRegistration) {
devInfo, err := d.LoadExistingDeviceInfo()
if err == nil && devInfo.UserID != 0 {
d.registration = devInfo
return
}
err = os.ErrNotExist
if os.IsNotExist(err) {
devInfo, err = d.newRegistrationDevice()
if err != nil {
os.Exit(1)
}
log.Println("Register device successfully!!!")
log.Printf("Your device id: %v\n", devInfo.DeviceID)
os.Exit(0)
}
if err != nil {
log.Println("Load/Register device info failed", err)
}
return
}
func getCountryCodeAndMobile(countrycode, mobile string) (int, string, error) {
var (
sc = bufio.NewScanner(os.Stdin)
codeInt int
)
if len(countrycode) == 0 {
fmt.Print("\nWhat is your phone number's country code? (digits only, e.g. 86): ")
if !sc.Scan() {
err := errors.New("Please provide a phone country code, e.g. 86")
log.Println(err)
return 0, "", err
}
countrycode = sc.Text()
}
codeInt, err := strconv.Atoi(strings.TrimSpace(countrycode))
if err != nil {
log.Println("Invalid country code. Parse country code failed", err)
return 0, "", err
}
if len(mobile) == 0 {
fmt.Print("\nWhat is your phone number? (digits only): ")
if !sc.Scan() {
err = errors.New("Please provide a phone number, e.g. 1232211")
log.Println(err)
return 0, "", err
}
mobile = sc.Text()
}
mobile = strings.TrimSpace(mobile)
return codeInt, mobile, nil
}
func registerDevice(client authy.Client, userStatus authy.UserStatus) (resp authy.CompleteDeviceRegistrationResponse, err error) {
// Begin a device registration using Authy app push notification
regStart, err := client.RequestDeviceRegistration(nil, userStatus.AuthyID, authy.ViaMethodPush)
if err != nil {
log.Println("Start register device failed", err)
return
}
if !regStart.Success {
err = fmt.Errorf("Authy did not accept the device registration request: %+v", regStart)
log.Println(err)
return
}
var regPIN string
timeout := time.Now().Add(5 * time.Minute)
for {
if timeout.Before(time.Now()) {
err = errors.New("Gave up waiting for user to respond to Authy device registration request")
log.Println(err)
return
}
log.Printf("Checking device registration status (%s until we give up)", time.Until(timeout).Truncate(time.Second))
regStatus, err1 := client.CheckDeviceRegistration(nil, userStatus.AuthyID, regStart.RequestID)
if err1 != nil {
err = err1
log.Println(err)
return
}
if regStatus.Status == "accepted" {
regPIN = regStatus.PIN
break
} else if regStatus.Status != "pending" {
err = fmt.Errorf("Invalid status while waiting for device registration: %s", regStatus.Status)
log.Println(err)
return
}
time.Sleep(5 * time.Second)
}
resp, err = client.CompleteDeviceRegistration(nil, userStatus.AuthyID, regPIN)
if err != nil {
log.Println(err)
return
}
if resp.Device.SecretSeed == "" {
err = errors.New("Something went wrong completing the device registration")
log.Println(err)
return
}
return
}
func (d *Device) newRegistrationDevice() (devInfo DeviceRegistration, err error) {
codeInt, mobile, err := getCountryCodeAndMobile(d.conf.CountryCode, d.conf.Mobile)
client, err := authy.NewClient()
if err != nil {
log.Println("New authy client failed", err)
return
}
userStatus, err := client.QueryUser(nil, codeInt, mobile)
if err != nil {
log.Println("Query user failed", err)
return
}
if !userStatus.IsActiveUser() {
err = errors.New("There doesn't seem to be an Authy account attached to that phone number")
log.Println(err)
return
}
resp, err := registerDevice(client, userStatus)
devInfo = DeviceRegistration{
UserID: resp.AuthyID,
DeviceID: resp.Device.ID,
Seed: resp.Device.SecretSeed,
APIKey: resp.Device.APIKey,
}
d.registration = devInfo
err = d.SaveDeviceInfo()
if err != nil {
log.Println("Save device info failed", err)
}
return
}
// SaveDeviceInfo ..
func (d *Device) SaveDeviceInfo() (err error) {
regrPath, err := d.ConfigPath(configFileName)
if err != nil {
return
}
f, err := os.OpenFile(regrPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
if err != nil {
return
}
defer f.Close()
err = json.NewEncoder(f).Encode(d.registration)
return
}
// LoadExistingDeviceInfo ...
func (d *Device) LoadExistingDeviceInfo() (devInfo DeviceRegistration, err error) {
devPath, err := d.ConfigPath(configFileName)
if err != nil {
log.Println("Get device info file path failed", err)
os.Exit(1)
}
f, err := os.Open(devPath)
if err != nil {
return
}
defer f.Close()
err = json.NewDecoder(f).Decode(&devInfo)
return
}
// ConfigPath get config file path
// Return the path to the config file
// If the file does not exist, it will be created at $HOME ( or optionally AUTHY_ROOT )
func (d *Device) ConfigPath(fname string) (string, error) {
if len(d.conf.ConfigFilePath) == 0 {
authy_root_path, root_dir_exists := os.LookupEnv("AUTHY_ROOT")
devPath, err := homedir.Dir()
if root_dir_exists {
devPath = authy_root_path
d.conf.ConfigFilePath = devPath
} else {
if err != nil {
return "", err
}
}
d.conf.ConfigFilePath = devPath
}
return filepath.Join(d.conf.ConfigFilePath, fname), nil
}
// DeleteMainPassword delete main password
func (d *Device) DeleteMainPassword() {
d.registration.MainPassword = ""
err := d.SaveDeviceInfo()
if err != nil {
log.Fatal("SaveDeviceInfo failed", err)
}
}