2015-05-12 00:43:54 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
|
|
|
"net/http"
|
2015-07-05 15:21:05 +02:00
|
|
|
|
|
|
|
"github.com/labstack/echo"
|
2015-05-12 00:43:54 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
2015-06-10 05:06:51 +02:00
|
|
|
BasicValidateFunc func(string, string) bool
|
2015-05-12 00:43:54 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2015-07-05 15:21:05 +02:00
|
|
|
Basic = "Basic"
|
2015-05-12 00:43:54 +02:00
|
|
|
)
|
|
|
|
|
2015-06-10 05:06:51 +02:00
|
|
|
// BasicAuth returns an HTTP basic authentication middleware.
|
|
|
|
//
|
|
|
|
// For valid credentials it calls the next handler.
|
2015-05-21 23:02:29 +02:00
|
|
|
// For invalid Authorization header it sends "404 - Bad Request" response.
|
|
|
|
// For invalid credentials, it sends "401 - Unauthorized" response.
|
2015-06-10 05:06:51 +02:00
|
|
|
func BasicAuth(fn BasicValidateFunc) echo.HandlerFunc {
|
2015-05-20 23:38:51 +02:00
|
|
|
return func(c *echo.Context) error {
|
2015-06-10 05:06:51 +02:00
|
|
|
// Skip WebSocket
|
2015-05-23 05:26:52 +02:00
|
|
|
if (c.Request().Header.Get(echo.Upgrade)) == echo.WebSocket {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-05-22 13:40:01 +02:00
|
|
|
auth := c.Request().Header.Get(echo.Authorization)
|
2015-06-10 05:06:51 +02:00
|
|
|
l := len(Basic)
|
|
|
|
he := echo.NewHTTPError(http.StatusBadRequest)
|
2015-05-12 00:43:54 +02:00
|
|
|
|
2015-06-10 05:06:51 +02:00
|
|
|
if len(auth) > l+1 && auth[:l] == Basic {
|
|
|
|
b, err := base64.StdEncoding.DecodeString(auth[l+1:])
|
|
|
|
if err == nil {
|
2015-05-12 00:43:54 +02:00
|
|
|
cred := string(b)
|
|
|
|
for i := 0; i < len(cred); i++ {
|
|
|
|
if cred[i] == ':' {
|
|
|
|
// Verify credentials
|
2015-05-21 23:02:29 +02:00
|
|
|
if fn(cred[:i], cred[i+1:]) {
|
|
|
|
return nil
|
2015-05-12 00:43:54 +02:00
|
|
|
}
|
2015-06-10 05:06:51 +02:00
|
|
|
he.SetCode(http.StatusUnauthorized)
|
2015-05-12 00:43:54 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-06-10 05:06:51 +02:00
|
|
|
return he
|
|
|
|
}
|
|
|
|
}
|