Skip to content

Commit

Permalink
add authorization in Request
Browse files Browse the repository at this point in the history
  • Loading branch information
exelban committed Feb 26, 2020
1 parent cad52c4 commit 990fe50
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
22 changes: 22 additions & 0 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
Expand All @@ -17,6 +18,11 @@ func Request(ctx context.Context, method string, url string, b []byte, auth bool
}

req.Header.Add("Content-Type", "application/json")
if auth {
if err := SetAuthorization(ctx, req); err != nil {
return nil, err
}
}
if err := InjectToReq(ctx, req); err != nil {
return nil, err
}
Expand All @@ -43,3 +49,19 @@ func Request(ctx context.Context, method string, url string, b []byte, auth bool

return body, nil
}

// SetAuthorization - take token from context value and set as Bearer token in Authorization header.
func SetAuthorization(ctx context.Context, req *http.Request) error {
jwtToken := ctx.Value("token")
if jwtToken == nil || jwtToken == "" {
return errors.New("no token in context")
}

if req == nil {
return errors.New("empty request")
}

req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", jwtToken))

return nil
}
18 changes: 18 additions & 0 deletions request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,21 @@ func TestRequest(t *testing.T) {
require.Equal(t, []byte("OK"), resp)
})
}

func TestSetAuthorization(t *testing.T) {
t.Run("empty context", func(t *testing.T) {
ctx := context.Background()
require.Error(t, SetAuthorization(ctx, nil))
})
t.Run("empty request", func(t *testing.T) {
ctx := context.Background()
ctx = context.WithValue(ctx, "token", "test")
require.Error(t, SetAuthorization(ctx, nil))
})
t.Run("ok", func(t *testing.T) {
ctx := context.Background()
ctx = context.WithValue(ctx, "token", "test")
req := httptest.NewRequest("GET", "http://test.com", nil)
require.NoError(t, SetAuthorization(ctx, req))
})
}

0 comments on commit 990fe50

Please sign in to comment.