Ejemplo n.º 1
0
Archivo: server.go Proyecto: ab22/abcd
// handleWithMiddlewares applies all middlewares to the specified route. Some
// middleware functions are applied depending on the route's properties, such
// as ValidateAuth and Authorize middlewares. These last 2 functions require
// that the route RequiresAuth() and that RequiredRoles() > 0.
func (s *Server) handleWithMiddlewares(route routes.Route) httputils.ContextHandler {
	return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		serverCtx := context.WithValue(ctx, "cookieStore", s.cookieStore)
		serverCtx = context.WithValue(serverCtx, "route", route)
		serverCtx = context.WithValue(serverCtx, "config", s.cfg)

		h := route.HandlerFunc()
		h = handlers.HandleHTTPError(h)
		h = handlers.GzipContent(h)

		if route.RequiresAuth() {
			if requiredRoles := route.RequiredRoles(); len(requiredRoles) > 0 {
				h = handlers.Authorize(h)
			}

			h = handlers.ValidateAuth(h)
		}

		return h(serverCtx, w, r)
	}
}