func (mw *AuthMiddleware) MiddlewareFunc(handler rest.HandlerFunc) rest.HandlerFunc {
	if mw.Realm == "" {
		log.Fatal("Realm is required")
	}
	return func(writer rest.ResponseWriter, request *rest.Request) {
		authHeader := request.Header.Get("Authorization")
		if authHeader == "" {
			request.Env["USER"] = nil
			handler(writer, request)
			return
		}
		emailOrKey, password, err := mw.decodeBasicAuthHeader(authHeader)
		if err != nil {
			rest.Error(writer, "Invalid authentication", http.StatusBadRequest)
			return
		}
		user, err := auth.Instance.Authenticate(emailOrKey, password)
		if err == nil {
			request.Env["USER"] = user
			handler(writer, request)
			return
		}
		log.Println("Unauthorized " + emailOrKey)
		mw.unauthorized(writer)
		return
	}
}
MiddlewareFunc makes AuthMiddleware implement the Middleware interface.
package api
import (
	"encoding/base64"
	"errors"
	"github.com/ant0ine/go-json-rest/rest"
	"github.com/openaccounting/oa-server/core/auth"
	"log"
	"net/http"
	"strings"
)
type AuthMiddleware struct {
	Realm string
}