Skip to content
This repository has been archived by the owner on Feb 8, 2023. It is now read-only.

Commit

Permalink
support skipper
Browse files Browse the repository at this point in the history
  • Loading branch information
zensh committed Mar 23, 2017
1 parent a9469b5 commit 990586c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
22 changes: 18 additions & 4 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
)

// Version ...
const Version = "1.5.0"
const Version = "1.5.1"

// TokenExtractor is a function that takes a gear.Context as input and
// returns either a string token or an empty string. Default to:
Expand All @@ -28,11 +28,15 @@ type TokenExtractor func(ctx *gear.Context) (token string)
// Auth is helper type. It combine JWT and Crypto object, and some useful mothod for JWT.
// You can use it as a gear middleware.
type Auth struct {
j *jwt.JWT
ex TokenExtractor
j *jwt.JWT
ex TokenExtractor
skipper func(*gear.Context) bool
}

// New returns a Auth instance.
//
// auther := auth.New([]byte("my key"))
//
func New(keys ...interface{}) *Auth {
a := new(Auth)
a.SetJWT(jwt.New(keys...))
Expand All @@ -57,11 +61,18 @@ func (a *Auth) SetJWT(j *jwt.JWT) {
a.j = j
}

// SetTokenParser set a custom tokenExtractor to auth. Default to:
// SetTokenParser set a custom tokenExtractor to auth.
func (a *Auth) SetTokenParser(ex TokenExtractor) {
a.ex = ex
}

// SetSkipper set a skip function to auth.
// If skip function return true, the auth middleware process will be skipped.
func (a *Auth) SetSkipper(fn func(*gear.Context) bool) *Auth {
a.skipper = fn
return a
}

// New implements gear.Any interface, then we can use it with ctx.Any:
//
// any, err := ctx.Any(auther)
Expand Down Expand Up @@ -109,6 +120,9 @@ func (a *Auth) FromCtx(ctx *gear.Context) (josejwt.Claims, error) {
// app.Use(auther.Serve)
//
func (a *Auth) Serve(ctx *gear.Context) error {
if a.skipper != nil && a.skipper(ctx) {
return nil
}
_, err := ctx.Any(a)
return err
}
7 changes: 7 additions & 0 deletions auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ func TestGearAuth(t *testing.T) {
assert := assert.New(t)

a := New([]byte("my key"))
a.SetSkipper(func(ctx *gear.Context) bool {
return ctx.Path == "/skip"
})
app := gear.New()
app.UseHandler(a)
srv := app.Start()
Expand All @@ -45,6 +48,10 @@ func TestGearAuth(t *testing.T) {
res, err = req.Get(host)
assert.Nil(err)
assert.Equal(401, res.StatusCode)

res, err = req.Get(host + "/skip")
assert.Nil(err)
assert.Equal(421, res.StatusCode)
})

t.Run("should work", func(t *testing.T) {
Expand Down

0 comments on commit 990586c

Please sign in to comment.