Skip to content

Commit

Permalink
Merge pull request #13 from jtrw/develop
Browse files Browse the repository at this point in the history
Add AuthBearer middleware function and test
  • Loading branch information
nilBora authored Jan 22, 2024
2 parents 9b45b49 + 73387ef commit c1ae76f
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
29 changes: 29 additions & 0 deletions auth_bearer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package rest

import (
"net/http"
"strings"
)

func AuthBearer(token string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {

authorization := r.Header.Get("Authorization")
headerToken := strings.TrimSpace(strings.Replace(authorization, "Bearer", "", 1))

if headerToken == "" {
http.Error(w, "Token not Found", http.StatusUnauthorized)
return
}

if headerToken != token {
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}

next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
38 changes: 38 additions & 0 deletions auth_bearer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package rest

import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"io"
"net/http"
"net/http/httptest"
"testing"
)

func TestBearer_AuthBearer(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte("blabla blabla"))
require.NoError(t, err)
})
ts := httptest.NewServer(AuthBearer("123456")(handler))
defer ts.Close()

resp, err := http.Get(ts.URL + "/ping")
require.Nil(t, err)
assert.Equal(t, 401, resp.StatusCode)
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t, "Token not Found\n", string(b))

req, err := http.NewRequest("GET", ts.URL+"/ping", nil)
require.NoError(t, err)
req.Header.Set("Authorization", "Bearer 123456")
resp, err = http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
defer resp.Body.Close()
b, err = io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t, "blabla blabla", string(b))
}

0 comments on commit c1ae76f

Please sign in to comment.