func Test_SessionsDeleteValue(t *testing.T) {
	n := negroni.Classic()

	store := cookiestore.New([]byte("secret123"))
	n.Use(sessions.Sessions("my_session", store))

	mux := http.NewServeMux()

	mux.HandleFunc("/testsession", func(w http.ResponseWriter, req *http.Request) {
		session := sessions.GetSession(req)
		session.Set("hello", "world")
		session.Delete("hello")
		fmt.Fprintf(w, "OK")
	})

	mux.HandleFunc("/show", func(w http.ResponseWriter, req *http.Request) {
		session := sessions.GetSession(req)
		if session.Get("hello") == "world" {
			t.Error("Session value deleting failed")
		}
		fmt.Fprintf(w, "OK")
	})

	n.UseHandler(mux)

	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/testsession", nil)
	n.ServeHTTP(res, req)

	res2 := httptest.NewRecorder()
	req2, _ := http.NewRequest("GET", "/show", nil)
	req2.Header.Set("Cookie", res.Header().Get("Set-Cookie"))
	n.ServeHTTP(res2, req2)
}
Пример #2
0
func TestRecoveryMiddlewareHandlesPanic(t *testing.T) {
	var (
		router = mux.NewRouter()
		app    = negroni.Classic()
		r      *http.Request
		err    error
		match  *mux.RouteMatch
	)

	// Add a test GET route without a middleware
	routes.AddRoutes([]routes.Route{
		routes.Route{
			Name:    "panic_route",
			Method:  "GET",
			Pattern: "/panic",
			HandlerFunc: func(w http.ResponseWriter, r *http.Request) {
				panic("oh no")
			},
		},
	}, router.PathPrefix("/foo").Subrouter())

	// Test the foobar_route
	r, err = http.NewRequest("GET", "http://1.2.3.4/foo/panic", nil)
	assert.NoError(t, err, "Request setup should not get an error")

	// Test the route matches expected name
	match = new(mux.RouteMatch)
	router.Match(r, match)
	assert.Equal(t, "panic_route", match.Route.GetName())

	// Test that panic does not crash the app
	app.UseHandler(router)
	app.ServeHTTP(httptest.NewRecorder(), r)
}
Пример #3
0
func Test_LoginRequired(t *testing.T) {
	recorder := httptest.NewRecorder()
	n := negroni.Classic()
	n.Use(sessions.Sessions("my_session", cookiestore.New([]byte("secret123"))))
	n.Use(Google(&Config{
		ClientID:     "foo",
		ClientSecret: "foo",
		RedirectURL:  "foo",
	}))

	n.Use(LoginRequired())

	mux := http.NewServeMux()

	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "OK")
	})

	n.UseHandler(mux)
	r, _ := http.NewRequest("GET", "/", nil)
	n.ServeHTTP(recorder, r)
	if recorder.Code != 302 {
		t.Errorf("Not being redirected to the auth page although user is not logged in. %d\n", recorder.Code)
	}
}
Пример #4
0
func Test_LogoutOnAccessTokenExpiration(t *testing.T) {
	recorder := httptest.NewRecorder()
	s := cookiestore.New([]byte("secret123"))

	n := negroni.Classic()
	n.Use(sessions.Sessions("my_session", s))
	n.Use(Google(&Config{
		ClientID:     "foo",
		ClientSecret: "foo",
		RedirectURL:  "foo",
	}))

	mux := http.NewServeMux()
	mux.HandleFunc("/addtoken", func(w http.ResponseWriter, req *http.Request) {
		SetToken(req, "dummy token")
		fmt.Fprintf(w, "OK")
	})

	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		tok := GetToken(req)
		if tok != nil {
			t.Errorf("User not logged out although access token is expired. %v\n", tok)
		}
	})
	n.UseHandler(mux)
	addtoken, _ := http.NewRequest("GET", "/addtoken", nil)
	index, _ := http.NewRequest("GET", "/", nil)
	n.ServeHTTP(recorder, addtoken)
	n.ServeHTTP(recorder, index)
}
Пример #5
0
func main() {

	router := mux.NewRouter()
	router.HandleFunc("/", index)
	n := negroni.Classic()
	n.UseHandler(router)
	n.Run(":8080")

}
Пример #6
0
func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", index)
	// The classic function probides built-in middleware functions
	// for Recovery, Logging and serving Static files under the
	// "public" directory
	n := negroni.Classic()
	n.UseHandler(mux)
	n.Run(":8080")
}
Пример #7
0
func NewRouter() http.Handler {
	n := negroni.Classic()
	router := &fakeRouter{mux: mux.NewRouter()}
	controller := &controller{persistorCreator: models.NewPersistor}
	router.mux.HandleFunc("/near", controller.nearHandler).Methods("POST")
	router.mux.HandleFunc("/store", controller.storeHandler).Methods("POST")
	router.mux.HandleFunc("/recent/{id}", controller.recentStrokes).Methods("GET")
	n.Use(router)
	return n
}
func Test_Flashes(t *testing.T) {
	n := negroni.Classic()

	store := cookiestore.New([]byte("secret123"))
	n.Use(sessions.Sessions("my_session", store))

	mux := http.NewServeMux()

	mux.HandleFunc("/set", func(w http.ResponseWriter, req *http.Request) {
		session := sessions.GetSession(req)
		session.AddFlash("hello world")
		fmt.Fprintf(w, "OK")
	})

	mux.HandleFunc("/show", func(w http.ResponseWriter, req *http.Request) {
		session := sessions.GetSession(req)
		l := len(session.Flashes())
		if l != 1 {
			t.Error("Flashes count does not equal 1. Equals ", l)
		}
		fmt.Fprintf(w, "OK")
	})

	mux.HandleFunc("/showagain", func(w http.ResponseWriter, req *http.Request) {
		session := sessions.GetSession(req)
		l := len(session.Flashes())
		if l != 0 {
			t.Error("flashes count is not 0 after reading. Equals ", l)
		}
		fmt.Fprintf(w, "OK")
	})

	n.UseHandler(mux)

	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/set", nil)
	n.ServeHTTP(res, req)

	res2 := httptest.NewRecorder()
	req2, _ := http.NewRequest("GET", "/show", nil)
	req2.Header.Set("Cookie", res.Header().Get("Set-Cookie"))
	n.ServeHTTP(res2, req2)

	res3 := httptest.NewRecorder()
	req3, _ := http.NewRequest("GET", "/showagain", nil)
	req3.Header.Set("Cookie", res2.Header().Get("Set-Cookie"))
	n.ServeHTTP(res3, req3)
}
Пример #9
0
func main() {
	flag.StringVar(&masterConnection, "master", "redis-master:6379", "The connection string to the Redis master as <hostname/ip>:<port>")
	flag.StringVar(&slaveConnection, "slave", "redis-slave:6379", "The connection string to the Redis slave as <hostname/ip>:<port>")
	flag.StringVar(&masterPassword, "master-password", "", "The password used to connect to the master")
	flag.StringVar(&slavePassword, "slave-password", "", "The password used to connect to the slave")
	flag.IntVar(&healthCheckTime, "health-check", 15, "Period to check all connections")
	flag.BoolVar(&showVersion, "version", false, "Shows the version")
	flag.Parse()

	if showVersion {
		log.Printf("Version: %s\n", appVersion)
		return
	}
	// Iniitialize metrics
	healthCheckTimer := time.NewTicker(time.Duration(healthCheckTime) * time.Second)
	quit := make(chan struct{})
	go func() {
		for {
			select {
			case <-healthCheckTimer.C:
				log.Println("Called Health check")
				getHealthStatus()
			case <-quit:
				healthCheckTimer.Stop()
				return
			}
		}
	}()

	r := mux.NewRouter()
	r.Path("/read/{key}").Methods("GET").HandlerFunc(readTodoHandler)
	r.Path("/insert/{key}/{value}").Methods("GET").HandlerFunc(insertTodoHandler)
	r.Path("/delete/{key}/{value}").Methods("GET").HandlerFunc(deleteTodoHandler)
	r.Path("/health").Methods("GET").HandlerFunc(healthCheckHandler)
	r.Path("/metrics").Methods("GET").Handler(prometheus.Handler())
	r.Path("/whoami").Methods("GET").HandlerFunc(whoAmIHandler)
	r.Path("/version").Methods("GET").HandlerFunc(versionHandler)

	n := negroni.Classic()
	n.UseHandler(r)
	http.ListenAndServe(":3000", n)

	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
	log.Println(<-ch)
	close(quit)
}
func Test_Options(t *testing.T) {
	n := negroni.Classic()
	store := cookiestore.New([]byte("secret123"))
	store.Options(sessions.Options{
		Domain: "negroni-sessions.goincremental.com",
	})

	n.Use(sessions.Sessions("my_session", store))

	mux := http.NewServeMux()

	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		session := sessions.GetSession(req)
		session.Set("hello", "world")
		session.Options(sessions.Options{
			Path: "/foo/bar/bat",
		})
		fmt.Fprintf(w, "OK")
	})

	mux.HandleFunc("/foo", func(w http.ResponseWriter, req *http.Request) {
		session := sessions.GetSession(req)
		session.Set("hello", "world")
		fmt.Fprintf(w, "OK")
	})

	n.UseHandler(mux)

	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/", nil)
	n.ServeHTTP(res, req)

	res2 := httptest.NewRecorder()
	req2, _ := http.NewRequest("GET", "/foo", nil)
	n.ServeHTTP(res2, req2)

	s := strings.Split(res.Header().Get("Set-Cookie"), ";")
	if s[1] != " Path=/foo/bar/bat" {
		t.Error("Error writing path with options:", s[1])
	}

	s = strings.Split(res2.Header().Get("Set-Cookie"), ";")
	if s[1] != " Domain=negroni-sessions.goincremental.com" {
		t.Error("Error writing domain with options:", s[1])
	}
}
func Test_SessionsClear(t *testing.T) {
	n := negroni.Classic()
	data := map[string]string{
		"hello":  "world",
		"foo":    "bar",
		"apples": "oranges",
	}

	store := cookiestore.New([]byte("secret123"))
	n.Use(sessions.Sessions("my_session", store))

	mux := http.NewServeMux()

	mux.HandleFunc("/testsession", func(w http.ResponseWriter, req *http.Request) {
		session := sessions.GetSession(req)
		for k, v := range data {
			session.Set(k, v)
		}
		session.Clear()
		fmt.Fprintf(w, "OK")
	})

	mux.HandleFunc("/show", func(w http.ResponseWriter, req *http.Request) {
		session := sessions.GetSession(req)
		for k, v := range data {
			if session.Get(k) == v {
				t.Fatal("Session clear failed")
			}
		}
		fmt.Fprintf(w, "OK")
	})

	n.UseHandler(mux)

	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/testsession", nil)
	n.ServeHTTP(res, req)

	res2 := httptest.NewRecorder()
	req2, _ := http.NewRequest("GET", "/show", nil)
	req2.Header.Set("Cookie", res.Header().Get("Set-Cookie"))
	n.ServeHTTP(res2, req2)
}
Пример #12
0
func RunFunc() {
	r := render.New()
	mux, store := InitServerMux(r)
	n := negroni.Classic()
	n.Use(negroni.HandlerFunc(CookieMiddleware(store)))
	n.Use(negroni.HandlerFunc(RecoveryErr()))
	timeourHandler := http.TimeoutHandler(context.ClearHandler(mux), time.Duration(3*time.Second), timeoutErrMessage)
	n.UseHandler(timeourHandler)
	//All the middlerware we used
	l := log.New(os.Stdout, "[negroni] ", 0)
	l.Printf("listening on :80")
	server := http.Server{Addr: ":80", Handler: n}
	server.SetKeepAlivesEnabled(true)
	go MainMonitor()
	InitSchoolDB()
	InitCourseMap()
	InitSchoolStructs()
	l.Fatal(server.ListenAndServe())
}
Пример #13
0
func Test_Logout(t *testing.T) {
	recorder := httptest.NewRecorder()
	s := cookiestore.New([]byte("secret123"))

	n := negroni.Classic()
	n.Use(sessions.Sessions("my_session", s))
	n.Use(Google(&Config{
		ClientID:     "foo",
		ClientSecret: "foo",
		RedirectURL:  "foo",
	}))

	mux := http.NewServeMux()

	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		SetToken(req, "dummy token")
		fmt.Fprintf(w, "OK")
	})

	mux.HandleFunc("/get", func(w http.ResponseWriter, req *http.Request) {
		tok := GetToken(req)
		if tok != nil {
			t.Errorf("User credentials are still kept in the session.")
		}
		fmt.Fprintf(w, "OK")
	})

	n.UseHandler(mux)
	logout, _ := http.NewRequest("GET", "/logout", nil)
	index, _ := http.NewRequest("GET", "/", nil)

	n.ServeHTTP(httptest.NewRecorder(), index)
	n.ServeHTTP(recorder, logout)

	if recorder.Code != 302 {
		t.Errorf("Not being redirected to the next page.")
	}
}
Пример #14
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)
		}
	})
}