package web import ( "fmt" "gitlab.quimbo.fr/odwrtw/canape-sql/auth" "github.com/Sirupsen/logrus" "github.com/codegangsta/negroni" "github.com/gorilla/mux" "github.com/jmoiron/sqlx" "github.com/unrolled/render" ) // Env describes an environement object passed to all handlers type Env struct { Database *sqlx.DB Log *logrus.Entry Router *mux.Router Render *render.Render Auth *auth.Authorizer loginRoute string } // NewEnv returns a new *Env func NewEnv(db *sqlx.DB, auth *auth.Authorizer, log *logrus.Entry, templatesDir string) *Env { e := &Env{ Database: db, Log: log, Router: mux.NewRouter(), Auth: auth, } tmplFuncs = append(tmplFuncs, map[string]interface{}{ "URL": func(name string, pairs ...string) (string, error) { return e.GetURL(name, pairs...) }, }) e.Render = render.New(render.Options{ Directory: templatesDir, Layout: "layout", Funcs: tmplFuncs, DisableHTTPErrorRendering: true, RequirePartials: true, }) return e } // Handle add route func (e *Env) Handle(name, route string, H HandlerFunc) { e.Router.Handle(route, Handler{e, H}).Name(name) } // HandleRole add route and take care of user's role func (e *Env) HandleRole(name, route string, H HandlerFunc, role string) { e.Router.Handle(route, negroni.New( auth.NewMiddlewareRole(e.Auth, e.GetLoginRouteGetter(), role), negroni.Wrap(Handler{e, H}), )).Name(name) } // GetURL returns URL string from URL name and params // Usefull for redirection and templates func (e *Env) GetURL(name string, pairs ...string) (string, error) { route := e.Router.Get(name) if route == nil { return "", fmt.Errorf("No route find for the given name: %s", name) } URL, err := route.URL(pairs...) if err != nil { return "", err } return URL.String(), nil } // SetLoginRoute sets the route name of login page for further use // with GetLoginRouteGetter func (e *Env) SetLoginRoute(name string) error { route, err := e.GetURL(name) if err != nil { return err } e.loginRoute = route return nil } // GetLoginRouteGetter allow some code parts like middleware access // to login route name func (e *Env) GetLoginRouteGetter() func() string { return func() string { if e.loginRoute == "" { panic("Env: login route not set") } return e.loginRoute } }