Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

enhancement: correct use of OAuth state (#450)

Guilherme Oenningec4934774ee8
diff --git a/.test.env b/.test.env
index d0c822fd6..8aa473f5f 100644
--- a/.test.env
+++ b/.test.env
@@ -2,7 +2,7 @@ GO_ENV=test
LOG_LEVEL=DEBUG
HOST_MODE=multi
DATABASE_URL=postgres://fider_test:fider_test_pw@localhost:5566/fider_test?sslmode=disable
-AUTH_ENDPOINT=http://login.test.fider.io:3000
+HOST_DOMAIN=test.fider.io
JWT_SECRET=SOME_RANDOM_TOKEN_JUST_FOR_TESTING
CDN_HOST=
diff --git a/app/handlers/oauth.go b/app/handlers/oauth.go
index df8ebfe9a..944332845 100644
--- a/app/handlers/oauth.go
+++ b/app/handlers/oauth.go
@@ -3,12 +3,14 @@ package handlers
import (
"fmt"
"net/url"
+ "strings"
"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/uuid"
"github.com/getfider/fider/app/pkg/web"
"github.com/getfider/fider/app/pkg/web/util"
)
@@ -19,14 +21,29 @@ type oauthUserProfile struct {
Email string
}
-// OAuthToken exchanges Authorization Code for Authentication Token
+// OAuthToken exchanges OAuth Code for a user profile
+// The user profile is then used to either get an existing user on Fider or creating a new one
+// Once Fider user is retrieved/created, an authentication cookie is store in user's browser
func OAuthToken() web.HandlerFunc {
return func(c web.Context) error {
provider := c.Param("provider")
+ redirectURL, _ := url.ParseRequestURI(c.QueryParam("redirect"))
+ redirectURL.ResolveReference(c.Request.URL)
code := c.QueryParam("code")
if code == "" {
- return c.Redirect(c.BaseURL())
+ return c.Redirect(redirectURL.String())
+ }
+
+ identifier := c.QueryParam("identifier")
+ cookie, err := c.Request.Cookie(web.CookieOAuthIdentifier)
+ if err != nil {
+ return c.Failure(errors.Wrap(err, "failed to get oauth identifier cookie"))
+ }
+
+ c.RemoveCookie(web.CookieOAuthIdentifier)
+ if identifier == "" || cookie.Value == "" || identifier != cookie.Value {
+ return c.Redirect(redirectURL.String())
}
oauthUser, err := c.Services().OAuth.GetProfile(provider, code)
@@ -43,7 +60,7 @@ func OAuthToken() web.HandlerFunc {
if err != nil {
if errors.Cause(err) == app.ErrNotFound {
if c.Tenant().IsPrivate {
- return c.Redirect(c.BaseURL() + "/not-invited")
+ return c.Redirect("/not-invited")
}
user = &models.User{
@@ -78,36 +95,36 @@ func OAuthToken() web.HandlerFunc {
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
+// OAuthCallback handles the redirect back from the OAuth provider
+// This callback can run on either Tenant or Login address
+// If the request is for a sign in, we redirect the user to the tenant address
+// If the request is for a sign up, we exchange the OAuth code and get the user profile
func OAuthCallback() web.HandlerFunc {
return func(c web.Context) error {
provider := c.Param("provider")
- redirect := c.QueryParam("state")
- redirectURL, err := url.ParseRequestURI(redirect)
+ state := c.QueryParam("state")
+ parts := strings.Split(state, "|")
+
+ redirectURL, err := url.ParseRequestURI(parts[0])
if err != nil {
return c.Failure(err)
}
code := c.QueryParam("code")
if code == "" {
- return c.Redirect(redirect)
+ return c.Redirect(redirectURL.String())
}
//Sign in process
if redirectURL.Path != "/signup" {
var query = redirectURL.Query()
query.Set("code", code)
- query.Set("path", redirectURL.Path)
+ query.Set("redirect", redirectURL.RequestURI())
+ query.Set("identifier", parts[1])
redirectURL.RawQuery = query.Encode()
redirectURL.Path = fmt.Sprintf("/oauth/%s/token", provider)
return c.Redirect(redirectURL.String())
@@ -141,11 +158,16 @@ func OAuthCallback() web.HandlerFunc {
}
}
-// SignInByOAuth handles OAuth sign in
+// SignInByOAuth is responsible for redirecting the user to the OAuth authorization URL for given provider
+// A cookie is stored in user's browser with a random identifier that is later used to verify the authenticity of the request
func SignInByOAuth() web.HandlerFunc {
return func(c web.Context) error {
provider := c.Param("provider")
- authURL, err := c.Services().OAuth.GetAuthURL(provider, c.QueryParam("redirect"))
+ identifier := uuid.NewV4().String()
+
+ c.AddCookie(web.CookieOAuthIdentifier, identifier, time.Now().Add(5*time.Minute))
+
+ authURL, err := c.Services().OAuth.GetAuthURL(provider, c.QueryParam("redirect"), identifier)
if err != nil {
return c.Failure(err)
}
diff --git a/app/handlers/oauth_test.go b/app/handlers/oauth_test.go
index dfbec0801..319acb64d 100644
--- a/app/handlers/oauth_test.go
+++ b/app/handlers/oauth_test.go
@@ -41,7 +41,7 @@ func TestSignInByOAuthHandler(t *testing.T) {
Execute(handlers.SignInByOAuth())
Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(response.Header().Get("Location")).Equals("http://avengers.test.fider.io/oauth/token?provider=facebook&redirect=")
+ Expect(response.Header().Get("Location")).ContainsSubstring("http://avengers.test.fider.io/oauth/token?provider=facebook&redirect=|")
}
func TestCallbackHandler_InvalidState(t *testing.T) {
@@ -75,12 +75,12 @@ func TestCallbackHandler_SignIn(t *testing.T) {
server, _ := mock.NewServer()
code, response := server.
- WithURL("http://login.test.fider.io/oauth/callback?state=http://avengers.test.fider.io&code=123").
+ WithURL("http://login.test.fider.io/oauth/callback?state=http://avengers.test.fider.io|888&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=")
+ Expect(response.Header().Get("Location")).Equals("http://avengers.test.fider.io/oauth/facebook/token?code=123&identifier=888&redirect=%2F")
}
func TestCallbackHandler_SignIn_WithPath(t *testing.T) {
@@ -88,12 +88,12 @@ func TestCallbackHandler_SignIn_WithPath(t *testing.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").
+ WithURL("http://login.test.fider.io/oauth/callback?state=http://avengers.test.fider.io/some-page|888&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")
+ Expect(response.Header().Get("Location")).Equals("http://avengers.test.fider.io/oauth/facebook/token?code=123&identifier=888&redirect=%2Fsome-page")
}
func TestCallbackHandler_SignUp(t *testing.T) {
@@ -123,13 +123,14 @@ func TestOAuthTokenHandler_ExistingUserAndProvider(t *testing.T) {
server, _ := mock.NewServer()
code, response := server.
- WithURL("http://demo.test.fider.io/oauth/facebook/token?code=123").
+ WithURL("http://demo.test.fider.io/oauth/facebook/token?code=123&identifier=888&redirect=/hello").
+ AddCookie(web.CookieOAuthIdentifier, "888").
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")
+ Expect(response.Header().Get("Location")).Equals("/hello")
ExpectFiderAuthCookie(response, mock.JonSnow)
}
@@ -138,13 +139,14 @@ func TestOAuthTokenHandler_NewUser(t *testing.T) {
server, services := mock.NewServer()
code, response := server.
- WithURL("http://demo.test.fider.io/oauth/facebook/token?code=456&path=/hello").
+ WithURL("http://demo.test.fider.io/oauth/facebook/token?code=456&identifier=888&redirect=/hello").
+ AddCookie(web.CookieOAuthIdentifier, "888").
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")
+ Expect(response.Header().Get("Location")).Equals("/hello")
user, err := services.Users.GetByEmail("[email protected]")
Expect(err).IsNil()
@@ -167,7 +169,8 @@ func TestOAuthTokenHandler_NewUserWithoutEmail(t *testing.T) {
})
code, response := server.
- WithURL("http://demo.test.fider.io/oauth/facebook/token?code=798").
+ WithURL("http://demo.test.fider.io/oauth/facebook/token?code=798&identifier=888&redirect=/").
+ AddCookie(web.CookieOAuthIdentifier, "888").
OnTenant(mock.DemoTenant).
AddParam("provider", oauth.FacebookProvider).
Execute(handlers.OAuthToken())
@@ -186,7 +189,7 @@ func TestOAuthTokenHandler_NewUserWithoutEmail(t *testing.T) {
Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io")
+ Expect(response.Header().Get("Location")).Equals("/")
ExpectFiderAuthCookie(response, &models.User{
ID: 4,
Name: "Mark",
@@ -207,7 +210,8 @@ func TestOAuthTokenHandler_ExistingUser_WithoutEmail(t *testing.T) {
})
code, response := server.
- WithURL("http://demo.test.fider.io/oauth/facebook/token?code=456").
+ WithURL("http://demo.test.fider.io/oauth/facebook/token?code=456&identifier=888&redirect=/").
+ AddCookie(web.CookieOAuthIdentifier, "888").
OnTenant(mock.DemoTenant).
AddParam("provider", oauth.FacebookProvider).
Execute(handlers.OAuthToken())
@@ -217,19 +221,20 @@ func TestOAuthTokenHandler_ExistingUser_WithoutEmail(t *testing.T) {
_, err := services.Users.GetByID(4)
Expect(errors.Cause(err)).Equals(app.ErrNotFound)
- Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io")
+ Expect(response.Header().Get("Location")).Equals("/")
ExpectFiderAuthCookie(response, &models.User{
ID: 3,
Name: "Some Facebook Guy",
})
}
-func TestCallbackHandler_ExistingUser_NewProvider(t *testing.T) {
+func TestOAuthTokenHandler_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").
+ WithURL("http://demo.test.fider.io/oauth/facebook/token?code=123&identifier=888&redirect=/").
+ AddCookie(web.CookieOAuthIdentifier, "888").
OnTenant(mock.DemoTenant).
AddParam("provider", oauth.GoogleProvider).
Execute(handlers.OAuthToken())
@@ -240,17 +245,18 @@ func TestCallbackHandler_ExistingUser_NewProvider(t *testing.T) {
Expect(err).IsNil()
Expect(user.Providers).HasLen(2)
- Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io")
+ Expect(response.Header().Get("Location")).Equals("/")
ExpectFiderAuthCookie(response, mock.JonSnow)
}
-func TestCallbackHandler_NewUser_PrivateTenant(t *testing.T) {
+func TestOAuthTokenHandler_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").
+ WithURL("http://ideas.theavengers.com/oauth/facebook/token?code=456&identifier=888&redirect=/").
+ AddCookie(web.CookieOAuthIdentifier, "888").
OnTenant(mock.AvengersTenant).
AddParam("provider", oauth.FacebookProvider).
Execute(handlers.OAuthToken())
@@ -260,7 +266,24 @@ func TestCallbackHandler_NewUser_PrivateTenant(t *testing.T) {
Expect(user).IsNil()
Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(response.Header().Get("Location")).Equals("http://ideas.theavengers.com/not-invited")
+ Expect(response.Header().Get("Location")).Equals("/not-invited")
+ ExpectFiderAuthCookie(response, nil)
+}
+
+func TestOAuthTokenHandler_InvalidIdentifier(t *testing.T) {
+ RegisterT(t)
+ server, _ := mock.NewServer()
+ mock.AvengersTenant.IsPrivate = true
+
+ code, response := server.
+ WithURL("http://ideas.theavengers.com/oauth/facebook/token?code=456&identifier=888&redirect=/").
+ AddCookie(web.CookieOAuthIdentifier, "777").
+ OnTenant(mock.AvengersTenant).
+ AddParam("provider", oauth.FacebookProvider).
+ Execute(handlers.OAuthToken())
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+ Expect(response.Header().Get("Location")).Equals("/")
ExpectFiderAuthCookie(response, nil)
}
diff --git a/app/handlers/signin_test.go b/app/handlers/signin_test.go
index bb29704f8..0f53bf3a1 100644
--- a/app/handlers/signin_test.go
+++ b/app/handlers/signin_test.go
@@ -318,15 +318,25 @@ func TestSignInPageHandler_PrivateTenant_UnauthenticatedUser(t *testing.T) {
}
func ExpectFiderAuthCookie(response *httptest.ResponseRecorder, expected *models.User) {
- cookie := web.ParseCookie(response.Header().Get("Set-Cookie"))
+ cookies := response.HeaderMap["Set-Cookie"]
if expected == nil {
- Expect(cookie).IsNil()
+ for _, c := range cookies {
+ cookie := web.ParseCookie(c)
+ Expect(cookie.Name).NotEquals(web.CookieAuthName)
+ }
} else {
- Expect(cookie.Name).Equals(web.CookieAuthName)
- ExpectFiderToken(cookie.Value, expected)
- Expect(cookie.HttpOnly).IsTrue()
- Expect(cookie.Path).Equals("/")
- Expect(cookie.Expires).TemporarilySimilar(time.Now().Add(365*24*time.Hour), 5*time.Second)
+ for _, c := range cookies {
+ cookie := web.ParseCookie(c)
+ if cookie.Name == web.CookieAuthName {
+ Expect(cookie.Name).Equals(web.CookieAuthName)
+ ExpectFiderToken(cookie.Value, expected)
+ Expect(cookie.HttpOnly).IsTrue()
+ Expect(cookie.Path).Equals("/")
+ Expect(cookie.Expires).TemporarilySimilar(time.Now().Add(365*24*time.Hour), 5*time.Second)
+ return
+ }
+ }
+ panic("Cookie not found...")
}
}
diff --git a/app/middlewares/setup.go b/app/middlewares/setup.go
index 7ff7bc08d..0ab7990da 100644
--- a/app/middlewares/setup.go
+++ b/app/middlewares/setup.go
@@ -14,6 +14,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/pkg/web"
+ "github.com/getfider/fider/app/pkg/web/util"
"github.com/getfider/fider/app/storage/postgres"
)
@@ -128,10 +129,12 @@ func WebSetup() web.MiddlewareFunc {
trx.SetLogger(c.Logger())
+ oauthBaseURL := webutil.GetOAuthBaseURL(c)
+
c.SetActiveTransaction(trx)
c.SetServices(&app.Services{
Tenants: postgres.NewTenantStorage(trx),
- OAuth: web.NewOAuthService(c.AuthEndpoint()),
+ OAuth: web.NewOAuthService(oauthBaseURL),
Users: postgres.NewUserStorage(trx),
Ideas: postgres.NewIdeaStorage(trx),
Tags: postgres.NewTagStorage(trx),
diff --git a/app/pkg/env/env.go b/app/pkg/env/env.go
index 3b2765418..fed9427f6 100644
--- a/app/pkg/env/env.go
+++ b/app/pkg/env/env.go
@@ -60,16 +60,7 @@ func HasLegal() bool {
// MultiTenantDomain returns domain name of current instance for multi tenant hosts
func MultiTenantDomain() string {
if !IsSingleHostMode() {
- endpoint := MustGet("AUTH_ENDPOINT")
- firstIdx := strings.Index(endpoint, ".")
- if firstIdx != -1 {
- lastIdx := strings.LastIndex(endpoint, ":")
- if lastIdx != -1 && lastIdx > firstIdx {
- return endpoint[firstIdx:lastIdx]
- }
- return endpoint[firstIdx:]
- }
- panic(fmt.Sprintf("Could not extract domain from %s", endpoint))
+ return "."+MustGet("HOST_DOMAIN")
}
return ""
}
diff --git a/app/pkg/env/env_test.go b/app/pkg/env/env_test.go
index aa8db8d69..8dbc58036 100644
--- a/app/pkg/env/env_test.go
+++ b/app/pkg/env/env_test.go
@@ -91,29 +91,29 @@ func TestHasLegal(t *testing.T) {
func TestMultiTenantDomain(t *testing.T) {
RegisterT(t)
- os.Setenv("AUTH_ENDPOINT", "https://login.test.fider.io:3000")
+ os.Setenv("HOST_DOMAIN", "test.fider.io")
Expect(env.MultiTenantDomain()).Equals(".test.fider.io")
- os.Setenv("AUTH_ENDPOINT", "https://login.test.fider.io")
- Expect(env.MultiTenantDomain()).Equals(".test.fider.io")
- os.Setenv("HOST_MODE", "single")
- Expect(env.MultiTenantDomain()).IsEmpty()
+ os.Setenv("HOST_DOMAIN", "dev.fider.io")
+ Expect(env.MultiTenantDomain()).Equals(".dev.fider.io")
+ os.Setenv("HOST_DOMAIN", "fider.io")
+ Expect(env.MultiTenantDomain()).Equals(".fider.io")
}
func TestGetPublicIP(t *testing.T) {
RegisterT(t)
os.Setenv("HOST_MODE", "multi")
- os.Setenv("AUTH_ENDPOINT", "https://login.dev.fider.io")
+ os.Setenv("HOST_DOMAIN", "dev.fider.io")
ip, err := env.GetPublicIP()
Expect(err).IsNil()
Expect(ip).Equals("127.0.0.1")
- os.Setenv("AUTH_ENDPOINT", "https://login.fider.io")
+ os.Setenv("HOST_DOMAIN", "fider.io")
ip, err = env.GetPublicIP()
Expect(err).IsNil()
Expect(ip).Equals("174.138.111.44")
- os.Setenv("AUTH_ENDPOINT", "invalidinvalidinvalid.io")
+ os.Setenv("HOST_DOMAIN", "invalidinvalidinvalid.io")
ip, err = env.GetPublicIP()
Expect(err).IsNotNil()
Expect(ip).IsEmpty()
diff --git a/app/pkg/mock/oauth.go b/app/pkg/mock/oauth.go
index fa77b178c..5fac83665 100644
--- a/app/pkg/mock/oauth.go
+++ b/app/pkg/mock/oauth.go
@@ -6,8 +6,8 @@ import "github.com/getfider/fider/app/pkg/oauth"
type OAuthService struct{}
//GetAuthURL returns authentication url for given provider
-func (s *OAuthService) GetAuthURL(provider string, redirect string) (string, error) {
- return "http://avengers.test.fider.io/oauth/token?provider=" + provider + "&redirect=" + redirect, nil
+func (s *OAuthService) GetAuthURL(provider, redirect, identifier string) (string, error) {
+ return "http://avengers.test.fider.io/oauth/token?provider=" + provider + "&redirect=" + redirect + "|" + identifier, nil
}
//GetProfile returns user profile based on provider and code
diff --git a/app/pkg/oauth/oauth.go b/app/pkg/oauth/oauth.go
index 677dfa956..947b8f010 100644
--- a/app/pkg/oauth/oauth.go
+++ b/app/pkg/oauth/oauth.go
@@ -32,7 +32,7 @@ type ProviderOption struct {
//Service provides OAuth operations
type Service interface {
- GetAuthURL(provider string, redirect string) (string, error)
+ GetAuthURL(provider, redirect, identifier string) (string, error)
GetProfile(provider string, code string) (*UserProfile, error)
ListProviders() ([]*ProviderOption, error)
}
diff --git a/app/pkg/web/context.go b/app/pkg/web/context.go
index 0867ef41b..624da4919 100644
--- a/app/pkg/web/context.go
+++ b/app/pkg/web/context.go
@@ -48,16 +48,18 @@ var (
const CookieAuthName = "auth"
// CookieSignUpAuthName is the name of the cookie that holds the temporary Authentication Token
-const CookieSignUpAuthName = "signup_auth"
+const CookieSignUpAuthName = "__signup_auth"
+
+// CookieOAuthIdentifier is the name of the cookie that holds the temporary OAuth identifier string
+const CookieOAuthIdentifier = "__oauth_identifier"
var (
- preffixKey = "__CTX_"
- tenantContextKey = preffixKey + "TENANT"
- userContextKey = preffixKey + "USER"
- authEndpointContextKey = preffixKey + "AUTH_ENDPOINT"
- transactionContextKey = preffixKey + "TRANSACTION"
- servicesContextKey = preffixKey + "SERVICES"
- tasksContextKey = preffixKey + "TASKS"
+ preffixKey = "__CTX_"
+ tenantContextKey = preffixKey + "TENANT"
+ userContextKey = preffixKey + "USER"
+ transactionContextKey = preffixKey + "TRANSACTION"
+ servicesContextKey = preffixKey + "SERVICES"
+ tasksContextKey = preffixKey + "TASKS"
)
//Context shared between http pipeline
@@ -370,20 +372,6 @@ func (ctx *Context) TenantBaseURL(tenant *models.Tenant) string {
return address
}
-//AuthEndpoint auth endpoint
-func (ctx *Context) AuthEndpoint() string {
- endpoint, ok := ctx.Get(authEndpointContextKey).(string)
- if !ok {
- if env.IsSingleHostMode() {
- endpoint = ctx.BaseURL()
- } else {
- endpoint = env.MustGet("AUTH_ENDPOINT")
- }
- ctx.Set(authEndpointContextKey, endpoint)
- }
- return endpoint
-}
-
//QueryParam returns querystring parameter for given key
func (ctx *Context) QueryParam(key string) string {
return ctx.Request.URL.Query().Get(key)
diff --git a/app/pkg/web/oauth.go b/app/pkg/web/oauth.go
index 878faf8f7..0bdce24e9 100644
--- a/app/pkg/web/oauth.go
+++ b/app/pkg/web/oauth.go
@@ -23,11 +23,6 @@ import (
"golang.org/x/oauth2/google"
)
-type providerSettings struct {
- profileURL string
- config func(authEndpoint string) *oauth2.Config
-}
-
var (
systemProviders = []*models.OAuthConfig{
&models.OAuthConfig{
@@ -74,18 +69,18 @@ var (
//OAuthService implements real OAuth operations using Golang's oauth2 package
type OAuthService struct {
- authEndpoint string
+ oauthBaseURL string
}
//NewOAuthService creates a new OAuthService
-func NewOAuthService(authEndpoint string) *OAuthService {
+func NewOAuthService(oauthBaseURL string) *OAuthService {
return &OAuthService{
- authEndpoint,
+ oauthBaseURL,
}
}
//GetAuthURL returns authentication url for given provider
-func (s *OAuthService) GetAuthURL(provider string, redirect string) (string, error) {
+func (s *OAuthService) GetAuthURL(provider, redirect, identifier string) (string, error) {
config, err := s.getConfig(provider)
if err != nil {
return "", err
@@ -95,9 +90,9 @@ func (s *OAuthService) GetAuthURL(provider string, redirect string) (string, err
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("redirect_uri", fmt.Sprintf("%s/oauth/%s/callback", s.oauthBaseURL, provider))
parameters.Add("response_type", "code")
- parameters.Add("state", redirect)
+ parameters.Add("state", redirect+"|"+identifier)
authURL.RawQuery = parameters.Encode()
return authURL.String(), nil
}
@@ -116,7 +111,7 @@ func (s *OAuthService) GetProfile(provider string, code string) (*oauth.UserProf
AuthURL: config.AuthorizeURL,
TokenURL: config.TokenURL,
},
- RedirectURL: fmt.Sprintf("%s/oauth/%s/callback", s.authEndpoint, provider),
+ RedirectURL: fmt.Sprintf("%s/oauth/%s/callback", s.oauthBaseURL, provider),
}).Exchange
oauthToken, err := exchange(oauth2.NoContext, code)
@@ -170,7 +165,7 @@ func (s *OAuthService) ListProviders() ([]*oauth.ProviderOption, error) {
list = append(list, &oauth.ProviderOption{
Provider: p.Provider,
DisplayName: p.DisplayName,
- URL: fmt.Sprintf("%s/oauth/%s", s.authEndpoint, p.Provider),
+ URL: fmt.Sprintf("/oauth/%s", p.Provider),
})
}
}
diff --git a/app/pkg/web/oauth_test.go b/app/pkg/web/oauth_test.go
index 2f5e30716..00af50594 100644
--- a/app/pkg/web/oauth_test.go
+++ b/app/pkg/web/oauth_test.go
@@ -15,30 +15,30 @@ func TestGetAuthURL_Facebook(t *testing.T) {
RegisterT(t)
svc := web.NewOAuthService("http://login.test.fider.io:3000")
- authURL, err := svc.GetAuthURL(oauth.FacebookProvider, "")
+ authURL, err := svc.GetAuthURL(oauth.FacebookProvider, "http://example.org", "456")
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=")
+ 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=http%3A%2F%2Fexample.org%7C456")
}
func TestGetAuthURL_Google(t *testing.T) {
RegisterT(t)
svc := web.NewOAuthService("http://login.test.fider.io:3000")
- authURL, err := svc.GetAuthURL(oauth.GoogleProvider, "")
+ authURL, err := svc.GetAuthURL(oauth.GoogleProvider, "http://example.org", "123")
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=")
+ 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=http%3A%2F%2Fexample.org%7C123")
}
func TestGetAuthURL_GitHub(t *testing.T) {
RegisterT(t)
svc := web.NewOAuthService("http://login.test.fider.io:3000")
- authURL, err := svc.GetAuthURL(oauth.GitHubProvider, "")
+ authURL, err := svc.GetAuthURL(oauth.GitHubProvider, "http://example.org", "456")
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=")
+ 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=http%3A%2F%2Fexample.org%7C456")
}
func TestParseProfileResponse_AllFields(t *testing.T) {
diff --git a/app/pkg/web/util/util.go b/app/pkg/web/util/webutil.go
similarity index 75%
rename from app/pkg/web/util/util.go
rename to app/pkg/web/util/webutil.go
index 6b0a1a7f4..165e57adb 100644
--- a/app/pkg/web/util/util.go
+++ b/app/pkg/web/util/webutil.go
@@ -51,7 +51,7 @@ func SetSignUpAuthCookie(ctx web.Context, user *models.User) {
})
}
-//GetSignUpAuthCookie retruns the temporary temporary domain-wide Auth Token and removes it
+//GetSignUpAuthCookie returns the temporary temporary domain-wide Auth Token and removes it
func GetSignUpAuthCookie(ctx web.Context) string {
cookie, err := ctx.Request.Cookie(web.CookieSignUpAuthName)
if err == nil {
@@ -67,3 +67,20 @@ func GetSignUpAuthCookie(ctx web.Context) string {
}
return ""
}
+
+// GetOAuthBaseURL returns the OAuth base URL used for host-wide OAuth authentication
+// For Single Tenant HostMode, BaseURL is the current BaseURL
+// For Multi Tenant HostMode, BaseURL is //login.{HOST_DOMAIN}
+func GetOAuthBaseURL(ctx web.Context) string {
+ if env.IsSingleHostMode() {
+ return ctx.BaseURL()
+ }
+
+ oauthBaseURL := ctx.Request.URL.Scheme + "://login" + env.MultiTenantDomain()
+ port := ctx.Request.URL.Port()
+ if port != "" {
+ oauthBaseURL += ":" + port
+ }
+
+ return oauthBaseURL
+}
diff --git a/app/pkg/web/util/webutil_test.go b/app/pkg/web/util/webutil_test.go
new file mode 100644
index 000000000..d3702c01d
--- /dev/null
+++ b/app/pkg/web/util/webutil_test.go
@@ -0,0 +1,46 @@
+package webutil_test
+
+import (
+ "net/url"
+ "os"
+ "testing"
+
+ "github.com/getfider/fider/app/pkg/web/util"
+
+ . "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/web"
+)
+
+func newContext(rawurl string) web.Context {
+ url, _ := url.Parse(rawurl)
+
+ return web.Context{
+ Request: web.Request{
+ URL: url,
+ },
+ }
+}
+
+func TestGetOAuthBaseURL(t *testing.T) {
+ RegisterT(t)
+
+ ctx := newContext("https://mydomain.com/hello-world")
+
+ os.Setenv("HOST_MODE", "multi")
+ Expect(webutil.GetOAuthBaseURL(ctx)).Equals("https://login.test.fider.io")
+
+ os.Setenv("HOST_MODE", "single")
+ Expect(webutil.GetOAuthBaseURL(ctx)).Equals("https://mydomain.com")
+}
+
+func TestGetOAuthBaseURL_WithPort(t *testing.T) {
+ RegisterT(t)
+
+ ctx := newContext("http://demo.test.fider.io:3000/hello-world")
+
+ os.Setenv("HOST_MODE", "multi")
+ Expect(webutil.GetOAuthBaseURL(ctx)).Equals("http://login.test.fider.io:3000")
+
+ os.Setenv("HOST_MODE", "single")
+ Expect(webutil.GetOAuthBaseURL(ctx)).Equals("http://demo.test.fider.io:3000")
+}