Skip to content

Commit

Permalink
Merge pull request #381 from MadAppGang/return-nil-token-from-context
Browse files Browse the repository at this point in the history
Return nil token when missing
  • Loading branch information
erudenko authored Jan 20, 2023
2 parents 13e59e3 + 483003b commit d990ee3
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
4 changes: 3 additions & 1 deletion jwt/middleware/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ func JWT(eh ErrorHandler, c validator.Config) (Handler, error) {
}

// TokenFromContext returns token from request context.
// Or nil if there is no token in context.
func TokenFromContext(ctx context.Context) model.Token {
return ctx.Value(model.TokenContextKey).(model.Token)
v, _ := ctx.Value(model.TokenContextKey).(model.Token)
return v
}
34 changes: 34 additions & 0 deletions jwt/middleware/middleware_test.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package middleware_test

import (
"context"
"net/http"
"os"
"reflect"
"testing"

"github.com/madappgang/identifo/v2/jwt/middleware"
"github.com/madappgang/identifo/v2/jwt/validator"
"github.com/madappgang/identifo/v2/model"
)

const (
Expand Down Expand Up @@ -89,3 +92,34 @@ type mockErrorHandler struct {
func (m *mockErrorHandler) Error(rw http.ResponseWriter, errorType middleware.Error, status int, description string) {
m.e = errorType
}

func TestTokenFromContext(t *testing.T) {
tests := []struct {
name string
ctx context.Context
want model.Token
}{
{
name: "no token",
ctx: context.Background(),
want: nil,
},
{
name: "nil token",
ctx: context.WithValue(context.Background(), model.TokenContextKey, nil),
want: nil,
},
{
name: "token exists",
ctx: context.WithValue(context.Background(), model.TokenContextKey, model.Token(&model.JWToken{})),
want: &model.JWToken{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := middleware.TokenFromContext(tt.ctx); !reflect.DeepEqual(got, tt.want) {
t.Errorf("TokenFromContext() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit d990ee3

Please sign in to comment.