Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

refactoring: organise how we fetch profiles from OAuth providers (#446)

Guilherme Oenningcadc4497d11f
diff --git a/app/cmd/routes.go b/app/cmd/routes.go
index 7eb6f85f3..5d91f6eae 100644
--- a/app/cmd/routes.go
+++ b/app/cmd/routes.go
@@ -7,7 +7,6 @@ import (
"github.com/getfider/fider/app/handlers"
"github.com/getfider/fider/app/middlewares"
"github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/oauth"
"github.com/getfider/fider/app/pkg/web"
)
@@ -37,12 +36,8 @@ func routes(r *web.Engine) *web.Engine {
noTenant.Get("/api/tenants/:subdomain/availability", handlers.CheckAvailability())
noTenant.Get("/signup", handlers.SignUp())
- noTenant.Get("/oauth/facebook", handlers.SignInByOAuth(oauth.FacebookProvider))
- noTenant.Get("/oauth/facebook/callback", handlers.OAuthCallback(oauth.FacebookProvider))
- noTenant.Get("/oauth/google", handlers.SignInByOAuth(oauth.GoogleProvider))
- noTenant.Get("/oauth/google/callback", handlers.OAuthCallback(oauth.GoogleProvider))
- noTenant.Get("/oauth/github", handlers.SignInByOAuth(oauth.GitHubProvider))
- noTenant.Get("/oauth/github/callback", handlers.OAuthCallback(oauth.GitHubProvider))
+ noTenant.Get("/oauth/:provider", handlers.SignInByOAuth())
+ noTenant.Get("/oauth/:provider/callback", handlers.OAuthCallback())
}
r.Use(middlewares.Tenant())
@@ -61,9 +56,7 @@ func routes(r *web.Engine) *web.Engine {
{
open.Get("/-/ui", handlers.Page("UI Toolkit", "A preview of Fider UI elements"))
open.Get("/signup/verify", handlers.VerifySignUpKey())
- open.Get("/oauth/facebook/token", handlers.OAuthToken(oauth.FacebookProvider))
- open.Get("/oauth/google/token", handlers.OAuthToken(oauth.GoogleProvider))
- open.Get("/oauth/github/token", handlers.OAuthToken(oauth.GitHubProvider))
+ open.Get("/oauth/:provider/token", handlers.OAuthToken())
open.Use(middlewares.OnlyActiveTenants())
open.Get("/signin", handlers.SignInPage())
open.Get("/not-invited", handlers.NotInvitedPage())
diff --git a/app/handlers/oauth.go b/app/handlers/oauth.go
new file mode 100644
index 000000000..df8ebfe9a
--- /dev/null
+++ b/app/handlers/oauth.go
@@ -0,0 +1,154 @@
+package handlers
+
+import (
+ "fmt"
+ "net/url"
+ "time"
+
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/jwt"
+ "github.com/getfider/fider/app/pkg/web"
+ "github.com/getfider/fider/app/pkg/web/util"
+)
+
+type oauthUserProfile struct {
+ Name string
+ ID string
+ Email string
+}
+
+// OAuthToken exchanges Authorization Code for Authentication Token
+func OAuthToken() web.HandlerFunc {
+ return func(c web.Context) error {
+ provider := c.Param("provider")
+
+ code := c.QueryParam("code")
+ if code == "" {
+ return c.Redirect(c.BaseURL())
+ }
+
+ oauthUser, err := c.Services().OAuth.GetProfile(provider, code)
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ users := c.Services().Users
+
+ user, err := users.GetByProvider(provider, oauthUser.ID)
+ if errors.Cause(err) == app.ErrNotFound && oauthUser.Email != "" {
+ user, err = users.GetByEmail(oauthUser.Email)
+ }
+ if err != nil {
+ if errors.Cause(err) == app.ErrNotFound {
+ if c.Tenant().IsPrivate {
+ return c.Redirect(c.BaseURL() + "/not-invited")
+ }
+
+ user = &models.User{
+ Name: oauthUser.Name,
+ Tenant: c.Tenant(),
+ Email: oauthUser.Email,
+ Role: models.RoleVisitor,
+ Providers: []*models.UserProvider{
+ &models.UserProvider{
+ UID: oauthUser.ID,
+ Name: provider,
+ },
+ },
+ }
+
+ err = users.Register(user)
+ if err != nil {
+ return c.Failure(err)
+ }
+ } else {
+ return c.Failure(err)
+ }
+ } else if !user.HasProvider(provider) {
+ err = users.RegisterProvider(user.ID, &models.UserProvider{
+ UID: oauthUser.ID,
+ Name: provider,
+ })
+ if err != nil {
+ return c.Failure(err)
+ }
+ }
+
+ webutil.AddAuthUserCookie(c, user)
+
+ redirectURL, _ := url.Parse(c.Request.URL.String())
+ var query = redirectURL.Query()
+ query.Del("code")
+ query.Del("path")
+ redirectURL.RawQuery = query.Encode()
+ redirectURL.Path = c.QueryParam("path")
+ return c.Redirect(redirectURL.String())
+ }
+}
+
+// OAuthCallback handles OAuth callbacks
+func OAuthCallback() web.HandlerFunc {
+ return func(c web.Context) error {
+ provider := c.Param("provider")
+ redirect := c.QueryParam("state")
+ redirectURL, err := url.ParseRequestURI(redirect)
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ code := c.QueryParam("code")
+ if code == "" {
+ return c.Redirect(redirect)
+ }
+
+ //Sign in process
+ if redirectURL.Path != "/signup" {
+ var query = redirectURL.Query()
+ query.Set("code", code)
+ query.Set("path", redirectURL.Path)
+ redirectURL.RawQuery = query.Encode()
+ redirectURL.Path = fmt.Sprintf("/oauth/%s/token", provider)
+ return c.Redirect(redirectURL.String())
+ }
+
+ //Sign up process
+ oauthUser, err := c.Services().OAuth.GetProfile(provider, code)
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ claims := jwt.OAuthClaims{
+ OAuthID: oauthUser.ID,
+ OAuthProvider: provider,
+ OAuthName: oauthUser.Name,
+ OAuthEmail: oauthUser.Email,
+ Metadata: jwt.Metadata{
+ ExpiresAt: time.Now().Add(10 * time.Minute).Unix(),
+ },
+ }
+
+ token, err := jwt.Encode(claims)
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ var query = redirectURL.Query()
+ query.Set("token", token)
+ redirectURL.RawQuery = query.Encode()
+ return c.Redirect(redirectURL.String())
+ }
+}
+
+// SignInByOAuth handles OAuth sign in
+func SignInByOAuth() web.HandlerFunc {
+ return func(c web.Context) error {
+ provider := c.Param("provider")
+ authURL, err := c.Services().OAuth.GetAuthURL(provider, c.QueryParam("redirect"))
+ if err != nil {
+ return c.Failure(err)
+ }
+ return c.Redirect(authURL)
+ }
+}
diff --git a/app/handlers/oauth_test.go b/app/handlers/oauth_test.go
new file mode 100644
index 000000000..dfbec0801
--- /dev/null
+++ b/app/handlers/oauth_test.go
@@ -0,0 +1,274 @@
+package handlers_test
+
+import (
+ "testing"
+
+ "net/http"
+ "net/url"
+
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/handlers"
+ "github.com/getfider/fider/app/models"
+ . "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/jwt"
+ "github.com/getfider/fider/app/pkg/mock"
+ "github.com/getfider/fider/app/pkg/oauth"
+ "github.com/getfider/fider/app/pkg/web"
+)
+
+func TestSignOutHandler(t *testing.T) {
+ RegisterT(t)
+
+ server, _ := mock.NewServer()
+ code, response := server.
+ WithURL("http://demo.test.fider.io/signout?redirect=/").
+ AddCookie(web.CookieAuthName, "some-value").
+ Execute(handlers.SignOut())
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+ Expect(response.Header().Get("Location")).Equals("/")
+ Expect(response.Header().Get("Set-Cookie")).ContainsSubstring(web.CookieAuthName + "=; Path=/; Expires=")
+ Expect(response.Header().Get("Set-Cookie")).ContainsSubstring("Max-Age=0; HttpOnly")
+}
+
+func TestSignInByOAuthHandler(t *testing.T) {
+ RegisterT(t)
+
+ server, _ := mock.NewServer()
+ code, response := server.
+ AddParam("provider", oauth.FacebookProvider).
+ Execute(handlers.SignInByOAuth())
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+ Expect(response.Header().Get("Location")).Equals("http://avengers.test.fider.io/oauth/token?provider=facebook&redirect=")
+}
+
+func TestCallbackHandler_InvalidState(t *testing.T) {
+ RegisterT(t)
+
+ server, _ := mock.NewServer()
+ code, _ := server.
+ WithURL("http://login.test.fider.io/oauth/callback?state=abc").
+ AddParam("provider", oauth.FacebookProvider).
+ Execute(handlers.OAuthCallback())
+
+ Expect(code).Equals(http.StatusInternalServerError)
+}
+
+func TestCallbackHandler_InvalidCode(t *testing.T) {
+ RegisterT(t)
+
+ server, _ := mock.NewServer()
+
+ code, response := server.
+ WithURL("http://login.test.fider.io/oauth/callback?state=http://avengers.test.fider.io").
+ AddParam("provider", oauth.FacebookProvider).
+ Execute(handlers.OAuthCallback())
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+ Expect(response.Header().Get("Location")).Equals("http://avengers.test.fider.io")
+}
+
+func TestCallbackHandler_SignIn(t *testing.T) {
+ RegisterT(t)
+
+ server, _ := mock.NewServer()
+ code, response := server.
+ WithURL("http://login.test.fider.io/oauth/callback?state=http://avengers.test.fider.io&code=123").
+ AddParam("provider", oauth.FacebookProvider).
+ Execute(handlers.OAuthCallback())
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+ Expect(response.Header().Get("Location")).Equals("http://avengers.test.fider.io/oauth/facebook/token?code=123&path=")
+}
+
+func TestCallbackHandler_SignIn_WithPath(t *testing.T) {
+ RegisterT(t)
+ server, _ := mock.NewServer()
+
+ code, response := server.
+ WithURL("http://login.test.fider.io/oauth/callback?state=http://avengers.test.fider.io/some-page&code=123").
+ AddParam("provider", oauth.FacebookProvider).
+ Execute(handlers.OAuthCallback())
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+ Expect(response.Header().Get("Location")).Equals("http://avengers.test.fider.io/oauth/facebook/token?code=123&path=%2Fsome-page")
+}
+
+func TestCallbackHandler_SignUp(t *testing.T) {
+ RegisterT(t)
+
+ server, _ := mock.NewServer()
+ code, response := server.
+ WithURL("http://login.test.fider.io/oauth/callback?state=http://demo.test.fider.io/signup&code=123").
+ AddParam("provider", oauth.FacebookProvider).
+ Execute(handlers.OAuthCallback())
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+
+ location, _ := url.Parse(response.Header().Get("Location"))
+ Expect(location.Host).Equals("demo.test.fider.io")
+ Expect(location.Scheme).Equals("http")
+ Expect(location.Path).Equals("/signup")
+ ExpectOAuthToken(location.Query().Get("token"), &jwt.OAuthClaims{
+ OAuthProvider: "facebook",
+ OAuthID: "FB123",
+ OAuthName: "Jon Snow",
+ OAuthEmail: "[email protected]",
+ })
+}
+
+func TestOAuthTokenHandler_ExistingUserAndProvider(t *testing.T) {
+ RegisterT(t)
+
+ server, _ := mock.NewServer()
+ code, response := server.
+ WithURL("http://demo.test.fider.io/oauth/facebook/token?code=123").
+ OnTenant(mock.DemoTenant).
+ AddParam("provider", oauth.FacebookProvider).
+ Execute(handlers.OAuthToken())
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+ Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io")
+ ExpectFiderAuthCookie(response, mock.JonSnow)
+}
+
+func TestOAuthTokenHandler_NewUser(t *testing.T) {
+ RegisterT(t)
+
+ server, services := mock.NewServer()
+ code, response := server.
+ WithURL("http://demo.test.fider.io/oauth/facebook/token?code=456&path=/hello").
+ OnTenant(mock.DemoTenant).
+ AddParam("provider", oauth.FacebookProvider).
+ Execute(handlers.OAuthToken())
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+ Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io/hello")
+
+ user, err := services.Users.GetByEmail("[email protected]")
+ Expect(err).IsNil()
+ Expect(user.Name).Equals("Some Facebook Guy")
+
+ ExpectFiderAuthCookie(response, user)
+}
+
+func TestOAuthTokenHandler_NewUserWithoutEmail(t *testing.T) {
+ RegisterT(t)
+
+ server, services := mock.NewServer()
+ services.Users.Register(&models.User{
+ Name: "Some Guy",
+ Email: "",
+ Tenant: mock.DemoTenant,
+ Providers: []*models.UserProvider{
+ &models.UserProvider{UID: "GO999", Name: oauth.GoogleProvider},
+ },
+ })
+
+ code, response := server.
+ WithURL("http://demo.test.fider.io/oauth/facebook/token?code=798").
+ OnTenant(mock.DemoTenant).
+ AddParam("provider", oauth.FacebookProvider).
+ Execute(handlers.OAuthToken())
+
+ user, err := services.Users.GetByID(3)
+ Expect(err).IsNil()
+ Expect(user.ID).Equals(3)
+ Expect(user.Name).Equals("Some Guy")
+ Expect(user.Providers).HasLen(1)
+
+ user, err = services.Users.GetByID(4)
+ Expect(err).IsNil()
+ Expect(user.ID).Equals(4)
+ Expect(user.Name).Equals("Mark")
+ Expect(user.Providers).HasLen(1)
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+
+ Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io")
+ ExpectFiderAuthCookie(response, &models.User{
+ ID: 4,
+ Name: "Mark",
+ })
+}
+
+func TestOAuthTokenHandler_ExistingUser_WithoutEmail(t *testing.T) {
+ RegisterT(t)
+
+ server, services := mock.NewServer()
+ services.Users.Register(&models.User{
+ Name: "Some Facebook Guy",
+ Email: "",
+ Tenant: mock.DemoTenant,
+ Providers: []*models.UserProvider{
+ &models.UserProvider{UID: "FB456", Name: oauth.FacebookProvider},
+ },
+ })
+
+ code, response := server.
+ WithURL("http://demo.test.fider.io/oauth/facebook/token?code=456").
+ OnTenant(mock.DemoTenant).
+ AddParam("provider", oauth.FacebookProvider).
+ Execute(handlers.OAuthToken())
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+
+ _, err := services.Users.GetByID(4)
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+
+ Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io")
+ ExpectFiderAuthCookie(response, &models.User{
+ ID: 3,
+ Name: "Some Facebook Guy",
+ })
+}
+
+func TestCallbackHandler_ExistingUser_NewProvider(t *testing.T) {
+ RegisterT(t)
+
+ server, services := mock.NewServer()
+ code, response := server.
+ WithURL("http://demo.test.fider.io/oauth/facebook/token?code=123").
+ OnTenant(mock.DemoTenant).
+ AddParam("provider", oauth.GoogleProvider).
+ Execute(handlers.OAuthToken())
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+
+ user, err := services.Users.GetByEmail("[email protected]")
+ Expect(err).IsNil()
+ Expect(user.Providers).HasLen(2)
+
+ Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io")
+ ExpectFiderAuthCookie(response, mock.JonSnow)
+}
+
+func TestCallbackHandler_NewUser_PrivateTenant(t *testing.T) {
+ RegisterT(t)
+ server, services := mock.NewServer()
+ mock.AvengersTenant.IsPrivate = true
+
+ code, response := server.
+ WithURL("http://ideas.theavengers.com/oauth/facebook/token?code=456").
+ OnTenant(mock.AvengersTenant).
+ AddParam("provider", oauth.FacebookProvider).
+ Execute(handlers.OAuthToken())
+
+ user, err := services.Users.GetByEmail("[email protected]")
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+ Expect(user).IsNil()
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+ Expect(response.Header().Get("Location")).Equals("http://ideas.theavengers.com/not-invited")
+ ExpectFiderAuthCookie(response, nil)
+}
+
+func ExpectOAuthToken(token string, expected *jwt.OAuthClaims) {
+ user, err := jwt.DecodeOAuthClaims(token)
+ Expect(err).IsNil()
+ Expect(user.OAuthID).Equals(expected.OAuthID)
+ Expect(user.OAuthName).Equals(expected.OAuthName)
+ Expect(user.OAuthEmail).Equals(expected.OAuthEmail)
+ Expect(user.OAuthProvider).Equals(expected.OAuthProvider)
+}
diff --git a/app/handlers/signin.go b/app/handlers/signin.go
index 834459f40..b0245d92a 100644
--- a/app/handlers/signin.go
+++ b/app/handlers/signin.go
@@ -1,155 +1,18 @@
package handlers
import (
- "fmt"
"net/http"
- "net/url"
- "strings"
"time"
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/errors"
- "github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/web"
"github.com/getfider/fider/app/pkg/web/util"
"github.com/getfider/fider/app/tasks"
)
-type oauthUserProfile struct {
- Name string
- ID string
- Email string
-}
-
-// OAuthToken exchanges Authorization Code for Authentication Token
-func OAuthToken(provider string) web.HandlerFunc {
- return func(c web.Context) error {
- code := c.QueryParam("code")
- if code == "" {
- return c.Redirect(c.BaseURL())
- }
-
- oauthUser, err := c.Services().OAuth.GetProfile(c.AuthEndpoint(), provider, code)
- if err != nil {
- return c.Failure(err)
- }
-
- users := c.Services().Users
-
- user, err := users.GetByProvider(provider, oauthUser.ID.String())
- if errors.Cause(err) == app.ErrNotFound && oauthUser.Email != "" {
- user, err = users.GetByEmail(oauthUser.Email)
- }
- if err != nil {
- if errors.Cause(err) == app.ErrNotFound {
- if c.Tenant().IsPrivate {
- return c.Redirect(c.BaseURL() + "/not-invited")
- }
-
- user = &models.User{
- Name: oauthUser.Name,
- Tenant: c.Tenant(),
- Email: oauthUser.Email,
- Role: models.RoleVisitor,
- Providers: []*models.UserProvider{
- &models.UserProvider{
- UID: oauthUser.ID.String(),
- Name: provider,
- },
- },
- }
-
- err = users.Register(user)
- if err != nil {
- return c.Failure(err)
- }
- } else {
- return c.Failure(err)
- }
- } else if !user.HasProvider(provider) {
- err = users.RegisterProvider(user.ID, &models.UserProvider{
- UID: oauthUser.ID.String(),
- Name: provider,
- })
- if err != nil {
- return c.Failure(err)
- }
- }
-
- webutil.AddAuthUserCookie(c, user)
-
- redirectURL, _ := url.Parse(c.Request.URL.String())
- var query = redirectURL.Query()
- query.Del("code")
- query.Del("path")
- redirectURL.RawQuery = query.Encode()
- redirectURL.Path = c.QueryParam("path")
- return c.Redirect(redirectURL.String())
- }
-}
-
-// OAuthCallback handles OAuth callbacks
-func OAuthCallback(provider string) web.HandlerFunc {
- return func(c web.Context) error {
- redirect := c.QueryParam("state")
- redirectURL, err := url.ParseRequestURI(redirect)
- if err != nil {
- return c.Failure(err)
- }
-
- code := c.QueryParam("code")
- if code == "" {
- return c.Redirect(redirect)
- }
-
- //Sign in process
- if redirectURL.Path != "/signup" {
- var query = redirectURL.Query()
- query.Set("code", code)
- query.Set("path", redirectURL.Path)
- redirectURL.RawQuery = query.Encode()
- redirectURL.Path = fmt.Sprintf("/oauth/%s/token", provider)
- return c.Redirect(redirectURL.String())
- }
-
- //Sign up process
- oauthUser, err := c.Services().OAuth.GetProfile(c.AuthEndpoint(), provider, code)
- if err != nil {
- return c.Failure(err)
- }
-
- claims := jwt.OAuthClaims{
- OAuthID: oauthUser.ID.String(),
- OAuthProvider: provider,
- OAuthName: oauthUser.Name,
- OAuthEmail: oauthUser.Email,
- Metadata: jwt.Metadata{
- ExpiresAt: time.Now().Add(10 * time.Minute).Unix(),
- },
- }
-
- token, err := jwt.Encode(claims)
- if err != nil {
- return c.Failure(err)
- }
-
- var query = redirectURL.Query()
- query.Set("token", token)
- redirectURL.RawQuery = query.Encode()
- return c.Redirect(redirectURL.String())
- }
-}
-
-// SignInByOAuth handles OAuth sign in
-func SignInByOAuth(provider string) web.HandlerFunc {
- return func(c web.Context) error {
- authURL := c.Services().OAuth.GetAuthURL(c.AuthEndpoint(), provider, c.QueryParam("redirect"))
- return c.Redirect(authURL)
- }
-}
-
// SignInPage renders the sign in page
func SignInPage() web.HandlerFunc {
return func(c web.Context) error {
@@ -295,11 +158,3 @@ func SignOut() web.HandlerFunc {
return c.Redirect(c.QueryParam("redirect"))
}
}
-
-func stripPort(hostport string) string {
- colon := strings.IndexByte(hostport, ':')
- if colon == -1 {
- return hostport
- }
- return hostport[:colon]
-}
diff --git a/app/handlers/signin_test.go b/app/handlers/signin_test.go
index e63507341..bb29704f8 100644
--- a/app/handlers/signin_test.go
+++ b/app/handlers/signin_test.go
@@ -6,253 +6,15 @@ import (
"net/http"
"net/http/httptest"
- "net/url"
- "github.com/getfider/fider/app"
"github.com/getfider/fider/app/handlers"
"github.com/getfider/fider/app/models"
. "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/mock"
- "github.com/getfider/fider/app/pkg/oauth"
"github.com/getfider/fider/app/pkg/web"
)
-func TestSignOutHandler(t *testing.T) {
- RegisterT(t)
-
- server, _ := mock.NewServer()
- code, response := server.
- WithURL("http://demo.test.fider.io/signout?redirect=/").
- AddCookie(web.CookieAuthName, "some-value").
- Execute(handlers.SignOut())
-
- Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(response.Header().Get("Location")).Equals("/")
- Expect(response.Header().Get("Set-Cookie")).ContainsSubstring(web.CookieAuthName + "=; Path=/; Expires=")
- Expect(response.Header().Get("Set-Cookie")).ContainsSubstring("Max-Age=0; HttpOnly")
-}
-
-func TestSignInByOAuthHandler(t *testing.T) {
- RegisterT(t)
-
- server, _ := mock.NewServer()
- code, response := server.Execute(handlers.SignInByOAuth(oauth.FacebookProvider))
-
- Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(response.Header().Get("Location")).Equals("http://avengers.test.fider.io/oauth/token?provider=facebook&redirect=")
-}
-
-func TestCallbackHandler_InvalidState(t *testing.T) {
- RegisterT(t)
-
- server, _ := mock.NewServer()
- code, _ := server.
- WithURL("http://login.test.fider.io/oauth/callback?state=abc").
- Execute(handlers.OAuthCallback(oauth.FacebookProvider))
-
- Expect(code).Equals(http.StatusInternalServerError)
-}
-
-func TestCallbackHandler_InvalidCode(t *testing.T) {
- RegisterT(t)
-
- server, _ := mock.NewServer()
-
- code, response := server.
- WithURL("http://login.test.fider.io/oauth/callback?state=http://avengers.test.fider.io").
- Execute(handlers.OAuthCallback(oauth.FacebookProvider))
-
- Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(response.Header().Get("Location")).Equals("http://avengers.test.fider.io")
-}
-
-func TestCallbackHandler_SignIn(t *testing.T) {
- RegisterT(t)
-
- server, _ := mock.NewServer()
- code, response := server.
- WithURL("http://login.test.fider.io/oauth/callback?state=http://avengers.test.fider.io&code=123").
- Execute(handlers.OAuthCallback(oauth.FacebookProvider))
-
- Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(response.Header().Get("Location")).Equals("http://avengers.test.fider.io/oauth/facebook/token?code=123&path=")
-}
-
-func TestCallbackHandler_SignIn_WithPath(t *testing.T) {
- RegisterT(t)
- server, _ := mock.NewServer()
-
- code, response := server.
- WithURL("http://login.test.fider.io/oauth/callback?state=http://avengers.test.fider.io/some-page&code=123").
- Execute(handlers.OAuthCallback(oauth.FacebookProvider))
-
- Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(response.Header().Get("Location")).Equals("http://avengers.test.fider.io/oauth/facebook/token?code=123&path=%2Fsome-page")
-}
-
-func TestCallbackHandler_SignUp(t *testing.T) {
- RegisterT(t)
-
- server, _ := mock.NewServer()
- code, response := server.
- WithURL("http://login.test.fider.io/oauth/callback?state=http://demo.test.fider.io/signup&code=123").
- Execute(handlers.OAuthCallback(oauth.FacebookProvider))
- Expect(code).Equals(http.StatusTemporaryRedirect)
-
- location, _ := url.Parse(response.Header().Get("Location"))
- Expect(location.Host).Equals("demo.test.fider.io")
- Expect(location.Scheme).Equals("http")
- Expect(location.Path).Equals("/signup")
- ExpectOAuthToken(location.Query().Get("token"), &jwt.OAuthClaims{
- OAuthProvider: "facebook",
- OAuthID: "FB123",
- OAuthName: "Jon Snow",
- OAuthEmail: "[email protected]",
- })
-}
-
-func TestOAuthTokenHandler_ExistingUserAndProvider(t *testing.T) {
- RegisterT(t)
-
- server, _ := mock.NewServer()
- code, response := server.
- WithURL("http://demo.test.fider.io/oauth/facebook/token?code=123").
- OnTenant(mock.DemoTenant).
- Execute(handlers.OAuthToken(oauth.FacebookProvider))
-
- Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io")
- ExpectFiderAuthCookie(response, mock.JonSnow)
-}
-
-func TestOAuthTokenHandler_NewUser(t *testing.T) {
- RegisterT(t)
-
- server, services := mock.NewServer()
- code, response := server.
- WithURL("http://demo.test.fider.io/oauth/facebook/token?code=456&path=/hello").
- OnTenant(mock.DemoTenant).
- Execute(handlers.OAuthToken(oauth.FacebookProvider))
-
- Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io/hello")
-
- user, err := services.Users.GetByEmail("[email protected]")
- Expect(err).IsNil()
- Expect(user.Name).Equals("Some Facebook Guy")
-
- ExpectFiderAuthCookie(response, user)
-}
-
-func TestOAuthTokenHandler_NewUserWithoutEmail(t *testing.T) {
- RegisterT(t)
-
- server, services := mock.NewServer()
- services.Users.Register(&models.User{
- Name: "Some Guy",
- Email: "",
- Tenant: mock.DemoTenant,
- Providers: []*models.UserProvider{
- &models.UserProvider{UID: "GO999", Name: oauth.GoogleProvider},
- },
- })
-
- code, response := server.
- WithURL("http://demo.test.fider.io/oauth/facebook/token?code=798").
- OnTenant(mock.DemoTenant).
- Execute(handlers.OAuthToken(oauth.FacebookProvider))
-
- user, err := services.Users.GetByID(3)
- Expect(err).IsNil()
- Expect(user.ID).Equals(3)
- Expect(user.Name).Equals("Some Guy")
- Expect(user.Providers).HasLen(1)
-
- user, err = services.Users.GetByID(4)
- Expect(err).IsNil()
- Expect(user.ID).Equals(4)
- Expect(user.Name).Equals("Mark")
- Expect(user.Providers).HasLen(1)
-
- Expect(code).Equals(http.StatusTemporaryRedirect)
-
- Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io")
- ExpectFiderAuthCookie(response, &models.User{
- ID: 4,
- Name: "Mark",
- })
-}
-
-func TestOAuthTokenHandler_ExistingUser_WithoutEmail(t *testing.T) {
- RegisterT(t)
-
- server, services := mock.NewServer()
- services.Users.Register(&models.User{
- Name: "Some Facebook Guy",
- Email: "",
- Tenant: mock.DemoTenant,
- Providers: []*models.UserProvider{
- &models.UserProvider{UID: "FB456", Name: oauth.FacebookProvider},
- },
- })
-
- code, response := server.
- WithURL("http://demo.test.fider.io/oauth/facebook/token?code=456").
- OnTenant(mock.DemoTenant).
- Execute(handlers.OAuthToken(oauth.FacebookProvider))
-
- Expect(code).Equals(http.StatusTemporaryRedirect)
-
- _, err := services.Users.GetByID(4)
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
-
- Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io")
- ExpectFiderAuthCookie(response, &models.User{
- ID: 3,
- Name: "Some Facebook Guy",
- })
-}
-
-func TestCallbackHandler_ExistingUser_NewProvider(t *testing.T) {
- RegisterT(t)
-
- server, services := mock.NewServer()
- code, response := server.
- WithURL("http://demo.test.fider.io/oauth/facebook/token?code=123").
- OnTenant(mock.DemoTenant).
- Execute(handlers.OAuthToken(oauth.GoogleProvider))
-
- Expect(code).Equals(http.StatusTemporaryRedirect)
-
- user, err := services.Users.GetByEmail("[email protected]")
- Expect(err).IsNil()
- Expect(user.Providers).HasLen(2)
-
- Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io")
- ExpectFiderAuthCookie(response, mock.JonSnow)
-}
-
-func TestCallbackHandler_NewUser_PrivateTenant(t *testing.T) {
- RegisterT(t)
- server, services := mock.NewServer()
- mock.AvengersTenant.IsPrivate = true
-
- code, response := server.
- WithURL("http://ideas.theavengers.com/oauth/facebook/token?code=456").
- OnTenant(mock.AvengersTenant).
- Execute(handlers.OAuthToken(oauth.FacebookProvider))
-
- user, err := services.Users.GetByEmail("[email protected]")
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
- Expect(user).IsNil()
-
- Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(response.Header().Get("Location")).Equals("http://ideas.theavengers.com/not-invited")
- ExpectFiderAuthCookie(response, nil)
-}
-
func TestSignInByEmailHandler_WithoutEmail(t *testing.T) {
RegisterT(t)
@@ -575,12 +337,3 @@ func ExpectFiderToken(token string, expected *models.User) {
Expect(user.UserName).Equals(expected.Name)
Expect(user.UserEmail).Equals(expected.Email)
}
-
-func ExpectOAuthToken(token string, expected *jwt.OAuthClaims) {
- user, err := jwt.DecodeOAuthClaims(token)
- Expect(err).IsNil()
- Expect(user.OAuthID).Equals(expected.OAuthID)
- Expect(user.OAuthName).Equals(expected.OAuthName)
- Expect(user.OAuthEmail).Equals(expected.OAuthEmail)
- Expect(user.OAuthProvider).Equals(expected.OAuthProvider)
-}
diff --git a/app/middlewares/setup.go b/app/middlewares/setup.go
index 123d918fc..7ff7bc08d 100644
--- a/app/middlewares/setup.go
+++ b/app/middlewares/setup.go
@@ -13,7 +13,6 @@ import (
"github.com/getfider/fider/app/pkg/worker"
"github.com/getfider/fider/app"
- "github.com/getfider/fider/app/pkg/oauth"
"github.com/getfider/fider/app/pkg/web"
"github.com/getfider/fider/app/storage/postgres"
)
@@ -132,7 +131,7 @@ func WebSetup() web.MiddlewareFunc {
c.SetActiveTransaction(trx)
c.SetServices(&app.Services{
Tenants: postgres.NewTenantStorage(trx),
- OAuth: &oauth.HTTPService{},
+ OAuth: web.NewOAuthService(c.AuthEndpoint()),
Users: postgres.NewUserStorage(trx),
Ideas: postgres.NewIdeaStorage(trx),
Tags: postgres.NewTagStorage(trx),
diff --git a/app/models/infra.go b/app/models/infra.go
index 1a2aca98e..3e1b4715b 100644
--- a/app/models/infra.go
+++ b/app/models/infra.go
@@ -24,3 +24,20 @@ type Notification struct {
Read bool `json:"read" db:"read"`
CreatedOn time.Time `json:"createdOn" db:"created_on"`
}
+
+// OAuthConfig is the configuration of a custom OAuth provider
+type OAuthConfig struct {
+ ID int `db:"id"`
+ Provider string `db:"provider"`
+ DisplayName string `db:"display_name"`
+ Status int `db:"status"`
+ ClientID string `db:"client_id"`
+ ClientSecret string `db:"client_secret"`
+ AuthorizeURL string `db:"authorize_url"`
+ TokenURL string `db:"token_url"`
+ ProfileURL string `db:"profile_url"`
+ Scope string `db:"scope"`
+ JSONUserIDPath string `db:"json_user_id_path"`
+ JSONNamePath string `db:"json_name_path"`
+ JSONEmailPath string `db:"json_email_path"`
+}
diff --git a/app/pkg/errors/errors.go b/app/pkg/errors/errors.go
index e35fc723f..6fd87802d 100644
--- a/app/pkg/errors/errors.go
+++ b/app/pkg/errors/errors.go
@@ -18,8 +18,9 @@ func caller(skip int) (string, int) {
}
//New creates a new error
-func New(text string) error {
+func New(format string, a ...interface{}) error {
file, line := caller(2)
+ text := fmt.Sprintf(format, a...)
return stdError.New(fmt.Sprintf("%s (%s:%d)", text, file, line))
}
diff --git a/app/pkg/jsonq/jsonq.go b/app/pkg/jsonq/jsonq.go
index e6a5d85b8..18e118293 100644
--- a/app/pkg/jsonq/jsonq.go
+++ b/app/pkg/jsonq/jsonq.go
@@ -28,14 +28,19 @@ func New(content string) *Query {
//String returns a string value from the json object based on its key
func (q *Query) String(key string) string {
- data := q.get(key)
- if data != nil {
- var str string
- err := json.Unmarshal(*data, &str)
- if err != nil {
- panic(err)
+ keys := strings.Split(key, ",")
+ for _, k := range keys {
+ data := q.get(strings.TrimSpace(k))
+ if data != nil {
+ var str json.Number
+ err := json.Unmarshal(*data, &str)
+ if err != nil {
+ panic(err)
+ }
+ if str != "" {
+ return str.String()
+ }
}
- return str
}
return ""
}
diff --git a/app/pkg/jsonq/jsonq_test.go b/app/pkg/jsonq/jsonq_test.go
index 7c2df656b..44aedd44f 100644
--- a/app/pkg/jsonq/jsonq_test.go
+++ b/app/pkg/jsonq/jsonq_test.go
@@ -15,6 +15,13 @@ func TestGet(t *testing.T) {
Expect(query.Int32("age")).Equals(23)
}
+func TestGet_NumberAsString(t *testing.T) {
+ RegisterT(t)
+
+ query := jsonq.New(`{ "age": 23 }`)
+ Expect(query.String("age")).Equals("23")
+}
+
func TestGetStringNested(t *testing.T) {
RegisterT(t)
@@ -22,6 +29,15 @@ func TestGetStringNested(t *testing.T) {
Expect(query.String("failures.name")).Equals("Jon Snow")
}
+func TestGetWithFallback(t *testing.T) {
+ RegisterT(t)
+
+ query := jsonq.New(`{ "name": "", "login": "jonsnow" }`)
+ Expect(query.String("login")).Equals("jonsnow")
+ Expect(query.String("name")).Equals("")
+ Expect(query.String("name, login")).Equals("jonsnow")
+}
+
func TestContains(t *testing.T) {
RegisterT(t)
diff --git a/app/pkg/mock/oauth.go b/app/pkg/mock/oauth.go
index a82ce2d97..a3955e04f 100644
--- a/app/pkg/mock/oauth.go
+++ b/app/pkg/mock/oauth.go
@@ -6,12 +6,12 @@ import "github.com/getfider/fider/app/pkg/oauth"
type OAuthService struct{}
//GetAuthURL returns authentication url for given provider
-func (p *OAuthService) GetAuthURL(authEndpoint string, provider string, redirect string) string {
- return "http://avengers.test.fider.io/oauth/token?provider=" + provider + "&redirect=" + redirect
+func (p *OAuthService) GetAuthURL(provider string, redirect string) (string, error) {
+ return "http://avengers.test.fider.io/oauth/token?provider=" + provider + "&redirect=" + redirect, nil
}
//GetProfile returns user profile based on provider and code
-func (p *OAuthService) GetProfile(authEndpoint string, provider string, code string) (*oauth.UserProfile, error) {
+func (p *OAuthService) GetProfile(provider string, code string) (*oauth.UserProfile, error) {
if provider == "facebook" && code == "123" {
return &oauth.UserProfile{
ID: "FB123",
diff --git a/app/pkg/oauth/http.go b/app/pkg/oauth/http.go
deleted file mode 100644
index f0b2bbd99..000000000
--- a/app/pkg/oauth/http.go
+++ /dev/null
@@ -1,133 +0,0 @@
-package oauth
-
-import (
- "encoding/json"
- "io/ioutil"
- "net/http"
- "net/url"
- "os"
- "strings"
-
- "github.com/getfider/fider/app/pkg/errors"
- "golang.org/x/oauth2"
- "golang.org/x/oauth2/facebook"
- "golang.org/x/oauth2/github"
- "golang.org/x/oauth2/google"
-)
-
-type providerSettings struct {
- profileURL func(token *oauth2.Token) string
- config func(authEndpoint string) *oauth2.Config
-}
-
-var (
- oauthSettings = map[string]*providerSettings{
- FacebookProvider: {
- profileURL: func(token *oauth2.Token) string {
- return "https://graph.facebook.com/me?fields=name,email&access_token=" + url.QueryEscape(token.AccessToken)
- },
- config: func(authEndpoint string) *oauth2.Config {
- return &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,
- }
- },
- },
- GoogleProvider: {
- profileURL: func(token *oauth2.Token) string {
- return "https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + url.QueryEscape(token.AccessToken)
- },
- config: func(authEndpoint string) *oauth2.Config {
- return &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,
- }
- },
- },
- GitHubProvider: {
- profileURL: func(token *oauth2.Token) string {
- return "https://api.github.com/user?access_token=" + url.QueryEscape(token.AccessToken)
- },
- config: func(authEndpoint string) *oauth2.Config {
- return &oauth2.Config{
- ClientID: os.Getenv("OAUTH_GITHUB_CLIENTID"),
- ClientSecret: os.Getenv("OAUTH_GITHUB_SECRET"),
- RedirectURL: authEndpoint + "/oauth/github/callback",
- Scopes: []string{
- "user:email",
- },
- Endpoint: github.Endpoint,
- }
- },
- },
- }
-)
-
-func doGet(url string, v interface{}) error {
- r, err := http.Get(url)
- if err != nil {
- return err
- }
-
- defer r.Body.Close()
-
- bytes, err := ioutil.ReadAll(r.Body)
- if err != nil {
- return errors.Wrap(err, "failed to request GET %s", url)
- }
-
- err = json.Unmarshal(bytes, v)
- if err != nil {
- return errors.Wrap(err, "failed unmarshal response")
- }
-
- return nil
-}
-
-//HTTPService implements real OAuth operations using Golang's oauth2 package
-type HTTPService struct{}
-
-//GetAuthURL returns authentication url for given provider
-func (p *HTTPService) GetAuthURL(authEndpoint string, provider string, redirect string) string {
- config := oauthSettings[provider].config(authEndpoint)
-
- 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 *HTTPService) GetProfile(authEndpoint string, provider string, code string) (*UserProfile, error) {
- settings := oauthSettings[provider]
- oauthToken, err := settings.config(authEndpoint).Exchange(oauth2.NoContext, code)
- if err != nil {
- return nil, errors.Wrap(err, "failed to exchange OAuth2 code with %s", provider)
- }
-
- profile := &UserProfile{}
- if err = doGet(settings.profileURL(oauthToken), profile); err != nil {
- return nil, err
- }
-
- //GitHub allows users to omit name, so we use their login name
- if strings.Trim(profile.Name, " ") == "" {
- profile.Name = profile.Login
- }
-
- return profile, nil
-}
diff --git a/app/pkg/oauth/http_test.go b/app/pkg/oauth/http_test.go
deleted file mode 100644
index 5beb3b6bc..000000000
--- a/app/pkg/oauth/http_test.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package oauth_test
-
-import (
- "testing"
-
- . "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/oauth"
-)
-
-func TestGetAuthURL_Facebook(t *testing.T) {
- RegisterT(t)
-
- svc := &oauth.HTTPService{}
- authURL := svc.GetAuthURL("http://login.test.fider.io:3000", oauth.FacebookProvider, "")
-
- Expect(authURL).Equals("https://www.facebook.com/dialog/oauth?client_id=&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Ffacebook%2Fcallback&response_type=code&scope=public_profile+email&state=")
-}
-
-func TestGetAuthURL_Google(t *testing.T) {
- RegisterT(t)
-
- svc := &oauth.HTTPService{}
- authURL := svc.GetAuthURL("http://login.test.fider.io:3000", oauth.GoogleProvider, "")
-
- Expect(authURL).Equals("https://accounts.google.com/o/oauth2/auth?client_id=&redirect_uri=http%3A%2F%2Flogin.test.fider.io%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=")
-}
-
-func TestGetAuthURL_GitHub(t *testing.T) {
- RegisterT(t)
-
- svc := &oauth.HTTPService{}
- authURL := svc.GetAuthURL("http://login.test.fider.io:3000", oauth.GitHubProvider, "")
-
- Expect(authURL).Equals("https://github.com/login/oauth/authorize?client_id=&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Fgithub%2Fcallback&response_type=code&scope=user%3Aemail&state=")
-}
diff --git a/app/pkg/oauth/oauth.go b/app/pkg/oauth/oauth.go
index 913ed5c1c..c9d7a4a6e 100644
--- a/app/pkg/oauth/oauth.go
+++ b/app/pkg/oauth/oauth.go
@@ -1,7 +1,7 @@
package oauth
import (
- "encoding/json"
+ "errors"
"os"
)
@@ -14,11 +14,13 @@ const (
GitHubProvider = "github"
)
+//ErrUserIDRequired is used when OAuth integration returns an empty user ID
+var ErrUserIDRequired = errors.New("UserID is required during OAuth integration")
+
//UserProfile represents an OAuth user profile
type UserProfile struct {
- ID json.Number
+ ID string
Name string
- Login string
Email string
}
@@ -36,6 +38,6 @@ func IsProviderEnabled(name string) bool {
//Service provides OAuth operations
type Service interface {
- GetAuthURL(authEndpoint string, provider string, redirect string) string
- GetProfile(authEndpoint string, provider string, code string) (*UserProfile, error)
+ GetAuthURL(provider string, redirect string) (string, error)
+ GetProfile(provider string, code string) (*UserProfile, error)
}
diff --git a/app/pkg/web/oauth.go b/app/pkg/web/oauth.go
new file mode 100644
index 000000000..bb7c594ec
--- /dev/null
+++ b/app/pkg/web/oauth.go
@@ -0,0 +1,181 @@
+package web
+
+import (
+ "fmt"
+ "io/ioutil"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+
+ "github.com/getfider/fider/app/pkg/validate"
+
+ "github.com/getfider/fider/app/pkg/jsonq"
+
+ "github.com/getfider/fider/app/models"
+
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/oauth"
+ "golang.org/x/oauth2"
+ "golang.org/x/oauth2/facebook"
+ "golang.org/x/oauth2/github"
+ "golang.org/x/oauth2/google"
+)
+
+type providerSettings struct {
+ profileURL string
+ config func(authEndpoint string) *oauth2.Config
+}
+
+var (
+ systemProviders = map[string]*models.OAuthConfig{
+ oauth.FacebookProvider: &models.OAuthConfig{
+ ProfileURL: "https://graph.facebook.com/me?fields=name,email",
+ ClientID: os.Getenv("OAUTH_FACEBOOK_APPID"),
+ ClientSecret: os.Getenv("OAUTH_FACEBOOK_SECRET"),
+ Scope: "public_profile email",
+ AuthorizeURL: facebook.Endpoint.AuthURL,
+ TokenURL: facebook.Endpoint.TokenURL,
+ JSONUserIDPath: "id",
+ JSONNamePath: "name",
+ JSONEmailPath: "email",
+ },
+ oauth.GoogleProvider: &models.OAuthConfig{
+ ProfileURL: "https://www.googleapis.com/oauth2/v2/userinfo",
+ ClientID: os.Getenv("OAUTH_GOOGLE_CLIENTID"),
+ ClientSecret: os.Getenv("OAUTH_GOOGLE_SECRET"),
+ Scope: "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",
+ AuthorizeURL: google.Endpoint.AuthURL,
+ TokenURL: google.Endpoint.TokenURL,
+ JSONUserIDPath: "id",
+ JSONNamePath: "name",
+ JSONEmailPath: "email",
+ },
+ oauth.GitHubProvider: &models.OAuthConfig{
+ ProfileURL: "https://api.github.com/user",
+ ClientID: os.Getenv("OAUTH_GITHUB_CLIENTID"),
+ ClientSecret: os.Getenv("OAUTH_GITHUB_SECRET"),
+ Scope: "user:email",
+ AuthorizeURL: github.Endpoint.AuthURL,
+ TokenURL: github.Endpoint.TokenURL,
+ JSONUserIDPath: "id",
+ JSONNamePath: "name, login",
+ JSONEmailPath: "email",
+ },
+ }
+)
+
+//OAuthService implements real OAuth operations using Golang's oauth2 package
+type OAuthService struct {
+ authEndpoint string
+}
+
+//NewOAuthService creates a new OAuthService
+func NewOAuthService(authEndpoint string) *OAuthService {
+ return &OAuthService{
+ authEndpoint,
+ }
+}
+
+//GetAuthURL returns authentication url for given provider
+func (s *OAuthService) GetAuthURL(provider string, redirect string) (string, error) {
+ config, err := s.getConfig(provider)
+ if err != nil {
+ return "", err
+ }
+
+ authURL, _ := url.Parse(config.AuthorizeURL)
+ parameters := url.Values{}
+ parameters.Add("client_id", config.ClientID)
+ parameters.Add("scope", config.Scope)
+ parameters.Add("redirect_uri", fmt.Sprintf("%s/oauth/%s/callback", s.authEndpoint, provider))
+ parameters.Add("response_type", "code")
+ parameters.Add("state", redirect)
+ authURL.RawQuery = parameters.Encode()
+ return authURL.String(), nil
+}
+
+//GetProfile returns user profile based on provider and code
+func (s *OAuthService) GetProfile(provider string, code string) (*oauth.UserProfile, error) {
+ config, err := s.getConfig(provider)
+ if err != nil {
+ return nil, err
+ }
+
+ exchange := (&oauth2.Config{
+ ClientID: config.ClientID,
+ ClientSecret: config.ClientSecret,
+ Endpoint: oauth2.Endpoint{
+ AuthURL: config.AuthorizeURL,
+ TokenURL: config.TokenURL,
+ },
+ RedirectURL: fmt.Sprintf("%s/oauth/%s/callback", s.authEndpoint, provider),
+ }).Exchange
+
+ oauthToken, err := exchange(oauth2.NoContext, code)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to exchange OAuth2 code with %s", provider)
+ }
+
+ bytes, err := s.doGet(config.ProfileURL, oauthToken.AccessToken)
+ if err != nil {
+ return nil, err
+ }
+
+ return s.ParseProfileResponse(string(bytes), config)
+}
+
+//ParseProfileResponse parses profile response into UserProfile model
+func (s *OAuthService) ParseProfileResponse(body string, config *models.OAuthConfig) (*oauth.UserProfile, error) {
+ query := jsonq.New(body)
+ profile := &oauth.UserProfile{
+ ID: strings.TrimSpace(query.String(config.JSONUserIDPath)),
+ Name: strings.TrimSpace(query.String(config.JSONNamePath)),
+ Email: strings.TrimSpace(query.String(config.JSONEmailPath)),
+ }
+
+ if profile.ID == "" {
+ return nil, oauth.ErrUserIDRequired
+ }
+
+ if profile.Name == "" && profile.Email != "" {
+ parts := strings.Split(profile.Email, "@")
+ profile.Name = parts[0]
+ }
+
+ if profile.Name == "" {
+ profile.Name = "Anonymous"
+ }
+
+ if !validate.Email(profile.Email).Ok {
+ profile.Email = ""
+ }
+
+ return profile, nil
+}
+
+func (s *OAuthService) doGet(url, accessToken string) ([]byte, error) {
+ req, _ := http.NewRequest("GET", url, nil)
+ req.Header.Set("Authorization", "Bearer "+accessToken)
+ r, err := http.DefaultClient.Do(req)
+
+ if err != nil {
+ return nil, err
+ }
+
+ defer r.Body.Close()
+ if r.StatusCode != 200 {
+ return nil, errors.New("failed to request GET %s with status code %d", url, r.StatusCode)
+ }
+
+ bytes, err := ioutil.ReadAll(r.Body)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to request GET %s", url)
+ }
+
+ return bytes, nil
+}
+
+func (s *OAuthService) getConfig(provider string) (*models.OAuthConfig, error) {
+ return systemProviders[provider], nil
+}
diff --git a/app/pkg/web/oauth_test.go b/app/pkg/web/oauth_test.go
new file mode 100644
index 000000000..2f5e30716
--- /dev/null
+++ b/app/pkg/web/oauth_test.go
@@ -0,0 +1,214 @@
+package web_test
+
+import (
+ "testing"
+
+ "github.com/getfider/fider/app/models"
+
+ . "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/oauth"
+ "github.com/getfider/fider/app/pkg/web"
+)
+
+func TestGetAuthURL_Facebook(t *testing.T) {
+ RegisterT(t)
+
+ svc := web.NewOAuthService("http://login.test.fider.io:3000")
+ authURL, err := svc.GetAuthURL(oauth.FacebookProvider, "")
+
+ Expect(err).IsNil()
+ Expect(authURL).Equals("https://www.facebook.com/dialog/oauth?client_id=&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Ffacebook%2Fcallback&response_type=code&scope=public_profile+email&state=")
+}
+
+func TestGetAuthURL_Google(t *testing.T) {
+ RegisterT(t)
+
+ svc := web.NewOAuthService("http://login.test.fider.io:3000")
+ authURL, err := svc.GetAuthURL(oauth.GoogleProvider, "")
+
+ Expect(err).IsNil()
+ Expect(authURL).Equals("https://accounts.google.com/o/oauth2/auth?client_id=&redirect_uri=http%3A%2F%2Flogin.test.fider.io%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=")
+}
+
+func TestGetAuthURL_GitHub(t *testing.T) {
+ RegisterT(t)
+
+ svc := web.NewOAuthService("http://login.test.fider.io:3000")
+ authURL, err := svc.GetAuthURL(oauth.GitHubProvider, "")
+
+ Expect(err).IsNil()
+ Expect(authURL).Equals("https://github.com/login/oauth/authorize?client_id=&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Fgithub%2Fcallback&response_type=code&scope=user%3Aemail&state=")
+}
+
+func TestParseProfileResponse_AllFields(t *testing.T) {
+ RegisterT(t)
+
+ svc := web.NewOAuthService("http://login.test.fider.io:3000")
+ profile, err := svc.ParseProfileResponse(
+ `{"name":"Jon Snow","email":"jon\u0040got.com","id":"789654"}`,
+ &models.OAuthConfig{
+ JSONUserIDPath: "id",
+ JSONNamePath: "name",
+ JSONEmailPath: "email",
+ },
+ )
+
+ Expect(err).IsNil()
+ Expect(profile.ID).Equals("789654")
+ Expect(profile.Name).Equals("Jon Snow")
+ Expect(profile.Email).Equals("[email protected]")
+}
+
+func TestParseProfileResponse_WithoutEmail(t *testing.T) {
+ RegisterT(t)
+
+ svc := web.NewOAuthService("http://login.test.fider.io:3000")
+ profile, err := svc.ParseProfileResponse(
+ `{"name":"Jon Snow","id":"1"}`,
+ &models.OAuthConfig{
+ JSONUserIDPath: "id",
+ JSONNamePath: "name",
+ JSONEmailPath: "email",
+ },
+ )
+
+ Expect(err).IsNil()
+ Expect(profile.ID).Equals("1")
+ Expect(profile.Name).Equals("Jon Snow")
+ Expect(profile.Email).Equals("")
+}
+
+func TestParseProfileResponse_NestedData(t *testing.T) {
+ RegisterT(t)
+
+ svc := web.NewOAuthService("http://login.test.fider.io:3000")
+ profile, err := svc.ParseProfileResponse(
+ `{
+ "id": "123",
+ "profile": {
+ "name": "Jon Snow",
+ "email": "[email protected]"
+ }
+ }`,
+ &models.OAuthConfig{
+ JSONUserIDPath: "id",
+ JSONNamePath: "profile.name",
+ JSONEmailPath: "profile.email",
+ },
+ )
+
+ Expect(err).IsNil()
+ Expect(profile.ID).Equals("123")
+ Expect(profile.Name).Equals("Jon Snow")
+ Expect(profile.Email).Equals("[email protected]")
+}
+
+func TestParseProfileResponse_WithFallback(t *testing.T) {
+ RegisterT(t)
+
+ svc := web.NewOAuthService("http://login.test.fider.io:3000")
+ profile, err := svc.ParseProfileResponse(
+ `{
+ "id": 123,
+ "profile": {
+ "login": "jonny",
+ "email": "[email protected]"
+ }
+ }`,
+ &models.OAuthConfig{
+ JSONUserIDPath: "id",
+ JSONNamePath: "profile.name, profile.login",
+ JSONEmailPath: "profile.email",
+ },
+ )
+
+ Expect(err).IsNil()
+ Expect(profile.ID).Equals("123")
+ Expect(profile.Name).Equals("jonny")
+ Expect(profile.Email).Equals("[email protected]")
+}
+
+func TestParseProfileResponse_UseEmailWhenNameIsEmpty(t *testing.T) {
+ RegisterT(t)
+
+ svc := web.NewOAuthService("http://login.test.fider.io:3000")
+ profile, err := svc.ParseProfileResponse(
+ `{
+ "id": "123",
+ "profile": {
+ "email": "[email protected]"
+ }
+ }`,
+ &models.OAuthConfig{
+ JSONUserIDPath: "id",
+ JSONNamePath: "profile.name",
+ JSONEmailPath: "profile.email",
+ },
+ )
+
+ Expect(err).IsNil()
+ Expect(profile.ID).Equals("123")
+ Expect(profile.Name).Equals("jon")
+ Expect(profile.Email).Equals("[email protected]")
+}
+
+func TestParseProfileResponse_InvalidEmail(t *testing.T) {
+ RegisterT(t)
+
+ svc := web.NewOAuthService("http://login.test.fider.io:3000")
+ profile, err := svc.ParseProfileResponse(
+ `{
+ "id": "AB123",
+ "profile": {
+ "name": "Jon Snow",
+ "email": "jon"
+ }
+ }`,
+ &models.OAuthConfig{
+ JSONUserIDPath: "id",
+ JSONNamePath: "profile.name",
+ JSONEmailPath: "profile.email",
+ },
+ )
+
+ Expect(err).IsNil()
+ Expect(profile.ID).Equals("AB123")
+ Expect(profile.Name).Equals("Jon Snow")
+ Expect(profile.Email).Equals("")
+}
+
+func TestParseProfileResponse_EmptyID(t *testing.T) {
+ RegisterT(t)
+
+ svc := web.NewOAuthService("http://login.test.fider.io:3000")
+ profile, err := svc.ParseProfileResponse(
+ `{}`,
+ &models.OAuthConfig{
+ JSONUserIDPath: "id",
+ JSONNamePath: "name",
+ JSONEmailPath: "email",
+ },
+ )
+
+ Expect(errors.Cause(err)).Equals(oauth.ErrUserIDRequired)
+ Expect(profile).IsNil()
+}
+
+func TestParseProfileResponse_EmptyName(t *testing.T) {
+ RegisterT(t)
+
+ svc := web.NewOAuthService("http://login.test.fider.io:3000")
+ profile, err := svc.ParseProfileResponse(
+ `{ "id": "A0" }`,
+ &models.OAuthConfig{
+ JSONUserIDPath: "id",
+ JSONNamePath: "name",
+ JSONEmailPath: "email",
+ },
+ )
+
+ Expect(err).IsNil()
+ Expect(profile.ID).Equals("A0")
+ Expect(profile.Name).Equals("Anonymous")
+}