Skip to content

Commit

Permalink
feat: add bearer helper
Browse files Browse the repository at this point in the history
  • Loading branch information
aeneasr committed Aug 25, 2020
1 parent 7be4086 commit ec6ca20
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
16 changes: 16 additions & 0 deletions session/helper.go
@@ -0,0 +1,16 @@
package session

import (
"net/http"
"strings"
)

func bearerTokenFromRequest(r *http.Request) (string, bool) {
parts := strings.Split(r.Header.Get("Authorization"), " ")

if len(parts) == 2 && strings.ToLower(parts[0]) == "bearer" {
return parts[1], true
}

return "", false
}
52 changes: 52 additions & 0 deletions session/helper_test.go
@@ -0,0 +1,52 @@
package session

import (
"fmt"
"net/http"
"testing"

"github.com/stretchr/testify/assert"
)

func TestBearerTokenFromRequest(t *testing.T) {
for k, tc := range []struct {
h http.Header
t string
f bool
}{
{
h: http.Header{"Authorization": {"Bearer token"}},
t: "token", f : true,
},
{
h: http.Header{"Authorization": {"bearer token"}},
t: "token", f : true,
},
{
h: http.Header{"Authorization": {"beaRer token"}},
t: "token", f : true,
},
{
h: http.Header{"Authorization": {"BEARER token"}},
t: "token", f : true,
},
{
h: http.Header{"Authorization": {"notbearer token"}},
},
{
h: http.Header{"Authorization": {"token"}},
},
{
h: http.Header{"Authorization": {}},
},
{
h: http.Header{},
},
} {
t.Run(fmt.Sprintf("case=%d", k), func(t *testing.T) {
token, found := bearerTokenFromRequest(&http.Request{Header: tc.h})
assert.Equal(t, tc.f, found)
assert.Equal(t, tc.t, token)
})
}
}

0 comments on commit ec6ca20

Please sign in to comment.