2015-05-12 00:43:54 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
|
|
|
"github.com/labstack/echo"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
AuthFunc func(string, string) bool
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
Basic = "Basic"
|
|
|
|
)
|
|
|
|
|
2015-05-21 23:02:29 +02:00
|
|
|
// BasicAuth returns an HTTP basic authentication middleware. For valid credentials
|
|
|
|
// it calls the next handler in the chain.
|
|
|
|
|
|
|
|
// For invalid Authorization header it sends "404 - Bad Request" response.
|
|
|
|
// For invalid credentials, it sends "401 - Unauthorized" response.
|
2015-05-12 00:43:54 +02:00
|
|
|
func BasicAuth(fn AuthFunc) echo.HandlerFunc {
|
2015-05-20 23:38:51 +02:00
|
|
|
return func(c *echo.Context) error {
|
2015-05-22 13:40:01 +02:00
|
|
|
auth := c.Request().Header.Get(echo.Authorization)
|
2015-05-12 00:43:54 +02:00
|
|
|
i := 0
|
2015-05-21 23:02:29 +02:00
|
|
|
code := http.StatusBadRequest
|
2015-05-12 00:43:54 +02:00
|
|
|
|
|
|
|
for ; i < len(auth); i++ {
|
|
|
|
c := auth[i]
|
|
|
|
// Ignore empty spaces
|
|
|
|
if c == ' ' {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check scheme
|
2015-05-12 15:18:49 +02:00
|
|
|
if i < len(Basic) {
|
2015-05-12 00:43:54 +02:00
|
|
|
// Ignore case
|
|
|
|
if i == 0 {
|
|
|
|
if c != Basic[i] && c != 'b' {
|
2015-05-21 23:02:29 +02:00
|
|
|
break
|
2015-05-12 00:43:54 +02:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if c != Basic[i] {
|
2015-05-21 23:02:29 +02:00
|
|
|
break
|
2015-05-12 00:43:54 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// Extract credentials
|
|
|
|
b, err := base64.StdEncoding.DecodeString(auth[i:])
|
|
|
|
if err != nil {
|
2015-05-21 23:02:29 +02:00
|
|
|
break
|
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-05-21 23:02:29 +02:00
|
|
|
code = http.StatusUnauthorized
|
|
|
|
break
|
2015-05-12 00:43:54 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-05-21 23:02:29 +02:00
|
|
|
return echo.NewHTTPError(code)
|
2015-05-12 00:43:54 +02:00
|
|
|
}
|
|
|
|
}
|