Ejemplo n.º 1
0
func Test_LoginRedirectAfterLoginRequired(t *testing.T) {
	recorder := httptest.NewRecorder()
	n := negroni.New()
	n.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	n.Use(Google(
		goauth2.Client("client_id", "client_secret"),
		goauth2.RedirectURL("refresh_url"),
		goauth2.Scope("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)
	}
}
Ejemplo n.º 2
0
func main() {
	fmt.Println("Starting sample auth...")

	n := negroni.Classic()

	n.Use(sessions.Sessions("mysession", cookiestore.New([]byte("secret12"))))

	n.Use(KeyCloak(&oauth2.Config{
		ClientID:     "grafana",
		ClientSecret: "10b54f7c-a8ed-4a61-abd7-eb993d12367b",
		RedirectURL:  "http://127.0.0.1:8090/oauth2callback",
		Scopes:       []string{"name", "email"}}))

	router := mux.NewRouter()

	router.HandleFunc("/", Home)
	router.HandleFunc("/version", Version)

	router.HandleFunc("/hello", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "World !")
	})

	n.Use(oauth2.LoginRequired())

	n.UseHandler(router)
	n.Run(":8090")
}
Ejemplo n.º 3
0
func Test_LogoutOnAccessTokenExpiration(t *testing.T) {
	recorder := httptest.NewRecorder()
	s := sessions.NewCookieStore([]byte("secret123"))

	n := negroni.Classic()
	n.Use(sessions.Sessions("my_session", s))
	n.Use(Google(
		goauth2.Client("foo", "foo"),
		goauth2.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)
}
Ejemplo n.º 4
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)
	}
}
Ejemplo n.º 5
0
func main() {
	// Load the configuration.
	err := envconfig.Process("elwinar", &configuration)
	if err != nil {
		log.Fatalln("unable to read the configuration from env:", err)
	}

	// Open the database connection.
	database, err = sqlx.Connect("sqlite3", configuration.Database)
	if err != nil {
		log.Fatalln("unable to open the database:", err)
	}

	// Initialize the router.
	router := httprouter.New()

	// Add the front-office handlers.
	router.GET("/", Index)
	router.GET("/read", List)
	router.GET("/article/:slug", View)
	router.GET("/fortune", Fortune)
	router.GET("/sitemap.xml", Sitemap)

	// Add the back-office handlers.
	router.GET("/login", Login)
	router.POST("/login", Authenticate)
	router.GET("/logout", Logout)
	router.GET("/write", Write)
	router.POST("/write", Create)
	router.GET("/article/:slug/edit", Edit)
	router.POST("/article/:slug/edit", Update)
	router.GET("/article/:slug/delete", Delete)
	router.GET("/article/:slug/publish", Publish)
	router.GET("/article/:slug/unpublish", Unpublish)

	// Initialize the server middleware stack.
	stack := negroni.New()
	stack.Use(gzip.Gzip(gzip.DefaultCompression))
	stack.Use(negroni.NewRecovery())
	stack.Use(negroni.NewStatic(http.Dir(configuration.Public)))
	stack.Use(sessions.Sessions("elwinar", cookiestore.New([]byte(configuration.Secret))))
	stack.UseHandler(router)

	// Initialize the HTTP server.
	server := &graceful.Server{
		Timeout: 1 * time.Second,
		Server: &http.Server{
			Addr:    fmt.Sprintf(":%d", configuration.Port),
			Handler: stack,
		},
	}

	// Run the server.
	err = server.ListenAndServe()
	if err != nil {
		log.Fatalln("unable to run the server:", err)
	}
}
Ejemplo n.º 6
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")
}
Ejemplo n.º 7
0
func main() {

	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", sessions.NewCookieStore([]byte("secret123"))))
	n.Use(oauth2.Google(
		goauth2.Client("client_id", "client_secret"),
		goauth2.RedirectURL("redirect_url"),
		goauth2.Scope("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.Expired() {
			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")
}
Ejemplo n.º 8
0
func Test_LoginRedirect(t *testing.T) {
	recorder := httptest.NewRecorder()
	n := negroni.New()
	n.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	n.Use(Google(
		goauth2.Client("client_id", "client_secret"),
		goauth2.RedirectURL("refresh_url"),
		goauth2.Scope("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)
	}
}
Ejemplo n.º 9
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.")
	}
}