-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #13 from jtrw/develop
Add AuthBearer middleware function and test
- Loading branch information
Showing
2 changed files
with
67 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | ||
} |