Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

refactoring: prepare for CDN (#414)

Guilherme Oenning934f49568145
diff --git a/app/handlers/signin.go b/app/handlers/signin.go
index 423432346..2d832e9ed 100644
--- a/app/handlers/signin.go
+++ b/app/handlers/signin.go
@@ -54,7 +54,7 @@ func OAuthCallback(provider string) web.HandlerFunc {
if env.IsSingleHostMode() {
tenant, err = c.Services().Tenants.First()
} else {
- tenant, err = c.Services().Tenants.GetByDomain(stripPort(redirectURL.Host))
+ tenant, err = c.Services().Tenants.GetByDomain(redirectURL.Hostname())
}
if err != nil {
return c.Failure(err)
diff --git a/app/middlewares/compress.go b/app/middlewares/compress.go
index 9c0649591..e3c57c486 100644
--- a/app/middlewares/compress.go
+++ b/app/middlewares/compress.go
@@ -33,7 +33,7 @@ func Compress() web.MiddlewareFunc {
}
return func(c web.Context) error {
res := c.Response
- if strings.Contains(c.Request.Header.Get("Accept-Encoding"), "gzip") {
+ if strings.Contains(c.Request.GetHeader("Accept-Encoding"), "gzip") {
writer := pool.Get().(*gzip.Writer)
defer pool.Put(writer)
gzipResponse := &gzipResponseWriter{response: res, writer: writer, buffer: &bytes.Buffer{}}
diff --git a/app/middlewares/domain.go b/app/middlewares/domain.go
index 75337a5e8..634c56cae 100644
--- a/app/middlewares/domain.go
+++ b/app/middlewares/domain.go
@@ -2,8 +2,6 @@ package middlewares
import (
"fmt"
- "net/http"
- "net/url"
"github.com/getfider/fider/app/models"
@@ -43,7 +41,7 @@ func SingleTenant() web.MiddlewareFunc {
func MultiTenant() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
return func(c web.Context) error {
- hostname := stripPort(c.Request.Host)
+ hostname := c.Request.URL.Hostname()
// If no tenant is specified, redirect user to getfider.com
// This is only valid for fider.io hosting
@@ -99,22 +97,3 @@ func CheckTenantPrivacy() web.MiddlewareFunc {
}
}
}
-
-// HostChecker checks for a specific host
-func HostChecker(baseURL string) web.MiddlewareFunc {
- return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
- u, err := url.Parse("http://" + baseURL)
- if err != nil {
- return c.Failure(err)
- }
-
- if c.Request.Host != u.Host {
- c.Logger().Errorf("%s is not valid for this operation. Only %s is allowed.", c.Request.Host, u.Host)
- return c.NoContent(http.StatusBadRequest)
- }
-
- return next(c)
- }
- }
-}
diff --git a/app/middlewares/domain_test.go b/app/middlewares/domain_test.go
index 425eedff2..d749adc0b 100644
--- a/app/middlewares/domain_test.go
+++ b/app/middlewares/domain_test.go
@@ -165,31 +165,6 @@ func TestSingleTenant_WithTenants_ShouldSetFirstToContext(t *testing.T) {
Expect(response.Body.String()).Equals("MyCompany")
}
-func TestHostChecker(t *testing.T) {
- RegisterT(t)
-
- server, _ := mock.NewServer()
-
- server.Use(middlewares.HostChecker("login.test.fider.io"))
- status, _ := server.WithURL("http://login.test.fider.io").Execute(func(c web.Context) error {
- return c.NoContent(http.StatusOK)
- })
-
- Expect(status).Equals(http.StatusOK)
-}
-
-func TestHostChecker_DifferentHost(t *testing.T) {
- RegisterT(t)
-
- server, _ := mock.NewServer()
- server.Use(middlewares.HostChecker("login.test.fider.io"))
- status, _ := server.WithURL("http://avengers.test.fider.io").Execute(func(c web.Context) error {
- return c.NoContent(http.StatusOK)
- })
-
- Expect(status).Equals(http.StatusBadRequest)
-}
-
func TestOnlyActiveTenants_Active(t *testing.T) {
RegisterT(t)
diff --git a/app/middlewares/jwt.go b/app/middlewares/jwt.go
index 117f03fbb..8f7ad4dfc 100644
--- a/app/middlewares/jwt.go
+++ b/app/middlewares/jwt.go
@@ -16,7 +16,7 @@ func JwtGetter() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
return func(c web.Context) error {
- cookie, err := c.Cookie(web.CookieAuthName)
+ cookie, err := c.Request.Cookie(web.CookieAuthName)
if err != nil {
if errors.Cause(err) == http.ErrNoCookie {
return next(c)
diff --git a/app/middlewares/setup.go b/app/middlewares/setup.go
index 215a5380c..047d397d5 100644
--- a/app/middlewares/setup.go
+++ b/app/middlewares/setup.go
@@ -89,7 +89,7 @@ func WebSetup(logger log.Logger) web.MiddlewareFunc {
emailer := app.NewEmailer(logger)
return func(next web.HandlerFunc) web.HandlerFunc {
return func(c web.Context) error {
- path := log.Magenta(c.Request.Method + " " + c.Request.URL.String())
+ path := log.Magenta(c.Request.Method + " " + c.Request.URL.RequestURI())
start := time.Now()
c.Logger().Debugf("%s started", path)
diff --git a/app/pkg/assert/assert.go b/app/pkg/assert/assert.go
index cbdae1f8b..10d1f1ab8 100644
--- a/app/pkg/assert/assert.go
+++ b/app/pkg/assert/assert.go
@@ -3,6 +3,7 @@ package assert
import (
"context"
"fmt"
+ "os"
"reflect"
"strings"
"testing"
@@ -36,10 +37,30 @@ func Fail(msg string, args ...interface{}) {
}
var currentT *testing.T
+var envVariables map[string]string
//RegisterT saves current testing.T for further usage by Expect
func RegisterT(t *testing.T) {
+ if currentT == nil {
+ copyEnv()
+ }
+
currentT = t
+ restartEnv()
+}
+
+func copyEnv() {
+ envVariables = make(map[string]string, 0)
+ for _, e := range os.Environ() {
+ key := strings.Split(e, "=")[0]
+ envVariables[key] = os.Getenv(key)
+ }
+}
+
+func restartEnv() {
+ for k, v := range envVariables {
+ os.Setenv(k, v)
+ }
}
//AnyAssertions is used to assert any kind of value
diff --git a/app/pkg/env/env.go b/app/pkg/env/env.go
index 19b83e815..5bf38096b 100644
--- a/app/pkg/env/env.go
+++ b/app/pkg/env/env.go
@@ -137,3 +137,12 @@ func Etc(p ...string) string {
func IsDevelopment() bool {
return Current() == "development"
}
+
+// Subdomain returns the Fider subdomain (if available) from given host
+func Subdomain(host string) string {
+ domain := MultiTenantDomain()
+ if domain != "" && strings.Contains(host, domain) {
+ return strings.Replace(host, domain, "", -1)
+ }
+ return ""
+}
diff --git a/app/pkg/env/env_test.go b/app/pkg/env/env_test.go
index 3dde7a989..4508bc46a 100644
--- a/app/pkg/env/env_test.go
+++ b/app/pkg/env/env_test.go
@@ -123,3 +123,17 @@ func TestGetPublicIP(t *testing.T) {
Expect(err).IsNil()
Expect(ip).Equals("")
}
+
+func TestSubdomain(t *testing.T) {
+ RegisterT(t)
+
+ Expect(env.Subdomain("demo.test.fider.io")).Equals("demo")
+ Expect(env.Subdomain("test.fider.io")).Equals("")
+ Expect(env.Subdomain("helloworld.com")).Equals("")
+
+ os.Setenv("HOST_MODE", "single")
+
+ Expect(env.Subdomain("demo.test.fider.io")).Equals("")
+ Expect(env.Subdomain("test.fider.io")).Equals("")
+ Expect(env.Subdomain("helloworld.com")).Equals("")
+}
diff --git a/app/pkg/mock/server.go b/app/pkg/mock/server.go
index 7a54dad02..c43551a3b 100644
--- a/app/pkg/mock/server.go
+++ b/app/pkg/mock/server.go
@@ -72,7 +72,7 @@ func (s *Server) AddParam(name string, value interface{}) *Server {
// AddHeader add key-value to current context headers
func (s *Server) AddHeader(name string, value string) *Server {
- s.context.Request.Header.Add(name, value)
+ s.context.Request.SetHeader(name, value)
return s
}
@@ -84,8 +84,8 @@ func (s *Server) AddCookie(name string, value string) *Server {
// WithURL set current context Request URL
func (s *Server) WithURL(fullURL string) *Server {
- s.context.Request.URL, _ = url.Parse(fullURL)
- s.context.Request.Host = s.context.Request.URL.Host
+ u, _ := url.Parse(fullURL)
+ s.context.Request.URL = u
return s
}
@@ -107,10 +107,9 @@ func (s *Server) ExecuteAsJSON(handler web.HandlerFunc) (int, *jsonq.Query) {
// ExecutePost executes given handler as POST and return response
func (s *Server) ExecutePost(handler web.HandlerFunc, body string) (int, *httptest.ResponseRecorder) {
s.context.Request.Method = "POST"
- s.context.Request.URL.Path = "/"
s.context.Request.Body = ioutil.NopCloser(strings.NewReader(body))
s.context.Request.ContentLength = int64(len(body))
- s.context.Request.Header.Set("Content-Type", web.UTF8JSONContentType)
+ s.context.Request.SetHeader("Content-Type", web.UTF8JSONContentType)
if err := s.middleware(handler)(s.context); err != nil {
s.context.Failure(err)
diff --git a/app/pkg/validate/subdomain.go b/app/pkg/validate/subdomain.go
index 668b00d2b..e50ea49eb 100644
--- a/app/pkg/validate/subdomain.go
+++ b/app/pkg/validate/subdomain.go
@@ -31,7 +31,7 @@ func Subdomain(tenants storage.Tenant, subdomain string) *Result {
case
"signup", "fider", "login", "customers", "admin", "setup", "about",
"wecanhearyou", "dev", "mail", "billing", "www", "web", "translate",
- "help", "support", "status", "staging":
+ "help", "support", "status", "staging", "cdn", "assets":
return Failed([]string{fmt.Sprintf("%s is a reserved subdomain.", subdomain)})
}
diff --git a/app/pkg/web/binder.go b/app/pkg/web/binder.go
index 0eb05df14..2abbb02e5 100644
--- a/app/pkg/web/binder.go
+++ b/app/pkg/web/binder.go
@@ -33,7 +33,7 @@ func methodHasBody(method string) bool {
//Bind request data to object i
func (b *DefaultBinder) Bind(target interface{}, c *Context) error {
if methodHasBody(c.Request.Method) && c.Request.ContentLength > 0 {
- contentType := strings.Split(c.Request.Header.Get("Content-Type"), ";")
+ contentType := strings.Split(c.Request.GetHeader("Content-Type"), ";")
if len(contentType) == 0 || contentType[0] != JSONContentType {
return ErrContentTypeNotAllowed
}
diff --git a/app/pkg/web/context.go b/app/pkg/web/context.go
index 75245edfe..df1689d74 100644
--- a/app/pkg/web/context.go
+++ b/app/pkg/web/context.go
@@ -4,7 +4,6 @@ import (
"bytes"
"encoding/json"
"fmt"
- "net"
"net/http"
"strconv"
"time"
@@ -63,7 +62,7 @@ var (
type Context struct {
id string
Response http.ResponseWriter
- Request *http.Request
+ Request Request
engine *Engine
logger log.Logger
params StringMap
@@ -174,7 +173,7 @@ func (ctx *Context) IsAuthenticated() bool {
//IsAjax returns true if request is AJAX
func (ctx *Context) IsAjax() bool {
- return strings.Contains(ctx.Request.Header.Get("Accept"), "application/json")
+ return strings.Contains(ctx.Request.GetHeader("Accept"), "application/json")
}
//Unauthorized returns a 403 response
@@ -221,7 +220,7 @@ func (ctx *Context) Failure(err error) error {
user = fmt.Sprintf("%s (%d)", ctx.User().Name, ctx.User().ID)
}
- url := ctx.CurrentURL()
+ url := ctx.Request.URL.String()
message := fmt.Sprintf("URL: %s\nTenant: %s\nUser: %s\n%s", url, tenant, user, err.Error())
ctx.Logger().Errorf(log.Red(message))
ctx.Render(http.StatusInternalServerError, "500.html", Props{
@@ -324,7 +323,7 @@ func (ctx *Context) AddAuthCookie(user *models.User) (string, error) {
//AddCookie adds a cookie
func (ctx *Context) AddCookie(name, value string, expires time.Time) {
- ctx.SetCookie(&http.Cookie{
+ http.SetCookie(ctx.Response, &http.Cookie{
Name: name,
Value: value,
HttpOnly: true,
@@ -335,7 +334,7 @@ func (ctx *Context) AddCookie(name, value string, expires time.Time) {
//RemoveCookie removes a cookie
func (ctx *Context) RemoveCookie(name string) {
- ctx.SetCookie(&http.Cookie{
+ http.SetCookie(ctx.Response, &http.Cookie{
Name: name,
Path: "/",
HttpOnly: true,
@@ -361,16 +360,13 @@ func (ctx *Context) ActiveTransaction() *dbx.Trx {
//BaseURL returns base URL
func (ctx *Context) BaseURL() string {
- protocol := "http"
- if ctx.Request.TLS != nil || ctx.Request.Header.Get("X-Forwarded-Proto") == "https" {
- protocol = "https"
+ address := ctx.Request.URL.Scheme + "://" + ctx.Request.URL.Hostname()
+
+ if ctx.Request.URL.Port() != "" {
+ address += ":" + ctx.Request.URL.Port()
}
- return protocol + "://" + ctx.Request.Host
-}
-//CurrentURL returns complete current URL
-func (ctx *Context) CurrentURL() string {
- return ctx.BaseURL() + ctx.Request.RequestURI
+ return address
}
//TenantBaseURL returns base URL for a given tenant
@@ -379,21 +375,15 @@ func (ctx *Context) TenantBaseURL(tenant *models.Tenant) string {
return ctx.BaseURL()
}
- protocol := "http"
- _, port, _ := net.SplitHostPort(ctx.Request.Host)
- if ctx.Request.TLS != nil || ctx.Request.Header.Get("X-Forwarded-Proto") == "https" {
- protocol = "https"
- }
-
- address := protocol + "://"
+ address := ctx.Request.URL.Scheme + "://"
if tenant.CNAME != "" {
address += tenant.CNAME
} else {
address += tenant.Subdomain + env.MultiTenantDomain()
}
- if port != "" {
- address += ":" + port
+ if ctx.Request.URL.Port() != "" {
+ address += ":" + ctx.Request.URL.Port()
}
return address
@@ -480,16 +470,6 @@ func (ctx *Context) Blob(code int, contentType string, b []byte) error {
return err
}
-// Cookie returns the named cookie provided in the request.
-func (ctx *Context) Cookie(name string) (*http.Cookie, error) {
- return ctx.Request.Cookie(name)
-}
-
-// SetCookie adds a `Set-Cookie` header in HTTP response.
-func (ctx *Context) SetCookie(cookie *http.Cookie) {
- http.SetCookie(ctx.Response, cookie)
-}
-
// NoContent sends a response with no body and a status code.
func (ctx *Context) NoContent(code int) error {
ctx.Response.WriteHeader(code)
diff --git a/app/pkg/web/context_test.go b/app/pkg/web/context_test.go
index 43b01f2ed..4c3bd24ba 100644
--- a/app/pkg/web/context_test.go
+++ b/app/pkg/web/context_test.go
@@ -14,7 +14,8 @@ import (
func newGetContext(params web.StringMap) *web.Context {
e := web.New(nil)
res := httptest.NewRecorder()
- req := httptest.NewRequest("GET", "http://demo.test.fider.io:3000/some/resource", nil)
+ req := httptest.NewRequest("GET", "/some/resource", nil)
+ req.Host = "demo.test.fider.io:3000"
ctx := e.NewContext(res, req, params)
return &ctx
}
@@ -22,7 +23,8 @@ func newGetContext(params web.StringMap) *web.Context {
func newBodyContext(method string, params web.StringMap, body, contentType string) *web.Context {
e := web.New(nil)
res := httptest.NewRecorder()
- req := httptest.NewRequest(method, "http://demo.test.fider.io:3000/some/resource", strings.NewReader(body))
+ req := httptest.NewRequest(method, "/some/resource", strings.NewReader(body))
+ req.Host = "demo.test.fider.io:3000"
req.Header.Set("Content-Type", contentType)
ctx := e.NewContext(res, req, params)
return &ctx
@@ -45,15 +47,6 @@ func TestBaseURL(t *testing.T) {
Expect(ctx.BaseURL()).Equals("http://demo.test.fider.io:3000")
}
-func TestCurrentURL(t *testing.T) {
- RegisterT(t)
-
- ctx := newGetContext(nil)
- ctx.Request.RequestURI = "/resource?id=23"
-
- Expect(ctx.CurrentURL()).Equals("http://demo.test.fider.io:3000/resource?id=23")
-}
-
func TestTenantURL(t *testing.T) {
RegisterT(t)
diff --git a/app/pkg/web/engine.go b/app/pkg/web/engine.go
index 75f1aa8eb..1e0b9b0dd 100644
--- a/app/pkg/web/engine.go
+++ b/app/pkg/web/engine.go
@@ -155,7 +155,7 @@ func (e *Engine) NewContext(res http.ResponseWriter, req *http.Request, params S
return Context{
id: strings.Replace(uuid.NewV4().String(), "-", "", 4),
Response: res,
- Request: req,
+ Request: WrapRequest(req),
engine: e,
logger: e.logger,
params: params,
@@ -251,14 +251,14 @@ func (g *Group) Static(prefix, root string) {
path := root + c.Param("filepath")
fi, err := os.Stat(path)
if err == nil && !fi.IsDir() {
- http.ServeFile(c.Response, c.Request, path)
+ http.ServeFile(c.Response, c.Request.instance, path)
return nil
}
return c.NotFound()
}
} else {
h = func(c Context) error {
- http.ServeFile(c.Response, c.Request, root)
+ http.ServeFile(c.Response, c.Request.instance, root)
return nil
}
}
diff --git a/app/pkg/web/renderer.go b/app/pkg/web/renderer.go
index f26de970d..a04c7f8de 100644
--- a/app/pkg/web/renderer.go
+++ b/app/pkg/web/renderer.go
@@ -141,7 +141,7 @@ func (r *Renderer) Render(w io.Writer, name string, props Props, ctx *Context) {
m["system"] = r.settings
m["baseURL"] = ctx.BaseURL()
- m["currentURL"] = ctx.CurrentURL()
+ m["currentURL"] = ctx.Request.URL.String()
m["tenant"] = ctx.Tenant()
m["auth"] = Map{
"endpoint": ctx.AuthEndpoint(),
diff --git a/app/pkg/web/request.go b/app/pkg/web/request.go
new file mode 100644
index 000000000..f40d5cc49
--- /dev/null
+++ b/app/pkg/web/request.go
@@ -0,0 +1,66 @@
+package web
+
+import (
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+
+ "github.com/getfider/fider/app/pkg/errors"
+)
+
+//Request wraps the http request object
+type Request struct {
+ instance *http.Request
+ Method string
+ ContentLength int64
+ Body io.ReadCloser
+ URL *url.URL
+}
+
+// WrapRequest returns Fider wrapper of HTTP Request
+func WrapRequest(request *http.Request) Request {
+ protocol := "http"
+ if request.TLS != nil || request.Header.Get("X-Forwarded-Proto") == "https" {
+ protocol = "https"
+ }
+
+ host := request.Host
+ if request.Header.Get("X-Forwarded-Host") != "" {
+ host = request.Header.Get("X-Forwarded-Host")
+ }
+
+ fullURL := protocol + "://" + host + request.RequestURI
+ u, err := url.Parse(fullURL)
+ if err != nil {
+ panic(errors.New(fmt.Sprintf("Failed to parse url '%s'", fullURL)))
+ }
+
+ return Request{
+ instance: request,
+ Method: request.Method,
+ ContentLength: request.ContentLength,
+ Body: request.Body,
+ URL: u,
+ }
+}
+
+// GetHeader returns the value of HTTP header from given key
+func (r *Request) GetHeader(key string) string {
+ return r.instance.Header.Get(key)
+}
+
+// SetHeader updates the value of HTTP header of given key
+func (r *Request) SetHeader(key, value string) {
+ r.instance.Header.Set(key, value)
+}
+
+// Cookie returns the named cookie provided in the request.
+func (r *Request) Cookie(name string) (*http.Cookie, error) {
+ return r.instance.Cookie(name)
+}
+
+// AddCookie adds a cookie
+func (r *Request) AddCookie(cookie *http.Cookie) {
+ r.instance.AddCookie(cookie)
+}
diff --git a/app/pkg/web/request_test.go b/app/pkg/web/request_test.go
new file mode 100644
index 000000000..413427a08
--- /dev/null
+++ b/app/pkg/web/request_test.go
@@ -0,0 +1,91 @@
+package web_test
+
+import (
+ "net/http"
+ "testing"
+
+ . "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/web"
+)
+
+func TestRequest_Basic(t *testing.T) {
+ RegisterT(t)
+
+ header := make(http.Header, 0)
+ header.Set("Content-Type", "application/json")
+
+ req := web.WrapRequest(
+ &http.Request{
+ Method: "GET",
+ Header: header,
+ Host: "helloworld.com",
+ },
+ )
+
+ Expect(req.Method).Equals("GET")
+ Expect(req.GetHeader("Content-Type")).Equals("application/json")
+ Expect(req.URL.Hostname()).Equals("helloworld.com")
+ Expect(req.URL.Scheme).Equals("http")
+ Expect(req.URL.RequestURI()).Equals("/")
+ Expect(req.URL.String()).Equals("http://helloworld.com")
+}
+
+func TestRequest_WithPort(t *testing.T) {
+ RegisterT(t)
+
+ header := make(http.Header, 0)
+ header.Set("Content-Type", "application/json")
+
+ req := web.WrapRequest(
+ &http.Request{
+ Method: "GET",
+ Header: header,
+ Host: "helloworld.com:3000",
+ RequestURI: "/echo",
+ },
+ )
+
+ Expect(req.Method).Equals("GET")
+ Expect(req.GetHeader("Content-Type")).Equals("application/json")
+ Expect(req.URL.Hostname()).Equals("helloworld.com")
+ Expect(req.URL.Scheme).Equals("http")
+ Expect(req.URL.Port()).Equals("3000")
+ Expect(req.URL.RequestURI()).Equals("/echo")
+ Expect(req.URL.String()).Equals("http://helloworld.com:3000/echo")
+}
+
+func TestRequest_BehindTLSTerminationProxy(t *testing.T) {
+ RegisterT(t)
+
+ header := make(http.Header, 0)
+ header.Set("X-Forwarded-Host", "feedback.mycompany.com")
+ header.Set("X-Forwarded-Proto", "https")
+
+ req := web.WrapRequest(
+ &http.Request{
+ Method: "GET",
+ Header: header,
+ Host: "demo.test.fider.io",
+ },
+ )
+
+ Expect(req.Method).Equals("GET")
+ Expect(req.URL.Hostname()).Equals("feedback.mycompany.com")
+ Expect(req.URL.Scheme).Equals("https")
+}
+
+func TestRequest_FullURL(t *testing.T) {
+ RegisterT(t)
+
+ req := web.WrapRequest(
+ &http.Request{
+ Host: "demo.test.fider.io",
+ RequestURI: "/echo?value=Jon",
+ },
+ )
+
+ Expect(req.URL.String()).Equals("http://demo.test.fider.io/echo?value=Jon")
+ Expect(req.URL.Path).Equals("/echo")
+ Expect(req.URL.Query().Get("value")).Equals("Jon")
+ Expect(req.URL.RequestURI()).Equals("/echo?value=Jon")
+}
diff --git a/app/storage/inmemory/tenant.go b/app/storage/inmemory/tenant.go
index 62db1669c..861c75457 100644
--- a/app/storage/inmemory/tenant.go
+++ b/app/storage/inmemory/tenant.go
@@ -2,7 +2,6 @@ package inmemory
import (
"net/http"
- "strings"
"time"
"github.com/getfider/fider/app"
@@ -51,7 +50,7 @@ func (s *TenantStorage) First() (*models.Tenant, error) {
// GetByDomain returns a tenant based on its domain
func (s *TenantStorage) GetByDomain(domain string) (*models.Tenant, error) {
for _, tenant := range s.tenants {
- if tenant.Subdomain == extractSubdomain(domain) || tenant.CNAME == domain {
+ if tenant.Subdomain == env.Subdomain(domain) || tenant.Subdomain == domain || tenant.CNAME == domain {
return tenant, nil
}
}
@@ -191,12 +190,3 @@ func (s *TenantStorage) GetLogo(id int) (*models.Upload, error) {
}
return nil, app.ErrNotFound
}
-
-func extractSubdomain(hostname string) string {
- domain := env.MultiTenantDomain()
- if domain == "" {
- return hostname
- }
-
- return strings.Replace(hostname, domain, "", -1)
-}
diff --git a/app/storage/postgres/tenant.go b/app/storage/postgres/tenant.go
index 5c97ea31a..9fda3b713 100644
--- a/app/storage/postgres/tenant.go
+++ b/app/storage/postgres/tenant.go
@@ -3,7 +3,6 @@ package postgres
import (
"database/sql"
"net/http"
- "strings"
"time"
"github.com/getfider/fider/app"
@@ -136,7 +135,7 @@ func (s *TenantStorage) First() (*models.Tenant, error) {
func (s *TenantStorage) GetByDomain(domain string) (*models.Tenant, error) {
tenant := dbTenant{}
- err := s.trx.Get(&tenant, "SELECT id, name, subdomain, cname, invitation, welcome_message, status, is_private, logo_id, custom_css FROM tenants WHERE subdomain = $1 OR cname = $2 ORDER BY cname DESC", extractSubdomain(domain), domain)
+ err := s.trx.Get(&tenant, "SELECT id, name, subdomain, cname, invitation, welcome_message, status, is_private, logo_id, custom_css FROM tenants WHERE subdomain = $1 OR subdomain = $2 OR cname = $3 ORDER BY cname DESC", env.Subdomain(domain), domain, domain)
if err != nil {
return nil, errors.Wrap(err, "failed to get tenant with domain '%s'", domain)
}
@@ -295,12 +294,3 @@ func (s *TenantStorage) GetLogo(id int) (*models.Upload, error) {
}
return upload, nil
}
-
-func extractSubdomain(hostname string) string {
- domain := env.MultiTenantDomain()
- if domain == "" {
- return hostname
- }
-
- return strings.Replace(hostname, domain, "", -1)
-}
diff --git a/app/storage/postgres/tenant_test.go b/app/storage/postgres/tenant_test.go
index ca967b2b1..008e3ffac 100644
--- a/app/storage/postgres/tenant_test.go
+++ b/app/storage/postgres/tenant_test.go
@@ -111,6 +111,27 @@ func TestTenantStorage_GetByDomain_Subdomain(t *testing.T) {
Expect(tenant.Status).Equals(models.TenantActive)
}
+func TestTenantStorage_GetByDomain_CNAME(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ tenant, err := tenants.Add("My Domain Inc.", "mydomain", models.TenantActive)
+ Expect(err).IsNil()
+ tenants.SetCurrentTenant(tenant)
+ tenants.UpdateSettings(&models.UpdateTenantSettings{
+ Title: "My Domain Inc.",
+ CNAME: "feedback.mycompany.com",
+ })
+
+ tenant, err = tenants.GetByDomain("feedback.mycompany.com")
+ Expect(err).IsNil()
+ Expect(tenant.ID).NotEquals(0)
+ Expect(tenant.Name).Equals("My Domain Inc.")
+ Expect(tenant.Subdomain).Equals("mydomain")
+ Expect(tenant.CNAME).Equals("feedback.mycompany.com")
+ Expect(tenant.Status).Equals(models.TenantActive)
+}
+
func TestTenantStorage_IsSubdomainAvailable_ExistingDomain(t *testing.T) {
SetupDatabaseTest(t)
defer TeardownDatabaseTest()