Open platform to collect and prioritize feedback
move oauth to its package
goenningd29844241568
diff --git a/app/identity/handler.go b/app/identity/handler.goindex 0c3d07bcc..494710058 100644--- a/app/identity/handler.go+++ b/app/identity/handler.go@@ -9,6 +9,7 @@ import ("github.com/WeCanHearYou/wechy/app""github.com/WeCanHearYou/wechy/app/infra""github.com/WeCanHearYou/wechy/app/models"+ "github.com/WeCanHearYou/wechy/app/pkg/oauth""github.com/WeCanHearYou/wechy/app/storage")@@ -21,12 +22,12 @@ type oauthUserProfile struct {// OAuthHandlers contains multiple oauth HTTP handlerstype OAuthHandlers struct {tenantStorage storage.Tenant- oauthService OAuthService+ oauthService oauth.ServiceuserStorage storage.User}// OAuth creates a new OAuthHandlers-func OAuth(tenantStorage storage.Tenant, oauthService OAuthService, userStorage storage.User) OAuthHandlers {+func OAuth(tenantStorage storage.Tenant, oauthService oauth.Service, userStorage storage.User) OAuthHandlers {return OAuthHandlers{tenantStorage, oauthService, userStorage}}diff --git a/app/identity/handler_test.go b/app/identity/handler_test.goindex 15cbd8324..f63b289b3 100644--- a/app/identity/handler_test.go+++ b/app/identity/handler_test.go@@ -9,21 +9,39 @@ import ("github.com/WeCanHearYou/wechy/app/identity""github.com/WeCanHearYou/wechy/app/mock"+ "github.com/WeCanHearYou/wechy/app/pkg/oauth"+ "github.com/WeCanHearYou/wechy/app/pkg/dbx"+ "github.com/WeCanHearYou/wechy/app/storage/postgres". "github.com/onsi/gomega")+var (+ db *dbx.Database+ oauthService oauth.Service+ TenantStorage *postgres.TenantStorage+ UserStorage *postgres.UserStorage+)++func setup() {+ db, _ = dbx.New()++ oauthService = &OAuthService{}+ TenantStorage = &postgres.TenantStorage{DB: db}+ UserStorage = &postgres.UserStorage{DB: db}+}+//OAuthService implements a mocked OAuthServicetype OAuthService struct{}//GetAuthURL returns authentication url for given provider-func (p OAuthService) GetAuthURL(provider string, redirect string) string {+func (p *OAuthService) GetAuthURL(provider string, redirect string) string {return "http://orange.test.canherayou.com/oauth/token?provider=" + provider + "&redirect=" + redirect}//GetProfile returns user profile based on provider and code-func (p OAuthService) GetProfile(provider string, code string) (*identity.OAuthUserProfile, error) {+func (p *OAuthService) GetProfile(provider string, code string) (*oauth.UserProfile, error) {if provider == "facebook" && code == "123" {- return &identity.OAuthUserProfile{+ return &oauth.UserProfile{ID: "FB1234",Name: "Jon Snow",Email: "[email protected]",@@ -31,7 +49,7 @@ func (p OAuthService) GetProfile(provider string, code string) (*identity.OAuthU}if provider == "google" && code == "123" {- return &identity.OAuthUserProfile{+ return &oauth.UserProfile{ID: "GO1234",Name: "Jon Snow",Email: "[email protected]",@@ -39,7 +57,7 @@ func (p OAuthService) GetProfile(provider string, code string) (*identity.OAuthU}if provider == "facebook" && code == "456" {- return &identity.OAuthUserProfile{+ return &oauth.UserProfile{ID: "FB5678",Name: "Some Facebook Guy",Email: "[email protected]",@@ -58,7 +76,7 @@ func TestLoginHandler(t *testing.T) {RegisterTestingT(t)server := mock.NewServer()- code, response := server.ExecuteRaw(handlers().Login(identity.OAuthFacebookProvider))+ code, response := server.ExecuteRaw(handlers().Login(oauth.FacebookProvider))Expect(code).To(Equal(http.StatusTemporaryRedirect))Expect(response.Header.Get("Location")).To(Equal("http://orange.test.canherayou.com/oauth/token?provider=facebook&redirect="))@@ -69,7 +87,7 @@ func TestCallbackHandler_InvalidState(t *testing.T) {server := mock.NewServer()server.Context.Request().URL, _ = url.Parse("http://login.test.canherayou.com/oauth/callback?state=abc")- code, _ := server.ExecuteRaw(handlers().Callback(identity.OAuthFacebookProvider))+ code, _ := server.ExecuteRaw(handlers().Callback(oauth.FacebookProvider))Expect(code).To(Equal(http.StatusInternalServerError))}@@ -79,7 +97,7 @@ func TestCallbackHandler_InvalidCode(t *testing.T) {server := mock.NewServer()server.Context.Request().URL, _ = url.Parse("http://login.test.canherayou.com/oauth/callback?state=http://orange.test.canhearyou.com")- code, response := server.ExecuteRaw(handlers().Callback(identity.OAuthFacebookProvider))+ code, response := server.ExecuteRaw(handlers().Callback(oauth.FacebookProvider))Expect(code).To(Equal(http.StatusTemporaryRedirect))Expect(response.Header.Get("Location")).To(Equal("http://orange.test.canhearyou.com"))@@ -90,7 +108,7 @@ func TestCallbackHandler_ExistingUserAndProvider(t *testing.T) {server := mock.NewServer()server.Context.Request().URL, _ = url.Parse("http://demo.test.canherayou.com/oauth/callback?state=http://demo.test.canhearyou.com&code=123")- code, response := server.ExecuteRaw(handlers().Callback(identity.OAuthFacebookProvider))+ code, response := server.ExecuteRaw(handlers().Callback(oauth.FacebookProvider))Expect(db.Count("SELECT id FROM users WHERE email = '[email protected]'")).To(Equal(1))@@ -103,7 +121,7 @@ func TestCallbackHandler_NewUser(t *testing.T) {server := mock.NewServer()server.Context.Request().URL, _ = url.Parse("http://login.test.canherayou.com/oauth/callback?state=http://orange.test.canhearyou.com&code=456")- code, response := server.ExecuteRaw(handlers().Callback(identity.OAuthFacebookProvider))+ code, response := server.ExecuteRaw(handlers().Callback(oauth.FacebookProvider))Expect(db.QueryInt("SELECT tenant_id FROM users WHERE email = '[email protected]'")).To(Equal(400))Expect(db.Exists("SELECT * FROM user_providers WHERE provider_uid = 'FB5678'")).To(BeTrue())@@ -117,7 +135,7 @@ func TestCallbackHandler_ExistingUser_NewProvider(t *testing.T) {server := mock.NewServer()server.Context.Request().URL, _ = url.Parse("http://login.test.canherayou.com/oauth/callback?state=http://demo.test.canhearyou.com&code=123")- code, response := server.ExecuteRaw(handlers().Callback(identity.OAuthGoogleProvider))+ code, response := server.ExecuteRaw(handlers().Callback(oauth.GoogleProvider))Expect(db.Count("SELECT id FROM users WHERE email = '[email protected]'")).To(Equal(1))Expect(db.QueryString("SELECT provider_uid FROM user_providers WHERE user_id = 300 and provider = 'facebook'")).To(Equal("FB1234"))diff --git a/app/identity/setup_test.go b/app/identity/setup_test.godeleted file mode 100644index 7f2e86128..000000000--- a/app/identity/setup_test.go+++ /dev/null@@ -1,21 +0,0 @@-package identity_test--import (- "github.com/WeCanHearYou/wechy/app/pkg/dbx"- "github.com/WeCanHearYou/wechy/app/storage/postgres"-)--var (- db *dbx.Database- oauthService *OAuthService- TenantStorage *postgres.TenantStorage- UserStorage *postgres.UserStorage-)--func setup() {- db, _ = dbx.New()-- oauthService = &OAuthService{}- TenantStorage = &postgres.TenantStorage{DB: db}- UserStorage = &postgres.UserStorage{DB: db}-}diff --git a/app/identity/oauth.go b/app/pkg/oauth/oauth.gosimilarity index 76%rename from app/identity/oauth.gorename to app/pkg/oauth/oauth.goindex 2b345f3f3..ef931c5e8 100644--- a/app/identity/oauth.go+++ b/app/pkg/oauth/oauth.go@@ -1,4 +1,4 @@-package identity+package oauthimport ("encoding/json"@@ -16,10 +16,10 @@ import ()const (- //OAuthFacebookProvider is const for 'facebook'- OAuthFacebookProvider = "facebook"- //OAuthGoogleProvider is const for 'google'- OAuthGoogleProvider = "google"+ //FacebookProvider is const for 'facebook'+ FacebookProvider = "facebook"+ //GoogleProvider is const for 'google'+ GoogleProvider = "google")type oauthProviderSettings struct {@@ -30,7 +30,7 @@ type oauthProviderSettings struct {var (authEndpoint = os.Getenv("AUTH_ENDPOINT")oauthSettings = map[string]*oauthProviderSettings{- OAuthFacebookProvider: &oauthProviderSettings{+ FacebookProvider: &oauthProviderSettings{profileURL: func(token *oauth2.Token) string {return "https://graph.facebook.com/me?fields=name,email&access_token=" + url.QueryEscape(token.AccessToken)},@@ -42,7 +42,7 @@ var (Endpoint: facebook.Endpoint,},},- OAuthGoogleProvider: &oauthProviderSettings{+ GoogleProvider: &oauthProviderSettings{profileURL: func(token *oauth2.Token) string {return "https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + url.QueryEscape(token.AccessToken)},@@ -75,24 +75,24 @@ func doGet(url string, v interface{}) error {return json.Unmarshal(bytes, v)}-//OAuthUserProfile represents an OAuth user profile-type OAuthUserProfile struct {+//UserProfile represents an OAuth user profile+type UserProfile struct {ID stringName stringEmail string}-//OAuthService provides OAuth operations-type OAuthService interface {+//Service provides OAuth operations+type Service interface {GetAuthURL(provider string, redirect string) string- GetProfile(provider string, code string) (*OAuthUserProfile, error)+ GetProfile(provider string, code string) (*UserProfile, error)}-//HTTPOAuthService implements real OAuth operations using Golang's oauth2 package-type HTTPOAuthService struct{}+//HTTPService implements real OAuth operations using Golang's oauth2 package+type HTTPService struct{}//GetAuthURL returns authentication url for given provider-func (p HTTPOAuthService) GetAuthURL(provider string, redirect string) string {+func (p *HTTPService) GetAuthURL(provider string, redirect string) string {config := oauthSettings[provider].configauthURL, _ := url.Parse(config.Endpoint.AuthURL)@@ -107,14 +107,14 @@ func (p HTTPOAuthService) GetAuthURL(provider string, redirect string) string {}//GetProfile returns user profile based on provider and code-func (p HTTPOAuthService) GetProfile(provider string, code string) (*OAuthUserProfile, error) {+func (p *HTTPService) GetProfile(provider string, code string) (*UserProfile, error) {settings := oauthSettings[provider]oauthToken, err := settings.config.Exchange(oauth2.NoContext, code)if err != nil {return nil, fmt.Errorf("OAuth code Exchange for %s failed with %s", provider, err)}- profile := &OAuthUserProfile{}+ profile := &UserProfile{}if err = doGet(settings.profileURL(oauthToken), profile); err != nil {return nil, fmt.Errorf("HTTP Get profile for %s failed with %s", provider, err)}diff --git a/app/identity/oauth_test.go b/app/pkg/oauth/oauth_test.gosimilarity index 72%rename from app/identity/oauth_test.gorename to app/pkg/oauth/oauth_test.goindex be8c1284b..48d86ebce 100644--- a/app/identity/oauth_test.go+++ b/app/pkg/oauth/oauth_test.go@@ -1,17 +1,17 @@-package identity_test+package oauth_testimport ("testing"- "github.com/WeCanHearYou/wechy/app/identity"+ "github.com/WeCanHearYou/wechy/app/pkg/oauth". "github.com/onsi/gomega")func TestGetAuthURL_Facebook(t *testing.T) {RegisterTestingT(t)- oauth := &identity.HTTPOAuthService{}- authURL := oauth.GetAuthURL(identity.OAuthFacebookProvider, "")+ svc := &oauth.HTTPService{}+ authURL := svc.GetAuthURL(oauth.FacebookProvider, "")Expect(authURL).To(Equal("https://www.facebook.com/dialog/oauth?client_id=&redirect_uri=http%3A%2F%2Flogin.test.canhearyou.com%3A3000%2Foauth%2Ffacebook%2Fcallback&response_type=code&scope=public_profile+email&state="))}@@ -19,8 +19,8 @@ func TestGetAuthURL_Facebook(t *testing.T) {func TestGetAuthURL_Google(t *testing.T) {RegisterTestingT(t)- oauth := &identity.HTTPOAuthService{}- authURL := oauth.GetAuthURL(identity.OAuthGoogleProvider, "")+ svc := &oauth.HTTPService{}+ authURL := svc.GetAuthURL(oauth.GoogleProvider, "")Expect(authURL).To(Equal("https://accounts.google.com/o/oauth2/auth?client_id=&redirect_uri=http%3A%2F%2Flogin.test.canhearyou.com%3A3000%2Foauth%2Fgoogle%2Fcallback&response_type=code&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&state="))}diff --git a/app/storage/postgres/identity_test.go b/app/storage/postgres/identity_test.goindex dc32e8d17..3c91a117d 100644--- a/app/storage/postgres/identity_test.go+++ b/app/storage/postgres/identity_test.go@@ -3,8 +3,8 @@ package postgres_testimport ("testing"- "github.com/WeCanHearYou/wechy/app/identity""github.com/WeCanHearYou/wechy/app/models"+ "github.com/WeCanHearYou/wechy/app/pkg/oauth""github.com/WeCanHearYou/wechy/app/pkg/dbx""github.com/WeCanHearYou/wechy/app/storage/postgres". "github.com/onsi/gomega"@@ -86,7 +86,7 @@ func TestUserStorage_Register(t *testing.T) {Providers: []*models.UserProvider{{UID: "123123123",- Name: identity.OAuthFacebookProvider,+ Name: oauth.FacebookProvider,},},}@@ -119,11 +119,11 @@ func TestUserStorage_Register_MultipleProviders(t *testing.T) {Providers: []*models.UserProvider{{UID: "123123123",- Name: identity.OAuthFacebookProvider,+ Name: oauth.FacebookProvider,},{UID: "456456456",- Name: identity.OAuthGoogleProvider,+ Name: oauth.GoogleProvider,},},}diff --git a/main.go b/main.goindex cca78c853..6e6fc443f 100644--- a/main.go+++ b/main.go@@ -1,8 +1,8 @@package mainimport (- "github.com/WeCanHearYou/wechy/app/identity""github.com/WeCanHearYou/wechy/app/models"+ "github.com/WeCanHearYou/wechy/app/pkg/oauth""github.com/WeCanHearYou/wechy/app/pkg/dbx""github.com/WeCanHearYou/wechy/app/pkg/env""github.com/WeCanHearYou/wechy/app/storage/postgres"@@ -42,7 +42,7 @@ func main() {}ctx := &WechyServices{- OAuth: &identity.HTTPOAuthService{},+ OAuth: &oauth.HTTPService{},Idea: &postgres.IdeaStorage{DB: db},User: &postgres.UserStorage{DB: db},Tenant: &postgres.TenantStorage{DB: db},diff --git a/router.go b/router.goindex 903d3deaa..1f62f9be3 100644--- a/router.go+++ b/router.go@@ -11,6 +11,7 @@ import ("github.com/WeCanHearYou/wechy/app/infra""github.com/WeCanHearYou/wechy/app/middlewares""github.com/WeCanHearYou/wechy/app/models"+ "github.com/WeCanHearYou/wechy/app/pkg/oauth""github.com/WeCanHearYou/wechy/app/pkg/env""github.com/WeCanHearYou/wechy/app/storage""github.com/labstack/echo"@@ -20,7 +21,7 @@ import (// WechyServices holds reference to all Wechy servicestype WechyServices struct {- OAuth identity.OAuthService+ OAuth oauth.ServiceUser storage.UserTenant storage.TenantIdea storage.Idea@@ -102,10 +103,10 @@ func GetMainEngine(ctx *WechyServices) *echo.Echo {{use(authGroup, middlewares.HostChecker(env.MustGet("AUTH_ENDPOINT")))- get(authGroup, "/facebook", oauthHandlers.Login(identity.OAuthFacebookProvider))- get(authGroup, "/facebook/callback", oauthHandlers.Callback(identity.OAuthFacebookProvider))- get(authGroup, "/google", oauthHandlers.Login(identity.OAuthGoogleProvider))- get(authGroup, "/google/callback", oauthHandlers.Callback(identity.OAuthGoogleProvider))+ get(authGroup, "/facebook", oauthHandlers.Login(oauth.FacebookProvider))+ get(authGroup, "/facebook/callback", oauthHandlers.Callback(oauth.FacebookProvider))+ get(authGroup, "/google", oauthHandlers.Login(oauth.GoogleProvider))+ get(authGroup, "/google/callback", oauthHandlers.Callback(oauth.GoogleProvider))}appGroup := group(router, "")