-
Notifications
You must be signed in to change notification settings - Fork 904
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(api): return appropriate status for unauthorized requests (#1116)
- Loading branch information
Showing
3 changed files
with
71 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
package api | ||
|
||
import ( | ||
"io" | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
|
||
. "github.com/onsi/ginkgo" | ||
. "github.com/onsi/gomega" | ||
) | ||
|
||
const ( | ||
token = "123123123" | ||
) | ||
|
||
func TestAPI(t *testing.T) { | ||
RegisterFailHandler(Fail) | ||
RunSpecs(t, "API Suite") | ||
} | ||
|
||
var _ = Describe("API", func() { | ||
api := New(token) | ||
|
||
Describe("RequireToken middleware", func() { | ||
It("should return 401 Unauthorized when token is not provided", func() { | ||
handlerFunc := api.RequireToken(testHandler) | ||
|
||
rec := httptest.NewRecorder() | ||
req := httptest.NewRequest("GET", "/hello", nil) | ||
|
||
handlerFunc(rec, req) | ||
|
||
Expect(rec.Code).To(Equal(http.StatusUnauthorized)) | ||
}) | ||
|
||
It("should return 401 Unauthorized when token is invalid", func() { | ||
handlerFunc := api.RequireToken(testHandler) | ||
|
||
rec := httptest.NewRecorder() | ||
req := httptest.NewRequest("GET", "/hello", nil) | ||
req.Header.Set("Authorization", "Bearer 123") | ||
|
||
handlerFunc(rec, req) | ||
|
||
Expect(rec.Code).To(Equal(http.StatusUnauthorized)) | ||
}) | ||
|
||
It("should return 200 OK when token is valid", func() { | ||
handlerFunc := api.RequireToken(testHandler) | ||
|
||
rec := httptest.NewRecorder() | ||
req := httptest.NewRequest("GET", "/hello", nil) | ||
req.Header.Set("Authorization", "Bearer " + token) | ||
|
||
handlerFunc(rec, req) | ||
|
||
Expect(rec.Code).To(Equal(http.StatusOK)) | ||
}) | ||
}) | ||
}) | ||
|
||
func testHandler(w http.ResponseWriter, req *http.Request) { | ||
_, _ = io.WriteString(w, "Hello!") | ||
} |