Skip to content

Commit

Permalink
Handle failed status code in provider requests (#313)
Browse files Browse the repository at this point in the history
  • Loading branch information
mraerino authored Feb 9, 2022
1 parent 195495c commit 4d8a3b3
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
19 changes: 19 additions & 0 deletions api/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package provider
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"

"golang.org/x/oauth2"
)
Expand Down Expand Up @@ -49,6 +51,15 @@ func chooseHost(base, defaultHost string) string {
return base
}

type RequestError struct {
code int
body string
}

func (r *RequestError) Error() string {
return fmt.Sprintf("Request failed with status %d:\n%s", r.code, r.body)
}

func makeRequest(ctx context.Context, tok *oauth2.Token, g *oauth2.Config, url string, dst interface{}) error {
client := g.Client(ctx, tok)
res, err := client.Get(url)
Expand All @@ -57,6 +68,14 @@ func makeRequest(ctx context.Context, tok *oauth2.Token, g *oauth2.Config, url s
}
defer res.Body.Close()

if res.StatusCode/100 != 2 {
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
return &RequestError{code: res.StatusCode, body: string(body)}
}

if err := json.NewDecoder(res.Body).Decode(dst); err != nil {
return err
}
Expand Down
44 changes: 44 additions & 0 deletions api/provider/provider_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package provider_test

import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/netlify/gotrue/api/provider"
"github.com/netlify/gotrue/conf"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/oauth2"
)

func TestGithubFail(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)

srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rw.WriteHeader(http.StatusTeapot)
fmt.Fprint(rw, "Something failed")
}))
t.Cleanup(srv.Close)

gh, err := provider.NewGithubProvider(conf.OAuthProviderConfiguration{
ClientID: "client-id",
Secret: "secret",
RedirectURI: "https://redirect.example.org/callback",
URL: srv.URL,
Enabled: true,
})
require.NoError(t, err)

user, err := gh.GetUserData(ctx, &oauth2.Token{
AccessToken: "my-token",
Expiry: time.Now().Add(time.Minute),
})
require.Error(t, err)
require.Nil(t, user)
assert.Equal(t, "Request failed with status 418:\nSomething failed", err.Error())
}

0 comments on commit 4d8a3b3

Please sign in to comment.