Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

Allow users to sign up using e-mail and name (#132)

Guilherme Oenningca7252159ef9
diff --git a/app/actions/actions_test.go b/app/actions/actions_test.go
index d4f6a7b12..56a51582c 100644
--- a/app/actions/actions_test.go
+++ b/app/actions/actions_test.go
@@ -20,13 +20,19 @@ var services = &app.Services{
Tenants: &inmemory.TenantStorage{},
}
-func ExpectFailed(result *validate.Result, field string) {
+func ExpectFailed(result *validate.Result, fields ...string) {
Expect(result.Ok).To(BeFalse())
Expect(result.Error).To(BeNil())
- if field == "" {
- Expect(len(result.Messages) > 0).To(BeTrue())
- } else {
- Expect(len(result.Failures[field]) > 0).To(BeTrue())
+ for _, field := range fields {
+ if field == "" {
+ Expect(len(result.Messages) > 0).To(BeTrue())
+ } else {
+ Expect(len(result.Failures[field]) > 0).To(BeTrue(), "Failures should contain field: "+field)
+ }
+ }
+
+ for field, _ := range result.Failures {
+ Expect(fields).To(ContainElement(field), "Failures should not contain field: "+field)
}
}
diff --git a/app/actions/signin.go b/app/actions/signin.go
index d008bc1aa..dc63f5bba 100644
--- a/app/actions/signin.go
+++ b/app/actions/signin.go
@@ -29,7 +29,7 @@ func (input *SignInByEmail) IsAuthorized(user *models.User) bool {
// Validate is current model is valid
func (input *SignInByEmail) Validate(services *app.Services) *validate.Result {
result := validate.Success()
- input.Model.Email = strings.Trim(strings.ToLower(input.Model.Email), " ")
+ input.Model.Email = strings.ToLower(strings.Trim(input.Model.Email, " "))
if input.Model.Email == "" {
result.AddFieldFailure("email", "E-mail is required.")
diff --git a/app/actions/signin_test.go b/app/actions/signin_test.go
index fd612b2c8..6c78a948d 100644
--- a/app/actions/signin_test.go
+++ b/app/actions/signin_test.go
@@ -2,6 +2,7 @@ package actions_test
import (
"testing"
+ "time"
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models"
@@ -42,8 +43,7 @@ func TestCompleteProfile_EmptyNameAndKey(t *testing.T) {
action := actions.CompleteProfile{Model: &models.CompleteProfile{}}
result := action.Validate(services)
- ExpectFailed(result, "name")
- ExpectFailed(result, "key")
+ ExpectFailed(result, "name", "key")
}
func TestCompleteProfile_LongName(t *testing.T) {
@@ -53,8 +53,7 @@ func TestCompleteProfile_LongName(t *testing.T) {
Name: "123456789012345678901234567890123456789012345678901", // 51 chars
}}
result := action.Validate(services)
- ExpectFailed(result, "name")
- ExpectFailed(result, "key")
+ ExpectFailed(result, "name", "key")
}
func TestCompleteProfile_UnknownKey(t *testing.T) {
@@ -66,7 +65,7 @@ func TestCompleteProfile_UnknownKey(t *testing.T) {
func TestCompleteProfile_ValidKey(t *testing.T) {
RegisterTestingT(t)
- services.Tenants.SaveVerificationKey("[email protected]", "1234567890")
+ services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, "[email protected]", "")
action := actions.CompleteProfile{Model: &models.CompleteProfile{Name: "Jon Snow", Key: "1234567890"}}
result := action.Validate(services)
ExpectSuccess(result)
diff --git a/app/actions/tenant.go b/app/actions/tenant.go
index 201108247..45cb4ce3a 100644
--- a/app/actions/tenant.go
+++ b/app/actions/tenant.go
@@ -7,6 +7,7 @@ import (
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/jwt"
+ "github.com/getfider/fider/app/pkg/uuid"
"github.com/getfider/fider/app/pkg/validate"
)
@@ -18,6 +19,7 @@ type CreateTenant struct {
// Initialize the model
func (input *CreateTenant) Initialize() interface{} {
input.Model = new(models.CreateTenant)
+ input.Model.VerificationKey = strings.Replace(uuid.NewV4().String(), "-", "", 4)
return input.Model
}
@@ -29,13 +31,38 @@ func (input *CreateTenant) IsAuthorized(user *models.User) bool {
// Validate is current model is valid
func (input *CreateTenant) Validate(services *app.Services) *validate.Result {
result := validate.Success()
+ input.Model.Name = strings.Trim(input.Model.Name, " ")
+ input.Model.Email = strings.ToLower(strings.Trim(input.Model.Email, " "))
+ input.Model.TenantName = strings.Trim(input.Model.TenantName, " ")
+ input.Model.Subdomain = strings.ToLower(strings.Trim(input.Model.Subdomain, " "))
var err error
- if input.Model.Token == "" {
- result.AddFieldFailure("token", "Please identify yourself before proceeding.")
+ if input.Model.Name == "" && input.Model.Email == "" {
+ if input.Model.Token == "" {
+ result.AddFieldFailure("token", "Please identify yourself before proceeding.")
+ } else {
+ if input.Model.UserClaims, err = jwt.DecodeOAuthClaims(input.Model.Token); err != nil {
+ return validate.Error(err)
+ }
+ }
} else {
- if input.Model.UserClaims, err = jwt.DecodeOAuthClaims(input.Model.Token); err != nil {
- return validate.Error(err)
+ if input.Model.Email == "" {
+ result.AddFieldFailure("email", "E-mail is required.")
+ } else {
+ if emailResult := validate.Email(input.Model.Email); !emailResult.Ok {
+ result.AddFieldFailure("email", emailResult.Messages...)
+ }
+ }
+
+ if len(input.Model.Email) > 200 {
+ result.AddFieldFailure("email", "E-mail must be less than 200 characters.")
+ }
+
+ if input.Model.Name == "" {
+ result.AddFieldFailure("name", "Name is required.")
+ }
+ if len(input.Model.Name) > 50 {
+ result.AddFieldFailure("name", "Name must be less than 50 characters.")
}
}
@@ -43,8 +70,8 @@ func (input *CreateTenant) Validate(services *app.Services) *validate.Result {
input.Model.Subdomain = "default"
}
- if input.Model.Name == "" {
- result.AddFieldFailure("name", "Name is required.")
+ if input.Model.TenantName == "" {
+ result.AddFieldFailure("tenantName", "Name is required.")
}
subdomainResult := validate.Subdomain(services.Tenants, input.Model.Subdomain)
@@ -52,8 +79,6 @@ func (input *CreateTenant) Validate(services *app.Services) *validate.Result {
result.AddFieldFailure("subdomain", subdomainResult.Messages...)
}
- input.Model.Subdomain = strings.ToLower(input.Model.Subdomain)
-
return result
}
diff --git a/app/actions/tenant_test.go b/app/actions/tenant_test.go
index 4d1a1b60e..5563e8e3d 100644
--- a/app/actions/tenant_test.go
+++ b/app/actions/tenant_test.go
@@ -9,26 +9,59 @@ import (
. "github.com/onsi/gomega"
)
+func TestCreateTenant_ShouldHaveVerificationKey(t *testing.T) {
+ RegisterTestingT(t)
+
+ action := actions.CreateTenant{}
+ action.Initialize()
+
+ Expect(action.Model.VerificationKey).NotTo(Equal(""))
+}
+
func TestCreateTenant_EmptyToken(t *testing.T) {
RegisterTestingT(t)
action := actions.CreateTenant{Model: &models.CreateTenant{Token: ""}}
result := action.Validate(services)
- ExpectFailed(result, "token")
+ ExpectFailed(result, "token", "tenantName", "subdomain")
+}
+
+func TestCreateTenant_EmptyTenantName(t *testing.T) {
+ RegisterTestingT(t)
+
+ action := actions.CreateTenant{Model: &models.CreateTenant{Token: jonSnowToken, TenantName: ""}}
+ result := action.Validate(services)
+ ExpectFailed(result, "tenantName", "subdomain")
+}
+
+func TestCreateTenant_EmptyEmail(t *testing.T) {
+ RegisterTestingT(t)
+
+ action := actions.CreateTenant{Model: &models.CreateTenant{Name: "Jon Snow", Email: ""}}
+ result := action.Validate(services)
+ ExpectFailed(result, "email", "tenantName", "subdomain")
+}
+
+func TestCreateTenant_InvalidEmail(t *testing.T) {
+ RegisterTestingT(t)
+
+ action := actions.CreateTenant{Model: &models.CreateTenant{Name: "Jon Snow", Email: "jonsnow"}}
+ result := action.Validate(services)
+ ExpectFailed(result, "email", "tenantName", "subdomain")
}
func TestCreateTenant_EmptyName(t *testing.T) {
RegisterTestingT(t)
- action := actions.CreateTenant{Model: &models.CreateTenant{Token: jonSnowToken, Name: ""}}
+ action := actions.CreateTenant{Model: &models.CreateTenant{Name: "", Email: "[email protected]"}}
result := action.Validate(services)
- ExpectFailed(result, "name")
+ ExpectFailed(result, "name", "tenantName", "subdomain")
}
func TestCreateTenant_EmptySubdomain(t *testing.T) {
RegisterTestingT(t)
- action := actions.CreateTenant{Model: &models.CreateTenant{Token: jonSnowToken, Name: "My Company"}}
+ action := actions.CreateTenant{Model: &models.CreateTenant{Token: jonSnowToken, TenantName: "My Company"}}
result := action.Validate(services)
ExpectFailed(result, "subdomain")
}
@@ -36,7 +69,7 @@ func TestCreateTenant_EmptySubdomain(t *testing.T) {
func TestCreateTenant_UpperCaseSubdomain(t *testing.T) {
RegisterTestingT(t)
- action := actions.CreateTenant{Model: &models.CreateTenant{Token: jonSnowToken, Name: "My Company", Subdomain: "MyCompany"}}
+ action := actions.CreateTenant{Model: &models.CreateTenant{Token: jonSnowToken, TenantName: "My Company", Subdomain: "MyCompany"}}
result := action.Validate(services)
ExpectSuccess(result)
Expect(action.Model.Subdomain).To(Equal("mycompany"))
diff --git a/app/handlers/signin.go b/app/handlers/signin.go
index e2c469da8..876f0e80c 100644
--- a/app/handlers/signin.go
+++ b/app/handlers/signin.go
@@ -139,12 +139,12 @@ func SignInByEmail() web.HandlerFunc {
return c.HandleValidation(result)
}
- err := c.Services().Tenants.SaveVerificationKey(input.Model.Email, input.Model.VerificationKey)
+ err := c.Services().Tenants.SaveVerificationKey(input.Model.VerificationKey, 15*time.Minute, input.Model.Email, "")
if err != nil {
return c.Failure(err)
}
- subject := fmt.Sprintf("Sign in to %s", c.Tenant().Name)
+ subject := fmt.Sprintf("Sign in to %s feedback forum", c.Tenant().Name)
link := fmt.Sprintf("%s/signin/verify?k=%s", c.BaseURL(), input.Model.VerificationKey)
message := fmt.Sprintf("Click and confirm that you want to sign in. This link will expire in 15 minutes and can only be used once. <br /><br /> <a href='%s'>%s</a>", link, link)
err = c.Services().Emailer.Send(c.Tenant().Name, input.Model.Email, subject, message)
@@ -174,8 +174,8 @@ func VerifySignInKey() web.HandlerFunc {
return c.Redirect(http.StatusTemporaryRedirect, c.BaseURL())
}
- //If key expired (15 minutes), go back to home page
- if time.Now().After(result.CreatedOn.Add(15 * time.Minute)) {
+ //If key expired, go back to home page
+ if time.Now().After(result.ExpiresOn) {
err = c.Services().Tenants.SetKeyAsVerified(key)
if err != nil {
return c.Failure(err)
@@ -183,13 +183,31 @@ func VerifySignInKey() web.HandlerFunc {
return c.Redirect(http.StatusTemporaryRedirect, c.BaseURL())
}
- user, err := c.Services().Users.GetByEmail(c.Tenant().ID, result.Email)
- if err != nil {
- if err == app.ErrNotFound {
- // This will render a page for /signin/verify URL using same variables as home page
- return Index()(c)
+ var user *models.User
+ if c.Tenant().Status == models.TenantInactive {
+ if err = c.Services().Tenants.Activate(c.Tenant().ID); err != nil {
+ return c.Failure(err)
+ }
+
+ user = &models.User{
+ Name: result.Name,
+ Email: result.Email,
+ Tenant: c.Tenant(),
+ Role: models.RoleAdministrator,
+ }
+
+ if err = c.Services().Users.Register(user); err != nil {
+ return c.Failure(err)
+ }
+ } else {
+ user, err = c.Services().Users.GetByEmail(c.Tenant().ID, result.Email)
+ if err != nil {
+ if err == app.ErrNotFound {
+ // This will render a page for /signin/verify URL using same variables as home page
+ return Index()(c)
+ }
+ return c.Failure(err)
}
- return c.Failure(err)
}
err = c.Services().Tenants.SetKeyAsVerified(key)
diff --git a/app/handlers/signin_test.go b/app/handlers/signin_test.go
index aa751c457..d156f5124 100644
--- a/app/handlers/signin_test.go
+++ b/app/handlers/signin_test.go
@@ -203,7 +203,7 @@ func TestVerifySignInKeyHandler_UsedKey(t *testing.T) {
server, services := mock.NewServer()
- services.Tenants.SaveVerificationKey("[email protected]", "1234567890")
+ services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, "[email protected]", "")
services.Tenants.SetKeyAsVerified("1234567890")
code, response := server.
@@ -220,9 +220,9 @@ func TestVerifySignInKeyHandler_ExpiredKey(t *testing.T) {
server, services := mock.NewServer()
- services.Tenants.SaveVerificationKey("[email protected]", "1234567890")
+ services.Tenants.SaveVerificationKey("1234567890", 5*time.Minute, "[email protected]", "")
request, _ := services.Tenants.FindVerificationByKey("1234567890")
- request.CreatedOn = request.CreatedOn.Add(-16 * time.Minute) //reduce 16 minutes
+ request.ExpiresOn = request.CreatedOn.Add(-6 * time.Minute) //reduce 1 minute
code, response := server.
OnTenant(mock.DemoTenant).
@@ -238,7 +238,7 @@ func TestVerifySignInKeyHandler_CorrectKey_ExistingUser(t *testing.T) {
server, services := mock.NewServer()
- services.Tenants.SaveVerificationKey("[email protected]", "1234567890")
+ services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, "[email protected]", "")
code, response := server.
OnTenant(mock.DemoTenant).
@@ -256,12 +256,12 @@ func TestVerifySignInKeyHandler_CorrectKey_ExistingUser(t *testing.T) {
Expect(response.Header().Get("Set-Cookie")).To(ContainSubstring(fmt.Sprintf("%s=%s;", web.CookieAuthName, token)))
}
-func TestVerifySignInKeyHandler_CorrectKey_ExistingNewUser(t *testing.T) {
+func TestVerifySignInKeyHandler_CorrectKey_NewUser(t *testing.T) {
RegisterTestingT(t)
server, services := mock.NewServer()
- services.Tenants.SaveVerificationKey("[email protected]", "1234567890")
+ services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, "[email protected]", "")
code, _ := server.
OnTenant(mock.DemoTenant).
@@ -271,6 +271,24 @@ func TestVerifySignInKeyHandler_CorrectKey_ExistingNewUser(t *testing.T) {
Expect(code).To(Equal(http.StatusOK))
}
+func TestVerifySignUpKeyHandler_InactiveTenant(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, services := mock.NewServer()
+
+ services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, "[email protected]", "Hot Pie")
+ mock.DemoTenant.Status = models.TenantInactive
+
+ code, response := server.
+ OnTenant(mock.DemoTenant).
+ WithURL("http://demo.test.fider.io/signup/verify?k=1234567890").
+ Execute(handlers.VerifySignUpKey())
+
+ Expect(code).To(Equal(http.StatusTemporaryRedirect))
+ Expect(response.Header().Get("Location")).To(Equal("http://demo.test.fider.io"))
+ //Expect(response.Header().Get("Set-Cookie")).To(ContainSubstring(fmt.Sprintf("%s=%s;", web.CookieAuthName, token)))
+}
+
func TestCompleteSignInProfileHandler_UnknownKey(t *testing.T) {
RegisterTestingT(t)
@@ -289,7 +307,7 @@ func TestCompleteSignInProfileHandler_ExistingUser_CorrectKey(t *testing.T) {
server, services := mock.NewServer()
- services.Tenants.SaveVerificationKey(mock.JonSnow.Email, "1234567890")
+ services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, mock.JonSnow.Email, "")
code, _ := server.
OnTenant(mock.DemoTenant).
@@ -304,7 +322,7 @@ func TestCompleteSignInProfileHandler_CorrectKey(t *testing.T) {
server, services := mock.NewServer()
- services.Tenants.SaveVerificationKey("[email protected]", "1234567890")
+ services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, "[email protected]", "")
code, response := server.
OnTenant(mock.DemoTenant).
diff --git a/app/handlers/signup.go b/app/handlers/signup.go
index dddc1e778..1a3661cd7 100644
--- a/app/handlers/signup.go
+++ b/app/handlers/signup.go
@@ -1,7 +1,9 @@
package handlers
import (
+ "fmt"
"net/http"
+ "time"
"strings"
@@ -36,34 +38,64 @@ func CreateTenant() web.HandlerFunc {
return c.HandleValidation(result)
}
- tenant, err := c.Services().Tenants.Add(input.Model.Name, input.Model.Subdomain)
+ socialSignUp := input.Model.Token != ""
+
+ status := models.TenantInactive
+ if socialSignUp {
+ status = models.TenantActive
+ }
+
+ tenant, err := c.Services().Tenants.Add(input.Model.TenantName, input.Model.Subdomain, status)
if err != nil {
return c.Failure(err)
}
+ c.Services().Tenants.SetCurrentTenant(tenant)
+
user := &models.User{
- Name: input.Model.UserClaims.OAuthName,
- Email: input.Model.UserClaims.OAuthEmail,
Tenant: tenant,
Role: models.RoleAdministrator,
- Providers: []*models.UserProvider{
+ }
+
+ if socialSignUp {
+ user.Name = input.Model.UserClaims.OAuthName
+ user.Email = input.Model.UserClaims.OAuthEmail
+ user.Providers = []*models.UserProvider{
{UID: input.Model.UserClaims.OAuthID, Name: input.Model.UserClaims.OAuthProvider},
- },
+ }
+ } else {
+ user.Name = input.Model.Name
+ user.Email = input.Model.Email
+
+ err := c.Services().Tenants.SaveVerificationKey(input.Model.VerificationKey, 48*time.Hour, user.Email, user.Name)
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ subject := "Verify your new Fider instance"
+ link := fmt.Sprintf("%s/signup/verify?k=%s", c.TenantBaseURL(tenant), input.Model.VerificationKey)
+ message := fmt.Sprintf("Click and confirm that you created a new Fider instance. This link will expire in 48 hours and can only be used once. <br /><br /> <a href='%s'>%s</a>", link, link)
+ err = c.Services().Emailer.Send("Fider", user.Email, subject, message)
+ if err != nil {
+ return c.Failure(err)
+ }
}
if err := c.Services().Users.Register(user); err != nil {
return c.Failure(err)
}
- token, err := c.AddAuthCookie(user)
- if err != nil {
- return c.Failure(err)
+ if socialSignUp {
+ token, err := c.AddAuthCookie(user)
+ if err != nil {
+ return c.Failure(err)
+ }
+ return c.Ok(web.Map{
+ "token": token,
+ })
}
- return c.Ok(web.Map{
- "id": tenant.ID,
- "token": token,
- })
+ return c.Ok(web.Map{})
}
}
@@ -83,3 +115,13 @@ func SignUp() web.HandlerFunc {
return c.Page(web.Map{})
}
}
+
+// VerifySignUpKey checks if verify key is correct, activate the tenant and sign in user
+func VerifySignUpKey() web.HandlerFunc {
+ return func(c web.Context) error {
+ if c.Tenant().Status == models.TenantInactive {
+ return VerifySignInKey()(c)
+ }
+ return c.NotFound()
+ }
+}
diff --git a/app/handlers/signup_test.go b/app/handlers/signup_test.go
index 8470d36ed..548ea48ea 100644
--- a/app/handlers/signup_test.go
+++ b/app/handlers/signup_test.go
@@ -34,7 +34,7 @@ func TestSignUpHandler_SingleTenant_WithTenants(t *testing.T) {
RegisterTestingT(t)
server, services := mock.NewSingleTenantServer()
- services.Tenants.Add("Game of Thrones", "got")
+ services.Tenants.Add("Game of Thrones", "got", models.TenantActive)
code, _ := server.Execute(handlers.SignUp())
Expect(code).To(Equal(307))
@@ -80,17 +80,63 @@ func TestCreateTenantHandler_EmptyInput(t *testing.T) {
Expect(code).To(Equal(400))
}
-func TestCreateTenantHandler_ValidInput(t *testing.T) {
+func TestCreateTenantHandler_WithSocialAccount(t *testing.T) {
RegisterTestingT(t)
- server, _ := mock.NewServer()
+ server, services := mock.NewServer()
token, _ := jwt.Encode(&models.OAuthClaims{
OAuthID: "123",
OAuthName: "Jon Snow",
OAuthEmail: "[email protected]",
OAuthProvider: "facebook",
})
- code, _ := server.ExecutePost(handlers.CreateTenant(), fmt.Sprintf(`{ "token": "%s", "name": "My Company", "subdomain": "mycompany" }`, token))
+ code, response := server.ExecutePostAsJSON(
+ handlers.CreateTenant(),
+ fmt.Sprintf(`{ "token": "%s", "tenantName": "My Company", "subdomain": "mycompany" }`, token),
+ )
+
+ tenant, err := services.Tenants.GetByDomain("mycompany")
+
+ Expect(code).To(Equal(200))
+ Expect(response.String("token")).NotTo(BeNil())
+
+ Expect(err).To(BeNil())
+ Expect(tenant.Name).To(Equal("My Company"))
+ Expect(tenant.Subdomain).To(Equal("mycompany"))
+ Expect(tenant.Status).To(Equal(models.TenantActive))
+
+ user, err := services.Users.GetByEmail(tenant.ID, "[email protected]")
+ Expect(err).To(BeNil())
+ Expect(user.Name).To(Equal("Jon Snow"))
+ Expect(user.Email).To(Equal("[email protected]"))
+ Expect(user.Role).To(Equal(models.RoleAdministrator))
+}
+
+func TestCreateTenantHandler_WithEmailAndName(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, services := mock.NewServer()
+ code, response := server.ExecutePostAsJSON(
+ handlers.CreateTenant(),
+ `{ "name": "Jon Snow", "email": "[email protected]", "tenantName": "My Company", "subdomain": "mycompany" }`,
+ )
Expect(code).To(Equal(200))
+ _, err := response.String("token")
+ Expect(err).NotTo(BeNil())
+
+ tenant, err := services.Tenants.GetByDomain("mycompany")
+
+ Expect(code).To(Equal(200))
+
+ Expect(err).To(BeNil())
+ Expect(tenant.Name).To(Equal("My Company"))
+ Expect(tenant.Subdomain).To(Equal("mycompany"))
+ Expect(tenant.Status).To(Equal(models.TenantInactive))
+
+ user, err := services.Users.GetByEmail(tenant.ID, "[email protected]")
+ Expect(err).To(BeNil())
+ Expect(user.Name).To(Equal("Jon Snow"))
+ Expect(user.Email).To(Equal("[email protected]"))
+ Expect(user.Role).To(Equal(models.RoleAdministrator))
}
diff --git a/app/middlewares/domain.go b/app/middlewares/domain.go
index 4ef9b4a23..68803e0f9 100644
--- a/app/middlewares/domain.go
+++ b/app/middlewares/domain.go
@@ -4,6 +4,8 @@ import (
"net/http"
"net/url"
+ "github.com/getfider/fider/app/models"
+
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/web"
@@ -62,6 +64,18 @@ func MultiTenant() web.MiddlewareFunc {
}
}
+// OnlyActiveTenants blocks requests for inactive tenants
+func OnlyActiveTenants() web.MiddlewareFunc {
+ return func(next web.HandlerFunc) web.HandlerFunc {
+ return func(c web.Context) error {
+ if c.Tenant().Status == models.TenantActive {
+ return next(c)
+ }
+ return c.NotFound()
+ }
+ }
+}
+
// HostChecker checks for a specific host
func HostChecker(baseURL string) web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
diff --git a/app/middlewares/domain_test.go b/app/middlewares/domain_test.go
index 37b16a45e..df39853ea 100644
--- a/app/middlewares/domain_test.go
+++ b/app/middlewares/domain_test.go
@@ -5,6 +5,7 @@ import (
"testing"
"github.com/getfider/fider/app/middlewares"
+ "github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/mock"
"github.com/getfider/fider/app/pkg/web"
. "github.com/onsi/gomega"
@@ -82,7 +83,7 @@ func TestSingleTenant_WithTenants_ShouldSetFirstToContext(t *testing.T) {
server, services := mock.NewSingleTenantServer()
server.Use(middlewares.SingleTenant())
- services.Tenants.Add("MyCompany", "mycompany")
+ services.Tenants.Add("MyCompany", "mycompany", models.TenantActive)
status, response := server.WithURL("http://somedomain.com").Execute(func(c web.Context) error {
return c.String(http.StatusOK, c.Tenant().Name)
@@ -116,3 +117,30 @@ func TestHostChecker_DifferentHost(t *testing.T) {
Expect(status).To(Equal(http.StatusBadRequest))
}
+
+func TestOnlyActiveTenants_Active(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, _ := mock.NewServer()
+
+ server.Use(middlewares.OnlyActiveTenants())
+ status, _ := server.OnTenant(mock.DemoTenant).Execute(func(c web.Context) error {
+ return c.NoContent(http.StatusOK)
+ })
+
+ Expect(status).To(Equal(http.StatusOK))
+}
+
+func TestOnlyActiveTenants_Inactive(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, _ := mock.NewServer()
+ mock.DemoTenant.Status = models.TenantInactive
+
+ server.Use(middlewares.OnlyActiveTenants())
+ status, _ := server.OnTenant(mock.DemoTenant).Execute(func(c web.Context) error {
+ return c.NoContent(http.StatusOK)
+ })
+
+ Expect(status).To(Equal(http.StatusNotFound))
+}
diff --git a/app/middlewares/jwt.go b/app/middlewares/jwt.go
index 4618b79c2..29b7ef9e1 100644
--- a/app/middlewares/jwt.go
+++ b/app/middlewares/jwt.go
@@ -25,7 +25,8 @@ func JwtGetter() web.MiddlewareFunc {
claims, err := jwt.DecodeFiderClaims(cookie.Value)
if err != nil {
- return err
+ c.RemoveCookie(web.CookieAuthName)
+ return next(c)
}
services := c.Services()
diff --git a/app/middlewares/noop.go b/app/middlewares/noop.go
deleted file mode 100644
index 0aebcf916..000000000
--- a/app/middlewares/noop.go
+++ /dev/null
@@ -1,12 +0,0 @@
-package middlewares
-
-import "github.com/getfider/fider/app/pkg/web"
-
-// Noop does nothing
-func Noop() web.MiddlewareFunc {
- return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
- return next(c)
- }
- }
-}
diff --git a/app/middlewares/setup.go b/app/middlewares/setup.go
index 4a5d9da16..56231221f 100644
--- a/app/middlewares/setup.go
+++ b/app/middlewares/setup.go
@@ -14,6 +14,15 @@ import (
"github.com/labstack/gommon/log"
)
+// Noop does nothing
+func Noop() web.MiddlewareFunc {
+ return func(next web.HandlerFunc) web.HandlerFunc {
+ return func(c web.Context) error {
+ return next(c)
+ }
+ }
+}
+
//Setup current context with some services
func Setup(db *dbx.Database, emailer email.Sender) web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
@@ -65,7 +74,6 @@ func AddServices() web.MiddlewareFunc {
services.Tenants.SetCurrentTenant(tenant)
services.OAuth = &oauth.HTTPService{}
services.Ideas = postgres.NewIdeaStorage(tenant, trx)
- services.Ideas = postgres.NewIdeaStorage(tenant, trx)
services.Users = postgres.NewUserStorage(trx)
return next(c)
}
diff --git a/app/models/identity.go b/app/models/identity.go
index 1ba7d359d..dc3c26c87 100644
--- a/app/models/identity.go
+++ b/app/models/identity.go
@@ -14,8 +14,16 @@ type Tenant struct {
Invitation string `json:"invitation"`
WelcomeMessage string `json:"welcomeMessage"`
CNAME string `json:"cname"`
+ Status int `json:"-"`
}
+var (
+ //TenantActive is the default status for most tenants
+ TenantActive = 1
+ //TenantInactive is used for signup via e-mail that requires user confirmation
+ TenantInactive = 2
+)
+
//User represents an user inside our application
type User struct {
ID int `json:"id"`
@@ -76,10 +84,13 @@ type OAuthClaims struct {
//CreateTenant is the input model used to create a tenant
type CreateTenant struct {
- Token string `json:"token"`
- Name string `json:"name"`
- Subdomain string `json:"subdomain"`
- UserClaims *OAuthClaims
+ Token string `json:"token"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ VerificationKey string
+ TenantName string `json:"tenantName"`
+ Subdomain string `json:"subdomain"`
+ UserClaims *OAuthClaims
}
//UpdateTenantSettings is the input model used to update tenant settings
@@ -99,8 +110,10 @@ type SignInByEmail struct {
//SignInRequest is the model used by e-mail verification process
type SignInRequest struct {
Email string
+ Name string
Key string
CreatedOn time.Time
+ ExpiresOn time.Time
VerifiedOn *time.Time
}
diff --git a/app/pkg/dbx/setup.sql b/app/pkg/dbx/setup.sql
index 07d9d9ba3..2808dfc8f 100644
--- a/app/pkg/dbx/setup.sql
+++ b/app/pkg/dbx/setup.sql
@@ -1,6 +1,6 @@
TRUNCATE TABLE tenants RESTART IDENTITY CASCADE;
-INSERT INTO tenants (name, subdomain, created_on, cname, invitation, welcome_message) VALUES ('Demonstration', 'demo', now(), '', '', '');
+INSERT INTO tenants (name, subdomain, created_on, cname, invitation, welcome_message, status) VALUES ('Demonstration', 'demo', now(), '', '', '', 1);
INSERT INTO users (name, email, tenant_id, created_on, role) VALUES ('Jon Snow', '[email protected]', 1, now(), 3);
INSERT INTO user_providers (user_id, provider, provider_uid, created_on) VALUES (1, 'facebook', 'FB1234', now());
@@ -8,7 +8,7 @@ INSERT INTO user_providers (user_id, provider, provider_uid, created_on) VALUES
INSERT INTO users (name, email, tenant_id, created_on, role) VALUES ('Arya Stark', '[email protected]', 1, now(), 1);
INSERT INTO user_providers (user_id, provider, provider_uid, created_on) VALUES (2, 'google', 'GO5678', now());
-INSERT INTO tenants (name, subdomain, created_on, cname, invitation, welcome_message) VALUES ('Orange Inc.', 'orange', now(), 'feedback.orangeinc.com', '', '');
+INSERT INTO tenants (name, subdomain, created_on, cname, invitation, welcome_message, status) VALUES ('Orange Inc.', 'orange', now(), 'feedback.orangeinc.com', '', '', 1);
INSERT INTO users (name, email, tenant_id, created_on, role) VALUES ('Tony Stark', '[email protected]', 2, now(), 3);
INSERT INTO user_providers (user_id, provider, provider_uid, created_on) VALUES (3, 'facebook', 'FB2222', now());
diff --git a/app/pkg/mock/server.go b/app/pkg/mock/server.go
index 7289b0450..6635a6bc3 100644
--- a/app/pkg/mock/server.go
+++ b/app/pkg/mock/server.go
@@ -99,17 +99,12 @@ func (s *Server) Execute(handler web.HandlerFunc) (int, *httptest.ResponseRecord
// ExecuteAsJSON given handler and return json response
func (s *Server) ExecuteAsJSON(handler web.HandlerFunc) (int, *jsonq.JsonQuery) {
-
- if err := s.middleware(handler)(s.context); err != nil {
- s.engine.HandleError(err, s.context)
- }
-
- return parseJSONBody(s)
+ code, response := s.Execute(handler)
+ return code, parseJSONBody(code, response)
}
// ExecutePost executes given handler as POST and return response
func (s *Server) ExecutePost(handler web.HandlerFunc, body string) (int, *httptest.ResponseRecorder) {
-
req, _ := http.NewRequest("POST", "/", strings.NewReader(body))
req.Header.Add("Content-Type", "application/json; charset=UTF-8")
s.context.SetRequest(req)
@@ -119,20 +114,25 @@ func (s *Server) ExecutePost(handler web.HandlerFunc, body string) (int, *httpte
}
return s.recorder.Code, s.recorder
+}
+// ExecutePostAsJSON executes given handler as POST and return json response
+func (s *Server) ExecutePostAsJSON(handler web.HandlerFunc, body string) (int, *jsonq.JsonQuery) {
+ code, response := s.ExecutePost(handler, body)
+ return code, parseJSONBody(code, response)
}
-func parseJSONBody(s *Server) (int, *jsonq.JsonQuery) {
+func parseJSONBody(code int, response *httptest.ResponseRecorder) *jsonq.JsonQuery {
- if s.recorder.Code == 200 && hasJSON(s.recorder) {
+ if code == 200 && hasJSON(response) {
var data interface{}
- decoder := json.NewDecoder(s.recorder.Body)
+ decoder := json.NewDecoder(response.Body)
decoder.Decode(&data)
query := jsonq.NewQuery(data)
- return s.recorder.Code, query
+ return query
}
- return s.recorder.Code, nil
+ return nil
}
func hasJSON(r *httptest.ResponseRecorder) bool {
diff --git a/app/pkg/mock/setup.go b/app/pkg/mock/setup.go
index 33195690b..7cde8e3c2 100644
--- a/app/pkg/mock/setup.go
+++ b/app/pkg/mock/setup.go
@@ -48,8 +48,8 @@ func createServices(seed bool) *app.Services {
}
if seed {
- DemoTenant, _ = services.Tenants.Add("Demonstration", "demo")
- OrangeTenant, _ = services.Tenants.Add("The Orange Inc.", "orange")
+ DemoTenant, _ = services.Tenants.Add("Demonstration", "demo", models.TenantActive)
+ OrangeTenant, _ = services.Tenants.Add("The Orange Inc.", "orange", models.TenantActive)
JonSnow = &models.User{
Name: "Jon Snow",
diff --git a/app/pkg/validate/domain_test.go b/app/pkg/validate/domain_test.go
index ea741322f..96b41404b 100644
--- a/app/pkg/validate/domain_test.go
+++ b/app/pkg/validate/domain_test.go
@@ -3,6 +3,7 @@ package validate_test
import (
"testing"
+ "github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/validate"
"github.com/getfider/fider/app/storage/inmemory"
. "github.com/onsi/gomega"
@@ -33,9 +34,9 @@ func TestValidSubdomains_Availability(t *testing.T) {
RegisterTestingT(t)
tenants := &inmemory.TenantStorage{}
- tenants.Add("Footbook", "footbook")
- tenants.Add("Your Company", "yourcompany")
- tenants.Add("New York", "newyork")
+ tenants.Add("Footbook", "footbook", models.TenantActive)
+ tenants.Add("Your Company", "yourcompany", models.TenantActive)
+ tenants.Add("New York", "newyork", models.TenantActive)
for _, subdomain := range []string{
"footbook",
diff --git a/app/pkg/web/context.go b/app/pkg/web/context.go
index b5149d129..e0079784b 100644
--- a/app/pkg/web/context.go
+++ b/app/pkg/web/context.go
@@ -227,6 +227,19 @@ func (ctx *Context) BaseURL() string {
return protocol + "://" + ctx.Request().Host
}
+//TenantBaseURL returns base URL for a given tenant
+func (ctx *Context) TenantBaseURL(tenant *models.Tenant) string {
+ if env.IsSingleHostMode() {
+ return ctx.BaseURL()
+ }
+
+ protocol := "http"
+ if ctx.Request().TLS != nil {
+ protocol = "https"
+ }
+ return protocol + "://" + tenant.Subdomain + env.MultiTenantDomain()
+}
+
//AuthEndpoint auth endpoint
func (ctx *Context) AuthEndpoint() string {
endpoint, ok := ctx.Get(authEndpointContextKey).(string)
diff --git a/app/storage/inmemory/tenant.go b/app/storage/inmemory/tenant.go
index fb08b6037..d54778a02 100644
--- a/app/storage/inmemory/tenant.go
+++ b/app/storage/inmemory/tenant.go
@@ -22,9 +22,9 @@ func (s *TenantStorage) SetCurrentTenant(tenant *models.Tenant) {
}
// Add given tenant to tenant list
-func (s *TenantStorage) Add(name string, subdomain string) (*models.Tenant, error) {
+func (s *TenantStorage) Add(name string, subdomain string, status int) (*models.Tenant, error) {
s.lastID = s.lastID + 1
- tenant := &models.Tenant{ID: s.lastID, Name: name, Subdomain: subdomain}
+ tenant := &models.Tenant{ID: s.lastID, Name: name, Subdomain: subdomain, Status: status}
s.tenants = append(s.tenants, tenant)
return tenant, nil
}
@@ -72,12 +72,25 @@ func (s *TenantStorage) UpdateSettings(settings *models.UpdateTenantSettings) er
return nil
}
+// Activate given tenant
+func (s *TenantStorage) Activate(id int) error {
+ for _, tenant := range s.tenants {
+ if tenant.ID == id {
+ tenant.Status = models.TenantActive
+ return nil
+ }
+ }
+ return app.ErrNotFound
+}
+
// SaveVerificationKey used by e-mail verification
-func (s *TenantStorage) SaveVerificationKey(email, key string) error {
+func (s *TenantStorage) SaveVerificationKey(key string, duration time.Duration, email, name string) error {
s.requests = append(s.requests, &models.SignInRequest{
Email: email,
+ Name: name,
Key: key,
CreatedOn: time.Now(),
+ ExpiresOn: time.Now().Add(duration),
VerifiedOn: nil,
})
return nil
diff --git a/app/storage/postgres/tenant.go b/app/storage/postgres/tenant.go
index c44e38e79..c33673162 100644
--- a/app/storage/postgres/tenant.go
+++ b/app/storage/postgres/tenant.go
@@ -29,6 +29,7 @@ type dbTenant struct {
CNAME string `db:"cname"`
Invitation string `db:"invitation"`
WelcomeMessage string `db:"welcome_message"`
+ Status int `db:"status"`
}
func (t *dbTenant) toModel() *models.Tenant {
@@ -39,22 +40,27 @@ func (t *dbTenant) toModel() *models.Tenant {
CNAME: t.CNAME,
Invitation: t.Invitation,
WelcomeMessage: t.WelcomeMessage,
+ Status: t.Status,
}
}
type dbSignInRequest struct {
ID int `db:"id"`
+ Name string `db:"name"`
Email string `db:"email"`
Key string `db:"key"`
CreatedOn time.Time `db:"created_on"`
+ ExpiresOn time.Time `db:"expires_on"`
VerifiedOn dbx.NullTime `db:"verified_on"`
}
func (t *dbSignInRequest) toModel() *models.SignInRequest {
model := &models.SignInRequest{
+ Name: t.Name,
Email: t.Email,
Key: t.Key,
CreatedOn: t.CreatedOn,
+ ExpiresOn: t.ExpiresOn,
VerifiedOn: nil,
}
@@ -71,11 +77,11 @@ func (s *TenantStorage) SetCurrentTenant(tenant *models.Tenant) {
}
// Add given tenant to tenant list
-func (s *TenantStorage) Add(name string, subdomain string) (*models.Tenant, error) {
+func (s *TenantStorage) Add(name string, subdomain string, status int) (*models.Tenant, error) {
var id int
- row := s.trx.QueryRow(`INSERT INTO tenants (name, subdomain, created_on, cname, invitation, welcome_message)
- VALUES ($1, $2, $3, '', '', '')
- RETURNING id`, name, subdomain, time.Now())
+ row := s.trx.QueryRow(`INSERT INTO tenants (name, subdomain, created_on, cname, invitation, welcome_message, status)
+ VALUES ($1, $2, $3, '', '', '', $4)
+ RETURNING id`, name, subdomain, time.Now(), status)
if err := row.Scan(&id); err != nil {
return nil, err
}
@@ -87,7 +93,7 @@ func (s *TenantStorage) Add(name string, subdomain string) (*models.Tenant, erro
func (s *TenantStorage) First() (*models.Tenant, error) {
tenant := dbTenant{}
- err := s.trx.Get(&tenant, "SELECT id, name, subdomain, cname, invitation, welcome_message FROM tenants LIMIT 1")
+ err := s.trx.Get(&tenant, "SELECT id, name, subdomain, cname, invitation, welcome_message, status FROM tenants ORDER BY id LIMIT 1")
if err == sql.ErrNoRows {
return nil, app.ErrNotFound
} else if err != nil {
@@ -101,7 +107,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 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 FROM tenants WHERE subdomain = $1 OR cname = $2 ORDER BY cname DESC", extractSubdomain(domain), domain)
if err == sql.ErrNoRows {
return nil, app.ErrNotFound
} else if err != nil {
@@ -123,17 +129,23 @@ func (s *TenantStorage) IsSubdomainAvailable(subdomain string) (bool, error) {
return !exists, err
}
+// Activate given tenant
+func (s *TenantStorage) Activate(id int) error {
+ query := "UPDATE tenants SET status = $1 WHERE id = $2"
+ return s.trx.Execute(query, models.TenantActive, id)
+}
+
// SaveVerificationKey used by e-mail verification process
-func (s *TenantStorage) SaveVerificationKey(email, key string) error {
- query := "INSERT INTO signin_requests (tenant_id, email, created_on, key) VALUES ($1, $2, $3, $4)"
- return s.trx.Execute(query, s.current.ID, email, time.Now(), key)
+func (s *TenantStorage) SaveVerificationKey(key string, duration time.Duration, email, name string) error {
+ query := "INSERT INTO signin_requests (tenant_id, email, created_on, expires_on, key, name) VALUES ($1, $2, $3, $4, $5, $6)"
+ return s.trx.Execute(query, s.current.ID, email, time.Now(), time.Now().Add(duration), key, name)
}
// FindVerificationByKey based on current tenant
func (s *TenantStorage) FindVerificationByKey(key string) (*models.SignInRequest, error) {
request := dbSignInRequest{}
- err := s.trx.Get(&request, "SELECT id, email, key, created_on, verified_on FROM signin_requests WHERE key = $1 LIMIT 1", key)
+ err := s.trx.Get(&request, "SELECT id, email, name, key, created_on, verified_on, expires_on FROM signin_requests WHERE key = $1 LIMIT 1", key)
if err == sql.ErrNoRows {
return nil, app.ErrNotFound
} else if err != nil {
diff --git a/app/storage/postgres/tenant_test.go b/app/storage/postgres/tenant_test.go
index a1a03d09b..1d91b237f 100644
--- a/app/storage/postgres/tenant_test.go
+++ b/app/storage/postgres/tenant_test.go
@@ -12,6 +12,37 @@ import (
. "github.com/onsi/gomega"
)
+func TestTenantStorage_Add_Activate(t *testing.T) {
+ RegisterTestingT(t)
+ db, _ := dbx.New()
+ db.Seed()
+ defer db.Close()
+
+ trx, _ := db.Begin()
+ defer trx.Rollback()
+
+ tenants := postgres.NewTenantStorage(trx)
+ tenant, err := tenants.Add("My Domain Inc.", "mydomain", models.TenantInactive)
+
+ Expect(err).To(BeNil())
+ Expect(tenant).NotTo(BeNil())
+
+ tenant, err = tenants.GetByDomain("mydomain")
+ Expect(err).To(BeNil())
+ Expect(tenant.Name).To(Equal("My Domain Inc."))
+ Expect(tenant.Subdomain).To(Equal("mydomain"))
+ Expect(tenant.Status).To(Equal(models.TenantInactive))
+
+ err = tenants.Activate(tenant.ID)
+ Expect(err).To(BeNil())
+
+ tenant, err = tenants.GetByDomain("mydomain")
+ Expect(err).To(BeNil())
+ Expect(tenant.Name).To(Equal("My Domain Inc."))
+ Expect(tenant.Subdomain).To(Equal("mydomain"))
+ Expect(tenant.Status).To(Equal(models.TenantActive))
+}
+
func TestTenantStorage_First(t *testing.T) {
RegisterTestingT(t)
db, _ := dbx.New()
@@ -72,7 +103,7 @@ func TestTenantStorage_GetByDomain_Subdomain(t *testing.T) {
defer trx.Rollback()
tenants := postgres.NewTenantStorage(trx)
- tenant, err := tenants.Add("My Domain Inc.", "mydomain")
+ tenant, err := tenants.Add("My Domain Inc.", "mydomain", models.TenantActive)
Expect(err).To(BeNil())
tenant, err = tenants.GetByDomain("mydomain")
@@ -82,6 +113,7 @@ func TestTenantStorage_GetByDomain_Subdomain(t *testing.T) {
Expect(tenant.Name).To(Equal("My Domain Inc."))
Expect(tenant.Subdomain).To(Equal("mydomain"))
Expect(tenant.CNAME).To(Equal(""))
+ Expect(tenant.Status).To(Equal(models.TenantActive))
}
func TestTenantStorage_IsSubdomainAvailable_ExistingDomain(t *testing.T) {
@@ -159,16 +191,18 @@ func TestTenantStorage_SaveFindSet_VerificationKey(t *testing.T) {
tenants.SetCurrentTenant(tenant)
//Save new Key
- err := tenants.SaveVerificationKey("[email protected]", "s3cr3tk3y")
+ err := tenants.SaveVerificationKey("s3cr3tk3y", 15*time.Minute, "[email protected]", "Jon Snow")
Expect(err).To(BeNil())
//Find and check values
result, err := tenants.FindVerificationByKey("s3cr3tk3y")
Expect(err).To(BeNil())
- Expect(time.Now().After(result.CreatedOn)).To(BeTrue())
+ Expect(result.CreatedOn).NotTo(Equal(time.Time{}))
Expect(result.VerifiedOn).To(BeNil())
Expect(result.Email).To(Equal("[email protected]"))
+ Expect(result.Name).To(Equal("Jon Snow"))
Expect(result.Key).To(Equal("s3cr3tk3y"))
+ Expect(result.ExpiresOn).To(BeTemporally("~", result.CreatedOn.Add(15*time.Minute), 1*time.Second))
//Set as verified check values
err = tenants.SetKeyAsVerified("s3cr3tk3y")
@@ -180,7 +214,9 @@ func TestTenantStorage_SaveFindSet_VerificationKey(t *testing.T) {
Expect(time.Now().After(result.CreatedOn)).To(BeTrue())
Expect(result.VerifiedOn.After(result.CreatedOn)).To(BeTrue())
Expect(result.Email).To(Equal("[email protected]"))
+ Expect(result.Name).To(Equal("Jon Snow"))
Expect(result.Key).To(Equal("s3cr3tk3y"))
+ Expect(result.ExpiresOn).To(BeTemporally("~", result.CreatedOn.Add(15*time.Minute), 1*time.Second))
}
func TestTenantStorage_FindUnknownVerificationKey(t *testing.T) {
diff --git a/app/storage/postgres/user_test.go b/app/storage/postgres/user_test.go
index 6fb0a5bfc..7b6405d99 100644
--- a/app/storage/postgres/user_test.go
+++ b/app/storage/postgres/user_test.go
@@ -169,7 +169,7 @@ func TestUserStorage_Register_MultipleProviders(t *testing.T) {
trx, _ := db.Begin()
defer trx.Rollback()
- trx.Execute("INSERT INTO tenants (name, subdomain, created_on) VALUES ('My Domain Inc.','mydomain', now())")
+ trx.Execute("INSERT INTO tenants (name, subdomain, created_on, status) VALUES ('My Domain Inc.','mydomain', now(), 1)")
users := postgres.NewUserStorage(trx)
user := &models.User{
diff --git a/app/storage/storage.go b/app/storage/storage.go
index 7d05f8eba..db33365a9 100644
--- a/app/storage/storage.go
+++ b/app/storage/storage.go
@@ -1,6 +1,10 @@
package storage
-import "github.com/getfider/fider/app/models"
+import (
+ "time"
+
+ "github.com/getfider/fider/app/models"
+)
// Idea contains read and write operations for ideas
type Idea interface {
@@ -29,12 +33,13 @@ type User interface {
// Tenant contains read and write operations for tenants
type Tenant interface {
- Add(name string, subdomain string) (*models.Tenant, error)
+ Add(name string, subdomain string, status int) (*models.Tenant, error)
First() (*models.Tenant, error)
+ Activate(id int) error
GetByDomain(domain string) (*models.Tenant, error)
UpdateSettings(settings *models.UpdateTenantSettings) error
IsSubdomainAvailable(subdomain string) (bool, error)
- SaveVerificationKey(email, key string) error
+ SaveVerificationKey(key string, duration time.Duration, email, name string) error
FindVerificationByKey(key string) (*models.SignInRequest, error)
SetKeyAsVerified(key string) error
SetCurrentTenant(*models.Tenant)
diff --git a/migrations/201709241236_add_tenant_status.up.sql b/migrations/201709241236_add_tenant_status.up.sql
new file mode 100644
index 000000000..4a2921aac
--- /dev/null
+++ b/migrations/201709241236_add_tenant_status.up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE tenants ADD status INT NOT NULL DEFAULT 1;
+ALTER TABLE tenants ALTER COLUMN status DROP DEFAULT;
\ No newline at end of file
diff --git a/migrations/201709241254_add_signin_request_name_expires_on.up.sql b/migrations/201709241254_add_signin_request_name_expires_on.up.sql
new file mode 100644
index 000000000..30aa75ee8
--- /dev/null
+++ b/migrations/201709241254_add_signin_request_name_expires_on.up.sql
@@ -0,0 +1,6 @@
+ALTER TABLE signin_requests ADD name VARCHAR(200) NULL;
+ALTER TABLE signin_requests ADD expires_on TIMESTAMPTZ NOT NULL DEFAULT now();
+
+UPDATE signin_requests SET expires_on = created_on + interval '15 minute';
+
+ALTER TABLE signin_requests ALTER COLUMN expires_on DROP DEFAULT;
\ No newline at end of file
diff --git a/public/components/common/DisplayError.tsx b/public/components/common/DisplayError.tsx
index de6ad4e6e..9e8ec9e6c 100644
--- a/public/components/common/DisplayError.tsx
+++ b/public/components/common/DisplayError.tsx
@@ -2,7 +2,7 @@ import * as React from 'react';
import { Session, Failure } from '@fider/services';
const arrayToTag = (items: string[]) => {
- return items.map((m) => <li>{m}</li>);
+ return items.map((m) => <li key={m}>{m}</li>);
};
interface DisplayErrorProps {
diff --git a/public/components/common/Form.tsx b/public/components/common/Form.tsx
index da26d5e84..26527b1df 100644
--- a/public/components/common/Form.tsx
+++ b/public/components/common/Form.tsx
@@ -33,7 +33,7 @@ export class Form extends React.Component<FormProps, FormState> {
}
public render() {
- return <form className="ui form" onSubmit={(e) => this.submit(e)}>
+ return <form autoComplete="off" className="ui form" onSubmit={(e) => this.submit(e)}>
<DisplayError error={this.state && this.state.failure} />
{ this.props.children }
</form>;
diff --git a/public/components/common/SignInControl.tsx b/public/components/common/SignInControl.tsx
index f3567ea83..d2294b2e6 100644
--- a/public/components/common/SignInControl.tsx
+++ b/public/components/common/SignInControl.tsx
@@ -68,17 +68,22 @@ export class SignInControl extends React.Component<SignInControlProps, SignInCon
<div className="column">
<SocialSignInButton provider="github" />
</div>;
+ const hasOAuth = !!(google || facebook || github);
return <div className="signin-options">
- <div className="ui stackable three column centered grid">
- { facebook }
- { google }
- { github }
- </div>
- <p className="info">We'll never post to any of your accounts</p>
+ {
+ hasOAuth && <div>
+ <div className="ui stackable three column centered grid">
+ { facebook }
+ { google }
+ { github }
+ </div>
+ <p className="info">We'll never post to any of your accounts</p>
+ <div className="ui horizontal divider">OR</div>
+ </div>
+ }
{ this.props.signInByEmail && <div>
- <div className="ui horizontal divider">OR</div>
<p>Enter your e-mail address to sign in</p>
<Form ref={(f) => { this.form = f!; } } onSubmit={() => this.signIn() }>
<div className="ui small action fluid input">
diff --git a/public/index.tsx b/public/index.tsx
index cc2f323ac..40c56eefb 100644
--- a/public/index.tsx
+++ b/public/index.tsx
@@ -51,13 +51,16 @@ const resolveRootComponent = (path: string): PageConfiguration | undefined => {
};
document.addEventListener('DOMContentLoaded', () => {
- const config = resolveRootComponent(location.pathname)!;
- ReactDOM.render(
- <div>
- <SignInModal />
- <div id={ config.id }>
- { config.component }
- </div>
- </div>, document.getElementById('root')
- );
+ const root = document.getElementById('root');
+ if (root) {
+ const config = resolveRootComponent(location.pathname)!;
+ ReactDOM.render(
+ <div>
+ <SignInModal />
+ <div id={ config.id }>
+ { config.component }
+ </div>
+ </div>, root
+ );
+ }
});
diff --git a/public/pages/admin/AdminHomePage.tsx b/public/pages/admin/AdminHomePage.tsx
index 74d94f2f0..85b1b0e71 100644
--- a/public/pages/admin/AdminHomePage.tsx
+++ b/public/pages/admin/AdminHomePage.tsx
@@ -81,8 +81,8 @@ export class AdminHomePage extends React.Component<{}, AdminHomePageState> {
value={ this.state.welcomeMessage } />
<p className="info">
<p>Use this space to change message of your initial page.</p>
- <p>Common use cases for this are to briefly explain what is your Company/Product, why you created this space and how the visitors can collaborate.</p>
- <p>This field is powered by Commonmark, which means you can style and add links to your message. Learn more at <a target="_blank" href="http://commonmark.org/help/">http://commonmark.org/help/</a>.</p>
+ <p>Common use case for this area is a brief description of what is your company/product, why you created this space and how the visitors can collaborate.</p>
+ <p>This field is powered by Commonmark. You can style and add links to your message. Learn more at <a target="_blank" href="http://commonmark.org/help/">http://commonmark.org/help/</a>.</p>
</p>
</div>
<DisplayError fields={['invitation']} error={this.state.error} />
diff --git a/public/pages/signup/SignUpPage.scss b/public/pages/signup/SignUpPage.scss
index 5d77d6a6f..2dd0737bd 100644
--- a/public/pages/signup/SignUpPage.scss
+++ b/public/pages/signup/SignUpPage.scss
@@ -12,7 +12,7 @@
height: 100px;
}
- input#name {
- width: 310px;
+ .ui.basic.red.label {
+ width: auto;
}
}
\ No newline at end of file
diff --git a/public/pages/signup/SignUpPage.tsx b/public/pages/signup/SignUpPage.tsx
index 975861094..ec9ecf98a 100644
--- a/public/pages/signup/SignUpPage.tsx
+++ b/public/pages/signup/SignUpPage.tsx
@@ -9,6 +9,7 @@ const logo = require('@fider/assets/images/logo-small.png');
import { inject, injectables } from '@fider/di';
import { Session, TenantService, Failure } from '@fider/services';
+import { showModal } from '@fider/utils/page';
import './SignUpPage.scss';
@@ -19,8 +20,11 @@ interface OAuthUser {
}
interface SignUpPageState {
- name?: string;
+ submitted: boolean;
+ tenantName: string;
error?: Failure;
+ name?: string;
+ email?: string;
subdomain: {
available: boolean,
message?: string,
@@ -39,123 +43,158 @@ export class SignUpPage extends React.Component<{}, SignUpPageState> {
public service: TenantService;
constructor(props: {}) {
- super(props);
- this.state = {
- subdomain: { available: false }
- };
-
- this.settings = this.session.getAppSettings();
- this.checkAvailability = td.debounce(300, this.checkAvailability);
-
- setTitle(this.session.isSingleHostMode() ? 'Installation · Fider' : 'Sign up · Fider');
-
- const token = getQueryString('token');
- if (token) {
- const data = decode(token);
- this.user = {
- token,
- name: data['oauth/name'],
- email: data['oauth/email']
- };
+ super(props);
+ this.state = {
+ submitted: false,
+ tenantName: '',
+ subdomain: { available: false }
+ };
+
+ this.settings = this.session.getAppSettings();
+ this.checkAvailability = td.debounce(300, this.checkAvailability);
+
+ setTitle(this.session.isSingleHostMode() ? 'Installation · Fider' : 'Sign up · Fider');
+
+ const token = getQueryString('token');
+ if (token) {
+ const data = decode(token);
+ if (data) {
+ this.user = {
+ token,
+ name: data['oauth/name'],
+ email: data['oauth/email']
+ };
}
+ }
+ }
+
+ public componentDidUpdate() {
+ if (this.state.submitted) {
+ showModal('#submitted-modal', { closable: false });
+ }
}
private async confirm() {
- const result = await this.service.create(
- this.user && this.user.token,
- this.state.name,
- this.state.subdomain.value
- );
- if (result.ok) {
- if (this.session.isSingleHostMode()) {
- location.reload();
- } else {
- location.href = `${location.protocol}//${this.state.subdomain.value}${this.settings.domain}?token=${result.data.token}`;
- }
- } else if (result.error) {
- this.setState({ error: result.error });
+ const result = await this.service.create({
+ token: this.user && this.user.token,
+ tenantName: this.state.tenantName,
+ subdomain: this.state.subdomain.value,
+ name: this.state.name,
+ email: this.state.email,
+ });
+
+ if (result.ok) {
+ if (result.data.token) {
+ if (this.session.isSingleHostMode()) {
+ location.reload();
+ } else {
+ location.href = `${location.protocol}//${this.state.subdomain.value}${this.settings.domain}?token=${result.data.token}`;
+ }
+ } else {
+ this.setState({ submitted: true });
}
+ } else if (result.error) {
+ this.setState({ error: result.error, submitted: false });
+ }
}
private async checkAvailability(subdomain: string) {
- const result = await this.service.checkAvailability(subdomain);
-
- this.setState({
- subdomain: {
- value: subdomain,
- available: !result.data.message,
- message: result.data.message,
- }
- });
+ const result = await this.service.checkAvailability(subdomain);
+
+ this.setState({
+ subdomain: {
+ value: subdomain,
+ available: !result.data.message,
+ message: result.data.message,
+ }
+ });
}
public render() {
- return <div>
- <EnvironmentInfo />
- <div className="page ui container">
- <img className="logo" src={logo} />
-
- <h3 className="ui header">1. Who are you?</h3>
- <DisplayError fields={['token']} error={this.state.error} />
-
- {
- this.user ?
- <div>
- <p>
- Hello, &nbsp;
- <Gravatar name={this.user.name} email={this.user.email} />
- <b>{this.user.name}</b> ({this.user.email})
- </p>
- </div> :
- <div>
- <p>We need to identify you in order to setup your new Fider instance.</p>
- <SignInControl signInByEmail={ false } />
+ const modal = this.state.submitted &&
+ <div id="submitted-modal" className="ui modal small">
+ <div className="header">Thank you for registering!</div>
+ <div className="content">
+ <p>Please check your inbox for a confirmation link to finish your registration.</p>
+ </div>
+ </div>;
+
+ return <div>
+ <EnvironmentInfo />
+ <div className="page ui container">
+ { modal }
+ <img className="logo" src={logo} />
+
+ <h3 className="ui header">1. Who are you?</h3>
+ <DisplayError fields={['token']} error={this.state.error} />
+
+ {
+ this.user ?
+ <div>
+ <p>
+ Hello, &nbsp;
+ <Gravatar name={this.user.name} email={this.user.email} />
+ <b>{this.user.name}</b> ({this.user.email})
+ </p>
+ </div> :
+ <div>
+ <p>We need to identify you to setup your new Fider account.</p>
+ <SignInControl signInByEmail={ false } />
+ <div className="ui form">
+ <DisplayError fields={['name', 'email']} error={this.state.error} />
+ <div className="fluid field">
+ <input id="name" onChange={(e) => this.setState({ name: e.currentTarget.value }) } type="text" placeholder="your name" className="small" />
+ </div>
+ <div className="fluid field">
+ <input id="email" onChange={(e) => this.setState({ email: e.currentTarget.value }) } type="text" placeholder="[email protected]" className="small" />
+ </div>
</div>
- }
+ </div>
+ }
- <div className="ui section divider"></div>
+ <div className="ui section divider"></div>
- <h3 className="ui header">2. What is this Feedback Forum for?</h3>
+ <h3 className="ui header">2. What is this Feedback Forum for?</h3>
- <DisplayError fields={['name', 'subdomain']} error={this.state.error} />
- <div className="ui form">
- <div className="inline field">
- <input id="name" type="text"
- placeholder="Your Company/Product Name"
- maxLength={60}
- onChange={(e) => this.setState({ name: e.currentTarget.value })}/>
- </div>
- { !this.session.isSingleHostMode() && <div className="inline field">
- <div className="ui right labeled input">
- <input id="subdomain" type="text"
- maxLength={40}
- placeholder="subdomain"
- onChange={(e) => this.checkAvailability(e.currentTarget.value)} />
- <div className="ui label">{ this.settings.domain }</div>
- {
- this.state.subdomain.available &&
- <div className="ui left pointing green basic label">
- Great!
- </div>
- }
- {
- this.state.subdomain.message &&
- <div className="ui left pointing red basic label">
- { this.state.subdomain.message }
- </div>
- }
- </div>
- </div> }
+ <DisplayError fields={['tenantName', 'subdomain']} error={this.state.error} />
+ <div className="ui form">
+ <div className="fluid field">
+ <input id="tenantName" type="text"
+ placeholder="your company or product name"
+ maxLength={60}
+ onChange={(e) => this.setState({ tenantName: e.currentTarget.value })}/>
</div>
- <div className="ui section divider"></div>
+ { !this.session.isSingleHostMode() && <div className="fluid field">
+ <div className="ui right labeled input">
+ <input id="subdomain" type="text"
+ maxLength={40}
+ placeholder="subdomain"
+ onChange={(e) => this.checkAvailability(e.currentTarget.value)} />
+ <div className="ui label">{ this.settings.domain }</div>
+ {
+ this.state.subdomain.available &&
+ <div className="ui left pointing green basic label">
+ Great!
+ </div>
+ }
+ {
+ this.state.subdomain.message &&
+ <div className="ui left pointing red basic label">
+ { this.state.subdomain.message }
+ </div>
+ }
+ </div>
+ </div> }
+ </div>
+ <div className="ui section divider"></div>
- <h3 className="ui header">3. Review and continue</h3>
+ <h3 className="ui header">3. Review and continue</h3>
- <p>Make sure information provided above is correct before proceeding.</p>
+ <p>Make sure information provided above is correct before proceeding.</p>
- <Button className="positive" size="large" onClick={() => this.confirm()}>Confirm</Button>
- </div>
- <Footer />
- </div>;
+ <Button className="positive" size="large" onClick={() => this.confirm()}>Confirm</Button>
+ </div>
+ <Footer />
+ </div>;
}
}
diff --git a/public/services/TenantService.ts b/public/services/TenantService.ts
index 74e64fb2c..ded6152f3 100644
--- a/public/services/TenantService.ts
+++ b/public/services/TenantService.ts
@@ -3,7 +3,7 @@ import { injectable } from '@fider/di';
import { Tenant } from '@fider/models';
export interface TenantService {
- create(token?: string, name?: string, subdomain?: string): Promise<Result<CreateTenantResponse>>;
+ create(request: CreateTenantRequest): Promise<Result<CreateTenantResponse>>;
updateSettings(title: string, invitation: string, welcomeMessage: string): Promise<Result>;
checkAvailability(subdomain: string): Promise<Result<CheckAvailabilityResponse>>;
signIn(email: string): Promise<Result>;
@@ -14,17 +14,22 @@ export interface CheckAvailabilityResponse {
message: string;
}
+export interface CreateTenantRequest {
+ tenantName: string;
+ subdomain?: string;
+ name?: string;
+ token?: string;
+ email?: string;
+}
+
export interface CreateTenantResponse {
- id: number;
- token: string;
+ token?: string;
}
@injectable()
export class HttpTenantService implements TenantService {
- public async create(token?: string, name?: string, subdomain?: string): Promise<Result<CreateTenantResponse>> {
- return await post<CreateTenantResponse>('/api/tenants', {
- token, name, subdomain,
- });
+ public async create(request: CreateTenantRequest): Promise<Result<CreateTenantResponse>> {
+ return await post<CreateTenantResponse>('/api/tenants', request);
}
public async updateSettings(title: string, invitation: string, welcomeMessage: string): Promise<Result> {
diff --git a/public/utils/jwt.ts b/public/utils/jwt.ts
index 7777af683..f81dc202a 100644
--- a/public/utils/jwt.ts
+++ b/public/utils/jwt.ts
@@ -1,4 +1,10 @@
export function decode(token: string): any {
+ if (token) {
const segments = token.split('.');
- return JSON.parse(window.atob(segments[1]));
+ try {
+ return JSON.parse(window.atob(segments[1]));
+ } catch {
+ return undefined;
+ }
+ }
}
diff --git a/router.go b/router.go
index 4bef5c4f4..01cd22bb7 100644
--- a/router.go
+++ b/router.go
@@ -54,27 +54,29 @@ func GetMainEngine(settings *models.AppSettings) *web.Engine {
assets.Static("/", "dist")
}
- signup := r.Group("")
+ noTenant := r.Group("")
{
- signup.Use(middlewares.Setup(db, emailer))
- signup.Use(middlewares.AddServices())
-
- signup.Post("/api/tenants", handlers.CreateTenant())
- signup.Get("/api/tenants/:subdomain/availability", handlers.CheckAvailability())
- signup.Get("/signup", handlers.SignUp())
+ noTenant.Use(middlewares.Setup(db, emailer))
+ noTenant.Use(middlewares.AddServices())
+
+ noTenant.Post("/api/tenants", handlers.CreateTenant())
+ noTenant.Get("/api/tenants/:subdomain/availability", handlers.CheckAvailability())
+ noTenant.Get("/signup", handlers.SignUp())
+
+ noTenant.Get("/oauth/facebook", handlers.SignIn(oauth.FacebookProvider))
+ noTenant.Get("/oauth/facebook/callback", handlers.OAuthCallback(oauth.FacebookProvider))
+ noTenant.Get("/oauth/google", handlers.SignIn(oauth.GoogleProvider))
+ noTenant.Get("/oauth/google/callback", handlers.OAuthCallback(oauth.GoogleProvider))
+ noTenant.Get("/oauth/github", handlers.SignIn(oauth.GitHubProvider))
+ noTenant.Get("/oauth/github/callback", handlers.OAuthCallback(oauth.GitHubProvider))
}
- auth := r.Group("/oauth")
+ verify := r.Group("")
{
- auth.Use(middlewares.Setup(db, emailer))
- auth.Use(middlewares.AddServices())
-
- auth.Get("/facebook", handlers.SignIn(oauth.FacebookProvider))
- auth.Get("/facebook/callback", handlers.OAuthCallback(oauth.FacebookProvider))
- auth.Get("/google", handlers.SignIn(oauth.GoogleProvider))
- auth.Get("/google/callback", handlers.OAuthCallback(oauth.GoogleProvider))
- auth.Get("/github", handlers.SignIn(oauth.GitHubProvider))
- auth.Get("/github/callback", handlers.OAuthCallback(oauth.GitHubProvider))
+ verify.Use(middlewares.Setup(db, emailer))
+ verify.Use(middlewares.Tenant())
+ verify.Use(middlewares.AddServices())
+ verify.Get("/signup/verify", handlers.VerifySignUpKey())
}
page := r.Group("")
@@ -84,6 +86,7 @@ func GetMainEngine(settings *models.AppSettings) *web.Engine {
page.Use(middlewares.AddServices())
page.Use(middlewares.JwtGetter())
page.Use(middlewares.JwtSetter())
+ page.Use(middlewares.OnlyActiveTenants())
public := page.Group("")
{
diff --git a/views/base.html b/views/base.html
index c83758af1..b2e66a615 100644
--- a/views/base.html
+++ b/views/base.html
@@ -28,7 +28,7 @@
</script>
{{ end }}
{{ end }}
- <div id="root"></div>{{template "content" .}}
+ {{template "content" .}}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.js" integrity="sha256-1uk/AXiYWDJQQgWL10P3Vz5qhIsyBxnwo4dwmw4cYHc=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js" integrity="sha256-UEqn5+tyzezD6A5HBMNTlc5mXkmt+ohTfCBPtXMaGb0=" crossorigin="anonymous"></script>
diff --git a/views/index.html b/views/index.html
index 6f8e228ac..edf5934be 100644
--- a/views/index.html
+++ b/views/index.html
@@ -5,4 +5,4 @@
{{define "javascript"}} {{ range $key, $value := . }}{{ $first := index $key 1 }}{{ if ne $first 95 }}set({{ $key }}, {{ $value }});{{ end }}{{ end }} {{end}}
-{{define "content"}}{{end}}
\ No newline at end of file
+{{define "content"}}<div id="root"></div>{{end}}
\ No newline at end of file