diff --git a/jwt.go b/jwt.go index fe1aef3..f4cb00f 100644 --- a/jwt.go +++ b/jwt.go @@ -1,6 +1,10 @@ package jwt -import "errors" +import ( + "encoding/json" + "errors" + "net/http" +) type Config struct { Secret string @@ -17,3 +21,18 @@ func NewMiddleware(c *Config) (*JWTMiddleware, error) { m := &JWTMiddleware{config: *c} return m, nil } + +func (m *JWTMiddleware) Secure(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h.ServeHTTP(w, r) + }) +} + +func (m *JWTMiddleware) Auth(w http.ResponseWriter, r *http.Request) { + var b interface{} + err := json.NewDecoder(r.Body).Decode(&b) + if err != nil { + panic(err) + } + w.Write([]byte("test")) +} diff --git a/jwt_test.go b/jwt_test.go index 93b416e..ddeaf8e 100644 --- a/jwt_test.go +++ b/jwt_test.go @@ -1,8 +1,19 @@ package jwt -import "testing" +import ( + "bytes" + "encoding/json" + "io/ioutil" + "net/http" + "net/http/httptest" + "testing" +) -func TestNewJWTMiddleware(t *testing.T) { +var testHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte("test")) +}) + +func newJWTMiddlewareOrFatal(t *testing.T) *JWTMiddleware { config := &Config{ Secret: "password", } @@ -10,6 +21,11 @@ func TestNewJWTMiddleware(t *testing.T) { if err != nil { t.Fatalf("new middleware: %v", err) } + return middleware +} + +func TestNewJWTMiddleware(t *testing.T) { + middleware := newJWTMiddlewareOrFatal(t) if middleware.config.Secret != "password" { t.Errorf("expected 'password', got %v", middleware.config.Secret) } @@ -21,3 +37,36 @@ func TestNewJWTMiddlewareNoConfig(t *testing.T) { t.Error("expected configuration error, received none") } } + +func TestSecureHandler(t *testing.T) { + middleware := newJWTMiddlewareOrFatal(t) + resp := httptest.NewRecorder() + req, _ := http.NewRequest("GET", "http://example.com", nil) + middleware.Secure(testHandler).ServeHTTP(resp, req) + if resp.Body.String() != "test" { + t.Errorf("expected 'test', got %v", resp.Body.String()) + } +} + +func TestAuthHandler(t *testing.T) { + middleware := newJWTMiddlewareOrFatal(t) + authBody := map[string]interface{}{ + "email": "user@example.com", + "password": "password", + } + body, err := json.Marshal(authBody) + if err != nil { + t.Error(err) + } + ts := httptest.NewServer(http.HandlerFunc(middleware.Auth)) + defer ts.Close() + resp, err := http.Post(ts.URL, "application/json", bytes.NewReader(body)) + respBody, err := ioutil.ReadAll(resp.Body) + resp.Body.Close() + if err != nil { + t.Error(err) + } + if string(respBody) != "test" { + t.Errorf("expected 'test', got %v", respBody) + } +}