forked from dcu/go-authy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
84 lines (70 loc) · 2.09 KB
/
user.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
package authy
import (
"encoding/json"
"io/ioutil"
"net/http"
"strconv"
)
// User is an Authy User
type User struct {
HTTPResponse *http.Response
ID string
UserData struct {
ID int `json:"id"`
} `json:"user"`
Errors map[string]string `json:"errors"`
Message string `json:"message"`
}
// UserStatus is a user with information loaded from Authy API
type UserStatus struct {
HTTPResponse *http.Response
ID string
StatusData struct {
ID int `json:"authy_id"`
Confirmed bool `json:"confirmed"`
Registered bool `json:"registered"`
Country int `json:"country_code"`
PhoneNumber string `json:"phone_number"`
Devices []string `json:"devices"`
} `json:"status"`
Message string `json:"message"`
Success bool `json:"success"`
}
// NewUser returns an instance of User
func NewUser(httpResponse *http.Response) (*User, error) {
userResponse := &User{HTTPResponse: httpResponse}
defer closeResponseBody(httpResponse)
body, err := ioutil.ReadAll(httpResponse.Body)
if err != nil {
Logger.Println("Error reading from API:", err)
return userResponse, err
}
err = json.Unmarshal(body, userResponse)
if err != nil {
Logger.Println("Error parsing JSON:", err)
return userResponse, err
}
userResponse.ID = strconv.Itoa(userResponse.UserData.ID)
return userResponse, nil
}
// NewUserStatus returns an instance of UserStatus
func NewUserStatus(httpResponse *http.Response) (*UserStatus, error) {
statusResponse := &UserStatus{HTTPResponse: httpResponse}
defer closeResponseBody(httpResponse)
body, err := ioutil.ReadAll(httpResponse.Body)
if err != nil {
Logger.Println("Error reading from API:", err)
return statusResponse, err
}
err = json.Unmarshal(body, statusResponse)
if err != nil {
Logger.Println("Error parsing JSON:", err)
return statusResponse, err
}
statusResponse.ID = strconv.Itoa(statusResponse.StatusData.ID)
return statusResponse, nil
}
// Valid returns true if the user was created successfully
func (response *User) Valid() bool {
return response.HTTPResponse.StatusCode == 200
}