1
0
mirror of https://github.com/labstack/echo.git synced 2026-05-16 09:48:24 +02:00

initial commit

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana
2015-03-01 09:45:13 -08:00
commit 7c9a0b6489
17 changed files with 1619 additions and 0 deletions
+69
View File
@@ -0,0 +1,69 @@
package middleware
import (
"encoding/base64"
"errors"
"strings"
"github.com/dgrijalva/jwt-go"
"github.com/labstack/bolt"
)
type (
BasicAuthFunc func(usr, pwd string) bool
AuthorizedHandler bolt.HandlerFunc
UnauthorizedHandler func(c *bolt.Context, err error)
JwtKeyFunc func(kid string) ([]byte, error)
Claims map[string]interface{}
)
var (
ErrBasicAuth = errors.New("bolt: basic auth error")
ErrJwtAuth = errors.New("bolt: jwt auth error")
)
func BasicAuth(ah AuthorizedHandler, uah UnauthorizedHandler, fn BasicAuthFunc) bolt.HandlerFunc {
return func(c *bolt.Context) {
auth := strings.Fields(c.Request.Header.Get("Authorization"))
if len(auth) == 2 {
scheme := auth[0]
s, err := base64.StdEncoding.DecodeString(auth[1])
if err != nil {
uah(c, err)
return
}
cred := strings.Split(string(s), ":")
if scheme == "Basic" && len(cred) == 2 {
if ok := fn(cred[0], cred[1]); ok {
ah(c)
return
}
}
}
uah(c, ErrBasicAuth)
}
}
func JwtAuth(ah AuthorizedHandler, uah UnauthorizedHandler, fn JwtKeyFunc) bolt.HandlerFunc {
return func(c *bolt.Context) {
auth := strings.Fields(c.Request.Header.Get("Authorization"))
if len(auth) == 2 {
t, err := jwt.Parse(auth[1], func(token *jwt.Token) (interface{}, error) {
if kid := token.Header["kid"]; kid != nil {
return fn(kid.(string))
}
return fn("")
})
if t.Valid {
c.Set("claims", Claims(t.Claims))
ah(c)
c.Next()
} else {
// TODO: capture errors
uah(c, err)
}
return
}
uah(c, ErrJwtAuth)
}
}
+32
View File
@@ -0,0 +1,32 @@
package middleware
import (
"log"
"time"
"github.com/labstack/bolt"
"labstack.com/common/utils"
)
func Logger() bolt.HandlerFunc {
return func(c *bolt.Context) {
start := time.Now()
c.Next()
end := time.Now()
color := utils.Green
m := c.Request.Method
p := c.Request.URL.Path
s := c.Response.Status()
switch {
case s >= 500:
color = utils.Red
case s >= 400:
color = utils.Yellow
case s >= 300:
color = utils.Cyan
}
log.Printf("%s %s %s %s", m, p, color(s), end.Sub(start))
}
}
+1
View File
@@ -0,0 +1 @@
package middleware