func newNegroniMiddleware(ctx *RouterContext, middleWareFuncs []http.HandlerFunc, controllerMethod ControllerMethod) *negroni.Negroni {
	negroniHandlers := []negroni.Handler{}
	for ind, _ := range middleWareFuncs {
		negroniHandlers = append(negroniHandlers, negroni.Wrap(middleWareFuncs[ind]))
	}
	negroniHandlers = append(negroniHandlers, negroni.Wrap(createHttpHandlerFunc(ctx, controllerMethod)))
	return negroni.New(negroniHandlers...)
}
func newNegroniMiddleware(middleWareFuncs []http.HandlerFunc, controllerMethod http.HandlerFunc) *negroni.Negroni {
	negroniHandlers := []negroni.Handler{}
	for ind, _ := range middleWareFuncs {
		negroniHandlers = append(negroniHandlers, negroni.Wrap(middleWareFuncs[ind]))
	}
	negroniHandlers = append(negroniHandlers, negroni.Wrap(http.HandlerFunc(controllerMethod)))
	return negroni.New(negroniHandlers...)
}
Example #3
0
func Init(apps map[string]interface{}, router *mux.Router) {
	Applications = apps

	// /echo/* Endpoints
	echoRouter := mux.NewRouter()
	// /* Endpoints
	pageRouter := mux.NewRouter()

	for uri, meta := range Applications {
		switch app := meta.(type) {
		case EchoApplication:
			handlerFunc := func(w http.ResponseWriter, r *http.Request) {
				echoReq := r.Context().Value("echoRequest").(*EchoRequest)
				echoResp := NewEchoResponse()

				if echoReq.GetRequestType() == "LaunchRequest" {
					if app.OnLaunch != nil {
						app.OnLaunch(echoReq, echoResp)
					}
				} else if echoReq.GetRequestType() == "IntentRequest" {
					if app.OnIntent != nil {
						app.OnIntent(echoReq, echoResp)
					}
				} else if echoReq.GetRequestType() == "SessionEndedRequest" {
					if app.OnSessionEnded != nil {
						app.OnSessionEnded(echoReq, echoResp)
					}
				} else {
					http.Error(w, "Invalid request.", http.StatusBadRequest)
				}

				json, _ := echoResp.String()
				w.Header().Set("Content-Type", "application/json;charset=UTF-8")
				w.Write(json)
			}

			if app.Handler != nil {
				handlerFunc = app.Handler
			}

			echoRouter.HandleFunc(uri, handlerFunc).Methods("POST")
		case StdApplication:
			pageRouter.HandleFunc(uri, app.Handler).Methods(app.Methods)
		}
	}

	router.PathPrefix("/echo/").Handler(negroni.New(
		negroni.HandlerFunc(validateRequest),
		negroni.HandlerFunc(verifyJSON),
		negroni.Wrap(echoRouter),
	))

	router.PathPrefix("/").Handler(negroni.New(
		negroni.Wrap(pageRouter),
	))
}
Example #4
0
func main() {
	flag.Parse()

	store.Init()

	p := func(name string, handler http.HandlerFunc) http.Handler {
		return prometheus.InstrumentHandler(name, handler)
	}

	router := mux.NewRouter()
	router.Handle("/metrics", prometheus.Handler())
	router.Handle("/", p("/", home))
	router.Handle("/login", p("/login", login))
	router.Handle("/verify", p("/verify", verify))

	apiRouter := mux.NewRouter()
	apiRouter.Handle("/api/logout", p("/logout", logout))
	apiRouter.Handle("/api/user", p("/user", user))
	apiRouter.Handle("/api/user/project", p("/user/project", userProject))
	apiRouter.Handle("/api/project", p("/project", project))
	apiRouter.Handle("/api/project/member", p("/task/member", member))
	apiRouter.Handle("/api/task", p("/task", task))
	apiRouter.Handle("/api/task/worker", p("/task/worker", worker))
	apiRouter.Handle("/api/milestone", p("/milestone", milestone))
	apiRouter.Handle("/api/friend", p("/friend", friend))
	apiRouter.Handle("/api/chat", p("/chat", chat))
	apiRouter.HandleFunc("/api/ws", ws)
	router.PathPrefix("/api").Handler(negroni.New(
		negroni.HandlerFunc(apiMiddleware),
		negroni.Wrap(apiRouter),
	))

	adminRouter := mux.NewRouter()
	adminRouter.Handle("/api/admin/user", p("/admin/user", adminUser))
	adminRouter.Handle("/api/admin/project", p("/admin/project", adminProject))
	router.PathPrefix("/api/admin").Handler(negroni.New(
		negroni.HandlerFunc(adminMiddleware),
		negroni.Wrap(adminRouter),
	))

	go h.run()

	n := negroni.Classic()
	n.UseHandler(router)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	n.Run(":" + port)
}
Example #5
0
func main() {
	var err error
	db, err = sqlx.Connect("postgres", "user=postgres password=postgres dbname=messenger sslmode=disable")
	if err != nil {
		log.Fatalln(err)
	}
	CreateSchema(false)

	r := mux.NewRouter()
	authBase := mux.NewRouter()
	apiBase := mux.NewRouter()
	auth := authBase.PathPrefix("/auth").Subrouter()
	api := apiBase.PathPrefix("/api").Subrouter()

	r.PathPrefix("/auth").Handler(negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
		negroni.Wrap(authBase),
	))

	jwtSecret = "a very secret string"
	// must be authenticated to  use api routes
	jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
		ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
			return []byte(jwtSecret), nil
		},
		SigningMethod: jwt.SigningMethodHS256,
		UserProperty:  "jwt_user",
	})
	r.PathPrefix("/api").Handler(negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
		negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
		negroni.Wrap(apiBase),
	))

	// used to check if server is live
	auth.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "pong")
	}).Methods("POST")

	auth.Path("/signup").HandlerFunc(Signup).Methods("POST")
	auth.Path("/login").HandlerFunc(Login).Methods("POST")

	api.Path("/messages").HandlerFunc(NewMessage).Methods("POST")
	api.HandleFunc("/{user}/messages", GetUsersMessages).Methods("GET")

	log.Fatal(http.ListenAndServe(":8080", r))

}
Example #6
0
// AddRoutes adds routes to a router instance. If there are middlewares defined
// for a route, a new negroni app is created and wrapped as a http.Handler
func AddRoutes(routes []Route, router *mux.Router) {
	var (
		handler http.Handler
		n       *negroni.Negroni
	)

	for _, route := range routes {
		// Add any specified middlewares
		if len(route.Middlewares) > 0 {
			n = negroni.New()

			for _, middleware := range route.Middlewares {
				n.Use(middleware)
			}

			// Wrap the handler in the negroni app with middlewares
			n.Use(negroni.Wrap(route.HandlerFunc))
			handler = n
		} else {
			handler = route.HandlerFunc
		}

		router.Methods(route.Method).
			Path(route.Pattern).
			Name(route.Name).
			Handler(handler)
	}
}
Example #7
0
func serverRun(cmd *cobra.Command, args []string) {
	// MongoDB setup
	CreateUniqueIndexes()
	// Web Server Setup
	CreateStore()
	webRouter := CreateWebRouter()
	teamRouter := CreateTeamRouter()

	app := negroni.New()
	webRouter.PathPrefix("/").Handler(negroni.New(
		negroni.HandlerFunc(RequireLogin),
		negroni.Wrap(teamRouter),
	))
	app.Use(negroni.NewLogger())
	app.Use(negroni.NewStatic(http.Dir("static")))
	app.Use(negroni.HandlerFunc(CheckSessionID))

	app.UseHandler(webRouter)

	l := log.New(os.Stdout, "[negroni] ", 0)
	http_port := viper.GetString("server.http_port")
	https_port := viper.GetString("server.https_port")
	cert := viper.GetString("server.cert")
	key := viper.GetString("server.key")

	l.Printf("Server running at: https://%s:%s", viper.GetString("server.ip"), https_port)

	go http.ListenAndServe(":"+http_port, http.HandlerFunc(redir))

	l.Fatal(http.ListenAndServeTLS(":"+https_port, cert, key, app))
}
Example #8
0
func (ea *EventApi) Init(cfg map[string]*json.RawMessage) (err error) {
	// setup the routes
	ea.router = httprouter.New()
	ea.router.GET("/", middleware.Join(
		s.Server.ErrorWrap.Do(ea.list),
		s.Server.CheckPerms("superuser", SESSION_EXPIRE)))
	ea.router.POST("/", middleware.Join(
		s.Server.ErrorWrap.Do(ea.post),
		s.Server.CheckPerms("superuser", SESSION_EXPIRE)))

	ea.router.GET("/:id", middleware.Join(
		s.Server.ErrorWrap.Do(ea.get),
		s.Server.CheckPerms("(superuser|admin-auth-event-${id})", SESSION_EXPIRE)))
	ea.router.DELETE("/:id", middleware.Join(
		s.Server.ErrorWrap.Do(ea.delete),
		s.Server.CheckPerms("superuser", SESSION_EXPIRE)))

	// setup prepared sql queries
	if ea.insertStmt, err = s.Server.Db.PrepareNamed("INSERT INTO event (name, auth_method, auth_method_config) VALUES (:name, :auth_method, :auth_method_config) RETURNING id"); err != nil {
		return
	}

	if ea.getStmt, err = s.Server.Db.Preparex("SELECT * FROM event WHERE id = $1"); err != nil {
		return
	}

	if ea.delStmt, err = s.Server.Db.Preparex("DELETE FROM event WHERE id = $1"); err != nil {
		return
	}

	// add the routes to the server
	handler := negroni.New(negroni.Wrap(ea.router))
	s.Server.Mux.OnMux("api/v1/event", handler)
	return
}
Example #9
0
func (a *Api) Run() error {
	globalMux := http.NewServeMux()

	router := mux.NewRouter()
	router.HandleFunc("/", a.index).Methods("GET")
	router.HandleFunc("/create", a.create).Methods("POST")
	router.HandleFunc("/ip", a.getIP).Methods("GET")
	router.HandleFunc("/state", a.getState).Methods("GET")
	router.HandleFunc("/start", a.start).Methods("GET")
	router.HandleFunc("/kill", a.kill).Methods("GET")
	router.HandleFunc("/remove", a.remove).Methods("GET")
	router.HandleFunc("/restart", a.restart).Methods("GET")
	router.HandleFunc("/stop", a.stop).Methods("GET")
	// enable auth if token is present
	if a.config.AuthToken != "" {
		am := auth.NewAuthMiddleware(a.config.AuthToken)
		globalMux.Handle("/", negroni.New(
			negroni.HandlerFunc(am.Handler),
			negroni.Wrap(http.Handler(router)),
		))
	} else {

		globalMux.Handle("/", router)
	}

	log.Infof("rivet version %s", version.FULL_VERSION)
	log.Infof("listening: addr=%s", a.config.ListenAddr)
	n := negroni.New()
	n.UseHandler(globalMux)
	return http.ListenAndServe(a.config.ListenAddr, n)
}
Example #10
0
func SetAuthenticationRoutes(router *mux.Router) *mux.Router {

	tokenRouter := mux.NewRouter()

	tokenRouter.Handle("/api/auth/token/new", negroni.New(
		negroni.HandlerFunc(controllers.Login),
	)).Methods("POST")

	tokenRouter.Handle("/api/auth/logout", negroni.New(
		negroni.HandlerFunc(auth.RequireTokenAuthentication),
		negroni.HandlerFunc(controllers.Logout),
	))

	tokenRouter.Handle("/api/auth/token/refresh", negroni.New(
		negroni.HandlerFunc(auth.RequireTokenAuthentication),
		negroni.HandlerFunc(controllers.RefreshToken),
	)).Methods("GET")

	tokenRouter.Handle("/api/auth/token/validate", negroni.New(
		negroni.HandlerFunc(auth.RequireTokenAuthentication),
		negroni.HandlerFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
			w.WriteHeader(http.StatusOK)
		}),
	))

	router.PathPrefix("/api/auth").Handler(negroni.New(
		negroni.Wrap(tokenRouter),
	))

	return router
}
Example #11
0
func main() {
	router := http.NewServeMux()
	// links our `api/admin` route to our protected handler
	router.HandleFunc("/api/login", controllers.AuthHandler)
	router.Handle("/api/users", negroni.New(
		negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
		negroni.Wrap(http.HandlerFunc(controllers.UsersHandler)),
	))
	router.Handle("/api/authenticated", negroni.New(
		negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
		negroni.Wrap(http.HandlerFunc(controllers.AuthenticateHandler)),
	))
	// serves the static files for angular js application as well as all other resources
	router.Handle("/", http.FileServer(http.Dir("./static/")))
	http.ListenAndServe(":8080", router)
}
Example #12
0
// main is the entry point for lagann
func main() {
	flag.Parse()

	client = etcd.NewClient([]string{"http://" + *etcdmachine + ":4001"})

	routing := http.NewServeMux()
	usermux := routes.New()

	n := negroni.Classic()
	n.UseHandler(routing)

	routing.HandleFunc(constants.ROOT_MUXPATH, root)
	routing.HandleFunc(constants.REGISTER_URL, register)
	routing.HandleFunc(constants.LOGIN_URL, login)

	usermux.Post(constants.APP_CREATE_URL, createApp)
	usermux.Post(constants.APP_SHARING_URL, addSharing)

	auth, _ := auth.NewAuth("http://"+*etcdmachine+":4001", constants.ETCD_LAGANN_AUTHKEYS)

	routing.Handle(constants.USER_MUXPATH, negroni.New(
		auth,
		negroni.Wrap(usermux),
	))

	n.Run(":3000")
}
Example #13
0
// BuildRoutes returns the routes for the application.
func BuildRoutes() http.Handler {
	router := mux.NewRouter()

	router.HandleFunc("/", HomeHandler)
	router.HandleFunc("/login-success", LoginSuccessHandler)
	router.HandleFunc("/verify", VerifyHandler)
	router.HandleFunc("/logout", LogoutHandler)
	router.HandleFunc("/game", GameHandler)

	// profile routes with LoginRequiredMiddleware
	profileRouter := mux.NewRouter()
	profileRouter.HandleFunc("/profile", ProfileHandler)

	router.PathPrefix("/profile").Handler(negroni.New(
		negroni.HandlerFunc(LoginRequiredMiddleware),
		negroni.Wrap(profileRouter),
	))

	// apply the base middleware to the main router
	n := negroni.New(
		negroni.HandlerFunc(CsrfMiddleware),
		negroni.HandlerFunc(UserMiddleware),
	)
	n.UseHandler(router)

	return n
}
Example #14
0
func router(config clientConfig) *mux.Router {
	r := mux.NewRouter()
	r.HandleFunc("/", indexHandler(config))
	r.Handle("/favicon.ico", http.NotFoundHandler())

	authMiddleware := negroni.HandlerFunc(ShotgunAuthMiddleware(config))

	entityRoutes := mux.NewRouter()
	entityRoutes.Path("/{entity_type}/{id:[0-9]+}").HandlerFunc(entityGetHandler(config)).Methods("GET")
	entityRoutes.Path("/{entity_type}/{id:[0-9]+}").HandlerFunc(entityUpdateHandler(config)).Methods("PATCH")
	entityRoutes.Path("/{entity_type}/{id:[0-9]+}").
		HandlerFunc(entityDeleteHandler(config)).Methods("DELETE")
	entityRoutes.Path("/{entity_type}/{id:[0-9]+}/revive").
		HandlerFunc(entityReviveHandler(config)).Methods("POST")
	// entityRoutes.Path("/{entity_type}/{id:[0-9]+}/followers").
	// 	HandlerFunc(entityGetFollowersHandler(config)).Methods("GET")
	//entityRoutes.Path("/{entity_type}/{id:[0-9]+}/followers").
	//             HandlerFunc(entityAddFollowersHandler(config)).Methods("POST")
	//entityRoutes.Path("/{entity_type}/{id:[0-9]+}/followers/{user_type}/{user_id:[0-9]+}").
	//		       HandlerFunc(entityDeleteFollowersHandler(config)).Methods("DELETE")
	entityRoutes.Path("/{entity_type}").HandlerFunc(entityGetAllHandler(config)).Methods("GET")
	entityRoutes.Path("/{entity_type}").HandlerFunc(entityCreateHandler(config)).Methods("POST")

	// Adds auth on the sub router so that / can be accessed freely.
	r.PathPrefix("/{entity_type}").Handler(negroni.New(
		authMiddleware,
		negroni.Wrap(entityRoutes),
	))

	return r
}
Example #15
0
func StaticPathFallback(path string) http.Handler {
	return negroni.New(
		negroni.NewStatic(http.Dir(path)),
		negroni.Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			r.URL.Path = "/"
			http.FileServer(http.Dir(path)).ServeHTTP(w, r)
		})))
}
Example #16
0
func NewApi(store account.Storable, pubsub account.PubSub) *Api {
	api := &Api{router: NewRouter(), auth: auth.NewAuth(store), Events: make(chan Event, DEFAULT_EVENTS_CHANNEL_LEN)}
	api.Storage(store)
	api.PubSub(pubsub)

	api.router.NotFoundHandler(http.HandlerFunc(api.notFoundHandler))
	api.router.AddHandler(RouterArguments{Path: "/", Methods: []string{"GET"}, Handler: homeHandler})

	//  Auth (login, logout, signup)
	api.router.AddHandler(RouterArguments{Path: "/auth/login", Methods: []string{"POST"}, Handler: api.userLogin})
	api.router.AddHandler(RouterArguments{Path: "/auth/logout", Methods: []string{"DELETE"}, Handler: api.userLogout})
	api.router.AddHandler(RouterArguments{Path: "/auth/signup", Methods: []string{"POST"}, Handler: api.userSignup})
	api.router.AddHandler(RouterArguments{Path: "/auth/password", Methods: []string{"PUT"}, Handler: api.userChangePassword})

	// Middlewares
	private := api.router.AddSubrouter("/api")
	api.router.AddMiddleware("/api", negroni.New(
		negroni.NewRecovery(),
		negroni.HandlerFunc(api.errorMiddleware),
		negroni.HandlerFunc(api.requestIdMiddleware),
		negroni.HandlerFunc(api.authorizationMiddleware),
		negroni.HandlerFunc(api.contextClearerMiddleware),
		negroni.Wrap(private),
	))

	// Users
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/users", Methods: []string{"DELETE"}, Handler: api.userDelete})

	// Teams
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/teams", Methods: []string{"POST"}, Handler: authorizationRequiredHandler(api.teamCreate)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/teams", Methods: []string{"GET"}, Handler: authorizationRequiredHandler(api.teamList)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/teams/{alias}", Methods: []string{"PUT"}, Handler: authorizationRequiredHandler(api.teamUpdate)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/teams/{alias}", Methods: []string{"DELETE"}, Handler: authorizationRequiredHandler(api.teamDelete)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/teams/{alias}", Methods: []string{"GET"}, Handler: authorizationRequiredHandler(api.teamInfo)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/teams/{alias}/users", Methods: []string{"PUT"}, Handler: authorizationRequiredHandler(api.teamAddUsers)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/teams/{alias}/users", Methods: []string{"DELETE"}, Handler: authorizationRequiredHandler(api.teamRemoveUsers)})

	// Services
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/services", Methods: []string{"POST"}, Handler: authorizationRequiredHandler(api.serviceCreate)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/services", Methods: []string{"GET"}, Handler: authorizationRequiredHandler(api.serviceList)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/services/{subdomain}", Methods: []string{"GET"}, Handler: authorizationRequiredHandler(api.serviceInfo)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/services/{subdomain}", Methods: []string{"DELETE"}, Handler: authorizationRequiredHandler(api.serviceDelete)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/services/{subdomain}", Methods: []string{"PUT"}, Handler: authorizationRequiredHandler(api.serviceUpdate)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/services/{subdomain}/plugins", Methods: []string{"PUT"}, Handler: authorizationRequiredHandler(api.pluginSubsribe)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/services/{subdomain}/plugins/{plugin_name}", Methods: []string{"DELETE"}, Handler: authorizationRequiredHandler(api.pluginUnsubsribe)})

	// Apps
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/apps", Methods: []string{"POST"}, Handler: authorizationRequiredHandler(api.appCreate)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/apps/{client_id}", Methods: []string{"DELETE"}, Handler: authorizationRequiredHandler(api.appDelete)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/apps/{client_id}", Methods: []string{"GET"}, Handler: authorizationRequiredHandler(api.appInfo)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/apps/{client_id}", Methods: []string{"PUT"}, Handler: authorizationRequiredHandler(api.appUpdate)})

	// Hooks
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/hooks", Methods: []string{"PUT"}, Handler: authorizationRequiredHandler(api.hookSave)})
	api.router.AddHandler(RouterArguments{PathPrefix: "/api", Path: "/hooks/{name}", Methods: []string{"DELETE"}, Handler: authorizationRequiredHandler(api.hookDelete)})

	return api
}
Example #17
0
func Router(cfg config.Config) http.Handler {
	r := mux.NewRouter()

	RegisterRoutes(r, cfg)

	return negroni.New(
		negroni.Wrap(r),
	)
}
Example #18
0
func RegisterRoutes(r *mux.Router, cfg config.Config) {
	routes := gen.BuildRoutes()
	jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
		ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
			return []byte(cfg.Secret), nil
		},
		// When set, the middleware verifies that tokens are signed with the specific signing algorithm
		// If the signing method is not constant the ValidationKeyGetter callback can be used to implement additional checks
		// Important to avoid security issues described here: https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
		SigningMethod: jwt.SigningMethodHS256,
	})

	corsMlw := cors.New(cors.Options{
		AllowedOrigins:     cfg.CORSAllowedOrigins,
		AllowedMethods:     cfg.CORSAllowedMethods,
		AllowedHeaders:     cfg.CORSAllowedHeaders,
		ExposedHeaders:     cfg.CORSExposedHeaders,
		AllowCredentials:   cfg.CORSAllowCredentials,
		MaxAge:             cfg.CORSMaxAge,
		OptionsPassthrough: cfg.CORSOptionsPassThrough,
		Debug:              cfg.CORSDebug,
	})

	for _, rt := range routes {
		apiRouter := mux.NewRouter().StrictSlash(true)
		for _, route := range rt.Routes {
			handlerFunc := negroni.New()

			// Add CORS middleware
			handlerFunc.Use(corsMlw)

			// Add JWT middleware if route is protected
			if route.Protected {
				handlerFunc.Use(negroni.HandlerFunc(jwtMiddleware.HandlerWithNext))
			}

			apiRouter.
				Methods(route.Method...).
				Name(route.Name).
				Path(fmt.Sprintf("%s%s", rt.BasePattern, route.Pattern)).
				Queries(route.Queries...).
				HandlerFunc(route.HandlerFunc)

			// Add actual handler
			handlerFunc.Use(negroni.Wrap(apiRouter))
			r.PathPrefix(rt.BasePattern).Handler(handlerFunc)

			ctxLog.WithField("base-path", rt.BasePattern).
				WithField("protected", route.Protected).
				WithField("name", route.Name).
				WithField("path", fmt.Sprintf("%s%s", rt.BasePattern, route.Pattern)).
				WithField("method", route.Method).
				WithField("query", fmt.Sprintf("%+v", route.Queries)).
				Debugf("%+v", route)
		}
	}
}
Example #19
0
func (self *Server) Serve() error {
	self.mux = http.NewServeMux()
	self.router = httprouter.New()

	self.RoutePrefix = strings.TrimSuffix(self.RoutePrefix, `/`)

	// load route handlers
	if err := self.LoadRoutes(); err != nil {
		return err
	}

	staticHandler := negroni.NewStatic(self.MountProxy)

	if self.RoutePrefix != DEFAULT_ROUTE_PREFIX {
		staticHandler.Prefix = self.RoutePrefix
	}

	self.mux.HandleFunc(`/_bindings`, func(w http.ResponseWriter, req *http.Request) {
		if req.URL.Path == `/_bindings` {
			if data, err := json.Marshal(self.Config.Bindings); err == nil {
				w.Header().Set(`Content-Type`, `application/json`)

				if _, err := w.Write(data); err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
			} else {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}
	})

	// add custom http.Handlers to the mux
	for i, handler := range self.Handlers {
		log.Debugf("Setting up custom handler %d for pattern '%s'", i, handler.Pattern)
		self.mux.Handle(handler.Pattern, handler.Handler)
	}

	// add custom http.HandleFuncs to the mux
	for i, handleFunc := range self.HandleFuncs {
		log.Debugf("Setting up custom handler function %d for pattern '%s'", i, handleFunc.Pattern)
		self.mux.HandleFunc(handleFunc.Pattern, handleFunc.HandleFunc)
	}

	// fallback to httprouter (these are the routes defined in the configuration)
	self.mux.Handle(`/`, self.router)

	self.server = negroni.New()
	self.server.Use(negroni.NewRecovery())
	self.server.Use(staticHandler)
	self.server.Use(negroni.Wrap(self.mux))

	self.server.Run(fmt.Sprintf("%s:%d", self.Address, self.Port))
	return nil
}
Example #20
0
func (s *Server) RouteGroup(path string, routing func(*Group)) {
	g := &Group{
		PathPrefix: s.PathPrefix + path,
		Router:     mux.NewRouter(),
		Negroni:    negroni.New(),
	}
	routing(g)
	g.Negroni.Use(negroni.Wrap(g.Router))
	s.Router.PathPrefix(s.PathPrefix + path).Handler(g.Negroni)
}
Example #21
0
func NewRouter() *mux.Router {
	router := mux.NewRouter().StrictSlash(true)

	jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
		ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
			decoded, err := base64.URLEncoding.DecodeString(os.Getenv("AUTH0_CLIENT_SECRET"))
			if err != nil {
				return nil, err
			}
			return decoded, nil
		},
	})

	for _, route := range routes {
		var handler http.Handler

		handler = route.HandlerFunc
		handler = Logger(handler, route.Name)

		if route.rtype == SECURED {
			handler = negroni.New(
				negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
				negroni.Wrap(handler),
			)
		}

		router.
			Methods(route.Method).
			Path(route.Pattern).
			Name(route.Name).
			Handler(handler)
	}

	router.HandleFunc("/auth", CallbackHandler)
	router.Handle("/user", negroni.New(
		negroni.HandlerFunc(IsAuthenticated),
		negroni.Wrap(http.HandlerFunc(UserHandler)),
	))

	router.PathPrefix("/public/").Handler(http.StripPrefix("/public/", http.FileServer(http.Dir("public/"))))

	return router
}
Example #22
0
func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", VoteHandler)

	n := negroni.New(
		negroni.NewLogger(),
		negroni.Wrap(mux),
	)
	n.Run(":" + os.Getenv("PORT"))
}
func loadStandard() http.Handler {
	mux := httprouter.New()
	mux.GET("/hello", hello)

	mux.GET("/admin/hello", Join(hello, CheckPerms("admin", secret, 1)))

	mux.GET("/user/:id/hello", Join(hello, CheckPerms("user-$id", secret, 1)))

	mux.GET("/useroradmin/:id/hello", Join(hello, CheckPerms("(admin|user-$id)", secret, 10)))

	return negroni.New(negroni.Wrap(mux))
}
Example #24
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
}
Example #25
0
func New(runInDebugMode bool, templatesLocation string, usersPasswordFileLocation string, storageFactory model.VFStorageGroup, srvlog *logs.ServerLog) http.Handler {

	if defaultRouter != nil {
		return defaultRouter
	}

	serverlog = srvlog
	defaultUserAuthenticator = auth.NewBasicAuthenticator("myrealm", auth.HtpasswdFileProvider(usersPasswordFileLocation))
	defaultStorageFactory = storageFactory
	results.TemplatesDir = templatesLocation
	results.DebugMode = runInDebugMode

	defaultRouter = mux.NewRouter()
	adminRouter := mux.NewRouter()
	apiRouter := mux.NewRouter()

	handleVFolder(apiRouter)
	handleCtrlPanel(adminRouter)
	handlePlayground(apiRouter)

	defaultRouter.PathPrefix("/api").Handler(
		negroni.New(
			negroni.HandlerFunc(authorized),
			negroni.Wrap(apiRouter),
		),
	)

	defaultRouter.PathPrefix("/admin").Handler(
		negroni.New(
			negroni.HandlerFunc(authorized),
			negroni.HandlerFunc(adminOnly),
			negroni.Wrap(adminRouter),
		),
	)

	defaultRouter.PathPrefix("/static").Handler(http.StripPrefix("/static", http.FileServer(http.Dir("./server/static"))))

	return defaultRouter
}
Example #26
0
func StartServer() {
	r := mux.NewRouter()

	r.HandleFunc("/", home.HomeHandler)
	r.HandleFunc("/callback", callback.CallbackHandler)
	r.Handle("/user", negroni.New(
		negroni.HandlerFunc(middlewares.IsAuthenticated),
		negroni.Wrap(http.HandlerFunc(user.UserHandler)),
	))
	r.PathPrefix("/public/").Handler(http.StripPrefix("/public/", http.FileServer(http.Dir("public/"))))
	http.Handle("/", r)
	http.ListenAndServe(":8080", nil)
}
Example #27
0
func TestUtils(t *testing.T) {
	mux := httprouter.New()
	mux.GET("/no_hello", hello_utils)

	mux.GET("/one_hello", Join(hello_utils, HandlerFunc(test_middleware)))
	mux.GET("/two_hello", Join(hello_utils, HandlerFunc(test_middleware), HandlerFunc(test_middleware)))

	server := negroni.New(negroni.Wrap(mux))

	testBody(t, server, "GET", "/no_hello", http.StatusOK, "World")
	testBody(t, server, "GET", "/one_hello", http.StatusOK, "Hello!World")
	testBody(t, server, "GET", "/two_hello", http.StatusOK, "Hello!Hello!World")
}
Example #28
0
func SetTaskRoutes(router *mux.Router) *mux.Router {
	taskRouter := mux.NewRouter()
	taskRouter.HandleFunc("/tasks", controllers.CreateTask).Methods("POST")
	taskRouter.HandleFunc("/tasks/{id}", controllers.UpdateTask).Methods("PUT")
	taskRouter.HandleFunc("/tasks", controllers.GetTasks).Methods("GET")
	taskRouter.HandleFunc("/tasks/{id}", controllers.GetTaskById).Methods("GET")
	taskRouter.HandleFunc("/tasks/users/{id}", controllers.GetTasksByUser).Methods("GET")
	taskRouter.HandleFunc("/tasks/{id}", controllers.DeleteTask).Methods("DELETE")
	router.PathPrefix("/tasks").Handler(negroni.New(
		negroni.HandlerFunc(common.Authorize),
		negroni.Wrap(taskRouter),
	))
	return router
}
Example #29
0
func SetNoteRoutes(router *mux.Router) *mux.Router {
	noteRouter := mux.NewRouter()
	noteRouter.HandleFunc("/notes", controllers.CreateNote).Methods("POST")
	noteRouter.HandleFunc("/notes/{id}", controllers.UpdateNote).Methods("PUT")
	noteRouter.HandleFunc("/notes/{id}", controllers.GetNoteById).Methods("GET")
	noteRouter.HandleFunc("/notes", controllers.GetNotes).Methods("GET")
	noteRouter.HandleFunc("/notes/tasks/{id}", controllers.GetNotesByTask).Methods("GET")
	noteRouter.HandleFunc("/notes/{id}", controllers.DeleteNote).Methods("DELETE")
	router.PathPrefix("/notes").Handler(negroni.New(
		negroni.HandlerFunc(common.Authorize),
		negroni.Wrap(noteRouter),
	))
	return router
}
Example #30
0
func main() {
	skill := alexa.New(os.Getenv("AMAZON_APPID"))

	router := mux.NewRouter()
	n := negroni.Classic()

	router.Handle("/echo/skill", negroni.New(
		negroni.HandlerFunc(skill.HandlerFuncWithNext),
		negroni.Wrap(new(EchoRequestHandler)),
	))

	n.UseHandler(router)
	n.Run(":8081")
}