Skip to content

Commit

Permalink
fix: move the check for Authenticator to login handler. (#69)
Browse files Browse the repository at this point in the history
  • Loading branch information
appleboy authored Apr 4, 2017
1 parent 6f16f24 commit f7347d7
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 19 deletions.
9 changes: 5 additions & 4 deletions auth_jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,6 @@ func (mw *GinJWTMiddleware) MiddlewareInit() error {
return errors.New("realm is required")
}

if mw.Authenticator == nil {
return errors.New("authenticator is required")
}

if mw.Key == nil {
return errors.New("secret key is required")
}
Expand Down Expand Up @@ -193,6 +189,11 @@ func (mw *GinJWTMiddleware) LoginHandler(c *gin.Context) {
return
}

if mw.Authenticator == nil {
mw.unauthorized(c, http.StatusInternalServerError, "Missing define authenticator func")
return
}

userID, ok := mw.Authenticator(loginVals.Username, loginVals.Password, c)

if !ok {
Expand Down
41 changes: 26 additions & 15 deletions auth_jwt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,21 +54,6 @@ func TestMissingRealm(t *testing.T) {
assert.Equal(t, "realm is required", err.Error())
}

func TestMissingAuthenticator(t *testing.T) {

authMiddleware := &GinJWTMiddleware{
Realm: "test zone",
Key: key,
Timeout: time.Hour,
MaxRefresh: time.Hour * 24,
}

err := authMiddleware.MiddlewareInit()

assert.Error(t, err)
assert.Equal(t, "authenticator is required", err.Error())
}

func TestMissingKey(t *testing.T) {

authMiddleware := &GinJWTMiddleware{
Expand Down Expand Up @@ -169,6 +154,32 @@ func TestInternalServerError(t *testing.T) {
})
}

func TestMissingAuthenticatorForLoginHandler(t *testing.T) {

authMiddleware := &GinJWTMiddleware{
Realm: "test zone",
Key: key,
Timeout: time.Hour,
MaxRefresh: time.Hour * 24,
}

handler := ginHandler(authMiddleware)
r := gofight.New()

r.POST("/login").
SetJSON(gofight.D{
"username": "admin",
"password": "admin",
}).
Run(handler, func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {
data := []byte(r.Body.String())
message, _ := jsonparser.GetString(data, "message")

assert.Equal(t, "Missing define authenticator func", message)
assert.Equal(t, http.StatusInternalServerError, r.Code)
})
}

func TestLoginHandler(t *testing.T) {

// the middleware to test
Expand Down

0 comments on commit f7347d7

Please sign in to comment.