Ejemplo n.º 1
0
func InitPost(r *mux.Router) {
	l4g.Debug("Initializing post api routes")

	r.Handle("/posts/{post_id}", negroni.New(
		negroni.HandlerFunc(RequireAuth),
		negroni.HandlerFunc(getPost),
	)).Methods("GET")

	sr := r.PathPrefix("/channels/{id}").Subrouter()

	sr.Handle("/create", negroni.New(
		negroni.HandlerFunc(RequireAuth),
		negroni.HandlerFunc(createPost),
	)).Methods("POST")

	sr.Handle("/update", negroni.New(
		negroni.HandlerFunc(RequireAuth),
		negroni.HandlerFunc(updatePost),
	)).Methods("POST")

	// {offset:[0-9]+}/{limit:[0-9]+}
	sr.Handle("/posts/", negroni.New(
		negroni.HandlerFunc(RequireAuth),
		negroni.HandlerFunc(getPosts),
	)).Methods("GET")
}
Ejemplo n.º 2
0
func setupRouters(router *mux.Router, parentMiddleWare []http.HandlerFunc, routers []*Router) {
	if len(routers) == 0 {
		return
	}

	for _, rd := range routers {
		combinedMiddleWareHandlers := []http.HandlerFunc{}
		combinedMiddleWareHandlers = append(combinedMiddleWareHandlers, parentMiddleWare...)
		combinedMiddleWareHandlers = append(combinedMiddleWareHandlers, rd.middlewares...)

		panicOnZeroMethods := len(rd.subRouters) == 0 //Panic if we have no controller methods and also no subrouters
		for method, handler := range GetControllerMethods(rd.controller, panicOnZeroMethods) {
			for _, urlPart := range rd.urlParts {
				muxRoute := router.Handle(urlPart, newNegroniMiddleware(combinedMiddleWareHandlers, handler))
				muxRoute.Methods(method)
			}
		}

		if len(rd.urlParts) == 0 {
			setupRouters(router, combinedMiddleWareHandlers, rd.subRouters)
			continue
		}

		for _, urlPart := range rd.urlParts {
			var subRouterToUse *mux.Router
			if urlPart != "" {
				subRouterToUse = router.PathPrefix(urlPart).Subrouter()
			} else {
				subRouterToUse = router
			}
			setupRouters(subRouterToUse, combinedMiddleWareHandlers, rd.subRouters)
		}
	}
}
Ejemplo n.º 3
0
func staticFileRouter(r *mux.Router) *mux.Router {
	// static
	r.PathPrefix("/static/").Handler(http.StripPrefix("/static/",
		myFileHandler{http.FileServer(http.Dir(*staticPath))}))
	// bootstrap ui insists on loading templates from this path
	r.PathPrefix("/template/").Handler(http.StripPrefix("/template/",
		myFileHandler{http.FileServer(http.Dir(*staticPath))}))

	// application pages
	appPages := []string{
		"/overview",
		"/search",
		"/indexes",
		"/analysis",
		"/monitor",
	}

	for _, p := range appPages {
		// if you try to use index.html it will redirect...poorly
		r.PathPrefix(p).Handler(RewriteURL("/",
			http.FileServer(http.Dir(*staticPath))))
	}

	r.Handle("/", http.RedirectHandler("/static/index.html", 302))

	return r
}
Ejemplo n.º 4
0
func fileServeRoutes(router *mux.Router) {
	controller := controllers.NewFileServeController()

	router.Handle("/image/{folder}/{file}", negroni.New(
		negroni.HandlerFunc(controller.GetImage),
	)).Methods("GET")
}
Ejemplo n.º 5
0
func homeRoutes(router *mux.Router) {
	controller := controllers.NewHomeController()

	router.Handle("/", negroni.New(
		negroni.HandlerFunc(controller.Home),
	)).Methods("GET")
}
Ejemplo n.º 6
0
func authRoutes(router *mux.Router) {
	controller := controllers.NewAuthController()

	router.Handle("/login", negroni.New(
		negroni.HandlerFunc(controller.Login),
	)).Methods("POST")
}
Ejemplo n.º 7
0
// Routing ... list of routing services
func (c AccountRouter) Routing(router *mux.Router, apiprefix string) {
	baseModel := base.BaseModel{Status: "ACTIVE", CreatedAt: time.Now()}
	httpUtilFunc := utilFunc.HTTPUtilityFunctions{}
	account := controllers.AccountController{c.DataStore, baseModel, httpUtilFunc}

	router.Handle(apiprefix+"/accounts",
		negroni.New(
			negroni.HandlerFunc(authentication.RequireTokenAuthentication),
			negroni.HandlerFunc(account.CreateAccount),
		)).Methods("POST")

	router.Handle(apiprefix+"/account/categories",
		negroni.New(
			negroni.HandlerFunc(authentication.RequireTokenAuthentication),
			negroni.HandlerFunc(account.CreateAccount),
		)).Methods("POST")

	router.Handle(apiprefix+"/account/fundsource",
		negroni.New(
			negroni.HandlerFunc(authentication.RequireTokenAuthentication),
			negroni.HandlerFunc(account.CreateAccountCategory),
		)).Methods("POST")

	router.Handle(apiprefix+"/account/limit",
		negroni.New(
			negroni.HandlerFunc(authentication.RequireTokenAuthentication),
			negroni.HandlerFunc(account.CreateAccountLimit),
		)).Methods("POST")
	router.Handle(apiprefix+"/account/funding",
		negroni.New(
			negroni.HandlerFunc(authentication.RequireTokenAuthentication),
			negroni.HandlerFunc(account.CreateAccountFundMapping),
		)).Methods("POST")

}
func setupRouters(ctx *RouterContext.RouterContext, router *mux.Router, parentMiddleWare []HttpHandlerFunc, routeDefinitions []*RouteDefinition) {
	if len(routeDefinitions) == 0 {
		return
	}

	for _, rh := range routeDefinitions {
		var routerToUse *mux.Router
		if rh.prefix != "" {
			routerToUse = router.PathPrefix(rh.prefix).Subrouter()
		} else {
			routerToUse = router
		}

		combinedMiddleWareHandlers := []HttpHandlerFunc{}
		combinedMiddleWareHandlers = append(combinedMiddleWareHandlers, parentMiddleWare...)
		combinedMiddleWareHandlers = append(combinedMiddleWareHandlers, rh.middlewares...)

		for _, singleRouteDefinition := range rh.routeDefinitions {
			for method, h := range GetIRouteControllers(singleRouteDefinition) {
				muxRoute := routerToUse.Handle(singleRouteDefinition.GetPathPart(), newNegroniMiddleware(ctx, combinedMiddleWareHandlers, h))
				muxRoute.Methods(method)
			}
		}

		setupRouters(ctx, routerToUse, combinedMiddleWareHandlers, rh.subRoutes)
	}
}
Ejemplo n.º 9
0
func (me *endPoint) setupMuxHandlers(mux *mux.Router) {

	fn := handleIncoming(me)

	m := interpose.New()
	for i, _ := range me.modules {
		m.Use(me.modules[i])
		//fmt.Println("using module:", me.modules[i], reflect.TypeOf(me.modules[i]))
	}
	m.UseHandler(http.HandlerFunc(fn))

	if me.info.Version == "*" {
		mux.Handle(me.muxUrl, m).Methods(me.httpMethod)
	} else {
		urlWithVersion := cleanUrl(me.info.Prefix, "v"+me.info.Version, me.muxUrl)
		urlWithoutVersion := cleanUrl(me.info.Prefix, me.muxUrl)

		// versioned url
		mux.Handle(urlWithVersion, m).Methods(me.httpMethod)

		// content type (style1)
		header1 := fmt.Sprintf("application/%s-v%s+json", me.info.Vendor, me.info.Version)
		mux.Handle(urlWithoutVersion, m).Methods(me.httpMethod).Headers("Accept", header1)

		// content type (style2)
		header2 := fmt.Sprintf("application/%s+json;version=%s", me.info.Vendor, me.info.Version)
		mux.Handle(urlWithoutVersion, m).Methods(me.httpMethod).Headers("Accept", header2)
	}
}
Ejemplo n.º 10
0
func EventListenerRoutes(router *mux.Router) *mux.Router {
	router.Handle("/event",
		negroni.New(
			negroni.HandlerFunc(controllers.EventController),
		)).Methods("POST")

	return router
}
Ejemplo n.º 11
0
func QueryRoutes(router *mux.Router) *mux.Router {
	router.Handle("/query",
		negroni.New(
			negroni.HandlerFunc(controllers.QueryController),
		)).Methods("POST")

	return router
}
Ejemplo n.º 12
0
// Adds defaults routes, ping and status.
func addRoutes(r *mux.Router) {
	ping := handlers.RecoveryFunc(handlers.Ping)
	time := handlers.RecoveryFunc(handlers.Time)
	status := handlers.RecoveryFunc(handlers.Status)
	r.Handle("/status/", status).Methods("GET")
	r.Handle("/ping/", ping).Methods("GET")
	r.Handle("/time/", time).Methods("GET")
}
Ejemplo n.º 13
0
func InitWebSocket(r *mux.Router) {
	l4g.Debug("Initializing websocket api")
	r.Handle("/websocket/{uuid}", negroni.New(
		negroni.HandlerFunc(RequireAuthAndUser),
		negroni.HandlerFunc(connect),
	)).Methods("GET")
	hub.Start()
}
Ejemplo n.º 14
0
func SetOfferingRoutes(router *mux.Router) *mux.Router {
	router.Handle("/offering",
		negroni.New(
			negroni.HandlerFunc(authentication.RequireTokenAuthentication),
			negroni.HandlerFunc(controllers.OfferingListController),
		)).Methods("GET")

	return router
}
Ejemplo n.º 15
0
func SetHelloRoutes(router *mux.Router) *mux.Router {
	router.Handle("/test/check",
		negroni.New(
			negroni.HandlerFunc(authentication.RequireTokenAuthentication),
			negroni.HandlerFunc(controllers.HelloController),
		)).Methods("GET")

	return router
}
Ejemplo n.º 16
0
// NewBlog returns a new Blog instance.
func NewBlog(router *mux.Router, tplPath, postDir string,
	pageSize int) (blog *Blog) {
	blog = &Blog{Router: router, TplPath: tplPath,
		PostDir: postDir, PageSize: pageSize}
	// Hook up paths for the main blog and post permalinks.
	router.Handle("/", blog)
	router.Handle("/post/{year:[0-9]+}/{month:[0-9]+}/{day:[0-9]+}/{name}/",
		blog).Name("post")
	return
}
Ejemplo n.º 17
0
// RegisterHealthHandler will create a new HealthCheckHandler from the
// given config and add a handler to the given router.
func RegisterHealthHandler(cfg *config.Server, monitor *ActivityMonitor, mx *mux.Router) HealthCheckHandler {
	// register health check
	hch := NewHealthCheckHandler(cfg)
	err := hch.Start(monitor)
	if err != nil {
		Log.Fatal("unable to start the HealthCheckHandler: ", err)
	}
	mx.Handle(hch.Path(), hch)
	return hch
}
Ejemplo n.º 18
0
func (a *App) SetRoutes(router *mux.Router) error {
	// Load App specific routes
	a.LoadRoutes()

	// Create a router for defining the routes which require authenticationAuth_fix
	//For routes require auth, will be checked by a middleware which
	//return error immediately

	authReqdRouter := mux.NewRouter().StrictSlash(true)

	//create a negroni with LoginReqd middleware
	n := negroni.New(negroni.HandlerFunc(a.LoginRequired), negroni.Wrap(authReqdRouter))

	// Set routes for core which doesnot require authentication
	for _, route := range CORE_ROUTES_NOAUTH {
		if validApiVersion(route.Version) {
			urlPattern := fmt.Sprintf("%s/v%d/%s", DEFAULT_API_PREFIX, route.Version, route.Pattern)
			router.Methods(route.Method).Path(urlPattern).Name(route.Name).Handler(http.HandlerFunc(route.HandlerFunc))
		} else {
			logger.Get().Info("Skipped the route: %s as version: %d is un spported", route.Name, route.Version)
		}
	}

	// Set routes for core which require authentication
	for _, route := range CORE_ROUTES {
		if validApiVersion(route.Version) {
			urlPattern := fmt.Sprintf("%s/v%d/%s", DEFAULT_API_PREFIX, route.Version, route.Pattern)
			authReqdRouter.Methods(route.Method).Path(urlPattern).Name(route.Name).Handler(http.HandlerFunc(route.HandlerFunc))
			router.Handle(urlPattern, n)
		} else {
			logger.Get().Info("Skipped the route: %s as version: %d is un spported", route.Name, route.Version)
		}
	}

	//Set the provider specific routes here
	//All the provider specific routes are assumed to be authenticated
	for _, route := range a.routes {
		logger.Get().Debug("%s", route)
		if validApiVersion(route.Version) {
			urlPattern := fmt.Sprintf("%s/v%d/%s", DEFAULT_API_PREFIX, route.Version, route.Pattern)
			authReqdRouter.
				Methods(route.Method).
				Path(urlPattern).
				Name(route.Name).
				Handler(http.HandlerFunc(a.ProviderHandler))
			router.Handle(urlPattern, n)
		} else {
			logger.Get().Info("Skipped the route: %s as version: %d is un spported", route.Name, route.Version)
		}
	}

	return nil
}
Ejemplo n.º 19
0
Archivo: rpc.go Proyecto: pgm/gozzle
func InitRpc(r *mux.Router, filename string) {
	db := OpenDb(filename)

	logReqService := CreateLogRequestService()
	s := rpc.NewServer()
	s.RegisterCodec(json.NewCodec(), "application/json")
	s.RegisterService(logReqService, "Log")

	go logReqService.ApplyWithDb(db)

	r.Handle("/rpc", s)
}
Ejemplo n.º 20
0
func InitPost(r *mux.Router) {
	l4g.Debug("Initializing post api routes")

	r.Handle("/posts/search", ApiUserRequired(searchPosts)).Methods("GET")

	sr := r.PathPrefix("/channels/{id:[A-Za-z0-9]+}").Subrouter()
	sr.Handle("/create", ApiUserRequired(createPost)).Methods("POST")
	sr.Handle("/update", ApiUserRequired(updatePost)).Methods("POST")
	sr.Handle("/posts/{offset:[0-9]+}/{limit:[0-9]+}", ApiUserRequiredActivity(getPosts, false)).Methods("GET")
	sr.Handle("/posts/{time:[0-9]+}", ApiUserRequiredActivity(getPostsSince, false)).Methods("GET")
	sr.Handle("/post/{post_id:[A-Za-z0-9]+}", ApiUserRequired(getPost)).Methods("GET")
	sr.Handle("/post/{post_id:[A-Za-z0-9]+}/delete", ApiUserRequired(deletePost)).Methods("POST")
}
Ejemplo n.º 21
0
func RegisterHandlers(
	m *mux.Router,
	db db.DbManager,
	jar *sessions.CookieStore,
	dest string,
) {
	m.Handle("/api/auth/login", loginHandler(db, jar))
	m.Handle("/api/auth/register", registerHandler(db, jar))
	m.Handle("/api/auth/logout", logoutHandler(jar))
	m.Handle("/api/auth/status", statusHandler(jar))
	m.Handle("/api/files", fileHandler(db, jar, dest))
	m.Handle("/api/files/{hash}", singleFileHandler(db))
}
Ejemplo n.º 22
0
func (h *Handler) SetRoutes(r *mux.Router, extractor func(h hydcon.ContextHandler) hydcon.ContextHandler) {
	r.Handle("/oauth2/connections", hydcon.NewContextAdapter(
		context.Background(),
		extractor,
		h.m.IsAuthenticated,
		h.m.IsAuthorized(connectionsPermission, "create", nil),
	).ThenFunc(h.Create)).Methods("POST")

	r.Handle("/oauth2/connections", hydcon.NewContextAdapter(
		context.Background(),
		extractor,
		h.m.IsAuthenticated,
	).ThenFunc(h.Find)).Queries("subject", "{subject}").Methods("GET")

	r.Handle("/oauth2/connections/{id}", hydcon.NewContextAdapter(
		context.Background(),
		extractor,
		h.m.IsAuthenticated,
	).ThenFunc(h.Get)).Methods("GET")

	r.Handle("/oauth2/connections/{id}", hydcon.NewContextAdapter(
		context.Background(),
		extractor,
		h.m.IsAuthenticated,
	).ThenFunc(h.Delete)).Methods("DELETE")
}
Ejemplo n.º 23
0
func setupRestAPI(router *mux.Router, oAuth *oAuthHandler) {
	handler := rest.ResourceHandler{
		EnableRelaxedContentType: true,
		PreRoutingMiddlewares:    []rest.Middleware{oAuth},
	}
	handler.SetRoutes(
		&rest.Route{"GET", "/api/me", func(w rest.ResponseWriter, req *rest.Request) {
			data := context.Get(req.Request, USERDATA)
			w.WriteJson(&data)
		}},
	)

	router.Handle("/api/me", &handler)
}
Ejemplo n.º 24
0
func SetRequestRoutes(router *mux.Router) *mux.Router {
	router.Handle("/request",
		negroni.New(
			negroni.HandlerFunc(authentication.RequireTokenAuthentication),
			negroni.HandlerFunc(controllers.RequestListController),
		)).Methods("GET")
	router.Handle("/request",
		negroni.New(
			negroni.HandlerFunc(authentication.RequireTokenAuthentication),
			negroni.HandlerFunc(controllers.RequestShowController),
		)).Methods("POST")

	return router
}
Ejemplo n.º 25
0
func (h *Handler) SetRoutes(r *mux.Router, extractor func(h hctx.ContextHandler) hctx.ContextHandler) {
	r.Handle("/allowed", hctx.NewContextAdapter(
		context.Background(),
		extractor,
		h.m.IsAuthenticated,
	).ThenFunc(h.Granted)).Methods("POST")

	r.Handle("/policies", hctx.NewContextAdapter(
		context.Background(),
		extractor,
		h.m.IsAuthenticated,
		h.m.IsAuthorized("rn:hydra:policies", "create", nil),
	).ThenFunc(h.Create)).Methods("POST")

	//	r.Handle("/policies", hctx.NewContextAdapter(
	//		context.Background(),
	//		extractor,
	//		h.m.IsAuthenticated,
	//	).ThenFunc(h.FindBySubject)).Query("subject").Methods("GET")

	r.Handle("/policies/{id}", hctx.NewContextAdapter(
		context.Background(),
		extractor,
		h.m.IsAuthenticated,
	).ThenFunc(h.Get)).Methods("GET")

	r.Handle("/policies/{id}", hctx.NewContextAdapter(
		context.Background(),
		extractor,
		h.m.IsAuthenticated,
	).ThenFunc(h.Delete)).Methods("DELETE")
}
func SetAuthenticationRoutes(router *mux.Router) *mux.Router {
	router.HandleFunc("/token-auth", controllers.Login).Methods("POST")
	router.Handle("/refresh-token-auth",
		negroni.New(
			negroni.HandlerFunc(authentication.RequireTokenAuthentication),
			negroni.HandlerFunc(controllers.RefreshToken),
		)).Methods("GET")
	router.Handle("/logout",
		negroni.New(
			negroni.HandlerFunc(authentication.RequireTokenAuthentication),
			negroni.HandlerFunc(controllers.Logout),
		)).Methods("GET")
	return router
}
Ejemplo n.º 27
0
// InitStaticRouterEx is like InitStaticRouter, but with optional
// manager parameter for more options.
func InitStaticRouterEx(r *mux.Router, staticDir, staticETag string,
	pages []string, pagesHandler http.Handler,
	mgr *cbgt.Manager) *mux.Router {
	prefix := ""
	if mgr != nil {
		prefix = mgr.Options()["urlPrefix"]
	}

	PIndexTypesInitRouter(r, "static.before", mgr)

	var s http.FileSystem
	if staticDir != "" {
		if _, err := os.Stat(staticDir); err == nil {
			log.Printf("http: serving assets from staticDir: %s", staticDir)
			s = http.Dir(staticDir)
		}
	}
	if s == nil {
		log.Printf("http: serving assets from embedded data")
		s = AssetFS()
	}

	r.PathPrefix(prefix + "/static/").Handler(
		http.StripPrefix(prefix+"/static/",
			ETagFileHandler{http.FileServer(s), staticETag}))

	// Bootstrap UI insists on loading templates from this path.
	r.PathPrefix(prefix + "/template/").Handler(
		http.StripPrefix(prefix+"/template/",
			ETagFileHandler{http.FileServer(s), staticETag}))

	// If client ask for any of the pages, redirect.
	for _, p := range pages {
		if pagesHandler != nil {
			r.PathPrefix(p).Handler(pagesHandler)
		} else {
			r.PathPrefix(p).Handler(RewriteURL("/", http.FileServer(s)))
		}
	}

	r.Handle(prefix+"/index.html",
		http.RedirectHandler(prefix+"/static/index.html", 302))
	r.Handle(prefix+"/",
		http.RedirectHandler(prefix+"/static/index.html", 302))

	PIndexTypesInitRouter(r, "static.after", mgr)

	return r
}
Ejemplo n.º 28
0
func (lua *LuaExt) RegisterRoute(r *mux.Router, middlewares *serverMiddleware.SharedMiddleware) {
	r.Handle("/", middlewares.Auth(http.HandlerFunc(lua.AppsHandler())))
	r.Handle("/stats", middlewares.Auth(http.HandlerFunc(lua.AppStatsHandler())))
	r.Handle("/logs", middlewares.Auth(http.HandlerFunc(lua.AppLogsHandler())))
	r.Handle("/register", middlewares.Auth(http.HandlerFunc(lua.RegisterHandler())))
	// TODO(tsileo) "/remove" endpoint
	// TODO(tsileo) "/logstream" endpoint to stream logs (SSE)
}
Ejemplo n.º 29
0
func (app *Application) addAgentHandlers(router *mux.Router) *mux.Router {
	if app.IsAgentMode() {
		router.HandleFunc("/", handlers.AgentGetRoot).Methods("GET")
		router.HandleFunc("/config", handlers.AgentGetConfig).Methods("GET")
		router.HandleFunc("/config/pools", handlers.AgentGetConfigPools).Methods("GET")
		router.HandleFunc("/stats", handlers.AgentGetStats).Methods("GET")

		if !app.IsReadOnly() {
			MustLoginApi := middlewares.MustLoginApi

			router.Handle("/config", MustLoginApi(http.HandlerFunc(handlers.AgentPostConfig))).Methods("POST")
		}
	}
	return router
}
Ejemplo n.º 30
0
func (e *Endpoint) registerRoutes(r *mux.Router) {
	r.Handle(e.Uri, e.Middleware.ReadList.ThenFunc(e.HandleReadList)).Methods("GET")
	r.Handle(e.Uri+"/{id}", e.Middleware.ReadOne.ThenFunc(e.HandleReadOne)).Methods("GET")

	if !e.DisableWrites {
		r.Handle(e.Uri, e.Middleware.Create.ThenFunc(e.HandleCreate)).Methods("POST")

		r.Handle(e.Uri+"/{id}", e.Middleware.Update.ThenFunc(e.HandleUpdate)).Methods("PUT")
		r.Handle(e.Uri+"/{id}", e.Middleware.Delete.ThenFunc(e.HandleDelete)).Methods("DELETE")
	}

}