github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/plugin/basic/middleware_test.go (about) 1 package basic 2 3 import ( 4 "encoding/base64" 5 "net/http" 6 "testing" 7 8 "github.com/hellofresh/janus/pkg/test" 9 "github.com/stretchr/testify/assert" 10 ) 11 12 func TestAuthorizedAccess(t *testing.T) { 13 mw := NewBasicAuth(setupRepo()) 14 15 w, err := test.Record( 16 "GET", 17 "/", 18 map[string]string{ 19 "Content-Type": "application/json", 20 "Authorization": "Basic " + basicAuth("test", "test"), 21 }, 22 mw(http.HandlerFunc(test.Ping)), 23 ) 24 assert.NoError(t, err) 25 26 assert.Equal(t, http.StatusOK, w.Code) 27 assert.Equal(t, "application/json", w.Header().Get("Content-Type")) 28 } 29 30 func TestInvalidBasicHeader(t *testing.T) { 31 mw := NewBasicAuth(setupRepo()) 32 33 w, err := test.Record( 34 "GET", 35 "/", 36 map[string]string{ 37 "Content-Type": "application/json", 38 "Authorization": "Basic wrong", 39 }, 40 mw(http.HandlerFunc(test.Ping)), 41 ) 42 assert.NoError(t, err) 43 44 assert.Equal(t, http.StatusUnauthorized, w.Code) 45 assert.Equal(t, "application/json", w.Header().Get("Content-Type")) 46 } 47 48 func TestUnauthorizedAccess(t *testing.T) { 49 mw := NewBasicAuth(setupRepo()) 50 51 w, err := test.Record( 52 "GET", 53 "/", 54 map[string]string{ 55 "Content-Type": "application/json", 56 "Authorization": "Basic " + basicAuth("wrong", "wrong"), 57 }, 58 mw(http.HandlerFunc(test.Ping)), 59 ) 60 assert.NoError(t, err) 61 62 assert.Equal(t, http.StatusUnauthorized, w.Code) 63 assert.Equal(t, "application/json", w.Header().Get("Content-Type")) 64 } 65 66 func basicAuth(username, password string) string { 67 auth := username + ":" + password 68 return base64.StdEncoding.EncodeToString([]byte(auth)) 69 } 70 71 func setupRepo() Repository { 72 repo := NewInMemoryRepository() 73 repo.Add(&User{Username: "test", Password: "test"}) 74 75 return repo 76 }