More explicit middleware creation

This commit is contained in:
Matthew Dillon 2015-04-17 16:39:58 -08:00
parent e0d56f0a29
commit 752c683a99
2 changed files with 33 additions and 9 deletions

24
jwt.go
View file

@ -6,6 +6,12 @@ import (
"net/http" "net/http"
) )
var (
ErrMissingConfig = errors.New("missing configuration")
ErrMissingSecret = errors.New("please provide a shared secret")
ErrMissingAuthFunc = errors.New("please provide an auth function")
)
type Config struct { type Config struct {
Secret string Secret string
Auth AuthFunc Auth AuthFunc
@ -14,14 +20,24 @@ type Config struct {
type AuthFunc func(string, string) (bool, error) type AuthFunc func(string, string) (bool, error)
type JWTMiddleware struct { type JWTMiddleware struct {
config Config secret string
auth AuthFunc
} }
func NewMiddleware(c *Config) (*JWTMiddleware, error) { func NewMiddleware(c *Config) (*JWTMiddleware, error) {
if c == nil { if c == nil {
return nil, errors.New("missing configuration") return nil, ErrMissingConfig
}
if c.Secret == "" {
return nil, ErrMissingSecret
}
if c.Auth == nil {
return nil, ErrMissingAuthFunc
}
m := &JWTMiddleware{
secret: c.Secret,
auth: c.Auth,
} }
m := &JWTMiddleware{config: *c}
return m, nil return m, nil
} }
@ -37,7 +53,7 @@ func (m *JWTMiddleware) GenerateToken(w http.ResponseWriter, r *http.Request) {
if err != nil { if err != nil {
panic(err) panic(err)
} }
result, err := m.config.Auth(b["email"], b["password"]) result, err := m.auth(b["email"], b["password"])
if err != nil { if err != nil {
panic(err) panic(err)
} }

View file

@ -31,16 +31,24 @@ func newJWTMiddlewareOrFatal(t *testing.T) *JWTMiddleware {
func TestNewJWTMiddleware(t *testing.T) { func TestNewJWTMiddleware(t *testing.T) {
middleware := newJWTMiddlewareOrFatal(t) middleware := newJWTMiddlewareOrFatal(t)
if middleware.config.Secret != "password" { if middleware.secret != "password" {
t.Errorf("expected 'password', got %v", middleware.config.Secret) t.Errorf("expected 'password', got %v", middleware.secret)
} }
// TODO: test auth func init // TODO: test auth func init
} }
func TestNewJWTMiddlewareNoConfig(t *testing.T) { func TestNewJWTMiddlewareNoConfig(t *testing.T) {
_, err := NewMiddleware(nil) cases := map[*Config]error{
if err == nil { nil: ErrMissingConfig,
t.Error("expected configuration error, received none") &Config{}: ErrMissingSecret,
&Config{Auth: authFunc}: ErrMissingSecret,
&Config{Secret: "secret"}: ErrMissingAuthFunc,
}
for config, jwtErr := range cases {
_, err := NewMiddleware(config)
if err != jwtErr {
t.Errorf("wanted error: %v, got error: %v using config: %v", jwtErr, err, config)
}
} }
} }