|
4 | 4 | "bytes" |
5 | 5 | "encoding/json" |
6 | 6 | "fmt" |
| 7 | + "io/ioutil" |
7 | 8 | "net/http" |
8 | 9 | "time" |
9 | 10 |
|
@@ -31,17 +32,23 @@ type TokenErrorResponse struct { |
31 | 32 | } |
32 | 33 |
|
33 | 34 | func (d *Depot) AuthorizeDevice() (*TokenResponse, error) { |
34 | | - res, err := http.Post(fmt.Sprintf("%s/api/internal/cli/auth-request", d.BaseURL), "application/json", nil) |
| 35 | + resp, err := http.Post(fmt.Sprintf("%s/api/internal/cli/auth-request", d.BaseURL), "application/json", nil) |
35 | 36 | if err != nil { |
36 | 37 | return nil, err |
37 | 38 | } |
38 | 39 |
|
39 | | - if res.StatusCode != http.StatusOK { |
40 | | - return nil, fmt.Errorf("unexpected status code: %d", res.StatusCode) |
| 40 | + body, err := ioutil.ReadAll(resp.Body) |
| 41 | + if err != nil { |
| 42 | + return nil, err |
| 43 | + } |
| 44 | + |
| 45 | + errorResponse, _ := tryParseErrorResponse(body) |
| 46 | + if errorResponse != nil { |
| 47 | + return nil, fmt.Errorf("%s", errorResponse.Error) |
41 | 48 | } |
42 | 49 |
|
43 | 50 | var response CLIAuthenticationResponse |
44 | | - err = json.NewDecoder(res.Body).Decode(&response) |
| 51 | + err = json.Unmarshal(body, &response) |
45 | 52 | if err != nil { |
46 | 53 | return nil, err |
47 | 54 | } |
@@ -70,30 +77,30 @@ func (d *Depot) AuthorizeDevice() (*TokenResponse, error) { |
70 | 77 | return nil, err |
71 | 78 | } |
72 | 79 |
|
73 | | - res, err := http.Post(response.TokenURL, "application/json", bytes.NewBuffer(tokenRequestBody)) |
| 80 | + resp, err := http.Post(response.TokenURL, "application/json", bytes.NewBuffer(tokenRequestBody)) |
74 | 81 | if err != nil { |
75 | 82 | return nil, err |
76 | 83 | } |
77 | 84 |
|
78 | | - if res.StatusCode == http.StatusOK { |
79 | | - var tokenResponse TokenResponse |
80 | | - err = json.NewDecoder(res.Body).Decode(&tokenResponse) |
81 | | - if err != nil { |
82 | | - return nil, err |
83 | | - } |
84 | | - return &tokenResponse, nil |
85 | | - } |
86 | | - |
87 | | - var errorResponse TokenErrorResponse |
88 | | - err = json.NewDecoder(res.Body).Decode(&errorResponse) |
| 85 | + body, err := ioutil.ReadAll(resp.Body) |
89 | 86 | if err != nil { |
90 | 87 | return nil, err |
91 | 88 | } |
92 | 89 |
|
93 | | - if errorResponse.Error == "authorization_pending" { |
94 | | - continue |
| 90 | + errorResponse, _ := tryParseErrorResponse(body) |
| 91 | + if errorResponse != nil { |
| 92 | + if errorResponse.Error == "authorization_pending" { |
| 93 | + continue |
| 94 | + } |
| 95 | + |
| 96 | + return nil, fmt.Errorf("error getting access token: %s", errorResponse.Error) |
95 | 97 | } |
96 | 98 |
|
97 | | - return nil, fmt.Errorf("error getting access token: %s", errorResponse.Error) |
| 99 | + var response TokenResponse |
| 100 | + err = json.Unmarshal(body, &response) |
| 101 | + if err != nil { |
| 102 | + return nil, err |
| 103 | + } |
| 104 | + return &response, nil |
98 | 105 | } |
99 | 106 | } |
0 commit comments