Roughing in some handlers

This commit is contained in:
Matthew Dillon 2015-04-17 15:30:35 -08:00
parent 2c1f9ce645
commit 7871c1db59
2 changed files with 71 additions and 3 deletions

21
jwt.go
View file

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

View file

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