예제 #1
0
func TestLoginHandler(t *testing.T) {
	expectedToken := "request_token"
	expectedSecret := "request_secret"
	data := url.Values{}
	data.Add("oauth_token", expectedToken)
	data.Add("oauth_token_secret", expectedSecret)
	data.Add("oauth_callback_confirmed", "true")
	server := NewRequestTokenServer(t, data)
	defer server.Close()

	config := &oauth1.Config{
		Endpoint: oauth1.Endpoint{
			RequestTokenURL: server.URL,
		},
	}
	success := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
		requestToken, requestSecret, err := RequestTokenFromContext(ctx)
		assert.Equal(t, expectedToken, requestToken)
		assert.Equal(t, expectedSecret, requestSecret)
		assert.Nil(t, err)
		fmt.Fprintf(w, "success handler called")
	}
	failure := testutils.AssertFailureNotCalled(t)

	// LoginHandler gets OAuth1 request token, assert that:
	// - success handler is called
	// - request token added to the ctx of the success handler
	// - request secret added to the ctx of the success handler
	// - failure handler is not called
	loginHandler := LoginHandler(config, ctxh.ContextHandlerFunc(success), failure)
	w := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/", nil)
	loginHandler.ServeHTTP(context.Background(), w, req)
	assert.Equal(t, "success handler called", w.Body.String())
}
예제 #2
0
func TestGithubHandler(t *testing.T) {
	jsonData := `{"id": 917408, "name": "Alyssa Hacker"}`
	expectedUser := &github.User{ID: github.Int(917408), Name: github.String("Alyssa Hacker")}
	proxyClient, server := newGithubTestServer(jsonData)
	defer server.Close()
	// oauth2 Client will use the proxy client's base Transport
	ctx := context.WithValue(context.Background(), oauth2.HTTPClient, proxyClient)
	anyToken := &oauth2.Token{AccessToken: "any-token"}
	ctx = oauth2Login.WithToken(ctx, anyToken)

	config := &oauth2.Config{}
	success := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
		githubUser, err := UserFromContext(ctx)
		assert.Nil(t, err)
		assert.Equal(t, expectedUser, githubUser)
		fmt.Fprintf(w, "success handler called")
	}
	failure := testutils.AssertFailureNotCalled(t)

	// GithubHandler assert that:
	// - Token is read from the ctx and passed to the Github API
	// - github User is obtained from the Github API
	// - success handler is called
	// - github User is added to the ctx of the success handler
	githubHandler := githubHandler(config, ctxh.ContextHandlerFunc(success), failure)
	w := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/", nil)
	githubHandler.ServeHTTP(ctx, w, req)
	assert.Equal(t, "success handler called", w.Body.String())
}
예제 #3
0
func TestCallbackHandler(t *testing.T) {
	expectedToken := "acces_token"
	expectedSecret := "access_secret"
	requestSecret := "request_secret"
	data := url.Values{}
	data.Add("oauth_token", expectedToken)
	data.Add("oauth_token_secret", expectedSecret)
	server := NewAccessTokenServer(t, data)
	defer server.Close()

	config := &oauth1.Config{
		Endpoint: oauth1.Endpoint{
			AccessTokenURL: server.URL,
		},
	}
	success := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
		accessToken, accessSecret, err := AccessTokenFromContext(ctx)
		assert.Equal(t, expectedToken, accessToken)
		assert.Equal(t, expectedSecret, accessSecret)
		assert.Nil(t, err)
		fmt.Fprintf(w, "success handler called")
	}
	failure := testutils.AssertFailureNotCalled(t)

	// CallbackHandler gets OAuth1 access token, assert that:
	// - success handler is called
	// - access token and secret added to the ctx of the success handler
	// - failure handler is not called
	callbackHandler := CallbackHandler(config, ctxh.ContextHandlerFunc(success), failure)
	w := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/?oauth_token=any_token&oauth_verifier=any_verifier", nil)
	ctx := WithRequestToken(context.Background(), "", requestSecret)
	callbackHandler.ServeHTTP(ctx, w, req)
	assert.Equal(t, "success handler called", w.Body.String())
}
예제 #4
0
func TestWebHandler(t *testing.T) {
	proxyClient, _, server := newDigitsTestServer(testAccountJSON)
	defer server.Close()

	config := &Config{
		ConsumerKey: testConsumerKey,
		Client:      proxyClient,
	}
	success := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
		account, err := AccountFromContext(ctx)
		assert.Nil(t, err)
		assert.Equal(t, testDigitsToken, account.AccessToken.Token)
		assert.Equal(t, testDigitsSecret, account.AccessToken.Secret)
		assert.Equal(t, "0123456789", account.PhoneNumber)

		endpoint, header, err := EchoFromContext(ctx)
		assert.Nil(t, err)
		assert.Equal(t, testAccountEndpoint, endpoint)
		assert.Equal(t, testAccountRequestHeader, header)
	}
	handler := LoginHandler(config, ctxh.ContextHandlerFunc(success), testutils.AssertFailureNotCalled(t))
	ts := httptest.NewServer(ctxh.NewHandler(handler))
	// POST OAuth Echo to server under test
	resp, err := http.PostForm(ts.URL, url.Values{accountEndpointField: {testAccountEndpoint}, accountRequestHeaderField: {testAccountRequestHeader}})
	assert.Nil(t, err)
	if assert.NotNil(t, resp) {
		assert.Equal(t, http.StatusOK, resp.StatusCode)
	}
}
예제 #5
0
func TestBitbucketHandler(t *testing.T) {
	jsonData := `{"username": "******", "display_name": "Atlas Ian"}`
	expectedUser := &User{Username: "******", DisplayName: "Atlas Ian"}
	proxyClient, server := newBitbucketTestServer(jsonData)
	defer server.Close()
	// oauth2 Client will use the proxy client's base Transport
	ctx := context.WithValue(context.Background(), oauth2.HTTPClient, proxyClient)
	anyToken := &oauth2.Token{AccessToken: "any-token"}
	ctx = oauth2Login.WithToken(ctx, anyToken)

	config := &oauth2.Config{}
	success := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
		bitbucketUser, err := UserFromContext(ctx)
		assert.Nil(t, err)
		assert.Equal(t, expectedUser, bitbucketUser)
		fmt.Fprintf(w, "success handler called")
	}
	failure := testutils.AssertFailureNotCalled(t)

	// BitbucketHandler assert that:
	// - Token is read from the ctx and passed to the Bitbucket API
	// - bitbucket User is obtained from the Bitbucket API
	// - success handler is called
	// - bitbucket User is added to the ctx of the success handler
	bitbucketHandler := bitbucketHandler(config, ctxh.ContextHandlerFunc(success), failure)
	w := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/", nil)
	bitbucketHandler.ServeHTTP(ctx, w, req)
	assert.Equal(t, "success handler called", w.Body.String())
}
예제 #6
0
func TestGoogleHandler(t *testing.T) {
	jsonData := `{"id": "900913", "name": "Ben Bitdiddle"}`
	expectedUser := &google.Userinfoplus{Id: "900913", Name: "Ben Bitdiddle"}
	proxyClient, server := newGoogleTestServer(jsonData)
	defer server.Close()
	// oauth2 Client will use the proxy client's base Transport
	ctx := context.WithValue(context.Background(), oauth2.HTTPClient, proxyClient)
	anyToken := &oauth2.Token{AccessToken: "any-token"}
	ctx = oauth2Login.WithToken(ctx, anyToken)

	config := &oauth2.Config{}
	success := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
		googleUser, err := UserFromContext(ctx)
		assert.Nil(t, err)
		// assert required fields; Userinfoplus contains other raw response info
		assert.Equal(t, expectedUser.Id, googleUser.Id)
		assert.Equal(t, expectedUser.Id, googleUser.Id)
		fmt.Fprintf(w, "success handler called")
	}
	failure := testutils.AssertFailureNotCalled(t)

	// GoogleHandler assert that:
	// - Token is read from the ctx and passed to the Google API
	// - google Userinfoplus is obtained from the Google API
	// - success handler is called
	// - google Userinfoplus is added to the ctx of the success handler
	googleHandler := googleHandler(config, ctxh.ContextHandlerFunc(success), failure)
	w := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/", nil)
	googleHandler.ServeHTTP(ctx, w, req)
	assert.Equal(t, "success handler called", w.Body.String())
}
예제 #7
0
func TestLoginHandler(t *testing.T) {
	expectedState := "state_val"
	expectedRedirect := "https://api.example.com/authorize?client_id=client_id&redirect_uri=redirect_url&response_type=code&state=state_val"
	config := &oauth2.Config{
		ClientID:     "client_id",
		ClientSecret: "client_secret",
		RedirectURL:  "redirect_url",
		Endpoint: oauth2.Endpoint{
			AuthURL: "https://api.example.com/authorize",
		},
	}
	failure := testutils.AssertFailureNotCalled(t)

	// LoginHandler assert that:
	// - redirects to the oauth2.Config AuthURL
	// - redirect status code is 302
	// - redirect url is the OAuth2 Config RedirectURL with the ClientID and ctx state
	loginHandler := LoginHandler(config, failure)
	w := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/", nil)
	ctx := WithState(context.Background(), expectedState)
	loginHandler.ServeHTTP(ctx, w, req)
	assert.Equal(t, http.StatusFound, w.Code)
	assert.Equal(t, expectedRedirect, w.HeaderMap.Get("Location"))
}
예제 #8
0
func TestTokenHandler(t *testing.T) {
	proxyClient, _, server := newDigitsTestServer(testAccountJSON)
	defer server.Close()
	// oauth1 Client will use the proxy client's base Transport
	ctx := context.WithValue(context.Background(), oauth1.HTTPClient, proxyClient)

	config := &oauth1.Config{}
	success := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
		account, err := AccountFromContext(ctx)
		assert.Nil(t, err)
		assert.Equal(t, testDigitsToken, account.AccessToken.Token)
		assert.Equal(t, testDigitsSecret, account.AccessToken.Secret)
		assert.Equal(t, "0123456789", account.PhoneNumber)

		accessToken, accessSecret, err := oauth1Login.AccessTokenFromContext(ctx)
		assert.Nil(t, err)
		assert.Equal(t, testDigitsToken, accessToken)
		assert.Equal(t, testDigitsSecret, accessSecret)
	}
	handler := TokenHandler(config, ctxh.ContextHandlerFunc(success), testutils.AssertFailureNotCalled(t))
	ts := httptest.NewServer(ctxh.NewHandlerWithContext(ctx, handler))
	// POST Digits access token to server under test
	resp, err := http.PostForm(ts.URL, url.Values{accessTokenField: {testDigitsToken}, accessTokenSecretField: {testDigitsSecret}})
	assert.Nil(t, err)
	if assert.NotNil(t, resp) {
		assert.Equal(t, resp.StatusCode, http.StatusOK)
	}
}
예제 #9
0
func TestTokenHandler(t *testing.T) {
	proxyClient, _, server := newTwitterVerifyServer(testTwitterUserJSON)
	defer server.Close()
	// oauth1 Client will use the proxy client's base Transport
	ctx := context.WithValue(context.Background(), oauth1.HTTPClient, proxyClient)

	config := &oauth1.Config{}
	success := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
		accessToken, accessSecret, err := oauth1Login.AccessTokenFromContext(ctx)
		assert.Nil(t, err)
		assert.Equal(t, testTwitterToken, accessToken)
		assert.Equal(t, testTwitterTokenSecret, accessSecret)

		user, err := UserFromContext(ctx)
		assert.Nil(t, err)
		assert.Equal(t, expectedUserID, user.ID)
		assert.Equal(t, "1234", user.IDStr)
	}
	handler := TokenHandler(config, ctxh.ContextHandlerFunc(success), testutils.AssertFailureNotCalled(t))
	ts := httptest.NewServer(ctxh.NewHandlerWithContext(ctx, handler))
	// POST token to server under test
	resp, err := http.PostForm(ts.URL, url.Values{accessTokenField: {testTwitterToken}, accessTokenSecretField: {testTwitterTokenSecret}})
	assert.Nil(t, err)
	if assert.NotNil(t, resp) {
		assert.Equal(t, resp.StatusCode, http.StatusOK)
	}
}
예제 #10
0
func TestCallbackHandler(t *testing.T) {
	expectedState := "d4e5f6"
	jsonData := `{
       "access_token":"2YotnFZFEjr1zCsicMWpAA",
       "token_type":"example",
       "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
       "example_parameter":"example_value"
     }`
	expectedToken := &oauth2.Token{
		AccessToken:  "2YotnFZFEjr1zCsicMWpAA",
		TokenType:    "example",
		RefreshToken: "tGzv3JOkF0XG5Qx2TlKWIA",
	}
	server := NewAccessTokenServer(t, jsonData)
	defer server.Close()

	config := &oauth2.Config{
		Endpoint: oauth2.Endpoint{
			TokenURL: server.URL,
		},
	}
	success := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
		token, err := TokenFromContext(ctx)
		assert.Equal(t, expectedToken.AccessToken, token.AccessToken)
		assert.Equal(t, expectedToken.TokenType, token.Type())
		assert.Equal(t, expectedToken.RefreshToken, token.RefreshToken)
		// real oauth2.Token populates internal raw field and unmockable Expiry time
		assert.Nil(t, err)
		fmt.Fprintf(w, "success handler called")
	}
	failure := testutils.AssertFailureNotCalled(t)

	// CallbackHandler gets OAuth2 access token, assert that:
	// - success handler is called
	// - access token added to the ctx of the success handler
	// - failure handler is not called
	callbackHandler := CallbackHandler(config, ctxh.ContextHandlerFunc(success), failure)
	w := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/?code=any_code&state=d4e5f6", nil)
	ctx := WithState(context.Background(), expectedState)
	callbackHandler.ServeHTTP(ctx, w, req)
	assert.Equal(t, "success handler called", w.Body.String())
}
예제 #11
0
func TestAuthRedirectHandler(t *testing.T) {
	requestToken := "request_token"
	expectedRedirect := "https://api.example.com/authorize?oauth_token=request_token"
	config := &oauth1.Config{
		Endpoint: oauth1.Endpoint{
			AuthorizeURL: "https://api.example.com/authorize",
		},
	}
	failure := testutils.AssertFailureNotCalled(t)

	// AuthRedirectHandler redirects to the AuthorizationURL, assert that:
	// - redirect status code is 302
	// - redirect url is the OAuth1 AuthorizeURL with the ctx request token
	authRedirectHandler := AuthRedirectHandler(config, failure)
	w := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/", nil)
	ctx := WithRequestToken(context.Background(), requestToken, "")
	authRedirectHandler.ServeHTTP(ctx, w, req)
	assert.Equal(t, http.StatusFound, w.Code)
	assert.Equal(t, expectedRedirect, w.HeaderMap.Get("Location"))
}