Open platform to collect and prioritize feedback
refactor oauth
goenningc1fc3108af59
diff --git a/handler/oauth.go b/handler/oauth.goindex 34bfcc012..2a7792fe1 100644--- a/handler/oauth.go+++ b/handler/oauth.go@@ -17,48 +17,49 @@ import ("github.com/labstack/echo")-type facebookUser struct {+type oauthUserProfile struct {Name stringID stringEmail string}-type googleUser struct {- Name string- ID string- Email string+type oauthProviderSettings struct {+ profileURL func(*oauth2.Token) string+ config *oauth2.Config}var (- fbClientID = os.Getenv("OAUTH_FACEBOOK_APPID")- fbClientSecret = os.Getenv("OAUTH_FACEBOOK_SECRET")- googleClientID = os.Getenv("OAUTH_GOOGLE_CLIENTID")- googleClientSecret = os.Getenv("OAUTH_GOOGLE_SECRET")- authEndpoint = os.Getenv("AUTH_ENDPOINT")-)--func newFacebookOAuthConfig() *oauth2.Config {- return &oauth2.Config{- ClientID: fbClientID,- ClientSecret: fbClientSecret,- RedirectURL: authEndpoint + "/oauth/facebook/callback",- Scopes: []string{"public_profile", "email"},- Endpoint: facebook.Endpoint,- }-}--func newGoogleOAuthConfig() *oauth2.Config {- return &oauth2.Config{- ClientID: googleClientID,- ClientSecret: googleClientSecret,- RedirectURL: authEndpoint + "/oauth/google/callback",- Scopes: []string{- "https://www.googleapis.com/auth/userinfo.profile",- "https://www.googleapis.com/auth/userinfo.email",+ authEndpoint = os.Getenv("AUTH_ENDPOINT")+ oauthSettings = map[string]*oauthProviderSettings{+ auth.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,+ },+ },+ auth.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,+ },},- Endpoint: google.Endpoint,}-}+)// OAuthHandlers contains multiple oauth HTTP handlerstype OAuthHandlers struct {@@ -85,112 +86,42 @@ func doGet(url string, v interface{}) error {return json.Unmarshal(bytes, v)}-func facebookMe(token *oauth2.Token) string {- return "https://graph.facebook.com/me?fields=name,email&access_token=" + url.QueryEscape(token.AccessToken)-}--func googleMe(token *oauth2.Token) string {- return "https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + url.QueryEscape(token.AccessToken)-}--// FacebookCallback handles OAuth Facebook callbacks-func (h OAuthHandlers) FacebookCallback() echo.HandlerFunc {+// 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")- config := newFacebookOAuthConfig()- token, err := config.Exchange(oauth2.NoContext, code)- if err != nil {- c.Logger().Errorf("facebookOAuthConfig.Exchange() failed with %s", err)- return c.Redirect(http.StatusTemporaryRedirect, redirect) //TODO: redirect to some error page- }-- fbUser := &facebookUser{}- if err = doGet(facebookMe(token), fbUser); err != nil {- c.Logger().Errorf("HTTP Facebook/Me failed with %s", err)- return c.Redirect(http.StatusTemporaryRedirect, redirect) //TODO: redirect to some error page- }-- user, err := h.ctx.Auth.GetByEmail(fbUser.Email)- if err != nil {- if err == auth.ErrUserNotFound {- user = &auth.User{- Name: fbUser.Name,- Email: fbUser.Email,- Providers: []*auth.UserProvider{- &auth.UserProvider{- UID: fbUser.ID,- Name: auth.OAuthFacebookProvider,- },- },- }- err = h.ctx.Auth.Register(user)- if err != nil {- c.Logger().Error(err)- }- } else {- c.Logger().Error(err)- }- }-- c.Logger().Infof("Logged in as %s", user)-- return c.Redirect(http.StatusTemporaryRedirect, redirect)- }-}--// FacebookLogin handles OAuth logins for Facebook-func (h OAuthHandlers) FacebookLogin() echo.HandlerFunc {- return func(c echo.Context) error {- config := newFacebookOAuthConfig()- 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())- }-}--// GoogleCallback handles OAuth Google callbacks-func (h OAuthHandlers) GoogleCallback() 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- config := newGoogleOAuthConfig()- token, err := config.Exchange(oauth2.NoContext, code)+ settings := oauthSettings[provider]+ token, err := settings.config.Exchange(oauth2.NoContext, code)if err != nil {- c.Logger().Errorf("googleOAuthConfig.Exchange() failed with %s", err)+ c.Logger().Errorf("%s oauthConfig.Exchange() failed with %s", provider, err)return c.Redirect(http.StatusTemporaryRedirect, redirect) //TODO: redirect to some error page}- gUser := &googleUser{}- if err = doGet(googleMe(token), gUser); err != nil {- c.Logger().Errorf("HTTP Google/Me failed with %s", err)+ oauthUser := &oauthUserProfile{}+ if err = doGet(settings.profileURL(token), 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.Auth.GetByEmail(gUser.Email)+ user, err := h.ctx.Auth.GetByEmail(oauthUser.Email)if err != nil {if err == auth.ErrUserNotFound {user = &auth.User{- Name: gUser.Name,- Email: gUser.Email,+ Name: oauthUser.Name,+ Email: oauthUser.Email,Providers: []*auth.UserProvider{&auth.UserProvider{- UID: gUser.ID,- Name: auth.OAuthGoogleProvider,+ UID: oauthUser.ID,+ Name: provider,},},}-err = h.ctx.Auth.Register(user)-if err != nil {c.Logger().Error(err)}@@ -198,16 +129,17 @@ func (h OAuthHandlers) GoogleCallback() echo.HandlerFunc {c.Logger().Error(err)}}+c.Logger().Infof("Logged in as %s", user)return c.Redirect(http.StatusTemporaryRedirect, redirect)}}-// GoogleLogin handles OAuth logins for Google-func (h OAuthHandlers) GoogleLogin() echo.HandlerFunc {+// Login handles OAuth logins+func (h OAuthHandlers) Login(provider string) echo.HandlerFunc {return func(c echo.Context) error {- config := newGoogleOAuthConfig()+ config := oauthSettings[provider].configauthURL, _ := url.Parse(config.Endpoint.AuthURL)parameters := url.Values{}parameters.Add("client_id", config.ClientID)diff --git a/router/router.go b/router/router.goindex e2a3261f2..d29f28f40 100644--- a/router/router.go+++ b/router/router.go@@ -5,6 +5,7 @@ import ("strings"+ "github.com/WeCanHearYou/wchy/auth""github.com/WeCanHearYou/wchy/context""github.com/WeCanHearYou/wchy/env""github.com/WeCanHearYou/wchy/handler"@@ -47,12 +48,12 @@ func GetMainEngine(ctx *context.WchyContext) *echo.Echo {router.Static("/public", "public")router.Static("/assets", "node_modules") //TODO: Don't expose node_modules- auth := router.Group("", HostChecker(env.MustGet("AUTH_ENDPOINT")))+ authGroup := router.Group("", HostChecker(env.MustGet("AUTH_ENDPOINT"))){- auth.GET("/oauth/facebook", handler.OAuth(ctx).FacebookLogin())- auth.GET("/oauth/facebook/callback", handler.OAuth(ctx).FacebookCallback())- auth.GET("/oauth/google", handler.OAuth(ctx).GoogleLogin())- auth.GET("/oauth/google/callback", handler.OAuth(ctx).GoogleCallback())+ 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("", MultiTenant(ctx))