2015-05-12 00:43:54 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
|
|
|
"net/http"
|
2015-07-05 15:21:05 +02:00
|
|
|
"net/http/httptest"
|
2015-05-12 00:43:54 +02:00
|
|
|
"testing"
|
2015-05-18 07:54:29 +02:00
|
|
|
|
|
|
|
"github.com/labstack/echo"
|
2015-05-30 19:54:55 +02:00
|
|
|
"github.com/stretchr/testify/assert"
|
2015-05-12 00:43:54 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestBasicAuth(t *testing.T) {
|
2015-05-30 19:54:55 +02:00
|
|
|
req, _ := http.NewRequest(echo.GET, "/", nil)
|
|
|
|
rec := httptest.NewRecorder()
|
|
|
|
c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
|
2015-05-12 00:43:54 +02:00
|
|
|
fn := func(u, p string) bool {
|
|
|
|
if u == "joe" && p == "secret" {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
2015-05-14 08:07:03 +02:00
|
|
|
ba := BasicAuth(fn)
|
2015-05-12 00:43:54 +02:00
|
|
|
|
|
|
|
// Valid credentials
|
|
|
|
auth := Basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:secret"))
|
|
|
|
req.Header.Set(echo.Authorization, auth)
|
2015-05-30 19:54:55 +02:00
|
|
|
assert.NoError(t, ba(c))
|
2015-05-12 00:43:54 +02:00
|
|
|
|
|
|
|
//---------------------
|
|
|
|
// Invalid credentials
|
|
|
|
//---------------------
|
|
|
|
|
2015-05-16 21:49:01 +02:00
|
|
|
// Incorrect password
|
2015-06-10 05:06:51 +02:00
|
|
|
auth = Basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:password"))
|
2015-05-12 00:43:54 +02:00
|
|
|
req.Header.Set(echo.Authorization, auth)
|
2015-05-21 23:02:29 +02:00
|
|
|
he := ba(c).(*echo.HTTPError)
|
2015-05-30 19:54:55 +02:00
|
|
|
assert.Equal(t, http.StatusUnauthorized, he.Code())
|
2015-05-18 07:54:29 +02:00
|
|
|
|
|
|
|
// Empty Authorization header
|
|
|
|
req.Header.Set(echo.Authorization, "")
|
2015-05-21 23:02:29 +02:00
|
|
|
he = ba(c).(*echo.HTTPError)
|
2015-05-30 19:54:55 +02:00
|
|
|
assert.Equal(t, http.StatusBadRequest, he.Code())
|
2015-05-12 00:43:54 +02:00
|
|
|
|
2015-05-18 07:54:29 +02:00
|
|
|
// Invalid Authorization header
|
2015-07-05 15:21:05 +02:00
|
|
|
auth = base64.StdEncoding.EncodeToString([]byte("invalid"))
|
2015-05-12 00:43:54 +02:00
|
|
|
req.Header.Set(echo.Authorization, auth)
|
2015-05-21 23:02:29 +02:00
|
|
|
he = ba(c).(*echo.HTTPError)
|
2015-05-30 19:54:55 +02:00
|
|
|
assert.Equal(t, http.StatusBadRequest, he.Code())
|
|
|
|
|
|
|
|
// WebSocket
|
|
|
|
c.Request().Header.Set(echo.Upgrade, echo.WebSocket)
|
|
|
|
assert.NoError(t, ba(c))
|
2015-05-12 00:43:54 +02:00
|
|
|
}
|