Ejemplo n.º 1
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
}
Ejemplo n.º 2
0
func main() {
	// Instantiate a new router
	r := httprouter.New()
	n := negroni.Classic()

	// Get a UserController instance
	//	uc := controllers.NewUserController(getSession())
	//	cc := controllers.NewCustomerController(getSession())
	//
	//	// Get a user resource
	//	r.GET("/user/:id", uc.GetUser)
	//	r.GET("/customer/:id",cc.GetCustomer)
	//
	//	// Create a new user
	//	r.POST("/user", uc.CreateUser)
	//	r.POST("/customer",cc.CreateCustomer)
	//
	//	r.PUT("/customer/:id",cc.UpdateCustomer)
	//
	//	// Remove an existing user
	//	r.DELETE("/user/:id", uc.RemoveUser)
	//	r.DELETE("/customer/:id",cc.RemoveCustomer)

	// Fire up the server
	r.HandlerFunc("GET", "/login", getToken)
	r.Handler("GET", "/api",
		negroni.New(negroni.HandlerFunc(AuthMiddleware1), negroni.HandlerFunc(APIHandler1), negroni.Handler(CreateCustomer1)))
	//	r.Handler("POST","/customer",
	//		negroni.New(negroni.HandlerFunc(AuthMiddleware1),negroni.HandlerFunc(APIHandler1),cc.CreateCustomer))
	n.UseHandler(r)
	http.ListenAndServe("localhost:8080", n)
}
Ejemplo n.º 3
0
// RunServer starts vertice httpd server.
func NewNegHandler() *negroni.Negroni {
	c := cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
	})

	m := &delayedRouter{}
	for _, handler := range megdHandlerList {
		m.Add(handler.method, handler.path, handler.h)
	}

	m.Add("Get", "/", Handler(index))
	m.Add("Get", "/logs", Handler(logs))
	m.Add("Get", "/ping", Handler(ping))
	//we can use this as a single click Terminal launch for docker.
	//m.Add("Get", "/apps/{appname}/shell", websocket.Handler(remoteShellHandler))
	n := negroni.New()
	n.Use(negroni.NewRecovery())
	n.Use(c)
	n.Use(newLoggerMiddleware())
	n.UseHandler(m)
	n.Use(negroni.HandlerFunc(contextClearerMiddleware))
	n.Use(negroni.HandlerFunc(flushingWriterMiddleware))
	n.Use(negroni.HandlerFunc(errorHandlingMiddleware))
	n.Use(negroni.HandlerFunc(authTokenMiddleware))
	n.UseHandler(http.HandlerFunc(runDelayedHandler))
	return n
}
Ejemplo n.º 4
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))
}
Ejemplo n.º 5
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")

}
Ejemplo n.º 6
0
//InitRoutes sets up our routes, whether anonymous or authenticated.
//Utilizing Negroni so we can have multiple handlers, each one with the ability to call the next.
func InitRoutes() *mux.Router {
	router := mux.NewRouter().StrictSlash(true)

	//anonymous routes
	//Get Environment
	router.Handle("/",
		negroni.New(
			negroni.HandlerFunc(controllers.GetRoute),
		)).Methods("GET")
	//Get Milestones By DealID
	router.Handle("/milestones/complete/{dealGUID}",
		negroni.New(
			negroni.HandlerFunc(controllers.GetDealCompletedMilestonesByDealGUID),
		)).Methods("GET")
	//Get Milestones with complete status By DealID
	router.Handle("/milestones/{dealGUID}",
		negroni.New(
			negroni.HandlerFunc(controllers.GetMilestonesByDealGUID),
		)).Methods("GET")
	//Post events for a deal
	router.Handle("/event/{dealGUID}/{eventName}",
		negroni.New(
			negroni.HandlerFunc(controllers.DealEventHandler),
		)).Methods("GET")
	//authenticated routes
	//...

	return router
}
Ejemplo n.º 7
0
func (a *Context) middlewares() {
	// logger should be first middleware
	a.Negroni.Use(negroni.HandlerFunc(a.reqLog))
	// a.Negroni.Use(h.NewRecovery(log))
	// a.Negroni.Use(negroni.HandlerFunc(cors))
	a.Negroni.Use(negroni.HandlerFunc(options))
	a.Negroni.Use(negroni.NewRecovery())
}
Ejemplo n.º 8
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.º 9
0
func (this *StatsHandler) RegisterRoutes(mux *bone.Mux, am *handlers.AuthHandler) {
	mux.Get("/api/stats", negroni.New(
		negroni.HandlerFunc(am.RequireTokenAuthentication),
		negroni.HandlerFunc(this.Get),
	))
	// TODO: check auth for websocket connection
	mux.Get("/api/statsws", http.HandlerFunc(this.GetWS))
}
Ejemplo n.º 10
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
}
Ejemplo n.º 11
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.º 12
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.º 13
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),
	))
}
Ejemplo n.º 14
0
func (this *StateHandler) RegisterRoutes(mux *bone.Mux, am *handlers.AuthHandler) {
	mux.Get("/api/state", negroni.New(
		negroni.HandlerFunc(am.RequireTokenAuthentication),
		negroni.HandlerFunc(this.Get),
	))
	mux.Post("/api/state", negroni.New(
		negroni.HandlerFunc(am.RequireTokenAuthentication),
		negroni.HandlerFunc(this.Post),
	))
}
Ejemplo n.º 15
0
func (this *HoverflyModeHandler) RegisterRoutes(mux *bone.Mux, am *handlers.AuthHandler) {
	mux.Get("/api/v2/hoverfly/mode", negroni.New(
		negroni.HandlerFunc(am.RequireTokenAuthentication),
		negroni.HandlerFunc(this.Get),
	))
	mux.Put("/api/v2/hoverfly/mode", negroni.New(
		negroni.HandlerFunc(am.RequireTokenAuthentication),
		negroni.HandlerFunc(this.Put),
	))
}
Ejemplo n.º 16
0
func (this *MiddlewareHandler) RegisterRoutes(mux *bone.Mux, am *handlers.AuthHandler) {
	mux.Get("/api/middleware", negroni.New(
		negroni.HandlerFunc(am.RequireTokenAuthentication),
		negroni.HandlerFunc(this.Redirect),
	))

	mux.Post("/api/middleware", negroni.New(
		negroni.HandlerFunc(am.RequireTokenAuthentication),
		negroni.HandlerFunc(this.Redirect),
	))
}
Ejemplo n.º 17
0
func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/favicon.ico", iconHandler)
	mux.HandleFunc("/", index)
	mux.HandleFunc("/message", message)
	n := negroni.Classic()
	n.Use(negroni.HandlerFunc(middlewareFirst))
	n.Use(negroni.HandlerFunc(middlewareSecond))
	n.UseHandler(mux)
	n.Run(":8080")
}
Ejemplo n.º 18
0
func TestWorkWithNegroni(t *testing.T) {
	m1 := func(ctx context.Context, w http.ResponseWriter, r *http.Request, next negroni.ContextHandlerFunc) {
		fmt.Fprint(w, "+middleware1")
		next(ctx, w, r)
	}
	m2 := func(ctx context.Context, w http.ResponseWriter, r *http.Request, next negroni.ContextHandlerFunc) {
		fmt.Fprint(w, "+middleware2")
		ctx = context.WithValue(ctx, "m2", "Hahaha")
		next(ctx, w, r)
	}
	m3 := func(ctx context.Context, w http.ResponseWriter, r *http.Request, next negroni.ContextHandlerFunc) {
		fmt.Fprint(w, "+middleware3")
		next(ctx, w, r)
	}
	h1 := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "+handler1:m2=%s", ctx.Value("m2").(string))
	}
	h2 := func(ctx context.Context, w http.ResponseWriter, r *http.Request, ps Params) {
		fmt.Fprintf(w, "+handler2:ps=%s, m2=%s", ps.ByName("name"), ctx.Value("m2").(string))
	}

	endrouter := New()
	endrouter.GET("/admin/handler2/:name", h2)
	endrouter.ContextHandlerFunc("GET", "/admin/handler1", h1)

	m12 := negroni.New(negroni.HandlerFunc(m1), negroni.HandlerFunc(m2), negroni.WrapCH(negroni.ContextHandlerFunc(h1)))
	m32 := negroni.New(negroni.HandlerFunc(m3), negroni.HandlerFunc(m2), negroni.WrapCH(endrouter))

	root := New()
	root.ContextHandler("GET", "/", m12)
	root.ContextHandler("GET", "/admin/*fp", m32)

	w := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/", nil)
	root.ServeHTTP(w, req)
	if w.Code != http.StatusOK || w.Body.String() != "+middleware1+middleware2+handler1:m2=Hahaha" {
		t.Errorf("GET / failed: %v", w)
	}

	w = httptest.NewRecorder()
	req, _ = http.NewRequest("GET", "/admin/handler2/lumieru", nil)
	root.ServeHTTP(w, req)
	if w.Code != http.StatusOK || w.Body.String() != "+middleware3+middleware2+handler2:ps=lumieru, m2=Hahaha" {
		t.Errorf("GET /admin/handler2/lumieru failed: %v", w)
	}

	w = httptest.NewRecorder()
	req, _ = http.NewRequest("GET", "/admin/handler1", nil)
	root.ServeHTTP(w, req)
	if w.Code != http.StatusOK || w.Body.String() != "+middleware3+middleware2+handler1:m2=Hahaha" {
		t.Errorf("GET /admin/handler1 failed: %v", w)
	}
}
Ejemplo n.º 19
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)
}
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.º 21
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.º 22
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.º 23
0
func main() {
	router := mux.NewRouter()
	n := negroni.Classic()

	router.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
		token := jwt.New(jwt.GetSigningMethod("RS256"))
		tokenString, _ := token.SignedString(privateKay)
		w.WriteHeader(http.StatusOK)
		fmt.Fprint(w, tokenString)
	})
	router.Handle("/api", negroni.New(negroni.HandlerFunc(AuthMiddleware), negroni.HandlerFunc(APIHandler)))
	n.UseHandler(router)
	http.ListenAndServe(":3000", n)
}
Ejemplo n.º 24
0
Archivo: web.go Proyecto: gmelika/rack
func startWeb() {
	if p := os.Getenv("PORT"); p != "" {
		port = p
	}

	n := negroni.New()

	n.Use(negroni.HandlerFunc(recovery))
	n.Use(negroni.HandlerFunc(development))
	n.Use(nlogger.New("ns=api.web", nil))

	n.UseHandler(controllers.NewRouter())

	n.Run(fmt.Sprintf(":%s", port))
}
Ejemplo n.º 25
0
//InitRoutes sets up our routes, whether anonymous or authenticated.
//Utilizing Negroni so we can have multiple handlers, each one with the ability to call the next.
func InitRoutes() *mux.Router {
	router := mux.NewRouter().StrictSlash(true)

	router.Handle("/",
		negroni.New(
			negroni.HandlerFunc(controllers.GetRoute),
		)).Methods("GET")

	router.Handle("/deal/{dealGuid}",
		negroni.New(
			negroni.HandlerFunc(controllers.GetDealByGuid),
		)).Methods("GET")

	return router
}
Ejemplo n.º 26
0
//Routing ...
func (base *BaseRouter) Routing(routes ...map[string]interface{}) {
	if base.WebServer == "negroni" {
		for i := range routes {
			url := routes[i]["url"].(string)
			method := routes[i]["method"].(string)
			funct := routes[i]["func"].([]handlerFunc)

			base.MuxRouter.Handle(base.APIPrefix+url,
				negroni.New(
					negroni.HandlerFunc(funct[0]),
					negroni.HandlerFunc(funct[1]),
				)).Methods(method)
		}
	}
}
Ejemplo n.º 27
0
func startWeb() {
	if p := os.Getenv("PORT"); p != "" {
		port = p
	}

	n := negroni.New()

	n.Use(negroni.HandlerFunc(recovery))
	n.Use(negroni.HandlerFunc(development))
	n.Use(negronilogrus.NewMiddleware())

	n.UseHandler(controllers.NewRouter())

	n.Run(fmt.Sprintf(":%s", port))
}
Ejemplo n.º 28
0
func JWTMiddleware() negroni.Handler {
	return negroni.HandlerFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
		if h := r.Header.Get("Authorization"); h != "" {
			token, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) {
				return verifyKey, nil
			})

			switch err.(type) {
			case nil:
				if !token.Valid {
					NotAllowed(w, r)
					return
				}
				context.Set(r, "token", token)
				next(w, r)
			case *jwt.ValidationError:
				vErr := err.(*jwt.ValidationError)
				switch vErr.Errors {
				case jwt.ValidationErrorExpired:
					BR(w, r, errors.New("Token Expired"), http.StatusUnauthorized)
					return
				default:
					BR(w, r, errors.New("Bad Token"), http.StatusUnauthorized)
					log.Println(vErr.Error())
					return
				}
			default:
				ISR(w, r, err)
				return
			}
		} else {
			BR(w, r, errors.New("Missing Token"), http.StatusUnauthorized)
		}
	})
}
Ejemplo n.º 29
0
// New creates a REST API server with a given config
func New(cfg *Config) (*Server, error) {
	// pull a few parameters from the configuration passed in by snapd
	https := cfg.HTTPS
	cpath := cfg.RestCertificate
	kpath := cfg.RestKey
	s := &Server{
		err:        make(chan error),
		killChan:   make(chan struct{}),
		addrString: cfg.Address,
	}
	if https {
		var err error
		s.snapTLS, err = newtls(cpath, kpath)
		if err != nil {
			return nil, err
		}
		protocolPrefix = "https"
	}

	restLogger.Info(fmt.Sprintf("Configuring REST API with HTTPS set to: %v", https))
	s.n = negroni.New(
		NewLogger(),
		negroni.NewRecovery(),
		negroni.HandlerFunc(s.authMiddleware),
	)
	s.r = httprouter.New()
	// Use negroni to handle routes
	s.n.UseHandler(s.r)
	return s, nil
}
Ejemplo n.º 30
0
func NewDispatcher(h ServiceHandler) http.Handler {
	rp := &Dispatcher{handler: h}
	t := h.service.Timeout
	if t <= 0 {
		t = DEFAULT_TIMEOUT
	}
	timeout := time.Duration(t)

	rp.Transport = &http.Transport{
		Dial:                timeoutDialer(timeout*time.Second, timeout*time.Second),
		Proxy:               http.ProxyFromEnvironment,
		TLSHandshakeTimeout: timeout * time.Second,
	}
	//Load middlewares before adding the reverse proxy to the stack.
	n := negroni.New()
	n.Use(middleware.NewRequestIdMiddleware())
	for _, m := range h.middlewares {
		n.Use(negroni.HandlerFunc(m.ProcessRequest))
	}

	rp.proxy = &ReverseProxy{
		Director:     rp.Director,
		Transport:    rp,
		Transformers: h.transformers,
	}
	n.UseHandler(rp.proxy)
	return n
}