forked from FabianVowie/Lithium
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
50 lines
1.5 KiB
50 lines
1.5 KiB
package middlewares
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/bxcodec/faker/v3"
|
|
"github.com/stretchr/testify/assert"
|
|
)
|
|
|
|
func TestAuthenticationMiddleware(t *testing.T) {
|
|
token := faker.Word()
|
|
middleware := CreateAuthenticationMiddleware(token)
|
|
|
|
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
})
|
|
|
|
middlewareHandler := middleware.Middleware(handler)
|
|
|
|
t.Run("AuthenticationMiddleware returns 403 response when authorization header is incorrect", func(t *testing.T) {
|
|
request, _ := http.NewRequest("GET", "/", nil)
|
|
responseRecorder := httptest.NewRecorder()
|
|
|
|
middlewareHandler.ServeHTTP(responseRecorder, request)
|
|
|
|
assert.Equal(t, 403, responseRecorder.Code)
|
|
})
|
|
|
|
t.Run("AuthenticationMiddleware returns 403 response when authorization header is missing Bearer prefix", func(t *testing.T) {
|
|
request, _ := http.NewRequest("GET", "/", nil)
|
|
request.Header.Set("Authorization", token)
|
|
responseRecorder := httptest.NewRecorder()
|
|
|
|
middlewareHandler.ServeHTTP(responseRecorder, request)
|
|
|
|
assert.Equal(t, 403, responseRecorder.Code)
|
|
})
|
|
|
|
t.Run("AuthenticationMiddleware continues when authorization header is correct", func(t *testing.T) {
|
|
request, _ := http.NewRequest("GET", "/", nil)
|
|
request.Header.Set("Authorization", "Bearer "+token)
|
|
responseRecorder := httptest.NewRecorder()
|
|
|
|
middlewareHandler.ServeHTTP(responseRecorder, request)
|
|
|
|
assert.Equal(t, 200, responseRecorder.Code)
|
|
})
|
|
}
|