2015-05-12 00:43:54 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
2015-07-05 15:21:05 +02:00
|
|
|
|
|
|
|
"github.com/labstack/echo"
|
2015-05-12 00:43:54 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
2016-03-20 00:47:20 +02:00
|
|
|
// BasicAuthConfig defines config for HTTP basic auth middleware.
|
2016-03-14 22:55:38 +02:00
|
|
|
BasicAuthConfig struct {
|
|
|
|
AuthFunc BasicAuthFunc
|
2016-02-18 07:01:47 +02:00
|
|
|
}
|
|
|
|
|
2016-03-20 00:47:20 +02:00
|
|
|
// BasicAuthFunc defines a function to validate basic auth credentials.
|
2016-02-18 07:01:47 +02:00
|
|
|
BasicAuthFunc func(string, string) bool
|
2015-05-12 00:43:54 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2016-02-08 09:02:37 +02:00
|
|
|
basic = "Basic"
|
2015-05-12 00:43:54 +02:00
|
|
|
)
|
|
|
|
|
2016-03-14 22:55:38 +02:00
|
|
|
var (
|
2016-03-20 00:47:20 +02:00
|
|
|
// DefaultBasicAuthConfig is the default basic auth middleware config.
|
2016-03-14 22:55:38 +02:00
|
|
|
DefaultBasicAuthConfig = BasicAuthConfig{}
|
|
|
|
)
|
|
|
|
|
2016-03-20 00:47:20 +02:00
|
|
|
// BasicAuth returns an HTTP basic auth middleware.
|
2015-06-10 05:06:51 +02:00
|
|
|
//
|
|
|
|
// For valid credentials it calls the next handler.
|
2015-05-21 23:02:29 +02:00
|
|
|
// For invalid credentials, it sends "401 - Unauthorized" response.
|
2016-03-19 05:02:02 +02:00
|
|
|
func BasicAuth(f BasicAuthFunc) echo.MiddlewareFunc {
|
2016-03-14 22:55:38 +02:00
|
|
|
c := DefaultBasicAuthConfig
|
2016-03-19 05:02:02 +02:00
|
|
|
c.AuthFunc = f
|
2016-03-14 22:55:38 +02:00
|
|
|
return BasicAuthFromConfig(c)
|
|
|
|
}
|
|
|
|
|
2016-03-20 00:47:20 +02:00
|
|
|
// BasicAuthFromConfig returns an HTTP basic auth middleware from config.
|
|
|
|
// See `BasicAuth()`.
|
2016-03-14 22:55:38 +02:00
|
|
|
func BasicAuthFromConfig(config BasicAuthConfig) echo.MiddlewareFunc {
|
2016-02-19 08:50:40 +02:00
|
|
|
return func(next echo.Handler) echo.Handler {
|
2016-02-18 07:49:31 +02:00
|
|
|
return echo.HandlerFunc(func(c echo.Context) error {
|
|
|
|
auth := c.Request().Header().Get(echo.Authorization)
|
|
|
|
l := len(basic)
|
|
|
|
|
|
|
|
if len(auth) > l+1 && auth[:l] == basic {
|
|
|
|
b, err := base64.StdEncoding.DecodeString(auth[l+1:])
|
|
|
|
if err == nil {
|
|
|
|
cred := string(b)
|
|
|
|
for i := 0; i < len(cred); i++ {
|
|
|
|
if cred[i] == ':' {
|
|
|
|
// Verify credentials
|
2016-03-14 22:55:38 +02:00
|
|
|
if config.AuthFunc(cred[:i], cred[i+1:]) {
|
2016-03-12 13:54:54 +02:00
|
|
|
return next.Handle(c)
|
2016-02-18 07:49:31 +02:00
|
|
|
}
|
2015-05-12 00:43:54 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2016-02-18 07:49:31 +02:00
|
|
|
c.Response().Header().Set(echo.WWWAuthenticate, basic+" realm=Restricted")
|
2016-03-12 20:18:40 +02:00
|
|
|
return echo.ErrUnauthorized
|
2016-02-18 07:49:31 +02:00
|
|
|
})
|
|
|
|
}
|
2015-06-10 05:06:51 +02:00
|
|
|
}
|