Example #1
0
func TestOAuth2HandlerBeginAuthURLWithBaseMultipleScope(t *testing.T) {

	common.SetSecurityKey("rAALj6QhRjsTo3VKzfWuK21qNZ5bFfqPJ9sYNerSYeKKoMIPAi9vaIusjmqyLE3S")

	base := "https://base.url/auth"

	config := &common.Config{Map: objx.MSI()}
	config.
		Set("client_id", "client_id").
		Set("redirect_uri", "redirect_uri").
		Set("scope", "scope1 scope2").
		Set("access_type", "access_type").
		Set("approval_prompt", "approval_prompt")

	state := &common.State{Map: objx.MSI("after", "http://www.stretchr.com/")}
	base64State, _ := state.Base64()

	url, err := GetBeginAuthURLWithBase(base, state, config)

	if assert.NoError(t, err) {
		assert.Contains(t, url, "client_id=client_id")
		assert.Contains(t, url, "redirect_uri=redirect_uri")
		assert.Contains(t, url, "scope=scope1+scope2")
		assert.Contains(t, url, "access_type=access_type")
		assert.Contains(t, url, "approval_prompt=approval_prompt")
		assert.Contains(t, url, "state="+base64State)
	}

}
Example #2
0
func TestUnMarshal_ObjxMap(t *testing.T) {

	obj1 := objx.MSI("name", "Mat", "age", 30, "language", "en")
	obj2 := objx.MSI("obj", obj1)
	obj3 := objx.MSI("another_obj", obj2)

	csvCodec := new(CsvCodec)
	bytes, _ := csvCodec.Marshal(obj3, nil)

	log.Printf("bytes = %s", string(bytes))

	// unmarshal it back
	var obj interface{}
	csvCodec.Unmarshal(bytes, &obj)

	if objmap, ok := obj.(map[string]interface{}); ok {
		if objmap2, ok := objmap["another_obj"].(map[string]interface{}); ok {
			if objmap3, ok := objmap2["obj"].(map[string]interface{}); ok {

				assert.Equal(t, "Mat", objmap3["name"])
				assert.Equal(t, 30, objmap3["age"])
				assert.Equal(t, "en", objmap3["language"])

			} else {
				assert.True(t, false, "another_obj.obj should be msi")
			}
		} else {
			assert.True(t, false, "another_obj should be msi")
		}
	} else {
		assert.True(t, false, "obj should be msi")
	}

}
func TestOAuth2Provider_Non200Response(t *testing.T) {

	config := &common.Config{
		Map: objx.MSI(
			OAuth2KeyRedirectUrl, OAuth2KeyRedirectUrl,
			OAuth2KeyScope, OAuth2KeyScope,
			OAuth2KeyClientID, OAuth2KeyClientID,
			OAuth2KeySecret, OAuth2KeySecret,
			OAuth2KeyAuthURL, OAuth2KeyAuthURL,
			OAuth2KeyTokenURL, OAuth2KeyTokenURL)}

	testTripperFactory := new(test.TestTripperFactory)
	testTripper := new(test.TestTripper)
	testProvider := new(test.TestProvider)

	testResponse := new(http.Response)
	testResponse.Header = make(http.Header)
	testResponse.Header.Set("Content-Type", "text/plain")
	testResponse.StatusCode = 401
	testResponse.Body = ioutil.NopCloser(strings.NewReader("No mate"))

	testTripperFactory.On("NewTripper", common.EmptyCredentials, mock.Anything).Return(testTripper, nil)
	testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

	data := objx.MSI(OAuth2KeyCode, []string{"123"})
	_, err := CompleteAuth(testTripperFactory, data, config, testProvider)

	if assert.Error(t, err) {
		assert.IsType(t, &common.AuthServerError{}, err)
	}

	mock.AssertExpectationsForObjects(t, testTripperFactory.Mock, testTripper.Mock, testProvider.Mock)

}
Example #4
0
func TestspotifyGetBeginAuthURL(t *testing.T) {

	common.SetSecurityKey("ABC123")

	state := &common.State{Map: objx.MSI("after", "http://www.chikin14niwa.com/")}

	g := New("clientID", "secret", "http://myapp.com/")

	url, err := g.GetBeginAuthURL(state, nil)

	if assert.NoError(t, err) {
		assert.Contains(t, url, "client_id=clientID")
		assert.Contains(t, url, "redirect_uri=http%3A%2F%2Fmyapp.com%2F")
		assert.Contains(t, url, "scope="+spotifyDefaultScope)
		assert.Contains(t, url, "access_type="+oauth2.OAuth2AccessTypeOnline)
		assert.Contains(t, url, "approval_prompt="+oauth2.OAuth2ApprovalPromptAuto)
	}

	state = &common.State{Map: objx.MSI("after", "http://www.chikin14niwa.com/")}

	g = New("clientID", "secret", "http://myapp.com/")

	url, err = g.GetBeginAuthURL(state, objx.MSI(oauth2.OAuth2KeyScope, "avatar"))

	if assert.NoError(t, err) {
		assert.Contains(t, url, "client_id=clientID")
		assert.Contains(t, url, "redirect_uri=http%3A%2F%2Fmyapp.com%2F")
		assert.Contains(t, url, "scope=avatar+"+spotifyDefaultScope)
		assert.Contains(t, url, "access_type="+oauth2.OAuth2AccessTypeOnline)
		assert.Contains(t, url, "approval_prompt="+oauth2.OAuth2ApprovalPromptAuto)
	}

}
Example #5
0
func TestNewUser(t *testing.T) {
	testProvider := new(test.TestProvider)
	testProvider.On("Name").Return("providerName")

	data := objx.MSI(
		spotifyKeyID, "123435467890",
		spotifyKeyName, "Mathew",
		spotifyKeyEmail, "*****@*****.**",
		spotifyKeyNickname, "Mat",
	)

	creds := &common.Credentials{Map: objx.MSI(oauth2.OAuth2KeyAccessToken, "ABC123")}

	user := NewUser(data, creds, testProvider)

	if assert.NotNil(t, user) {

		assert.Equal(t, data, user.Data())

		assert.Equal(t, "Mathew", user.Name())
		assert.Equal(t, "*****@*****.**", user.Email())
		assert.Equal(t, "Mat", user.Nickname())

		// check provider credentials
		creds := user.ProviderCredentials()[testProvider.Name()]
		if assert.NotNil(t, creds) {
			assert.Equal(t, "ABC123", creds.Get(oauth2.OAuth2KeyAccessToken).Str())
			assert.Equal(t, "123435467890", creds.Get(common.CredentialsKeyID).Str())
		}

	}

	mock.AssertExpectationsForObjects(t, testProvider.Mock)
}
Example #6
0
func TestNewUser(t *testing.T) {

	testProvider := new(test.TestProvider)
	testProvider.On("Name").Return("providerName")

	data := objx.MSI(
		instagramKeyID, "123435467890",
		instagramKeyName, "Raquel",
		instagramKeyNickname, "maggit",
		instagramKeyAvatarUrl, "http://instagram.com/")
	creds := &common.Credentials{Map: objx.MSI(oauth2.OAuth2KeyAccessToken, "ABC12345")}

	user := NewUser(data, creds, testProvider)

	if assert.NotNil(t, user) {

		assert.Equal(t, data, user.Data())

		assert.Equal(t, "Raquel", user.Name())
		assert.Equal(t, "maggit", user.Nickname())
		assert.Equal(t, "http://instagram.com/", user.AvatarURL())

		// check provider credentials
		creds := user.ProviderCredentials()[testProvider.Name()]
		if assert.NotNil(t, creds) {
			assert.Equal(t, "ABC12345", creds.Get(oauth2.OAuth2KeyAccessToken).Str())
			assert.Equal(t, "123435467890", creds.Get(common.CredentialsKeyID).Str())
		}

	}

	mock.AssertExpectationsForObjects(t, testProvider.Mock)

}
Example #7
0
func TestIDForProvider(t *testing.T) {
	user := new(User)
	user.data = objx.MSI(
		common.UserKeyProviderCredentials,
		map[string]*common.Credentials{
			"github": &common.Credentials{Map: objx.MSI(common.CredentialsKeyID, "githubid")},
			"google": &common.Credentials{Map: objx.MSI(common.CredentialsKeyID, "googleid")}})

	assert.Equal(t, "githubid", user.IDForProvider("github"))
	assert.Equal(t, "googleid", user.IDForProvider("google"))
}
Example #8
0
func TestGetUser(t *testing.T) {

	g := New("clientID", "secret", "http://myapp.com/")
	creds := &common.Credentials{Map: objx.MSI()}

	testTripperFactory := new(test.TestTripperFactory)
	testTripper := new(test.TestTripper)
	testTripperFactory.On("NewTripper", mock.Anything, g).Return(testTripper, nil)
	testResponse := new(http.Response)
	testResponse.Header = make(http.Header)
	testResponse.Header.Set("Content-Type", "application/json")
	testResponse.StatusCode = 200
	testResponse.Body = ioutil.NopCloser(strings.NewReader(`{"name":"their-name","id":"uniqueid","login":"******","email":"*****@*****.**","picture":"http://myface.com/","blog":"http://blog.com/"}`))
	testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

	g.tripperFactory = testTripperFactory

	user, err := g.GetUser(creds)

	if assert.NoError(t, err) && assert.NotNil(t, user) {

		assert.Equal(t, user.Name(), "their-name")
		assert.Equal(t, user.AuthCode(), "") // doesn't come from google
		assert.Equal(t, user.Email(), "*****@*****.**")
		assert.Equal(t, user.AvatarURL(), "http://myface.com/")
		assert.Equal(t, user.Data()["blog"], "http://blog.com/")

		googleCreds := user.ProviderCredentials()[googleName]
		if assert.NotNil(t, googleCreds) {
			assert.Equal(t, "uniqueid", googleCreds.Get(common.CredentialsKeyID).Str())
		}

	}

}
Example #9
0
func TestMarshalWithCodec_WithError(t *testing.T) {

	// func (s *WebCodecService) MarshalWithCodec(codec codecs.Codec, object interface{}, options ...interface{}) ([]byte, error) {

	testCodec := new(test.TestCodec)
	service := NewWebCodecService()

	// make some test stuff
	object := objx.MSI("Name", "Mat")
	var option1 string = "Option One"
	var option2 string = "Option Two"

	args := map[string]interface{}{option1: option1, option2: option2}

	// setup expectations
	testCodec.On("Marshal", object, args).Return(nil, assert.AnError)

	_, err := service.MarshalWithCodec(testCodec, object, args)

	assert.Equal(t, assert.AnError, err, "The error should get returned")

	// assert that our expectations were met
	mock.AssertExpectationsForObjects(t, testCodec.Mock)

}
Example #10
0
func TestMarshalWithCodec(t *testing.T) {

	testCodec := new(test.TestCodec)
	service := NewWebCodecService()

	// make some test stuff
	var bytesToReturn []byte = []byte("Hello World")
	var object objx.Map = objx.MSI("Name", "Mat")
	var option1 string = "Option One"
	var option2 string = "Option Two"

	args := map[string]interface{}{option1: option1, option2: option2}

	// setup expectations
	testCodec.On("Marshal", object, args).Return(bytesToReturn, nil)

	bytes, err := service.MarshalWithCodec(testCodec, object, args)

	if assert.Nil(t, err) {
		assert.Equal(t, string(bytesToReturn), string(bytes))
	}

	// assert that our expectations were met
	mock.AssertExpectationsForObjects(t, testCodec.Mock)

}
func TestRoundTrip(t *testing.T) {

	underlyingTripper := new(testifyhttp.TestRoundTripper)
	testProvider := new(test.TestProvider)
	creds := &common.Credentials{Map: objx.MSI()}
	creds.Set(OAuth2KeyAccessToken, "This is a real access token :)")

	tripper := new(OAuth2Tripper)
	tripper.underlyingTransport = underlyingTripper
	tripper.credentials = creds
	tripper.provider = testProvider

	request, _ := http.NewRequest("GET", "something", nil)

	underlyingTripper.On("RoundTrip", mock.Anything).Return(new(http.Response), nil)

	response, err := tripper.RoundTrip(request)

	if assert.NoError(t, err) {
		if assert.NotNil(t, response) {

			actualRequest := underlyingTripper.Calls[0].Arguments[0].(*http.Request)

			if assert.NotEqual(t, &actualRequest, &request, "Actual request should be different") {
				headerK, headerV := AuthorizationHeader(creds)
				assert.Equal(t, actualRequest.Header.Get(headerK), headerV)
			}

		}
	}

	mock.AssertExpectationsForObjects(t, testProvider.Mock, underlyingTripper.Mock)

}
Example #12
0
// GetBeginAuthURLWithBase returns the OAuth2 authorization URL from the given arguments.
//
// The state object will be encoded to base64 and signed to ensure integrity.
func GetBeginAuthURLWithBase(base string, state *common.State, config *common.Config) (string, error) {

	if config == nil {
		panic("OAuth2Handler: Must have valid Config specified.")
	}

	// copy the config
	params := objx.MSI(
		OAuth2KeyClientID, config.Get(OAuth2KeyClientID).Str(),
		OAuth2KeyRedirectUrl, config.Get(OAuth2KeyRedirectUrl).Str(),
		OAuth2KeyScope, config.Get(OAuth2KeyScope).Str(),
		OAuth2KeyAccessType, config.Get(OAuth2KeyAccessType).Str(),
		OAuth2KeyApprovalPrompt, config.Get(OAuth2KeyApprovalPrompt).Str(),
		OAuth2KeyResponseType, config.Get(OAuth2KeyResponseType).Str())

	// set the state
	stateValue, stateErr := state.SignedBase64(common.GetSecurityKey())

	if stateErr != nil {
		return "", stateErr
	}

	params.Set("state", stateValue)

	// generate the query part
	query, queryErr := params.URLQuery()

	if queryErr != nil {
		return "", queryErr
	}

	// put the strings together
	return base + "?" + query, nil
}
Example #13
0
func TestOAuth2HandlerBeginAuthURLWithBaseWithoutState(t *testing.T) {

	common.SetSecurityKey("rAALj6QhRjsTo3VKzfWuK21qNZ5bFfqPJ9sYNerSYeKKoMIPAi9vaIusjmqyLE3S")

	base := "https://base.url/auth"

	config := &common.Config{Map: objx.MSI()}
	config.
		Set("client_id", "client_id").
		Set("redirect_uri", "redirect_uri").
		Set("scope", "scope").
		Set("access_type", "access_type").
		Set("approval_prompt", "approval_prompt")

	url, err := GetBeginAuthURLWithBase(base, nil, config)

	if assert.NoError(t, err) {
		assert.Contains(t, url, "client_id=client_id")
		assert.Contains(t, url, "redirect_uri=redirect_uri")
		assert.Contains(t, url, "scope=scope")
		assert.Contains(t, url, "access_type=access_type")
		assert.Contains(t, url, "approval_prompt=approval_prompt")
		assert.NotContains(t, url, "state=")
	}

}
Example #14
0
func TestGetUser(t *testing.T) {

	g := New("clientID", "secret", "http://myapp.com/")
	creds := &common.Credentials{Map: objx.MSI()}

	testTripperFactory := new(test.TestTripperFactory)
	testTripper := new(test.TestTripper)
	testTripperFactory.On("NewTripper", mock.Anything, g).Return(testTripper, nil)
	testResponse := new(http.Response)
	testResponse.Header = make(http.Header)
	testResponse.Header.Set("Content-Type", "application/json")
	testResponse.StatusCode = 200
	testResponse.Body = ioutil.NopCloser(strings.NewReader(`{"full_name":"their-name","id":"uniqueid","username":"******","avatar_url":"http://myface.com/","online":true}`))
	testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

	g.tripperFactory = testTripperFactory

	user, err := g.GetUser(creds)

	if assert.NoError(t, err) && assert.NotNil(t, user) {
		assert.Equal(t, user.Name(), "their-name")
		assert.Equal(t, user.AuthCode(), "")
		assert.Equal(t, user.Nickname(), "loginname")
		assert.Equal(t, user.Email(), "") // doesn't come from soundcloud
		assert.Equal(t, user.AvatarURL(), "http://myface.com/")
		assert.Equal(t, user.Data()["online"], true)
	}

}
Example #15
0
func TestMarshalWithCodec_WithFacade(t *testing.T) {

	// func (s *WebCodecService) MarshalWithCodec(codec codecs.Codec, object interface{}, options ...interface{}) ([]byte, error) {

	testCodec := new(test.TestCodec)
	service := NewWebCodecService()

	// make some test stuff
	var bytesToReturn []byte = []byte("Hello World")
	testObjectWithFacade := new(test.TestObjectWithFacade)
	object := objx.MSI("Name", "Mat")
	var option1 string = "Option One"
	var option2 string = "Option Two"

	args := map[string]interface{}{option1: option1, option2: option2}

	// setup expectations
	testObjectWithFacade.On("PublicData", args).Return(object, nil)
	testCodec.On("Marshal", object, args).Return(bytesToReturn, nil)

	bytes, err := service.MarshalWithCodec(testCodec, testObjectWithFacade, args)

	if assert.Nil(t, err) {
		assert.Equal(t, string(bytesToReturn), string(bytes))
	}

	// assert that our expectations were met
	mock.AssertExpectationsForObjects(t, testCodec.Mock, testObjectWithFacade.Mock)

}
Example #16
0
func AowQuote(ctx context.Context) error {
	index := randInt(len(quotes))
	quote := quotes[index]
	key := ctx.PathParams().Get("apiKey").Str()

	if valid := isKeyValid(key); valid == true {
		return goweb.API.RespondWithData(ctx, objx.MSI("quote", quote))
	}
	return goweb.API.RespondWithError(ctx, 400, "Access Denied: Invalid API Key")
}
Example #17
0
func TestOAuth2Provider_CompleteAuth_JSON(t *testing.T) {

	config := &common.Config{
		Map: objx.MSI(
			OAuth2KeyRedirectUrl, OAuth2KeyRedirectUrl,
			OAuth2KeyScope, OAuth2KeyScope,
			OAuth2KeyClientID, OAuth2KeyClientID,
			OAuth2KeySecret, OAuth2KeySecret,
			OAuth2KeyAuthURL, OAuth2KeyAuthURL,
			OAuth2KeyTokenURL, OAuth2KeyTokenURL)}

	testTripperFactory := new(test.TestTripperFactory)
	testTripper := new(test.TestTripper)
	testProvider := new(test.TestProvider)

	creds := new(common.Credentials)

	testResponse := new(http.Response)
	testResponse.Header = make(http.Header)
	testResponse.Header.Set("Content-Type", "application/json")
	testResponse.StatusCode = 200
	testResponse.Body = ioutil.NopCloser(strings.NewReader(`{"expires_in":20,"access_token":"ACCESSTOKEN","refresh_token":"REFRESHTOKEN"}`))

	testTripperFactory.On("NewTripper", common.EmptyCredentials, mock.Anything).Return(testTripper, nil)
	testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

	data := objx.MSI(OAuth2KeyCode, []string{"123"})
	creds, err := CompleteAuth(testTripperFactory, data, config, testProvider)

	if assert.NoError(t, err) {
		if assert.NotNil(t, creds, "Creds should be returned") {

			assert.Equal(t, creds.Get(OAuth2KeyAccessToken).Str(), "ACCESSTOKEN")
			assert.Equal(t, creds.Get(OAuth2KeyRefreshToken).Str(), "REFRESHTOKEN")
			assert.Equal(t, creds.Get(OAuth2KeyExpiresIn).Data().(time.Duration), 20000000000)

		}
	}

	mock.AssertExpectationsForObjects(t, testTripperFactory.Mock, testTripper.Mock, testProvider.Mock)

}
Example #18
0
func TestAuthorizationHeader(t *testing.T) {

	creds := &common.Credentials{Map: objx.MSI()}
	accessTokenVal := "ACCESSTOKEN"
	creds.Set(OAuth2KeyAccessToken, accessTokenVal)
	k, v := AuthorizationHeader(creds)

	assert.Equal(t, k, "Authorization")
	assert.Equal(t, "Bearer "+accessTokenVal, v)

}
Example #19
0
func TestMarshal_mapWithTypes(t *testing.T) {

	data := map[string]interface{}{"name": "Mat", "age": 30, "yesOrNo": true}
	options := objx.MSI(OptionIncludeTypeAttributes, true)
	bytes, marshalErr := marshal(data, false, 0, options)

	if assert.NoError(t, marshalErr) {
		assert.Equal(t, "<object><name type=\"string\">Mat</name><age type=\"int\">30</age><yesOrNo type=\"bool\">true</yesOrNo></object>", string(bytes), "Output")
	}

}
Example #20
0
func TestGetUser(t *testing.T) {

	g := New("clientID", "secret", "http://myapp.com/")
	creds := &common.Credentials{Map: objx.MSI()}

	testTripperFactory := new(test.TestTripperFactory)
	testTripper := new(test.TestTripper)
	testTripperFactory.On("NewTripper", mock.Anything, g).Return(testTripper, nil)
	testResponse := new(http.Response)
	testResponse.Header = make(http.Header)
	testResponse.Header.Set("Content-Type", "application/json")
	testResponse.StatusCode = 200
	testResponse.Body = ioutil.NopCloser(strings.NewReader(`{
  "id": "631819186",
  "name": "their-name",
  "first_name": "Mat",
  "last_name": "Ryer",
  "link": "https://www.facebook.com/matryer",
  "username": "******",
  "bio": "http://www.stretchr.com/",
  "gender": "male",
  "email": "*****@*****.**",
  "timezone": -6,
  "locale": "en_GB",
  "verified": true,
  "updated_time": "2013-10-03T19:55:28+0000",
  "picture": {
    "url": "http://www.myface.com/"
  }
  }`))
	testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

	g.tripperFactory = testTripperFactory

	user, err := g.GetUser(creds)

	if assert.NoError(t, err) && assert.NotNil(t, user) {

		assert.Equal(t, user.Name(), "their-name")
		assert.Equal(t, user.AuthCode(), "") // doesn't come from github
		assert.Equal(t, user.Nickname(), "loginname")
		assert.Equal(t, user.Email(), "*****@*****.**")
		assert.Equal(t, user.AvatarURL(), "http://www.myface.com/")
		assert.Equal(t, user.Data()["link"], "https://www.facebook.com/matryer")

		facebookCreds := user.ProviderCredentials()[facebookName]
		if assert.NotNil(t, facebookCreds) {
			assert.Equal(t, "631819186", facebookCreds.Get(common.CredentialsKeyID).Str())
		}

	}

}
Example #21
0
func TestCredentials_PublicData(t *testing.T) {

	creds := &Credentials{objx.MSI("auth", "ABC123", CredentialsKeyID, 123)}

	publicData, _ := codecs.PublicData(creds, nil)

	if assert.NotNil(t, publicData) {
		assert.Equal(t, "ABC123", publicData.(objx.Map)["auth"])
		assert.Equal(t, "123", publicData.(objx.Map)[CredentialsKeyID], "CredentialsKeyID ("+CredentialsKeyID+") must be turned into a string.")
	}

}
Example #22
0
func TestGetUser(t *testing.T) {

	g := New("clientID", "secret", "http://myapp.com/")
	creds := &common.Credentials{Map: objx.MSI()}

	testTripperFactory := new(test.TestTripperFactory)
	testTripper := new(test.TestTripper)
	testTripperFactory.On("NewTripper", mock.Anything, g).Return(testTripper, nil)
	testResponse := new(http.Response)
	testResponse.Header = make(http.Header)
	testResponse.Header.Set("Content-Type", "application/json")
	testResponse.StatusCode = 200
	testResponse.Body = ioutil.NopCloser(strings.NewReader(`{
  "meta":  {
    "code": 200
  },
  "data":  {
    "username": "******",
    "bio": "Programer who loves golang",
    "website": "http://website.com",
    "profile_picture": "http://myinsta.com",
    "full_name": "Raquel H",
    "counts":  {
      "media": 1232323,
      "followed_by": 123,
      "follows": 123
    },
    "id": "12345678"
  }
}`))
	testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

	g.tripperFactory = testTripperFactory

	user, err := g.GetUser(creds)

	if assert.NoError(t, err) && assert.NotNil(t, user) {

		assert.Equal(t, user.Name(), "Raquel H")
		assert.Equal(t, user.AuthCode(), "") // doesn't come from instagram
		assert.Equal(t, user.Nickname(), "maggit")
		assert.Equal(t, user.AvatarURL(), "http://myinsta.com")
		assert.Equal(t, user.Data()["website"], "http://website.com")

		instagramCreds := user.ProviderCredentials()[instagramName]
		if assert.NotNil(t, instagramCreds) {
			assert.Equal(t, "uniqueid", instagramCreds.Get(common.CredentialsKeyID).Str())
		}

	}

}
func TestNewOAuth2Tripper(t *testing.T) {

	testProvider := new(test.TestProvider)
	creds := &common.Credentials{Map: objx.MSI()}
	var tripper common.Tripper = NewOAuth2Tripper(creds, testProvider)

	if assert.NotNil(t, tripper) {
		assert.Equal(t, creds, tripper.Credentials())
		assert.Equal(t, http.DefaultTransport, tripper.(*OAuth2Tripper).underlyingTransport)
		assert.Equal(t, testProvider, tripper.Provider())
	}

}
Example #24
0
func TestGetUser(t *testing.T) {

	g := New("clientID", "secret", "http://myapp.com/")
	creds := &common.Credentials{Map: objx.MSI()}

	testTripperFactory := new(test.TestTripperFactory)
	testTripper := new(test.TestTripper)
	testTripperFactory.On("NewTripper", mock.Anything, g).Return(testTripper, nil)
	testResponse := new(http.Response)
	testResponse.Header = make(http.Header)
	testResponse.Header.Set("Content-Type", "application/json")
	testResponse.StatusCode = 200
	testResponse.Body = ioutil.NopCloser(strings.NewReader(`{
  "display_name":"JMWizzler",
  "email":"*****@*****.**",
  "external_urls":{
    "spotify":"https://open.spotify.com/user/wizzler"
  },
  "href":"https://api.spotify.com/v1/users/wizzler",
  "id":"wizzler",
  "images":[{
    "height":null,
    "url":"https://fbcdn.example.com/2330_n.jpg",
    "width":null
  }],
  "type":"user",
  "uri":"spotify:user:wizzler"
}`))
	testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

	g.tripperFactory = testTripperFactory

	user, err := g.GetUser(creds)

	if assert.NoError(t, err) && assert.NotNil(t, user) {

		assert.Equal(t, user.Name(), "JMWizzler")
		assert.Equal(t, user.AuthCode(), "") // doesn't come from spotify
		assert.Equal(t, user.Nickname(), "") // doesn't come from spotify
		assert.Equal(t, user.Email(), "*****@*****.**")
		assert.Equal(t, user.AvatarURL(), "https://fbcdn.example.com/2330_n.jpg")
		assert.Equal(t, user.Data()["href"], "https://api.spotify.com/v1/users/wizzler")

		spotifyCreds := user.ProviderCredentials()[spotifyName]
		if assert.NotNil(t, spotifyCreds) {
			assert.Equal(t, "wizzler", spotifyCreds.Get(common.CredentialsKeyID).Str())
		}

	}

}
Example #25
0
func New(clientId, clientSecret, redirectUrl string) *LineProvider {
	p := new(LineProvider)
	p.config = &common.Config{Map: objx.MSI(
		oauth2.OAuth2KeyAuthURL, lineAuthURL,
		oauth2.OAuth2KeyTokenURL, lineTokenURL,
		oauth2.OAuth2KeyClientID, clientId,
		oauth2.OAuth2KeySecret, clientSecret,
		oauth2.OAuth2KeyRedirectUrl, redirectUrl,
		oauth2.OAuth2KeyScope, lineDefaultScope,
		oauth2.OAuth2KeyAccessType, oauth2.OAuth2AccessTypeOnline,
		oauth2.OAuth2KeyApprovalPrompt, oauth2.OAuth2ApprovalPromptAuto,
		oauth2.OAuth2KeyResponseType, oauth2.OAuth2KeyCode)}
	return p
}
Example #26
0
func New(cfg *Config) *HeroProvider {
	p := &HeroProvider{}
	p.config = &common.Config{Map: objx.MSI(
		oauth2.OAuth2KeyAuthURL, cfg.AuthURL,
		oauth2.OAuth2KeyTokenURL, cfg.TokenURL,
		oauth2.OAuth2KeyClientID, cfg.CLientID,
		oauth2.OAuth2KeySecret, cfg.CLientSecret,
		oauth2.OAuth2KeyRedirectUrl, cfg.RedirectURL,
		oauth2.OAuth2KeyScope, cfg.DefaultScope,
		oauth2.OAuth2KeyAccessType, oauth2.OAuth2AccessTypeOnline,
		oauth2.OAuth2KeyApprovalPrompt, oauth2.OAuth2ApprovalPromptAuto,
		oauth2.OAuth2KeyResponseType, oauth2.OAuth2KeyCode)}
	p.cfg = cfg
	return p
}
Example #27
0
func TestProviderPublicData(t *testing.T) {

	provider := new(test.TestProvider)

	provider.On("Name").Return("TestName")
	provider.On("DisplayName").Return("TestDisplayName")

	publicData, _ := ProviderPublicData(provider, objx.MSI("loginpathFormat", "~auth/%s/login"))
	publicDataMap := publicData.(map[string]interface{})

	assert.Equal(t, publicDataMap["name"], "TestName")
	assert.Equal(t, publicDataMap["display"], "TestDisplayName")
	assert.Equal(t, publicDataMap["loginpath"], "~auth/TestName/login")

}
Example #28
0
func TestSoundcloudGetBeginAuthURL(t *testing.T) {

	common.SetSecurityKey("ABC123")

	state := &common.State{Map: objx.MSI("after", "http://www.stretchr.com/")}

	g := New("clientID", "secret", "http://myapp.com/")

	url, err := g.GetBeginAuthURL(state, nil)

	if assert.NoError(t, err) {
		assert.Contains(t, url, "client_id=clientID")
		assert.Contains(t, url, "redirect_uri=http%3A%2F%2Fmyapp.com%2F")
		assert.Contains(t, url, "scope="+soundcloudDefaultScope)
		assert.Contains(t, url, "access_type="+oauth2.OAuth2AccessTypeOnline)
		assert.Contains(t, url, "approval_prompt="+oauth2.OAuth2ApprovalPromptAuto)
	}
}
Example #29
0
func TestGetUser(t *testing.T) {

	g := New("clientID", "secret", "http://myapp.com/")
	creds := &common.Credentials{Map: objx.MSI()}

	testTripperFactory := new(test.TestTripperFactory)
	testTripper := new(test.TestTripper)
	testTripperFactory.On("NewTripper", mock.Anything, g).Return(testTripper, nil)
	testResponse := new(http.Response)
	testResponse.Header = make(http.Header)
	testResponse.Header.Set("Content-Type", "application/json")
	testResponse.StatusCode = 200
	testResponse.Body = ioutil.NopCloser(strings.NewReader(`{
  "first_name": "Raquel",
  "last_name": "Hernandez",
  "email": "*****@*****.**",
  "profile_picture": "http://myuberpic.com",
  "promo_code": "somecode"
  "uuid": "imoqueid"
}`))
	testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

	g.tripperFactory = testTripperFactory

	user, err := g.GetUser(creds)

	if assert.NoError(t, err) && assert.NotNil(t, user) {

		assert.Equal(t, user.Name(), "Raquel")
		assert.Equal(t, user.AuthCode(), "") // doesn't come from uber
		assert.Equal(t, user.Nickname(), "*****@*****.**")
		assert.Equal(t, user.AvatarURL(), "http://myuberpic.com")
		assert.Equal(t, user.Data()["promo_code"], "somecode")

		uberCreds := user.ProviderCredentials()[uberName]
		if assert.NotNil(t, uberCreds) {
			assert.Equal(t, "uniqueid", uberCreds.Get(common.CredentialsKeyID).Str())
		}

	}

}
Example #30
0
// CompleteAuth takes a map of arguments that are used to
// complete the authorisation process, completes it, and returns
// the appropriate common.Credentials.
//
// The data must contain an OAuth2KeyCode obtained from the auth
// server.
func CompleteAuth(tripperFactory common.TripperFactory, data objx.Map, config *common.Config, provider common.Provider) (*common.Credentials, error) {

	// get the code
	codeList := data.Get(OAuth2KeyCode).Data()

	code, ok := codeList.(string)
	if !ok {

		if codeList == nil || len(codeList.([]string)) == 0 {
			return nil, &common.MissingParameterError{ParameterName: OAuth2KeyCode}
		}
		code = codeList.([]string)[0]
		if len(code) == 0 {
			return nil, &common.MissingParameterError{ParameterName: OAuth2KeyCode}
		}
	}

	client, clientErr := GetClient(tripperFactory, common.EmptyCredentials, provider)
	if clientErr != nil {
		return nil, clientErr
	}

	params := objx.MSI(OAuth2KeyGrantType, OAuth2GrantTypeAuthorizationCode,
		OAuth2KeyRedirectUrl, config.Get(OAuth2KeyRedirectUrl).Str(),
		OAuth2KeyScope, config.Get(OAuth2KeyScope).Str(),
		OAuth2KeyCode, code,
		OAuth2KeyClientID, config.Get(OAuth2KeyClientID).Str(),
		OAuth2KeySecret, config.Get(OAuth2KeySecret).Str())

	// post the form
	response, requestErr := client.PostForm(config.Get(OAuth2KeyTokenURL).Str(), params.URLValues())

	if requestErr != nil {
		return nil, requestErr
	}

	// make sure we close the body
	defer func() {
		if response.Body != nil {
			response.Body.Close()
		}
	}()

	// make sure we have an OK response
	if response.StatusCode != http.StatusOK {
		return nil, &common.AuthServerError{
			ErrorMessage: fmt.Sprintf("Server replied with %s.", response.Status),
			Response:     response,
		}
	}

	content, _, mimeTypeErr := mime.ParseMediaType(response.Header.Get("Content-Type"))

	if mimeTypeErr != nil {
		return nil, mimeTypeErr
	}

	// prepare the credentials object
	creds := &common.Credentials{Map: objx.MSI()}

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}

	switch content {
	case "application/x-www-form-urlencoded", "text/plain":

		vals, err := objx.FromURLQuery(string(body))
		if err != nil {
			return nil, err
		}

		// did an error occur?
		if len(vals.Get("error").Str()) > 0 {
			return nil, &common.AuthServerError{
				ErrorMessage: vals.Get("error").Str(),
				Response:     response,
			}
		}

		expiresIn, _ := time.ParseDuration(vals.Get(OAuth2KeyExpiresIn).Str() + "s")

		creds.Set(OAuth2KeyAccessToken, vals.Get(OAuth2KeyAccessToken).Str())
		creds.Set(OAuth2KeyRefreshToken, vals.Get(OAuth2KeyRefreshToken).Str())
		creds.Set(OAuth2KeyExpiresIn, expiresIn)

	default: // use JSON

		var data objx.Map

		jsonErr := json.Unmarshal(body, &data)

		if jsonErr != nil {
			return nil, jsonErr
		}

		// handle the time
		timeDuration := data.Get(OAuth2KeyExpiresIn).Float64()
		data.Set(OAuth2KeyExpiresIn, time.Duration(timeDuration)*time.Second)

		// merge this data into the creds
		creds.MergeHere(data)

	}

	return creds, nil
}