Пример #1
0
// BasicAuth returns an HTTP basic authentication middleware.
//
// For valid credentials it calls the next handler.
// For invalid credentials, it sends "401 - Unauthorized" response.
func BasicAuth(fn BasicValidateFunc) echo.MiddlewareFunc {
	return func(h echo.Handler) echo.Handler {
		return echo.HandlerFunc(func(c echo.Context) error {
			auth := c.Request().Header().Get(echo.HeaderAuthorization)
			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
							if fn(cred[:i], cred[i+1:]) {
								return nil
							}
						}
					}
				}
			}
			c.Response().Header().Set(echo.HeaderWWWAuthenticate, basic+" realm=Restricted")
			return echo.NewHTTPError(http.StatusUnauthorized)
		})
	}
}
Пример #2
0
// Recover returns a middleware which recovers from panics anywhere in the chain
// and handles the control to the centralized HTTPErrorHandler.
func Recover() echo.MiddlewareFunc {
	return func(h echo.Handler) echo.Handler {
		// TODO: Provide better stack trace `https://github.com/go-errors/errors` `https://github.com/docker/libcontainer/tree/master/stacktrace`
		return echo.HandlerFunc(func(c echo.Context) error {
			defer func() {
				if err := recover(); err != nil {
					trace := make([]byte, 1<<16)
					n := runtime.Stack(trace, true)
					c.Error(echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("panic recover\n %v\n stack trace %d bytes\n %s",
						err, n, trace[:n])))
				}
			}()
			return h.Handle(c)
		})
	}
}
Пример #3
0
func (c *Context) Errno(code int, args ...string) *echo.HTTPError {
	return echo.NewHTTPError(code, args...)
}