Beispiel #1
0
func main() {

	var wg sync.WaitGroup

	wg.Add(3)
	go func() {
		n := negroni.New()
		fmt.Println("Launching server on :3000")
		graceful.Run(":3000", 0, n)
		fmt.Println("Terminated server on :3000")
		wg.Done()
	}()
	go func() {
		n := negroni.New()
		fmt.Println("Launching server on :3001")
		graceful.Run(":3001", 0, n)
		fmt.Println("Terminated server on :3001")
		wg.Done()
	}()
	go func() {
		n := negroni.New()
		fmt.Println("Launching server on :3002")
		graceful.Run(":3002", 0, n)
		fmt.Println("Terminated server on :3002")
		wg.Done()
	}()
	fmt.Println("Press ctrl+c. All servers should terminate.")
	wg.Wait()

}
Beispiel #2
0
func main() {
	//Loads environment variables from a .env file
	godotenv.Load("environment")

	var (
		clientID     = getEnv("OAUTH2_CLIENT_ID", "client_id")
		clientSecret = getEnv("OAUTH2_CLIENT_SECRET", "client_secret")
		redirectURL  = getEnv("OAUTH2_REDIRECT_URL", "redirect_url")
	)

	secureMux := http.NewServeMux()

	// Routes that require a logged in user
	// can be protected by using a separate route handler
	// If the user is not authenticated, they will be
	// redirected to the login path.
	secureMux.HandleFunc("/restrict", func(w http.ResponseWriter, req *http.Request) {
		token := oauth2.GetToken(req)
		fmt.Fprintf(w, "OK: %s", token.Access())
	})

	secure := negroni.New()
	secure.Use(oauth2.LoginRequired())
	secure.UseHandler(secureMux)

	n := negroni.New()
	n.Use(sessions.Sessions("my_session", cookiestore.New([]byte("secret123"))))
	n.Use(oauth2.Google(&oauth2.Config{
		ClientID:     clientID,
		ClientSecret: clientSecret,
		RedirectURL:  redirectURL,
		Scopes:       []string{"https://www.googleapis.com/auth/drive"},
	}))

	router := http.NewServeMux()

	//routes added to mux do not require authentication
	router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		token := oauth2.GetToken(req)
		if token == nil || !token.Valid() {
			fmt.Fprintf(w, "not logged in, or the access token is expired")
			return
		}
		fmt.Fprintf(w, "logged in")
		return
	})

	//There is probably a nicer way to handle this than repeat the restricted routes again
	//of course, you could use something like gorilla/mux and define prefix / regex etc.
	router.Handle("/restrict", secure)

	n.UseHandler(router)

	n.Run(":3000")
}
func Test_LoginRedirectAfterLoginRequired(t *testing.T) {
	recorder := httptest.NewRecorder()
	n := negroni.New()
	n.Use(sessions.Sessions("my_session", cookiestore.New([]byte("secret123"))))
	n.Use(Google(&Config{
		ClientID:     "client_id",
		ClientSecret: "client_secret",
		RedirectURL:  "refresh_url",
		Scopes:       []string{"x", "y"},
	}))

	n.Use(LoginRequired())

	mux := http.NewServeMux()

	mux.HandleFunc("/login-required", func(w http.ResponseWriter, req *http.Request) {
		t.Log("hi there")
		fmt.Fprintf(w, "OK")
	})

	n.UseHandler(mux)

	r, _ := http.NewRequest("GET", "/login-required?key=value", nil)
	n.ServeHTTP(recorder, r)

	location := recorder.HeaderMap["Location"][0]
	if recorder.Code != 302 {
		t.Errorf("Not being redirected to the auth page.")
	}
	if location != "/login?next=%2Flogin-required%3Fkey%3Dvalue" {
		t.Errorf("Not being redirected to the right page, %v found", location)
	}
}
// RunServer runs the app
func RunServer() error {
	cnf, db, err := initConfigDB(true, true)
	if err != nil {
		return err
	}
	defer db.Close()
	if err := initServices(cnf, db); err != nil {
		return err
	}

	// Start a classic negroni app
	app := negroni.New()
	app.Use(negroni.NewRecovery())
	app.Use(negroni.NewLogger())
	app.Use(gzip.Gzip(gzip.DefaultCompression))
	app.Use(negroni.NewStatic(http.Dir("public")))

	// Create a router instance
	router := mux.NewRouter()

	// Add routes
	healthService.RegisterRoutes(router, "/v1")
	oauthService.RegisterRoutes(router, "/v1/oauth")
	webService.RegisterRoutes(router, "/web")

	// Set the router
	app.UseHandler(router)

	// Run the server on port 8080, gracefully stop on SIGTERM signal
	graceful.Run(":8080", 5*time.Second, app)

	return nil
}
Beispiel #5
0
// This function is called from main.go and from the tests
// to create a new application.
func NewApp(root string) *App {

	CheckEnv()

	// Use negroni for middleware
	ne := negroni.New()

	// Use gorilla/mux for routing
	ro := mux.NewRouter()

	// Use Render for template. Pass in path to templates folder
	// as well as asset helper functions.
	re := render.New(render.Options{
		IndentJSON:    true,
		StreamingJSON: true,
	})

	// Establish connection to DB as specified in database.go
	db := NewDB()
	models.New(db)

	// Add middleware to the stack
	ne.Use(negroni.NewRecovery())
	ne.Use(negroni.NewLogger())
	ne.UseHandler(ro)

	// Return a new App struct with all these things.
	return &App{ne, ro, re}
}
Beispiel #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)
	}
}
Beispiel #7
0
func (r *Reactor) Serve(bind string) {
	handlers := append(r.handlers, negroni.NewStatic(public.AssetFS()))
	n := negroni.New(handlers...)

	router := httprouter.New()
	router.HandlerFunc("GET", "/ws", core.NewReactorHandler(func(uc chan *core.DisplayUpdate, ue chan *core.UserEvent, req *http.Request, id string) http.Header {

		go func() {

			path := "/"

		mainLoop:
			for {
				if path == "" {
					path = "/"
				}
				// TODO lock etc.

				screenFactory, params := r.findScreenFactoryForPath(path)

				ctx := ScreenContext{
					Path:         path,
					ConnectionID: id,
					Params:       params,
					UpdateScreen: func(upd *core.DisplayUpdate) {
						uc <- upd
					},
				}

				currentScreen := screenFactory(ctx)

				if currentScreen != nil {

					currentScreen.Mount()

					for evt := range ue {
						if evt.Type == "popstate" {
							newPath := strings.TrimPrefix(evt.Value, "#")
							if newPath != path {
								path = newPath
								currentScreen.Unmount()
								continue mainLoop
							}
						}
						currentScreen.OnUserEvent(evt)
					}
					currentScreen.Unmount()
					return
				}

			}
		}()

		return nil
	}))
	n.UseHandler(router)
	n.Run(bind)
}
Beispiel #8
0
// RunServer runs the app
func RunServer() error {
	cnf, db, err := initConfigDB(true, true)
	if err != nil {
		return err
	}
	defer db.Close()

	// Initialise the health service
	healthService := health.NewService(db)

	// Initialise the oauth service
	oauthService := oauth.NewService(cnf, db)

	// Initialise the email service
	emailService := email.NewService(cnf)

	// Initialise the accounts service
	accountsService := accounts.NewService(
		cnf,
		db,
		oauthService,
		emailService,
		nil, // accounts.EmailFactory
	)

	// Initialise the facebook service
	facebookService := facebook.NewService(
		cnf,
		db,
		accountsService,
		nil, // facebook.Adapter
	)

	// Start a negroni app
	app := negroni.New()
	app.Use(negroni.NewRecovery())
	app.Use(negroni.NewLogger())
	app.Use(gzip.Gzip(gzip.DefaultCompression))

	// Create a router instance
	router := mux.NewRouter()

	// Register routes
	healthService.RegisterRoutes(router, "/v1")
	oauthService.RegisterRoutes(router, "/v1/oauth")
	accountsService.RegisterRoutes(router, "/v1")
	facebookService.RegisterRoutes(router, "/v1/facebook")

	// Set the router
	app.UseHandler(router)

	// Run the server on port 8080, gracefully stop on SIGTERM signal
	graceful.Run(":8080", 5*time.Second, app)

	return nil
}
Beispiel #9
0
func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/favicon.ico", iconHandler)
	mux.HandleFunc("/", index)
	mux.HandleFunc("/message", message)
	n := negroni.New()
	n.Use(negroni.HandlerFunc(middlewareFirst))
	n.Use(negroni.HandlerFunc(middlewareSecond))
	n.UseHandler(mux)
	n.Run(":8080")
}
Beispiel #10
0
func Create(port string, env string) http.Handler {
	serverPort = port

	r := mux.NewRouter().PathPrefix("/v1").Subrouter()
	r.Methods("GET").Path("/ws/app/{key}").HandlerFunc(controllers.Join)

	appsRouter := mux.NewRouter().PathPrefix("/v1/apps/{appId}").Subrouter()
	appsRouter.Methods("POST").Path("/events").HandlerFunc(controllers.CreateEvent)

	r.PathPrefix("/apps/{appId}").Handler(negroni.New(
		negroni.HandlerFunc(AuthMiddleware),
		negroni.Wrap(appsRouter),
	))

	n := negroni.New(negroni.HandlerFunc(BaseMiddleware))
	if env == "dev" {
		n.Use(negroni.HandlerFunc(LoggerMiddleware))
	}

	n.UseHandler(r)

	return n
}
Beispiel #11
0
func NewProxy(args ProxyArgs) Proxy {
	routeServiceConfig := routeservice.NewRouteServiceConfig(args.Logger, args.RouteServiceEnabled, args.RouteServiceTimeout, args.Crypto, args.CryptoPrev, args.RouteServiceRecommendHttps)

	p := &proxy{
		accessLogger: args.AccessLogger,
		traceKey:     args.TraceKey,
		ip:           args.Ip,
		logger:       args.Logger,
		registry:     args.Registry,
		reporter:     args.Reporter,
		transport: &http.Transport{
			Dial: func(network, addr string) (net.Conn, error) {
				conn, err := net.DialTimeout(network, addr, 5*time.Second)
				if err != nil {
					return conn, err
				}
				if args.EndpointTimeout > 0 {
					err = conn.SetDeadline(time.Now().Add(args.EndpointTimeout))
				}
				return conn, err
			},
			DisableKeepAlives:  true,
			DisableCompression: true,
			TLSClientConfig:    args.TLSConfig,
		},
		secureCookies:              args.SecureCookies,
		heartbeatOK:                args.HeartbeatOK, // 1->true, 0->false
		routeServiceConfig:         routeServiceConfig,
		extraHeadersToLog:          args.ExtraHeadersToLog,
		routeServiceRecommendHttps: args.RouteServiceRecommendHttps,
		healthCheckUserAgent:       args.HealthCheckUserAgent,
		forceForwardedProtoHttps:   args.ForceForwardedProtoHttps,
		defaultLoadBalance:         args.DefaultLoadBalance,
	}

	n := negroni.New()
	n.Use(&proxyWriterHandler{})
	n.Use(handlers.NewAccessLog(args.AccessLogger, args.ExtraHeadersToLog))
	n.Use(handlers.NewHealthcheck(args.HealthCheckUserAgent, p.heartbeatOK, args.Logger))
	n.Use(handlers.NewZipkin(args.EnableZipkin, args.ExtraHeadersToLog, args.Logger))

	n.UseHandler(p)
	handlers := &proxyHandler{
		handlers: n,
		proxy:    p,
	}

	return handlers
}
Beispiel #12
0
func (c *ServerCommand) buildMiddleware() error {
	logger, err := c.getLogrusMiddleware()
	if err != nil {
		return err
	}

	n := negroni.New()
	n.Use(negroni.NewRecovery())
	n.Use(logger)
	n.UseHandler(c.s.Handler)

	c.s.Handler = n

	return nil
}
Beispiel #13
0
func createTestNegroni() *negroni.Negroni {
	manager := createExpectedManager()

	router := mux.NewRouter()
	router.HandleFunc("/guest", fakeHandler).Name("TokenGetAllowed")
	router.HandleFunc("/user", fakeHandler).Name("TorrentsAdd")
	router.HandleFunc("/admin", fakeHandler).Name("DeleteEpisode")
	router.HandleFunc("/noname", fakeHandler)

	tmiddleware := NewMiddleware(manager, router)

	n := negroni.New()
	n.Use(tmiddleware)
	n.UseHandler(router)
	return n
}
// RunServer runs the app
func RunServer() error {
	cnf, db, err := initConfigDB(true, true)
	if err != nil {
		return err
	}
	defer db.Close()

	// Initialise the health service
	healthService := health.NewService(db)

	// Initialise the oauth service
	oauthService := oauth.NewService(cnf, db)

	// Initialise the web service
	webService := web.NewService(cnf, oauthService)

	// Start a classic negroni app
	app := negroni.New()
	app.Use(negroni.NewRecovery())
	app.Use(negroni.NewLogger())
	app.Use(gzip.Gzip(gzip.DefaultCompression))
	app.Use(negroni.NewStatic(http.Dir("public")))

	// Create a router instance
	router := mux.NewRouter()

	// Add routes for the health service (healthcheck endpoint)
	health.RegisterRoutes(router, healthService)

	// Add routes for the oauth service (REST tokens endpoint)
	oauth.RegisterRoutes(router, oauthService)

	// Add routes for the web package (register, login authorize web pages)
	web.RegisterRoutes(router, webService)

	// Set the router
	app.UseHandler(router)

	// Run the server on port 8080
	app.Run(":8080")

	return nil
}
Beispiel #15
0
// Run configured API service on the configured port. If you Registers
// middlewear for gziped responses and graceful shutdown with a 10
// second timeout.
func (a *APIApp) Run() error {
	var err error
	if !a.isResolved {
		err = a.Resolve()
	}

	n := negroni.New()
	for _, m := range a.middleware {
		n.Use(m)
	}

	n.UseHandler(a.router)

	listenOn := strings.Join([]string{a.address, strconv.Itoa(a.port)}, ":")
	grip.Noticeln("starting app on:", listenOn)

	graceful.Run(listenOn, 10*time.Second, n)
	return err
}
func Test_LoginRedirect(t *testing.T) {
	recorder := httptest.NewRecorder()
	n := negroni.New()
	n.Use(sessions.Sessions("my_session", cookiestore.New([]byte("secret123"))))
	n.Use(Google(&Config{
		ClientID:     "client_id",
		ClientSecret: "client_secret",
		RedirectURL:  "refresh_url",
		Scopes:       []string{"x", "y"},
	}))

	r, _ := http.NewRequest("GET", "/login", nil)
	n.ServeHTTP(recorder, r)

	location := recorder.HeaderMap["Location"][0]
	if recorder.Code != 302 {
		t.Errorf("Not being redirected to the auth page.")
	}
	t.Logf(location)
	if strings.HasPrefix("https://accounts.google.com/o/oauth2/auth?access_type=online&approval_prompt=auto&client_id=client_id&redirect_uri=refresh_url&response_type=code&scope=x+y&state=", location) {
		t.Errorf("Not being redirected to the right page, %v found", location)
	}
}
Beispiel #17
0
// BuildWebServer constructs a new web server with the right DAO and spirits handler
func BuildWebServer(db string, daoType int, statisticsDuration time.Duration) (*negroni.Negroni, error) {

	// spirit dao
	dao, err := dao.GetSpiritDAO(db, daoType)
	if err != nil {
		logger.WithField("error", err).WithField("connection string", db).Fatal("unable to connect to mongo db")
		return nil, err
	}

	// web server
	n := negroni.New()

	// new handler
	handler := NewSpiritHandler(dao)

	// new router
	router := NewRouter(handler)

	// add middleware for logging
	n.Use(negronilogrus.NewMiddlewareFromLogger(logger.StandardLogger(), "spirit"))

	// add recovery middleware in case of panic in handler func
	recovery := negroni.NewRecovery()
	recovery.PrintStack = false
	n.Use(recovery)

	// add statistics middleware
	n.Use(NewStatisticsMiddleware(statisticsDuration))

	// add as many middleware as you like

	// handler goes last
	n.UseHandler(router)

	return n, nil
}
Beispiel #18
0
func NewServer(sh chan bool) {
	serverOnce.Do(func() {
		shutdownCh = sh
		flag.Parse()
		go hub.run()
		r := mux.NewRouter()

		var buffer bytes.Buffer
		buffer.WriteString(":")
		buffer.WriteString(core.NewConfig().HttpConfig.Port)

		jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
			ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
				return []byte(core.NewConfig().JWTConfig.Secret), nil
			},
			Debug: true,
			Extractor: jwtmiddleware.FromFirst(jwtmiddleware.FromAuthHeader,
				func(r *http.Request) (string, error) {
					c, err := r.Cookie("Authentication")
					if err != nil {
						return "", err
					}
					authHeaderParts := strings.Split(c.Value, " ")
					if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {
						return "", fmt.Errorf("Authorization header format must be Bearer {token}")
					}
					return authHeaderParts[1], nil
				}),

			SigningMethod: jwt.SigningMethodHS256,
		})

		n := negroni.Classic()
		for _, v := range routes {
			if v.auth {
				r.Handle(v.path, negroni.New(
					negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
					negroni.Wrap(http.HandlerFunc(v.handleFunc)),
				)).Methods(v.method)
			} else {
				r.HandleFunc(v.path, v.handleFunc).Methods(v.method)
			}
		}

		n.UseHandler(r)
		server = &graceful.Server{
			Timeout: 10 * time.Second,
			Server: &http.Server{
				Addr:    buffer.String(),
				Handler: n,
			},
			BeforeShutdown: func() bool {
				log.Println("bye")
				return true
			},
		}

		err := server.ListenAndServe()
		if err != nil {
			log.Fatal("ListenAndServe: ", err)
		}
	})
}
Beispiel #19
0
// httpServer returns an http server
func (s *Server) httpServer(log *logrus.Entry) *http.Server {
	addr := fmt.Sprintf("%s:%d", s.config.HTTPServer.Host, s.config.HTTPServer.Port)
	log.Debugf("http server will listen on: %s", addr)

	mux := mux.NewRouter()
	for _, route := range []struct {
		// name of the route
		name string
		// path of the route
		path string
		// allowed methods for this route
		methods string
		// handler is the http handler to run if the route matches
		handler func(http.ResponseWriter, *http.Request)
		// excluded tells if the route should be added to the router,
		// it's in the negative form so that the default behaviour is to add
		// the route to the router
		excluded bool
	}{
		{
			name:    "GetMovies",
			path:    "/movies",
			methods: "GET",
			handler: s.movieIds,
		},
		{
			name:    "GetMovie",
			path:    "/movies/{id}",
			methods: "GET",
			handler: s.getMovieDetails,
		},
		{
			name:    "DeleteMovie",
			path:    "/movies/{id}",
			methods: "DELETE",
			handler: s.deleteMovie,
		},
		{
			name:     "DownloadMovie",
			path:     "/movies/{id}/download",
			methods:  "GET",
			handler:  s.serveMovie,
			excluded: !s.config.HTTPServer.ServeFiles,
		},
		{
			name:    "GetShows",
			path:    "/shows",
			methods: "GET",
			handler: s.showIds,
		},
		{
			name:    "GetShow",
			path:    "/shows/{id}",
			methods: "GET",
			handler: s.getShowDetails,
		},
		{
			name:    "GetSeason",
			path:    "/shows/{id}/seasons/{season:[0-9]+}",
			methods: "GET",
			handler: s.getSeasonDetails,
		},
		{
			name:    "GetEpisode",
			path:    "/shows/{id}/seasons/{season:[0-9]+}/episodes/{episode:[0-9]+}",
			methods: "GET",
			handler: s.getShowEpisodeIDDetails,
		},
		{
			name:    "DeleteEpisode",
			path:    "/shows/{id}/seasons/{season:[0-9]+}/episodes/{episode:[0-9]+}",
			methods: "DELETE",
			handler: s.deleteEpisode,
		},
		{
			name:     "DownloadEpisode",
			path:     "/shows/{id}/seasons/{season:[0-9]+}/episodes/{episode:[0-9]+}/download",
			methods:  "GET",
			handler:  s.serveShow,
			excluded: !s.config.HTTPServer.ServeFiles,
		},
		{
			name:    "Wishlist",
			path:    "/wishlist",
			methods: "GET",
			handler: s.wishlist,
		},
		{
			name:    "AddTorrent",
			path:    "/torrents",
			methods: "POST",
			handler: s.addTorrent,
		},
	} {
		if route.excluded {
			continue
		}

		// Register the route
		mux.HandleFunc(route.path, route.handler).Name(route.name).Methods(route.methods)
	}

	n := negroni.New()

	// Panic recovery
	n.Use(negroni.NewRecovery())

	// Use logrus as logger
	n.Use(negronilogrus.NewMiddlewareFromLogger(s.log.Logger, "httpServer"))

	// gzip compression
	n.Use(gzip.Gzip(gzip.DefaultCompression))

	// Add basic auth if configured
	if s.config.HTTPServer.BasicAuth {
		log.Info("server will require basic authentication")
		n.Use(NewBasicAuthMiddleware(s.config.HTTPServer.BasicAuthUser, s.config.HTTPServer.BasicAuthPassword))
	}

	// Add token auth middleware if token configuration file specified
	if s.tokenManager != nil {
		n.Use(token.NewMiddleware(s.tokenManager, mux))
		mux.HandleFunc("/tokens/allowed", s.tokenGetAllowed).Name("TokenGetAllowed")
	}

	// Wrap the router
	n.UseHandler(mux)

	return &http.Server{Addr: addr, Handler: n}
}