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-15 21:29:14 +02:00
|
|
|
// BasicAuth provides HTTP basic authentication.
|
2015-05-12 00:43:54 +02:00
|
|
|
func BasicAuth(fn AuthFunc) echo.HandlerFunc {
|
|
|
|
return func(c *echo.Context) (he *echo.HTTPError) {
|
|
|
|
auth := c.Request.Header.Get(echo.Authorization)
|
|
|
|
i := 0
|
|
|
|
he = &echo.HTTPError{Code: http.StatusUnauthorized}
|
|
|
|
|
|
|
|
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' {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if c != Basic[i] {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// Extract credentials
|
|
|
|
b, err := base64.StdEncoding.DecodeString(auth[i:])
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
cred := string(b)
|
|
|
|
for i := 0; i < len(cred); i++ {
|
|
|
|
if cred[i] == ':' {
|
|
|
|
// Verify credentials
|
|
|
|
if !fn(cred[:i], cred[i+1:]) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-05-12 05:51:34 +02:00
|
|
|
return
|
2015-05-12 00:43:54 +02:00
|
|
|
}
|
|
|
|
}
|