Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

refactor

goenning5c2de49957e3
diff --git a/auth/oauth.go b/auth/oauth.go
new file mode 100644
index 000000000..a54091c69
--- /dev/null
+++ b/auth/oauth.go
@@ -0,0 +1,123 @@
+package auth
+
+import (
+ "encoding/json"
+ "io/ioutil"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+
+ "fmt"
+
+ "golang.org/x/oauth2"
+ "golang.org/x/oauth2/facebook"
+ "golang.org/x/oauth2/google"
+)
+
+const (
+ //OAuthFacebookProvider is const for 'facebook'
+ OAuthFacebookProvider = "facebook"
+ //OAuthGoogleProvider is const for 'google'
+ OAuthGoogleProvider = "google"
+)
+
+type oauthProviderSettings struct {
+ profileURL func(token *oauth2.Token) string
+ config *oauth2.Config
+}
+
+var (
+ authEndpoint = os.Getenv("AUTH_ENDPOINT")
+ oauthSettings = map[string]*oauthProviderSettings{
+ OAuthFacebookProvider: &oauthProviderSettings{
+ profileURL: func(token *oauth2.Token) string {
+ return "https://graph.facebook.com/me?fields=name,email&access_token=" + url.QueryEscape(token.AccessToken)
+ },
+ config: &oauth2.Config{
+ ClientID: os.Getenv("OAUTH_FACEBOOK_APPID"),
+ ClientSecret: os.Getenv("OAUTH_FACEBOOK_SECRET"),
+ RedirectURL: authEndpoint + "/oauth/facebook/callback",
+ Scopes: []string{"public_profile", "email"},
+ Endpoint: facebook.Endpoint,
+ },
+ },
+ OAuthGoogleProvider: &oauthProviderSettings{
+ profileURL: func(token *oauth2.Token) string {
+ return "https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + url.QueryEscape(token.AccessToken)
+ },
+ config: &oauth2.Config{
+ ClientID: os.Getenv("OAUTH_GOOGLE_CLIENTID"),
+ ClientSecret: os.Getenv("OAUTH_GOOGLE_SECRET"),
+ RedirectURL: authEndpoint + "/oauth/google/callback",
+ Scopes: []string{
+ "https://www.googleapis.com/auth/userinfo.profile",
+ "https://www.googleapis.com/auth/userinfo.email",
+ },
+ Endpoint: google.Endpoint,
+ },
+ },
+ }
+)
+
+func doGet(url string, v interface{}) error {
+ r, err := http.Get(url)
+ defer r.Body.Close()
+ if err != nil {
+ return err
+ }
+
+ bytes, err := ioutil.ReadAll(r.Body)
+ if err != nil {
+ return err
+ }
+
+ return json.Unmarshal(bytes, v)
+}
+
+//OAuthUserProfile represents an OAuth user profile
+type OAuthUserProfile struct {
+ ID string
+ Name string
+ Email string
+}
+
+//OAuthService provides OAuth operations
+type OAuthService interface {
+ GetAuthURL(provider string, redirect string) string
+ GetProfile(provider string, code string) (*OAuthUserProfile, error)
+}
+
+//HTTPOAuthService implements real OAuth operations using Golang's oauth2 package
+type HTTPOAuthService struct{}
+
+//GetAuthURL returns authentication url for given provider
+func (p HTTPOAuthService) GetAuthURL(provider string, redirect string) string {
+ config := oauthSettings[provider].config
+
+ authURL, _ := url.Parse(config.Endpoint.AuthURL)
+ parameters := url.Values{}
+ parameters.Add("client_id", config.ClientID)
+ parameters.Add("scope", strings.Join(config.Scopes, " "))
+ parameters.Add("redirect_uri", config.RedirectURL)
+ parameters.Add("response_type", "code")
+ parameters.Add("state", redirect)
+ authURL.RawQuery = parameters.Encode()
+ return authURL.String()
+}
+
+//GetProfile returns user profile based on provider and code
+func (p HTTPOAuthService) GetProfile(provider string, code string) (*OAuthUserProfile, 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{}
+ if err = doGet(settings.profileURL(oauthToken), profile); err != nil {
+ return nil, fmt.Errorf("HTTP Get profile for %s failed with %s", provider, err)
+ }
+
+ return profile, nil
+}
diff --git a/context/wchy.go b/context/wchy.go
index a9b4e2800..ba2152bcc 100644
--- a/context/wchy.go
+++ b/context/wchy.go
@@ -1,6 +1,7 @@
package context
import "github.com/WeCanHearYou/wchy/service"
+import "github.com/WeCanHearYou/wchy/auth"
// WchySettings is an application-wide settings
type WchySettings struct {
@@ -10,6 +11,7 @@ type WchySettings struct {
// WchyContext is an application-wide context
type WchyContext struct {
+ OAuth auth.OAuthService
Health service.HealthCheckService
User service.UserService
Idea service.IdeaService
diff --git a/handler/auth.go b/handler/auth.go
new file mode 100644
index 000000000..614b329af
--- /dev/null
+++ b/handler/auth.go
@@ -0,0 +1,108 @@
+package handler
+
+import (
+ "net/http"
+ "net/url"
+
+ "golang.org/x/oauth2"
+
+ "github.com/WeCanHearYou/wchy/auth"
+ "github.com/WeCanHearYou/wchy/context"
+ "github.com/WeCanHearYou/wchy/model"
+ "github.com/WeCanHearYou/wchy/service"
+ "github.com/labstack/echo"
+)
+
+type oauthUserProfile struct {
+ Name string
+ ID string
+ Email string
+}
+
+type oauthProviderSettings struct {
+ profileURL func(*oauth2.Token) string
+ config *oauth2.Config
+}
+
+// OAuthHandlers contains multiple oauth HTTP handlers
+type OAuthHandlers struct {
+ ctx *context.WchyContext
+}
+
+// OAuth creates a new OAuthHandlers
+func OAuth(ctx *context.WchyContext) OAuthHandlers {
+ return OAuthHandlers{ctx: ctx}
+}
+
+// Callback handles OAuth callbacks
+func (h OAuthHandlers) Callback(provider string) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ var redirectURL *url.URL
+ var err error
+
+ redirect := c.QueryParam("state")
+ code := c.QueryParam("code")
+
+ if redirectURL, err = url.Parse(redirect); err != nil {
+ c.Logger().Errorf("Could not parse url %s", redirect)
+ return c.Redirect(http.StatusTemporaryRedirect, redirect) //TODO: redirect to some error page
+ }
+
+ //TODO: Check if code is empty (or other querystring parameter)
+ //Because the user can deny access to it
+
+ oauthUser, err := h.ctx.OAuth.GetProfile(provider, code)
+ if err != nil {
+ c.Logger().Error(err)
+ return c.Redirect(http.StatusTemporaryRedirect, redirect) //TODO: redirect to some error page
+ }
+
+ user, err := h.ctx.User.GetByEmail(oauthUser.Email)
+ if err != nil {
+ if err == service.ErrNotFound {
+ user = &model.User{
+ Name: oauthUser.Name,
+ Email: oauthUser.Email,
+ Providers: []*model.UserProvider{
+ &model.UserProvider{
+ UID: oauthUser.ID,
+ Name: provider,
+ },
+ },
+ }
+
+ err = h.ctx.User.Register(user)
+ if err != nil {
+ c.Logger().Error(err)
+ }
+ } else {
+ c.Logger().Error(err)
+ }
+ }
+
+ claims := &auth.WchyClaims{
+ UserID: user.ID,
+ UserName: user.Name,
+ UserEmail: user.Email,
+ }
+
+ var token string
+ if token, err = auth.Encode(claims); err != nil {
+ c.Logger().Errorf("Encoding claims failed with %s", err)
+ return c.Redirect(http.StatusTemporaryRedirect, redirect) //TODO: redirect to some error page
+ }
+
+ var query = redirectURL.Query()
+ query.Add("jwt", token)
+ redirectURL.RawQuery = query.Encode()
+ return c.Redirect(http.StatusTemporaryRedirect, redirectURL.String())
+ }
+}
+
+// Login handles OAuth logins
+func (h OAuthHandlers) Login(provider string) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ authURL := h.ctx.OAuth.GetAuthURL(provider, c.QueryParam("redirect"))
+ return c.Redirect(http.StatusTemporaryRedirect, authURL)
+ }
+}
diff --git a/handler/auth_test.go b/handler/auth_test.go
new file mode 100644
index 000000000..157db8c94
--- /dev/null
+++ b/handler/auth_test.go
@@ -0,0 +1,40 @@
+package handler_test
+
+import (
+ "testing"
+
+ "net/http"
+
+ "github.com/WeCanHearYou/wchy/auth"
+ "github.com/WeCanHearYou/wchy/context"
+ "github.com/WeCanHearYou/wchy/handler"
+ "github.com/WeCanHearYou/wchy/mock"
+ . "github.com/onsi/gomega"
+)
+
+//HTTPOAuthService implements real OAuth operations using Golang's oauth2 package
+type mockOAuthService struct{}
+
+//GetAuthURL returns authentication url for given provider
+func (p mockOAuthService) GetAuthURL(provider string, redirect string) string {
+ return "http://myapp/oauth/token?provider=" + provider + "&redirect=" + redirect
+}
+
+//GetProfile returns user profile based on provider and code
+func (p mockOAuthService) GetProfile(provider string, code string) (*auth.OAuthUserProfile, error) {
+ return nil, nil
+}
+
+func TestLoginHandlers(t *testing.T) {
+ RegisterTestingT(t)
+
+ ctx := &context.WchyContext{
+ OAuth: &mockOAuthService{},
+ }
+
+ server := mock.NewServer()
+ code, response := server.ExecuteRaw(handler.OAuth(ctx).Login(auth.OAuthFacebookProvider))
+
+ Expect(code).To(Equal(http.StatusTemporaryRedirect))
+ Expect(response.Header.Get("Location")).To(Equal("http://myapp/oauth/token?provider=facebook&redirect="))
+}
diff --git a/handler/oauth.go b/handler/oauth.go
deleted file mode 100644
index c37ad89d6..000000000
--- a/handler/oauth.go
+++ /dev/null
@@ -1,174 +0,0 @@
-package handler
-
-import (
- "encoding/json"
- "io/ioutil"
- "net/http"
- "net/url"
- "os"
- "strings"
-
- "golang.org/x/oauth2"
- "golang.org/x/oauth2/facebook"
- "golang.org/x/oauth2/google"
-
- "github.com/WeCanHearYou/wchy/auth"
- "github.com/WeCanHearYou/wchy/context"
- "github.com/WeCanHearYou/wchy/model"
- "github.com/WeCanHearYou/wchy/service"
- "github.com/labstack/echo"
-)
-
-type oauthUserProfile struct {
- Name string
- ID string
- Email string
-}
-
-type oauthProviderSettings struct {
- profileURL func(*oauth2.Token) string
- config *oauth2.Config
-}
-
-var (
- authEndpoint = os.Getenv("AUTH_ENDPOINT")
- oauthSettings = map[string]*oauthProviderSettings{
- service.OAuthFacebookProvider: &oauthProviderSettings{
- profileURL: func(token *oauth2.Token) string {
- return "https://graph.facebook.com/me?fields=name,email&access_token=" + url.QueryEscape(token.AccessToken)
- },
- config: &oauth2.Config{
- ClientID: os.Getenv("OAUTH_FACEBOOK_APPID"),
- ClientSecret: os.Getenv("OAUTH_FACEBOOK_SECRET"),
- RedirectURL: authEndpoint + "/oauth/facebook/callback",
- Scopes: []string{"public_profile", "email"},
- Endpoint: facebook.Endpoint,
- },
- },
- service.OAuthGoogleProvider: &oauthProviderSettings{
- profileURL: func(token *oauth2.Token) string {
- return "https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + url.QueryEscape(token.AccessToken)
- },
- config: &oauth2.Config{
- ClientID: os.Getenv("OAUTH_GOOGLE_CLIENTID"),
- ClientSecret: os.Getenv("OAUTH_GOOGLE_SECRET"),
- RedirectURL: authEndpoint + "/oauth/google/callback",
- Scopes: []string{
- "https://www.googleapis.com/auth/userinfo.profile",
- "https://www.googleapis.com/auth/userinfo.email",
- },
- Endpoint: google.Endpoint,
- },
- },
- }
-)
-
-// OAuthHandlers contains multiple oauth HTTP handlers
-type OAuthHandlers struct {
- ctx *context.WchyContext
-}
-
-// OAuth creates a new OAuthHandlers
-func OAuth(ctx *context.WchyContext) OAuthHandlers {
- return OAuthHandlers{ctx: ctx}
-}
-
-func doGet(url string, v interface{}) error {
- r, err := http.Get(url)
- defer r.Body.Close()
- if err != nil {
- return err
- }
-
- bytes, err := ioutil.ReadAll(r.Body)
- if err != nil {
- return err
- }
-
- return json.Unmarshal(bytes, v)
-}
-
-// Callback handles OAuth callbacks
-func (h OAuthHandlers) Callback(provider string) echo.HandlerFunc {
- return func(c echo.Context) error {
- redirect := c.QueryParam("state")
- code := c.QueryParam("code")
-
- //TODO: Check if code is empty (or other querystring parameter)
- //Because the user can deny access to it
-
- settings := oauthSettings[provider]
- oauthToken, err := settings.config.Exchange(oauth2.NoContext, code)
- if err != nil {
- c.Logger().Errorf("%s oauthConfig.Exchange() failed with %s", provider, err)
- return c.Redirect(http.StatusTemporaryRedirect, redirect) //TODO: redirect to some error page
- }
-
- oauthUser := &oauthUserProfile{}
- if err = doGet(settings.profileURL(oauthToken), oauthUser); err != nil {
- c.Logger().Errorf("HTTP Get profile for %s failed with %s", provider, err)
- return c.Redirect(http.StatusTemporaryRedirect, redirect) //TODO: redirect to some error page
- }
-
- user, err := h.ctx.User.GetByEmail(oauthUser.Email)
- if err != nil {
- if err == service.ErrNotFound {
- user = &model.User{
- Name: oauthUser.Name,
- Email: oauthUser.Email,
- Providers: []*model.UserProvider{
- &model.UserProvider{
- UID: oauthUser.ID,
- Name: provider,
- },
- },
- }
- err = h.ctx.User.Register(user)
- if err != nil {
- c.Logger().Error(err)
- }
- } else {
- c.Logger().Error(err)
- }
- }
-
- claims := &auth.WchyClaims{
- UserID: user.ID,
- UserName: user.Name,
- UserEmail: user.Email,
- }
-
- var token string
- if token, err = auth.Encode(claims); err != nil {
- c.Logger().Errorf("%s oauthConfig.Exchange() failed with %s", provider, err)
- return c.Redirect(http.StatusTemporaryRedirect, redirect) //TODO: redirect to some error page
- }
-
- var redirectURL *url.URL
- if redirectURL, err = url.Parse(redirect); err != nil {
- c.Logger().Errorf("Could not parse url %s", redirect)
- return c.Redirect(http.StatusTemporaryRedirect, redirect) //TODO: redirect to some error page
- }
-
- var query = redirectURL.Query()
- query.Add("jwt", token)
- redirectURL.RawQuery = query.Encode()
- return c.Redirect(http.StatusTemporaryRedirect, redirectURL.String())
- }
-}
-
-// Login handles OAuth logins
-func (h OAuthHandlers) Login(provider string) echo.HandlerFunc {
- return func(c echo.Context) error {
- config := oauthSettings[provider].config
- authURL, _ := url.Parse(config.Endpoint.AuthURL)
- parameters := url.Values{}
- parameters.Add("client_id", config.ClientID)
- parameters.Add("scope", strings.Join(config.Scopes, " "))
- parameters.Add("redirect_uri", config.RedirectURL)
- parameters.Add("response_type", "code")
- parameters.Add("state", c.QueryParam("redirect"))
- authURL.RawQuery = parameters.Encode()
- return c.Redirect(http.StatusTemporaryRedirect, authURL.String())
- }
-}
diff --git a/main.go b/main.go
index fba0f6d80..0cf473c6e 100644
--- a/main.go
+++ b/main.go
@@ -7,6 +7,7 @@ import (
"fmt"
+ "github.com/WeCanHearYou/wchy/auth"
"github.com/WeCanHearYou/wchy/context"
"github.com/WeCanHearYou/wchy/env"
"github.com/WeCanHearYou/wchy/router"
@@ -25,6 +26,7 @@ func main() {
}
ctx := &context.WchyContext{
+ OAuth: &auth.HTTPOAuthService{},
Health: &service.PostgresHealthCheckService{DB: db},
Idea: &service.PostgresIdeaService{DB: db},
User: &service.PostgresUserService{DB: db},
diff --git a/mock/server.go b/mock/server.go
index d6aee6dfb..30db529bb 100644
--- a/mock/server.go
+++ b/mock/server.go
@@ -36,7 +36,7 @@ func NewServer() *Server {
}
}
-// Execute a given handler using current server setup
+// Execute given handler and return response as JSON
func (s *Server) Execute(handler echo.HandlerFunc) (int, *jsonq.JsonQuery) {
handler(s.Context)
@@ -51,6 +51,12 @@ func (s *Server) Execute(handler echo.HandlerFunc) (int, *jsonq.JsonQuery) {
return s.recorder.Code, nil
}
+// ExecuteRaw executes given handler and return raw response
+func (s *Server) ExecuteRaw(handler echo.HandlerFunc) (int, *http.Response) {
+ handler(s.Context)
+ return s.recorder.Code, s.recorder.Result()
+}
+
func hasJSON(r *httptest.ResponseRecorder) bool {
isJSONContentType := strings.Contains(r.Result().Header.Get("Content-Type"), "application/json")
diff --git a/router/router.go b/router/router.go
index b1b0ac366..6d895578e 100644
--- a/router/router.go
+++ b/router/router.go
@@ -5,11 +5,11 @@ import (
"strings"
+ "github.com/WeCanHearYou/wchy/auth"
"github.com/WeCanHearYou/wchy/context"
"github.com/WeCanHearYou/wchy/env"
"github.com/WeCanHearYou/wchy/handler"
"github.com/WeCanHearYou/wchy/router/middleware"
- "github.com/WeCanHearYou/wchy/service"
"github.com/labstack/echo"
"github.com/labstack/gommon/log"
)
@@ -51,10 +51,10 @@ func GetMainEngine(ctx *context.WchyContext) *echo.Echo {
authGroup := router.Group("", middleware.HostChecker(env.MustGet("AUTH_ENDPOINT")))
{
- authGroup.GET("/oauth/facebook", handler.OAuth(ctx).Login(service.OAuthFacebookProvider))
- authGroup.GET("/oauth/facebook/callback", handler.OAuth(ctx).Callback(service.OAuthFacebookProvider))
- authGroup.GET("/oauth/google", handler.OAuth(ctx).Login(service.OAuthGoogleProvider))
- authGroup.GET("/oauth/google/callback", handler.OAuth(ctx).Callback(service.OAuthGoogleProvider))
+ authGroup.GET("/oauth/facebook", handler.OAuth(ctx).Login(auth.OAuthFacebookProvider))
+ authGroup.GET("/oauth/facebook/callback", handler.OAuth(ctx).Callback(auth.OAuthFacebookProvider))
+ authGroup.GET("/oauth/google", handler.OAuth(ctx).Login(auth.OAuthGoogleProvider))
+ authGroup.GET("/oauth/google/callback", handler.OAuth(ctx).Callback(auth.OAuthGoogleProvider))
}
app := router.Group("")
diff --git a/service/user.go b/service/user.go
index d745fe380..73c1d1919 100644
--- a/service/user.go
+++ b/service/user.go
@@ -6,13 +6,6 @@ import (
"github.com/WeCanHearYou/wchy/model"
)
-const (
- //OAuthFacebookProvider is const for 'facebook'
- OAuthFacebookProvider = "facebook"
- //OAuthGoogleProvider is const for 'google'
- OAuthGoogleProvider = "google"
-)
-
// UserService is used for user operations
type UserService interface {
GetByEmail(email string) (*model.User, error)
diff --git a/service/user_test.go b/service/user_test.go
index 16a64caf2..189ae330e 100644
--- a/service/user_test.go
+++ b/service/user_test.go
@@ -7,6 +7,7 @@ import (
sqlmock "gopkg.in/DATA-DOG/go-sqlmock.v1"
+ "github.com/WeCanHearYou/wchy/auth"
"github.com/WeCanHearYou/wchy/model"
"github.com/WeCanHearYou/wchy/service"
. "github.com/onsi/gomega"
@@ -62,7 +63,7 @@ func TestUserService_Register(t *testing.T) {
query.WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(int64(300)))
exec := mock.ExpectExec("INSERT INTO user_providers \\(user_id, provider, provider_uid\\) VALUES \\(\\$1, \\$2, \\$3\\)")
- exec.WithArgs(int64(300), service.OAuthFacebookProvider, "123123123")
+ exec.WithArgs(int64(300), auth.OAuthFacebookProvider, "123123123")
exec.WillReturnResult(driver.ResultNoRows)
mock.ExpectCommit()
@@ -74,7 +75,7 @@ func TestUserService_Register(t *testing.T) {
Providers: []*model.UserProvider{
{
UID: "123123123",
- Name: service.OAuthFacebookProvider,
+ Name: auth.OAuthFacebookProvider,
},
},
}
@@ -97,11 +98,11 @@ func TestUserService_Register_MultipleProviders(t *testing.T) {
query.WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(int64(300)))
exec := mock.ExpectExec("INSERT INTO user_providers \\(user_id, provider, provider_uid\\) VALUES \\(\\$1, \\$2, \\$3\\)")
- exec.WithArgs(int64(300), service.OAuthFacebookProvider, "123123123")
+ exec.WithArgs(int64(300), auth.OAuthFacebookProvider, "123123123")
exec.WillReturnResult(driver.ResultNoRows)
exec = mock.ExpectExec("INSERT INTO user_providers \\(user_id, provider, provider_uid\\) VALUES \\(\\$1, \\$2, \\$3\\)")
- exec.WithArgs(int64(300), service.OAuthGoogleProvider, "456456456")
+ exec.WithArgs(int64(300), auth.OAuthGoogleProvider, "456456456")
exec.WillReturnResult(driver.ResultNoRows)
mock.ExpectCommit()
@@ -113,11 +114,11 @@ func TestUserService_Register_MultipleProviders(t *testing.T) {
Providers: []*model.UserProvider{
{
UID: "123123123",
- Name: service.OAuthFacebookProvider,
+ Name: auth.OAuthFacebookProvider,
},
{
UID: "456456456",
- Name: service.OAuthGoogleProvider,
+ Name: auth.OAuthGoogleProvider,
},
},
}