Beispiel #1
0
func ExampleLogin() {
	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	m.Use(oauth2.Google(
		goauth2.Client("client_id", "client_secret"),
		goauth2.RedirectURL("redirect_url"),
		goauth2.Scope("https://www.googleapis.com/auth/drive"),
	))
	// Tokens are injected to the handlers
	m.Get("/", func(tokens oauth2.Tokens) string {
		if tokens.Expired() {
			return "not logged in, or the access token is expired"
		}
		return "logged in"
	})

	// Routes that require a logged in user
	// can be protected with oauth2.LoginRequired handler.
	// If the user is not authenticated, they will be
	// redirected to the login path.
	m.Get("/restrict", oauth2.LoginRequired, func(tokens oauth2.Tokens) string {
		return tokens.Access()
	})

	m.Run()
}
Beispiel #2
0
func Test_LogoutOnAccessTokenExpiration(t *testing.T) {
	recorder := httptest.NewRecorder()
	s := sessions.NewCookieStore([]byte("secret123"))

	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", s))
	m.Use(Google(
		oauth2.Client("foo", "foo"),
		oauth2.RedirectURL("foo"),
	))
	m.Get("/addtoken", func(s sessions.Session) {
		s.Set(keyToken, "dummy token")
	})

	m.Get("/", func(s sessions.Session) {
		if s.Get(keyToken) != nil {
			t.Errorf("User not logged out although access token is expired.")
		}
	})

	addtoken, _ := http.NewRequest("GET", "/addtoken", nil)
	index, _ := http.NewRequest("GET", "/", nil)
	m.ServeHTTP(recorder, addtoken)
	m.ServeHTTP(recorder, index)
}
func Example_webServer() {
	// Your credentials should be obtained from the Google
	// Developer Console (https://console.developers.google.com).
	opts, err := oauth2.New(
		oauth2.Client("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET"),
		oauth2.RedirectURL("YOUR_REDIRECT_URL"),
		oauth2.Scope(
			"https://www.googleapis.com/auth/bigquery",
			"https://www.googleapis.com/auth/blogger",
		),
		google.Endpoint(),
	)
	if err != nil {
		log.Fatal(err)
	}
	// Redirect user to Google's consent page to ask for permission
	// for the scopes specified above.
	url := opts.AuthCodeURL("state", "online", "auto")
	fmt.Printf("Visit the URL for the auth dialog: %v", url)

	// Handle the exchange code to initiate a transport
	t, err := opts.NewTransportFromCode("exchange-code")
	if err != nil {
		log.Fatal(err)
	}
	client := http.Client{Transport: t}
	client.Get("...")
}
Beispiel #4
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)
	}
}
Beispiel #5
0
func Test_Logout(t *testing.T) {
	recorder := httptest.NewRecorder()
	s := sessions.NewCookieStore([]byte("secret123"))

	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", s))
	m.Use(Google(
		oauth2.Client("foo", "foo"),
		oauth2.RedirectURL("foo"),
	))
	m.Get("/", func(s sessions.Session) {
		s.Set(keyToken, "dummy token")
	})
	m.Get("/get", func(s sessions.Session) {
		if s.Get(keyToken) != nil {
			t.Errorf("User credentials are still kept in the session.")
		}
	})

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

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

	if recorder.Code != 302 {
		t.Errorf("Not being redirected to the next page.")
	}
}
Beispiel #6
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)
}
Beispiel #7
0
func Test_InjectedTokens(t *testing.T) {
	recorder := httptest.NewRecorder()
	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	m.Use(Google(
		oauth2.Client("foo", "foo"),
		oauth2.RedirectURL("foo"),
	))
	m.Get("/", func(tokens Tokens) string {
		return "Hello world!"
	})
	r, _ := http.NewRequest("GET", "/", nil)
	m.ServeHTTP(recorder, r)
}
Beispiel #8
0
func NewServer(databaseName string) *martini.ClassicMartini {

	m := martini.Classic()
	c := config.GetConfig()

	// Setup middleware
	m.Use(db.DB(databaseName))
	m.Use(render.Renderer())
	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"http://localhost*"},
		AllowMethods:     []string{"POST", "GET"},
		AllowHeaders:     []string{"Origin"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	// Google OAuth
	m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte(c.Cookie_Auth),
		[]byte(c.Cookie_Enc))))

	m.Use(oauth2.Google(
		goauth2.Client(c.Client_Id, c.Client_Secret),
		goauth2.RedirectURL(c.OAuth_Callback),
		goauth2.Scope("email"),
	))

	// Static Assets
	m.Use(martini.Static("frontend/dist"))

	// Setup event routes
	m.Get(`/events`, controllers.GetAllEvents)
	m.Get(`/events/:id`, controllers.GetEvent)
	m.Post(`/events`, binding.Json(models.Event{}), binding.ErrorHandler, controllers.AddEvent)

	// Setup comment routes
	m.Get(`/events/:event_id/comments`, controllers.GetAllComments)
	m.Post(`/events/:event_id/comments`, binding.Json(models.Comment{}), binding.ErrorHandler, controllers.AddComment)

	// User route for Oauth
	m.Get(`/users`, oauth2.LoginRequired, controllers.GetLoggedInUser)

	// TODO Update, Delete for events
	//m.Put(`/events/:id`, UpdateEvent)
	//m.Delete(`/events/:id`, DeleteEvent)

	// Add the router action

	return m
}
Beispiel #9
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")
}
Beispiel #10
0
func Test_LoginRequired(t *testing.T) {
	recorder := httptest.NewRecorder()
	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	m.Use(Google(
		oauth2.Client("foo", "foo"),
		oauth2.RedirectURL("foo"),
	))
	m.Get("/", LoginRequired, func(tokens Tokens) string {
		return "Hello world!"
	})
	r, _ := http.NewRequest("GET", "/", nil)
	m.ServeHTTP(recorder, r)
	if recorder.Code != 302 {
		t.Errorf("Not being redirected to the auth page although user is not logged in.")
	}
}
Beispiel #11
0
func Test_LoginRedirect(t *testing.T) {
	recorder := httptest.NewRecorder()
	m := martini.New()
	m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	m.Use(Google(
		oauth2.Client("client_id", "client_secret"),
		oauth2.RedirectURL("redirect_url"),
		oauth2.Scope("x", "y"),
	))
	r, _ := http.NewRequest("GET", "/login", nil)
	m.ServeHTTP(recorder, r)
	location := recorder.HeaderMap["Location"][0]
	if recorder.Code != 302 {
		t.Errorf("Not being redirected to the auth page.")
	}
	if location != "https://accounts.google.com/o/oauth2/auth?client_id=client_id&redirect_uri=redirect_url&response_type=code&scope=x+y&state=%2F" {
		t.Errorf("Not being redirected to the right page, %v found", location)
	}
}
Beispiel #12
0
func Test_LoginRedirectAfterLoginRequired(t *testing.T) {
	recorder := httptest.NewRecorder()
	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	m.Use(Google(
		oauth2.Client("client_id", "client_secret"),
		oauth2.RedirectURL("redirect_url"),
		oauth2.Scope("x", "y"),
	))
	m.Get("/login-required", LoginRequired, func(tokens Tokens) (int, string) {
		return 200, tokens.Access()
	})
	r, _ := http.NewRequest("GET", "/login-required?key=value", nil)
	m.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)
	}
}
Beispiel #13
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)
	}
}
Beispiel #14
0
func Test_Logout(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("/", 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.")
	}
}
Beispiel #15
0
func Test_LoginRequired(t *testing.T) {
	recorder := httptest.NewRecorder()
	n := negroni.Classic()
	n.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	n.Use(Google(
		goauth2.Client("foo", "foo"),
		goauth2.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)
	}
}