fix(api): return appropriate status for unauthorized requests (#1116)

This commit is contained in:
Igor Zibarev 2021-11-12 14:16:24 +03:00 committed by GitHub
parent c0fd77d357
commit 81036b078b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 71 additions and 9 deletions

65
pkg/api/api_test.go Normal file
View file

@ -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!")
}