Skip to content

Commit

Permalink
added HandlerFunc to process handlerfunctions (in addition to Handler…
Browse files Browse the repository at this point in the history
… which only accepter a handler)
  • Loading branch information
adam-hanna committed Mar 10, 2017
1 parent 7121456 commit 0dfd559
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 6 deletions.
17 changes: 11 additions & 6 deletions jwt/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,14 @@ func (a *Auth) Handler(h http.Handler) http.Handler {
})
}

// HandlerFunc works identically to Handler, but takes a HandlerFunc instead of a Handler.
func (a *Auth) HandlerFunc(fn http.HandlerFunc) http.Handler {
if fn == nil {
return a.Handler(nil)
}
return a.Handler(fn)
}

// HandlerFuncWithNext is a special implementation for Negroni, but could be used elsewhere.
func (a *Auth) HandlerFuncWithNext(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
jwtErr := a.Process(w, r)
Expand Down Expand Up @@ -295,14 +303,12 @@ func (a *Auth) Process(w http.ResponseWriter, r *http.Request) *jwtError {

// grab the credentials from the request
var c credentials
err := a.buildCredentialsFromRequest(r, &c)
if err != nil {
if err := a.buildCredentialsFromRequest(r, &c); err != nil {
return newJwtError(err, 500)
}

// check the credential's validity; updating expiry's if necessary and/or allowed
err = c.validateAndUpdateCredentials()
if err != nil {
if err := c.validateAndUpdateCredentials(); err != nil {
return newJwtError(err, 500)
}

Expand All @@ -311,8 +317,7 @@ func (a *Auth) Process(w http.ResponseWriter, r *http.Request) *jwtError {
// if we've made it this far, everything is valid!
// And tokens have been refreshed if need-be
if !a.options.VerifyOnlyServer {
err = a.setCredentialsOnResponseWriter(w, &c)
if err != nil {
if err := a.setCredentialsOnResponseWriter(w, &c); err != nil {
return newJwtError(err, 500)
}
}
Expand Down
23 changes: 23 additions & 0 deletions jwt/auth_unit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -457,3 +457,26 @@ func TestGrabTokenClaims(t *testing.T) {
t.Errorf("Claims do not match expectations; Expected: bar; Received: %s", myNewClaims.CustomClaims["foo"].(string))
}
}

var myHandlerFunc = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("In Handler Func"))
})

func TestHandlerFunc(t *testing.T) {
var a Auth
handler := a.HandlerFunc(myHandlerFunc)

req, err := http.NewRequest("OPTIONS", "/test", nil)
if err != nil {
t.Fatal(err)
}

rr := httptest.NewRecorder()

handler.ServeHTTP(rr, req)

body := rr.Body.String()
if body != "In Handler Func" {
t.Errorf("expected: In Handler Func; received: %s", body)
}
}

0 comments on commit 0dfd559

Please sign in to comment.