Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

feature: Private Forum (#346)

Guilherme Oenning54ecbf454cae
diff --git a/app/actions/invite.go b/app/actions/invite.go
new file mode 100644
index 000000000..fe67540e5
--- /dev/null
+++ b/app/actions/invite.go
@@ -0,0 +1,88 @@
+package actions
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/validate"
+)
+
+// InviteUsers is used to invite new users into Fider
+type InviteUsers struct {
+ IsSampleInvite bool
+ Model *models.InviteUsers
+ Invitations []*models.UserInvitation
+}
+
+// Initialize the model
+func (input *InviteUsers) Initialize() interface{} {
+ input.Model = new(models.InviteUsers)
+ return input.Model
+}
+
+// IsAuthorized returns true if current user is authorized to perform this action
+func (input *InviteUsers) IsAuthorized(user *models.User, services *app.Services) bool {
+ return user != nil && user.IsCollaborator()
+}
+
+// Validate is current model is valid
+func (input *InviteUsers) Validate(user *models.User, services *app.Services) *validate.Result {
+ result := validate.Success()
+
+ if input.Model.Subject == "" {
+ result.AddFieldFailure("subject", "Subject is required.")
+ } else if len(input.Model.Subject) > 70 {
+ result.AddFieldFailure("subject", "Subject must be less than 70 characters.")
+ }
+
+ if input.Model.Message == "" {
+ result.AddFieldFailure("message", "Message is required.")
+ } else if !strings.Contains(input.Model.Message, app.InvitePlaceholder) {
+ msg := fmt.Sprintf("Your message is missing the invitation link placeholder. Please add '%s' to your message.", app.InvitePlaceholder)
+ result.AddFieldFailure("message", msg)
+ }
+
+ //When it's a sample invite, we skip recipients validation
+ if !input.IsSampleInvite {
+
+ if len(input.Model.Recipients) == 0 {
+ result.AddFieldFailure("recipients", "At least one recipient is required.")
+ } else if len(input.Model.Recipients) > 30 {
+ result.AddFieldFailure("recipients", "Too many recipients. We limit at 30 recipients per invite.")
+ }
+
+ for _, email := range input.Model.Recipients {
+ if email != "" {
+ emailResult := validate.Email(email)
+ if !emailResult.Ok {
+ result.AddFieldFailure("recipients", emailResult.Messages...)
+ }
+ }
+ }
+
+ if result.Ok {
+ input.Invitations = make([]*models.UserInvitation, 0)
+ for _, email := range input.Model.Recipients {
+ if email != "" {
+ _, err := services.Users.GetByEmail(email)
+ if errors.Cause(err) == app.ErrNotFound {
+ input.Invitations = append(input.Invitations, &models.UserInvitation{
+ Email: email,
+ VerificationKey: models.GenerateVerificationKey(),
+ })
+ }
+ }
+ }
+
+ if len(input.Invitations) == 0 {
+ result.AddFieldFailure("recipients", "All these addresses have already been registered on this site.")
+ }
+ }
+
+ }
+
+ return result
+}
diff --git a/app/actions/invite_test.go b/app/actions/invite_test.go
new file mode 100644
index 000000000..ea24bdedb
--- /dev/null
+++ b/app/actions/invite_test.go
@@ -0,0 +1,170 @@
+package actions_test
+
+import (
+ "fmt"
+ "testing"
+
+ "github.com/getfider/fider/app/actions"
+ "github.com/getfider/fider/app/models"
+
+ . "github.com/onsi/gomega"
+)
+
+func TestInviteUsers_Empty(t *testing.T) {
+ RegisterTestingT(t)
+
+ action := &actions.InviteUsers{Model: &models.InviteUsers{}}
+ result := action.Validate(nil, services)
+ ExpectFailed(result, "subject", "message", "recipients")
+ Expect(action.Invitations).To(BeNil())
+}
+
+func TestInviteUsers_Oversized(t *testing.T) {
+ RegisterTestingT(t)
+
+ action := &actions.InviteUsers{Model: &models.InviteUsers{
+ Subject: "Join us and share your ideas. Because we have a cool website and this subject needs to be very long",
+ Message: "Use this link to join %invite%",
+ Recipients: []string{"[email protected]"},
+ }}
+ result := action.Validate(nil, services)
+ ExpectFailed(result, "subject")
+ Expect(action.Invitations).To(BeNil())
+}
+
+func TestInviteUsers_MissingInvite(t *testing.T) {
+ RegisterTestingT(t)
+
+ action := &actions.InviteUsers{Model: &models.InviteUsers{
+ Subject: "Share your feedback.",
+ Message: "Please!",
+ Recipients: []string{"[email protected]"},
+ }}
+ result := action.Validate(nil, services)
+ ExpectFailed(result, "message")
+ Expect(action.Invitations).To(BeNil())
+}
+
+func TestInviteUsers_TooManyRecipients(t *testing.T) {
+ RegisterTestingT(t)
+
+ recipients := make([]string, 31)
+ for i := 0; i < len(recipients); i++ {
+ recipients[i] = fmt.Sprintf("jon.snow%[email protected]", i)
+ }
+
+ action := &actions.InviteUsers{Model: &models.InviteUsers{
+ Subject: "Share your feedback.",
+ Message: "Use this link to join %invite%",
+ Recipients: recipients,
+ }}
+ result := action.Validate(nil, services)
+ ExpectFailed(result, "recipients")
+ Expect(action.Invitations).To(BeNil())
+}
+
+func TestInviteUsers_InvalidRecipient(t *testing.T) {
+ RegisterTestingT(t)
+
+ action := &actions.InviteUsers{Model: &models.InviteUsers{
+ Subject: "Share your feedback.",
+ Message: "Use this link to join our community: %invite%",
+ Recipients: []string{
+ "jon.snow",
+ "@got.com",
+ },
+ }}
+ result := action.Validate(nil, services)
+ ExpectFailed(result, "recipients")
+ Expect(action.Invitations).To(BeNil())
+}
+
+func TestInviteUsers_Valid(t *testing.T) {
+ RegisterTestingT(t)
+
+ action := &actions.InviteUsers{Model: &models.InviteUsers{
+ Subject: "Share your feedback.",
+ Message: "Use this link to join our community: %invite%",
+ Recipients: []string{
+ "",
+ },
+ }}
+
+ ExpectSuccess(action.Validate(nil, services))
+
+ Expect(action.Invitations).To(HaveLen(2))
+
+ Expect(action.Invitations[0].Email).To(Equal("[email protected]"))
+ Expect(action.Invitations[0].VerificationKey).NotTo(BeEmpty())
+
+ Expect(action.Invitations[1].Email).To(Equal("[email protected]"))
+ Expect(action.Invitations[1].VerificationKey).NotTo(BeEmpty())
+}
+
+func TestInviteUsers_IgnoreAlreadyRegistered(t *testing.T) {
+ RegisterTestingT(t)
+
+ theTenant := &models.Tenant{ID: 1, Name: "The Tenant"}
+ services.Users.SetCurrentTenant(theTenant)
+ services.Users.Register(&models.User{
+ Name: "Tony",
+ Email: "[email protected]",
+ Tenant: theTenant,
+ })
+ action := &actions.InviteUsers{Model: &models.InviteUsers{
+ Subject: "Share your feedback.",
+ Message: "Use this link to join our community: %invite%",
+ Recipients: []string{
+ },
+ }}
+
+ ExpectSuccess(action.Validate(nil, services))
+
+ Expect(action.Invitations).To(HaveLen(2))
+
+ Expect(action.Invitations[0].Email).To(Equal("[email protected]"))
+ Expect(action.Invitations[0].VerificationKey).NotTo(BeEmpty())
+
+ Expect(action.Invitations[1].Email).To(Equal("[email protected]"))
+ Expect(action.Invitations[1].VerificationKey).NotTo(BeEmpty())
+}
+
+func TestInviteUsers_ShouldFail_WhenAllRecipientsIgnored(t *testing.T) {
+ RegisterTestingT(t)
+
+ theTenant := &models.Tenant{ID: 1, Name: "The Tenant"}
+ services.Users.SetCurrentTenant(theTenant)
+ services.Users.Register(&models.User{
+ Name: "Tony",
+ Email: "[email protected]",
+ Tenant: theTenant,
+ })
+ action := &actions.InviteUsers{Model: &models.InviteUsers{
+ Subject: "Share your feedback.",
+ Message: "Use this link to join our community: %invite%",
+ Recipients: []string{
+ },
+ }}
+
+ ExpectFailed(action.Validate(nil, services), "recipients")
+}
+
+func TestInviteUsers_SampleInvite_IgnoreRecipients(t *testing.T) {
+ RegisterTestingT(t)
+
+ action := &actions.InviteUsers{
+ IsSampleInvite: true,
+ Model: &models.InviteUsers{
+ Subject: "Share your feedback.",
+ Message: "Use this link to join our community: %invite%",
+ },
+ }
+
+ ExpectSuccess(action.Validate(nil, services))
+}
diff --git a/app/actions/signin.go b/app/actions/signin.go
index 2b51822c5..c9bc3b7ba 100644
--- a/app/actions/signin.go
+++ b/app/actions/signin.go
@@ -1,12 +1,8 @@
package actions
import (
- "strings"
-
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/errors"
- "github.com/getfider/fider/app/pkg/uuid"
"github.com/getfider/fider/app/pkg/validate"
)
@@ -18,7 +14,7 @@ type SignInByEmail struct {
// Initialize the model
func (input *SignInByEmail) Initialize() interface{} {
input.Model = new(models.SignInByEmail)
- input.Model.VerificationKey = strings.Replace(uuid.NewV4().String(), "-", "", 4)
+ input.Model.VerificationKey = models.GenerateVerificationKey()
return input.Model
}
@@ -79,15 +75,14 @@ func (input *CompleteProfile) Validate(user *models.User, services *app.Services
if input.Model.Key == "" {
result.AddFieldFailure("key", "Key is required.")
} else {
- request, err := services.Tenants.FindVerificationByKey(models.EmailVerificationKindSignIn, input.Model.Key)
- if err != nil {
- if errors.Cause(err) == app.ErrNotFound {
- result.AddFieldFailure("key", "Key is invalid.")
- } else {
- return validate.Error(err)
- }
+ request1, err1 := services.Tenants.FindVerificationByKey(models.EmailVerificationKindSignIn, input.Model.Key)
+ request2, err2 := services.Tenants.FindVerificationByKey(models.EmailVerificationKindUserInvitation, input.Model.Key)
+ if err1 == nil {
+ input.Model.Email = request1.Email
+ } else if err2 == nil {
+ input.Model.Email = request2.Email
} else {
- input.Model.Email = request.Email
+ result.AddFieldFailure("key", "Key is invalid.")
}
}
diff --git a/app/actions/signin_test.go b/app/actions/signin_test.go
index 9cd722a93..7f85d787c 100644
--- a/app/actions/signin_test.go
+++ b/app/actions/signin_test.go
@@ -65,10 +65,24 @@ func TestCompleteProfile_UnknownKey(t *testing.T) {
func TestCompleteProfile_ValidKey(t *testing.T) {
RegisterTestingT(t)
+
e := &models.SignInByEmail{Email: "[email protected]"}
services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, e)
action := actions.CompleteProfile{Model: &models.CompleteProfile{Name: "Jon Snow", Key: "1234567890"}}
result := action.Validate(nil, services)
+
+ ExpectSuccess(result)
+ Expect(action.Model.Email).To(Equal("[email protected]"))
+}
+
+func TestCompleteProfile_UserInvitation_ValidKey(t *testing.T) {
+ RegisterTestingT(t)
+
+ e := &models.UserInvitation{Email: "[email protected]"}
+ services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, e)
+ action := actions.CompleteProfile{Model: &models.CompleteProfile{Name: "Jon Snow", Key: "1234567890"}}
+ result := action.Validate(nil, services)
+
ExpectSuccess(result)
Expect(action.Model.Email).To(Equal("[email protected]"))
}
diff --git a/app/actions/tenant.go b/app/actions/tenant.go
index 22e7df9b3..f19566ae6 100644
--- a/app/actions/tenant.go
+++ b/app/actions/tenant.go
@@ -1,13 +1,10 @@
package actions
import (
- "strings"
-
"github.com/getfider/fider/app"
"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"
)
@@ -19,7 +16,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)
+ input.Model.VerificationKey = models.GenerateVerificationKey()
return input.Model
}
@@ -114,3 +111,24 @@ func (input *UpdateTenantSettings) Validate(user *models.User, services *app.Ser
return result
}
+
+//UpdateTenantPrivacy is the input model used to update tenant privacy settings
+type UpdateTenantPrivacy struct {
+ Model *models.UpdateTenantPrivacy
+}
+
+// Initialize the model
+func (input *UpdateTenantPrivacy) Initialize() interface{} {
+ input.Model = new(models.UpdateTenantPrivacy)
+ return input.Model
+}
+
+// IsAuthorized returns true if current user is authorized to perform this action
+func (input *UpdateTenantPrivacy) IsAuthorized(user *models.User, services *app.Services) bool {
+ return user != nil && user.Role == models.RoleAdministrator
+}
+
+// Validate is current model is valid
+func (input *UpdateTenantPrivacy) Validate(user *models.User, services *app.Services) *validate.Result {
+ return validate.Success()
+}
diff --git a/app/actions/user.go b/app/actions/user.go
index 5cf1c32ae..40c10647e 100644
--- a/app/actions/user.go
+++ b/app/actions/user.go
@@ -1,12 +1,9 @@
package actions
import (
- "strings"
-
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/errors"
- "github.com/getfider/fider/app/pkg/uuid"
"github.com/getfider/fider/app/pkg/validate"
)
@@ -56,7 +53,7 @@ type ChangeUserEmail struct {
// Initialize the model
func (input *ChangeUserEmail) Initialize() interface{} {
input.Model = new(models.ChangeUserEmail)
- input.Model.VerificationKey = strings.Replace(uuid.NewV4().String(), "-", "", 4)
+ input.Model.VerificationKey = models.GenerateVerificationKey()
return input.Model
}
diff --git a/app/const.go b/app/const.go
index 12ff0e9c8..72eb2cbfc 100644
--- a/app/const.go
+++ b/app/const.go
@@ -4,3 +4,6 @@ import "errors"
// ErrNotFound represents an object not found error
var ErrNotFound = errors.New("Object not found")
+
+// InvitePlaceholder represents the placeholder used by members to invite other users
+var InvitePlaceholder = "%invite%"
diff --git a/app/handlers/admin.go b/app/handlers/admin.go
index 1cc498d19..5f95359f0 100644
--- a/app/handlers/admin.go
+++ b/app/handlers/admin.go
@@ -12,6 +12,7 @@ func UpdateSettings() web.HandlerFunc {
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
+
err := c.Services().Tenants.UpdateSettings(input.Model)
if err != nil {
return c.Failure(err)
@@ -21,6 +22,23 @@ func UpdateSettings() web.HandlerFunc {
}
}
+// UpdatePrivacy update current tenant's privacy settings
+func UpdatePrivacy() web.HandlerFunc {
+ return func(c web.Context) error {
+ input := new(actions.UpdateTenantPrivacy)
+ if result := c.BindTo(input); !result.Ok {
+ return c.HandleValidation(result)
+ }
+
+ err := c.Services().Tenants.UpdatePrivacy(input.Model)
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ return c.Ok(web.Map{})
+ }
+}
+
// ManageMembers is the page used by administrators to change member's role
func ManageMembers() web.HandlerFunc {
return func(c web.Context) error {
diff --git a/app/handlers/admin_test.go b/app/handlers/admin_test.go
index dcd78897f..9ad7f0288 100644
--- a/app/handlers/admin_test.go
+++ b/app/handlers/admin_test.go
@@ -29,7 +29,24 @@ func TestUpdateSettingsHandler(t *testing.T) {
Expect(tenant.WelcomeMessage).To(Equal("Welcome to GoT Feedback Forum"))
}
-func TestUManageMembersHandler(t *testing.T) {
+func TestUpdatePrivacyHandler(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, services := mock.NewServer()
+ code, _ := server.
+ OnTenant(mock.DemoTenant).
+ AsUser(mock.JonSnow).
+ ExecutePost(
+ handlers.UpdatePrivacy(),
+ `{ "isPrivate": true }`,
+ )
+
+ tenant, _ := services.Tenants.GetByDomain("demo")
+ Expect(code).To(Equal(http.StatusOK))
+ Expect(tenant.IsPrivate).To(BeTrue())
+}
+
+func TestManageMembersHandler(t *testing.T) {
RegisterTestingT(t)
server, _ := mock.NewServer()
diff --git a/app/handlers/invite.go b/app/handlers/invite.go
new file mode 100644
index 000000000..d9e7079ce
--- /dev/null
+++ b/app/handlers/invite.go
@@ -0,0 +1,50 @@
+package handlers
+
+import (
+ "strings"
+
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/actions"
+ "github.com/getfider/fider/app/pkg/email"
+ "github.com/getfider/fider/app/pkg/markdown"
+ "github.com/getfider/fider/app/pkg/web"
+ "github.com/getfider/fider/app/tasks"
+)
+
+// SendSampleInvite to current user's email
+func SendSampleInvite() web.HandlerFunc {
+ return func(c web.Context) error {
+ input := &actions.InviteUsers{IsSampleInvite: true}
+ if result := c.BindTo(input); !result.Ok {
+ return c.HandleValidation(result)
+ }
+
+ if c.User().Email != "" {
+ input.Model.Message = strings.Replace(input.Model.Message, app.InvitePlaceholder, "*the link to accept invitation will be here*", -1)
+ to := email.NewRecipient(c.User().Name, c.User().Email, email.Params{
+ "subject": input.Model.Subject,
+ "message": markdown.Parse(input.Model.Message),
+ })
+ err := c.Services().Emailer.Send("invite_email", email.Params{}, c.Tenant().Name, to)
+ if err != nil {
+ return c.Failure(err)
+ }
+ }
+
+ return c.Ok(web.Map{})
+ }
+}
+
+// SendInvites sends an email to each recipient
+func SendInvites() web.HandlerFunc {
+ return func(c web.Context) error {
+ input := new(actions.InviteUsers)
+ if result := c.BindTo(input); !result.Ok {
+ return c.HandleValidation(result)
+ }
+
+ c.Enqueue(tasks.SendInvites(input.Model.Subject, input.Model.Message, input.Invitations))
+
+ return c.Ok(web.Map{})
+ }
+}
diff --git a/app/handlers/signin.go b/app/handlers/signin.go
index 79c9ff6fd..4ada48fd9 100644
--- a/app/handlers/signin.go
+++ b/app/handlers/signin.go
@@ -69,6 +69,10 @@ func OAuthCallback(provider string) web.HandlerFunc {
}
if err != nil {
if errors.Cause(err) == app.ErrNotFound {
+ if tenant.IsPrivate {
+ return c.Redirect(http.StatusTemporaryRedirect, c.TenantBaseURL(tenant)+"/not-invited")
+ }
+
user = &models.User{
Name: oauthUser.Name,
Tenant: tenant,
@@ -125,8 +129,25 @@ func OAuthCallback(provider string) web.HandlerFunc {
}
}
-// SignIn handles OAuth sign in
-func SignIn(provider string) web.HandlerFunc {
+// SignInPage renders the sign in page
+func SignInPage() web.HandlerFunc {
+ return func(c web.Context) error {
+ if c.IsAuthenticated() || !c.Tenant().IsPrivate {
+ return c.Redirect(http.StatusTemporaryRedirect, c.BaseURL())
+ }
+ return c.Page(web.Map{})
+ }
+}
+
+// NotInvitedPage renders the not invited page
+func NotInvitedPage() web.HandlerFunc {
+ return func(c web.Context) error {
+ return c.Render(http.StatusForbidden, "not-invited.html", web.Map{})
+ }
+}
+
+// SignInByOAuth handles OAuth sign in
+func SignInByOAuth(provider string) web.HandlerFunc {
return func(c web.Context) error {
authURL := c.Services().OAuth.GetAuthURL(c.AuthEndpoint(), provider, c.QueryParam("redirect"))
return c.Redirect(http.StatusTemporaryRedirect, authURL)
@@ -180,7 +201,20 @@ func VerifySignInKey(kind models.EmailVerificationKind) web.HandlerFunc {
user, err = c.Services().Users.GetByEmail(result.Email)
if err != nil {
if errors.Cause(err) == app.ErrNotFound {
- // This will render a page for /signin/verify URL using same variables as home page
+ if c.Tenant().IsPrivate {
+ return NotInvitedPage()(c)
+ }
+ return Index()(c)
+ }
+ return c.Failure(err)
+ }
+ } else if kind == models.EmailVerificationKindUserInvitation {
+ user, err = c.Services().Users.GetByEmail(result.Email)
+ if err != nil {
+ if errors.Cause(err) == app.ErrNotFound {
+ if c.Tenant().IsPrivate {
+ return SignInPage()(c)
+ }
return Index()(c)
}
return c.Failure(err)
diff --git a/app/handlers/signin_test.go b/app/handlers/signin_test.go
index 38ecd080e..ccce5f765 100644
--- a/app/handlers/signin_test.go
+++ b/app/handlers/signin_test.go
@@ -32,11 +32,11 @@ func TestSignOutHandler(t *testing.T) {
Expect(response.Header().Get("Set-Cookie")).To(ContainSubstring(web.CookieAuthName + "=;"))
}
-func TestSignInHandler(t *testing.T) {
+func TestSignInByOAuthHandler(t *testing.T) {
RegisterTestingT(t)
server, _ := mock.NewServer()
- code, response := server.Execute(handlers.SignIn(oauth.FacebookProvider))
+ code, response := server.Execute(handlers.SignInByOAuth(oauth.FacebookProvider))
Expect(code).To(Equal(http.StatusTemporaryRedirect))
Expect(response.Header().Get("Location")).To(Equal("http://avengers.test.fider.io/oauth/token?provider=facebook&redirect="))
@@ -176,6 +176,24 @@ func TestCallbackHandler_ExistingUser_NewProvider(t *testing.T) {
Expect(response.Header().Get("Location")).To(Equal("http://demo.test.fider.io?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjoxLCJ1c2VyL25hbWUiOiJKb24gU25vdyIsInVzZXIvZW1haWwiOiJqb24uc25vd0Bnb3QuY29tIn0.S7P8zTU0rVovmchNbwamBewYbO96GdJcOygn7tbsikw"))
}
+func TestCallbackHandler_NewUser_PrivateTenant(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, services := mock.NewServer()
+ mock.AvengersTenant.IsPrivate = true
+
+ code, response := server.
+ WithURL("http://login.test.fider.io/oauth/callback?state=http://avengers.test.fider.io&code=456").
+ Execute(handlers.OAuthCallback(oauth.FacebookProvider))
+
+ user, err := services.Users.GetByEmail("[email protected]")
+ Expect(errors.Cause(err)).To(Equal(app.ErrNotFound))
+ Expect(user).To(BeNil())
+
+ Expect(code).To(Equal(http.StatusTemporaryRedirect))
+ Expect(response.Header().Get("Location")).To(Equal("http://avengers.test.fider.io/not-invited"))
+}
+
func TestSignInByEmailHandler_WithoutEmail(t *testing.T) {
RegisterTestingT(t)
@@ -284,6 +302,88 @@ func TestVerifySignInKeyHandler_CorrectKey_NewUser(t *testing.T) {
Expect(code).To(Equal(http.StatusOK))
}
+func TestVerifySignInKeyHandler_PrivateTenant_SignInRequest_NonInviteNewUser(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, services := mock.NewServer()
+ mock.DemoTenant.IsPrivate = true
+
+ e := &models.SignInByEmail{Email: "[email protected]"}
+ services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, e)
+
+ code, _ := server.
+ OnTenant(mock.DemoTenant).
+ WithURL("http://demo.test.fider.io/signin/verify?k=1234567890").
+ Execute(handlers.VerifySignInKey(models.EmailVerificationKindSignIn))
+
+ Expect(code).To(Equal(http.StatusForbidden))
+}
+
+func TestVerifySignInKeyHandler_PrivateTenant_SignInRequest_RegisteredUser(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, services := mock.NewServer()
+ mock.DemoTenant.IsPrivate = true
+
+ services.Users.Register(&models.User{
+ Name: "Hot Pie",
+ Email: "[email protected]",
+ Tenant: mock.DemoTenant,
+ })
+
+ e := &models.SignInByEmail{Email: "[email protected]"}
+ services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, e)
+
+ code, response := server.
+ OnTenant(mock.DemoTenant).
+ WithURL("http://demo.test.fider.io/signin/verify?k=1234567890").
+ Execute(handlers.VerifySignInKey(models.EmailVerificationKindSignIn))
+
+ Expect(code).To(Equal(http.StatusTemporaryRedirect))
+ Expect(response.Header().Get("Location")).To(Equal("http://demo.test.fider.io"))
+}
+
+func TestVerifySignInKeyHandler_PrivateTenant_InviteRequest_ExistingUser(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, services := mock.NewServer()
+ mock.DemoTenant.IsPrivate = true
+
+ services.Users.Register(&models.User{
+ Name: "Hot Pie",
+ Email: "[email protected]",
+ Tenant: mock.DemoTenant,
+ })
+
+ e := &models.UserInvitation{Email: "[email protected]"}
+ services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, e)
+
+ code, response := server.
+ OnTenant(mock.DemoTenant).
+ WithURL("http://demo.test.fider.io/invite/verify?k=1234567890").
+ Execute(handlers.VerifySignInKey(models.EmailVerificationKindUserInvitation))
+
+ Expect(code).To(Equal(http.StatusTemporaryRedirect))
+ Expect(response.Header().Get("Location")).To(Equal("http://demo.test.fider.io"))
+}
+
+func TestVerifySignInKeyHandler_PrivateTenant_InviteRequest_NewUser(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, services := mock.NewServer()
+ mock.DemoTenant.IsPrivate = true
+
+ e := &models.UserInvitation{Email: "[email protected]"}
+ services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, e)
+
+ code, _ := server.
+ OnTenant(mock.DemoTenant).
+ WithURL("http://demo.test.fider.io/invite/verify?k=1234567890").
+ Execute(handlers.VerifySignInKey(models.EmailVerificationKindUserInvitation))
+
+ Expect(code).To(Equal(http.StatusOK))
+}
+
func TestVerifySignUpKeyHandler_InactiveTenant(t *testing.T) {
RegisterTestingT(t)
@@ -364,3 +464,44 @@ func TestCompleteSignInProfileHandler_CorrectKey(t *testing.T) {
Expect(err).To(BeNil())
Expect(request.VerifiedOn).NotTo(BeNil())
}
+
+func TestSignInPageHandler_AuthenticatedUser(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, _ := mock.NewServer()
+ code, response := server.
+ OnTenant(mock.DemoTenant).
+ AsUser(mock.AryaStark).
+ WithURL("http://demo.test.fider.io/signin").
+ Execute(handlers.SignInPage())
+
+ Expect(code).To(Equal(http.StatusTemporaryRedirect))
+ Expect(response.Header().Get("Location")).To(Equal("http://demo.test.fider.io"))
+}
+
+func TestSignInPageHandler_NonPrivateTenant(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, _ := mock.NewServer()
+ code, response := server.
+ OnTenant(mock.DemoTenant).
+ WithURL("http://demo.test.fider.io/signin").
+ Execute(handlers.SignInPage())
+
+ Expect(code).To(Equal(http.StatusTemporaryRedirect))
+ Expect(response.Header().Get("Location")).To(Equal("http://demo.test.fider.io"))
+}
+
+func TestSignInPageHandler_PrivateTenant_UnauthenticatedUser(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, _ := mock.NewServer()
+ mock.DemoTenant.IsPrivate = true
+
+ code, _ := server.
+ OnTenant(mock.DemoTenant).
+ WithURL("http://demo.test.fider.io/signin").
+ Execute(handlers.SignInPage())
+
+ Expect(code).To(Equal(http.StatusOK))
+}
diff --git a/app/middlewares/domain.go b/app/middlewares/domain.go
index 261a39222..1ee31e85f 100644
--- a/app/middlewares/domain.go
+++ b/app/middlewares/domain.go
@@ -79,6 +79,18 @@ func OnlyActiveTenants() web.MiddlewareFunc {
}
}
+// CheckTenantPrivacy blocks requests of unauthenticated users for private tenants
+func CheckTenantPrivacy() web.MiddlewareFunc {
+ return func(next web.HandlerFunc) web.HandlerFunc {
+ return func(c web.Context) error {
+ if c.Tenant().IsPrivate && !c.IsAuthenticated() {
+ return c.Redirect(http.StatusTemporaryRedirect, "/signin")
+ }
+ return next(c)
+ }
+ }
+}
+
// 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 95e5373d7..8eb5520ce 100644
--- a/app/middlewares/domain_test.go
+++ b/app/middlewares/domain_test.go
@@ -157,3 +157,51 @@ func TestOnlyActiveTenants_Inactive(t *testing.T) {
Expect(status).To(Equal(http.StatusNotFound))
}
+
+func TestCheckTenantPrivacy_Private_Unauthenticated(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, _ := mock.NewServer()
+ mock.DemoTenant.IsPrivate = true
+
+ server.Use(middlewares.CheckTenantPrivacy())
+ status, response := server.OnTenant(mock.DemoTenant).Execute(func(c web.Context) error {
+ return c.NoContent(http.StatusOK)
+ })
+
+ Expect(status).To(Equal(http.StatusTemporaryRedirect))
+ Expect(response.HeaderMap.Get("Location")).To(Equal("/signin"))
+}
+
+func TestCheckTenantPrivacy_Private_Authenticated(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, _ := mock.NewServer()
+ mock.DemoTenant.IsPrivate = true
+
+ server.Use(middlewares.CheckTenantPrivacy())
+ status, _ := server.
+ OnTenant(mock.DemoTenant).
+ AsUser(mock.AryaStark).
+ Execute(func(c web.Context) error {
+ return c.NoContent(http.StatusOK)
+ })
+
+ Expect(status).To(Equal(http.StatusOK))
+}
+
+func TestCheckTenantPrivacy_NotPrivate_Unauthenticated(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, _ := mock.NewServer()
+ mock.DemoTenant.IsPrivate = false
+
+ server.Use(middlewares.CheckTenantPrivacy())
+ status, _ := server.
+ OnTenant(mock.DemoTenant).
+ Execute(func(c web.Context) error {
+ return c.NoContent(http.StatusOK)
+ })
+
+ Expect(status).To(Equal(http.StatusOK))
+}
diff --git a/app/models/identity.go b/app/models/identity.go
index 57496f433..d2977f19a 100644
--- a/app/models/identity.go
+++ b/app/models/identity.go
@@ -1,9 +1,11 @@
package models
import (
+ "strings"
"time"
jwt "github.com/dgrijalva/jwt-go"
+ "github.com/getfider/fider/app/pkg/uuid"
)
//Tenant represents a tenant
@@ -15,6 +17,7 @@ type Tenant struct {
WelcomeMessage string `json:"welcomeMessage"`
CNAME string `json:"cname"`
Status int `json:"-"`
+ IsPrivate bool `json:"isPrivate"`
}
var (
@@ -56,6 +59,8 @@ const (
EmailVerificationKindSignUp EmailVerificationKind = 2
//EmailVerificationKindChangeEmail is the change user email process
EmailVerificationKindChangeEmail EmailVerificationKind = 3
+ //EmailVerificationKindUserInvitation is the sign in invitation sent to an user
+ EmailVerificationKindUserInvitation EmailVerificationKind = 4
)
//HasProvider returns true if current user has registered with given provider
@@ -132,13 +137,17 @@ func (e *CreateTenant) GetKind() EmailVerificationKind {
return EmailVerificationKindSignUp
}
-//UpdateTenantSettings is the input model used to update tenant settings
+//UpdateTenantSettings is the input model used to update tenant general settings
type UpdateTenantSettings struct {
Title string `json:"title"`
Invitation string `json:"invitation"`
WelcomeMessage string `json:"welcomeMessage"`
CNAME string `json:"cname" format:"lower"`
- UserClaims *OAuthClaims
+}
+
+//UpdateTenantPrivacy is the input model used to update tenant privacy settings
+type UpdateTenantPrivacy struct {
+ IsPrivate bool `json:"isPrivate"`
}
//SignInByEmail is the input model when user request to sign in by email
@@ -194,6 +203,32 @@ func (e *ChangeUserEmail) GetKind() EmailVerificationKind {
return EmailVerificationKindChangeEmail
}
+//UserInvitation is the model used to register an invite sent to an user
+type UserInvitation struct {
+ Email string
+ VerificationKey string
+}
+
+//GetEmail returns the invited user's email
+func (e *UserInvitation) GetEmail() string {
+ return e.Email
+}
+
+//GetName returns empty for this kind of process
+func (e *UserInvitation) GetName() string {
+ return ""
+}
+
+//GetUser returns the current user performing this action
+func (e *UserInvitation) GetUser() *User {
+ return nil
+}
+
+//GetKind returns EmailVerificationKindUserInvitation
+func (e *UserInvitation) GetKind() EmailVerificationKind {
+ return EmailVerificationKindUserInvitation
+}
+
//NewEmailVerification is used to register a new email verification process
type NewEmailVerification interface {
GetEmail() string
@@ -232,3 +267,15 @@ type ChangeUserRole struct {
UserID int `route:"user_id"`
Role Role `json:"role"`
}
+
+// InviteUsers is used to invite new users into Fider
+type InviteUsers struct {
+ Subject string `json:"subject"`
+ Message string `json:"message"`
+ Recipients []string `json:"recipients" format:"lower"`
+}
+
+// GenerateVerificationKey used on email verifications
+func GenerateVerificationKey() string {
+ return strings.Replace(uuid.NewV4().String(), "-", "", 4)
+}
diff --git a/app/pkg/dbx/setup.sql b/app/pkg/dbx/setup.sql
index a614947ac..ded7fc3d3 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, status) VALUES ('Demonstration', 'demo', now(), '', '', '', 1);
+INSERT INTO tenants (name, subdomain, created_on, cname, invitation, welcome_message, status, is_private) VALUES ('Demonstration', 'demo', now(), '', '', '', 1, false);
INSERT INTO users (name, email, tenant_id, created_on, role) VALUES ('Jon Snow', '[email protected]', 1, now(), 3);
INSERT INTO user_providers (user_id, tenant_id, provider, provider_uid, created_on) VALUES (1, 1, 'facebook', 'FB1234', now());
@@ -10,7 +10,7 @@ INSERT INTO user_providers (user_id, tenant_id, provider, provider_uid, created_
INSERT INTO users (name, email, tenant_id, created_on, role) VALUES ('Sansa Stark', '[email protected]', 1, now(), 1);
-INSERT INTO tenants (name, subdomain, created_on, cname, invitation, welcome_message, status) VALUES ('Avengers', 'avengers', now(), 'feedback.avengers.com', '', '', 1);
+INSERT INTO tenants (name, subdomain, created_on, cname, invitation, welcome_message, status, is_private) VALUES ('Avengers', 'avengers', now(), 'feedback.avengers.com', '', '', 1, false);
INSERT INTO users (name, email, tenant_id, created_on, role) VALUES ('Tony Stark', '[email protected]', 2, now(), 3);
INSERT INTO user_providers (user_id, tenant_id, provider, provider_uid, created_on) VALUES (4, 2, 'facebook', 'FB2222', now());
diff --git a/app/pkg/validate/general.go b/app/pkg/validate/general.go
index 1988473c9..faeaf3dea 100644
--- a/app/pkg/validate/general.go
+++ b/app/pkg/validate/general.go
@@ -21,7 +21,7 @@ func Email(email string) *Result {
}
if !emailRegex.MatchString(email) {
- return Failed([]string{"Email address is invalid."})
+ return Failed([]string{fmt.Sprintf("'%s' is not a valid email address.", email)})
}
return Success()
diff --git a/app/pkg/web/binder.go b/app/pkg/web/binder.go
index edb40434b..0eb05df14 100644
--- a/app/pkg/web/binder.go
+++ b/app/pkg/web/binder.go
@@ -70,18 +70,28 @@ func (b *DefaultBinder) bindRoute(idx int, target reflect.Value, targetType refl
func (b *DefaultBinder) format(idx int, target reflect.Value, targetType reflect.Type) {
field := target.Field(idx)
+ fieldType := field.Type()
+ fieldTypeKind := fieldType.Kind()
+ format := targetType.Field(idx).Tag.Get("format")
- if field.Type() != stringType {
- return
+ if fieldType == stringType {
+ value := field.Interface().(string)
+ field.SetString(applyFormat(format, value))
+ } else if fieldTypeKind == reflect.Slice && fieldType.Elem() == stringType {
+ values := field.Interface().([]string)
+ for i, value := range values {
+ field.Index(i).SetString(applyFormat(format, value))
+ }
}
- format := targetType.Field(idx).Tag.Get("format")
- str := field.Interface().(string)
- str = strings.TrimSpace(str)
+}
+
+func applyFormat(format string, value string) string {
+ value = strings.TrimSpace(value)
if format == "lower" {
- str = strings.ToLower(str)
+ value = strings.ToLower(value)
} else if format == "upper" {
- str = strings.ToUpper(str)
+ value = strings.ToUpper(value)
}
- field.SetString(str)
+ return value
}
diff --git a/app/pkg/web/binder_test.go b/app/pkg/web/binder_test.go
index eed104342..fee7f26e7 100644
--- a/app/pkg/web/binder_test.go
+++ b/app/pkg/web/binder_test.go
@@ -44,13 +44,33 @@ func TestDefaultBinder_TrimSpaces(t *testing.T) {
ctx := newBodyContext("POST", params, body, "application/json")
u := new(user)
err := binder.Bind(u, ctx)
- Expect(err).To(BeNil())
Expect(u.Name).To(Equal("Jon Snow"))
+ Expect(err).To(BeNil())
Expect(u.Email).To(Equal("[email protected]"))
Expect(u.Color).To(Equal("FF00AD"))
Expect(u.Other).To(Equal(""))
}
+func TestDefaultBinder_Array_TrimSpaces(t *testing.T) {
+ RegisterTestingT(t)
+
+ type user struct {
+ Providers []string `json:"providers" format:"lower"`
+ }
+
+ params := make(web.StringMap, 0)
+ body := `{ "providers": [ " Google", " FACEBOOK ", " MicroSoft " ] }`
+ ctx := newBodyContext("POST", params, body, "application/json")
+ u := new(user)
+ err := binder.Bind(u, ctx)
+ Expect(err).To(BeNil())
+ Expect(u.Providers).To(Equal([]string{
+ "google",
+ "facebook",
+ "microsoft",
+ }))
+}
+
func TestDefaultBinder_DELETE(t *testing.T) {
RegisterTestingT(t)
diff --git a/app/pkg/web/renderer.go b/app/pkg/web/renderer.go
index 9e9303a58..d6d712fe1 100644
--- a/app/pkg/web/renderer.go
+++ b/app/pkg/web/renderer.go
@@ -32,6 +32,7 @@ func NewRenderer(settings *models.SystemSettings, logger log.Logger) *Renderer {
}
r.add("index.html")
+ r.add("not-invited.html")
r.add("403.html")
r.add("404.html")
r.add("410.html")
diff --git a/app/storage/inmemory/tenant.go b/app/storage/inmemory/tenant.go
index 677cd794d..6b7ca179a 100644
--- a/app/storage/inmemory/tenant.go
+++ b/app/storage/inmemory/tenant.go
@@ -76,7 +76,7 @@ func (s *TenantStorage) IsCNAMEAvailable(cname string) (bool, error) {
return true, nil
}
-// UpdateSettings of given tenant
+// UpdateSettings of current tenant
func (s *TenantStorage) UpdateSettings(settings *models.UpdateTenantSettings) error {
for _, tenant := range s.tenants {
if tenant.ID == s.current.ID {
@@ -90,6 +90,17 @@ func (s *TenantStorage) UpdateSettings(settings *models.UpdateTenantSettings) er
return nil
}
+// UpdatePrivacy settings of current tenant
+func (s *TenantStorage) UpdatePrivacy(settings *models.UpdateTenantPrivacy) error {
+ for _, tenant := range s.tenants {
+ if tenant.ID == s.current.ID {
+ tenant.IsPrivate = settings.IsPrivate
+ return nil
+ }
+ }
+ return nil
+}
+
// Activate given tenant
func (s *TenantStorage) Activate(id int) error {
for _, tenant := range s.tenants {
diff --git a/app/storage/postgres/tenant.go b/app/storage/postgres/tenant.go
index bd1227679..1c5c0df4d 100644
--- a/app/storage/postgres/tenant.go
+++ b/app/storage/postgres/tenant.go
@@ -18,6 +18,7 @@ type dbTenant struct {
Invitation string `db:"invitation"`
WelcomeMessage string `db:"welcome_message"`
Status int `db:"status"`
+ IsPrivate bool `db:"is_private"`
}
func (t *dbTenant) toModel() *models.Tenant {
@@ -33,6 +34,7 @@ func (t *dbTenant) toModel() *models.Tenant {
Invitation: t.Invitation,
WelcomeMessage: t.WelcomeMessage,
Status: t.Status,
+ IsPrivate: t.IsPrivate,
}
}
@@ -96,8 +98,8 @@ func (s *TenantStorage) SetCurrentUser(user *models.User) {
func (s *TenantStorage) Add(name string, subdomain string, status int) (*models.Tenant, error) {
var id int
err := s.trx.Get(&id,
- `INSERT INTO tenants (name, subdomain, created_on, cname, invitation, welcome_message, status)
- VALUES ($1, $2, $3, '', '', '', $4)
+ `INSERT INTO tenants (name, subdomain, created_on, cname, invitation, welcome_message, status, is_private)
+ VALUES ($1, $2, $3, '', '', '', $4, false)
RETURNING id`, name, subdomain, time.Now(), status)
if err != nil {
return nil, err
@@ -110,7 +112,7 @@ func (s *TenantStorage) Add(name string, subdomain string, status int) (*models.
func (s *TenantStorage) First() (*models.Tenant, error) {
tenant := dbTenant{}
- err := s.trx.Get(&tenant, "SELECT id, name, subdomain, cname, invitation, welcome_message, status FROM tenants ORDER BY id LIMIT 1")
+ err := s.trx.Get(&tenant, "SELECT id, name, subdomain, cname, invitation, welcome_message, status, is_private FROM tenants ORDER BY id LIMIT 1")
if err != nil {
return nil, errors.Wrap(err, "failed to get first tenant")
}
@@ -122,7 +124,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 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 FROM tenants WHERE subdomain = $1 OR cname = $2 ORDER BY cname DESC", extractSubdomain(domain), domain)
if err != nil {
return nil, errors.Wrap(err, "failed to get tenant with domain '%s'", domain)
}
@@ -130,7 +132,7 @@ func (s *TenantStorage) GetByDomain(domain string) (*models.Tenant, error) {
return tenant.toModel(), nil
}
-// UpdateSettings of given tenant
+// UpdateSettings of current tenant
func (s *TenantStorage) UpdateSettings(settings *models.UpdateTenantSettings) error {
query := "UPDATE tenants SET name = $1, invitation = $2, welcome_message = $3, cname = $4 WHERE id = $5"
_, err := s.trx.Execute(query, settings.Title, settings.Invitation, settings.WelcomeMessage, settings.CNAME, s.current.ID)
@@ -140,6 +142,16 @@ func (s *TenantStorage) UpdateSettings(settings *models.UpdateTenantSettings) er
return nil
}
+// UpdatePrivacy settings of current tenant
+func (s *TenantStorage) UpdatePrivacy(settings *models.UpdateTenantPrivacy) error {
+ query := "UPDATE tenants SET is_private = $1 WHERE id = $2"
+ _, err := s.trx.Execute(query, settings.IsPrivate, s.current.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed update tenant privacy settings")
+ }
+ return nil
+}
+
// IsSubdomainAvailable returns true if subdomain is available to use
func (s *TenantStorage) IsSubdomainAvailable(subdomain string) (bool, error) {
exists, err := s.trx.Exists("SELECT id FROM tenants WHERE subdomain = $1", subdomain)
diff --git a/app/storage/postgres/tenant_test.go b/app/storage/postgres/tenant_test.go
index 68d4ee808..cd2f145f5 100644
--- a/app/storage/postgres/tenant_test.go
+++ b/app/storage/postgres/tenant_test.go
@@ -26,6 +26,7 @@ func TestTenantStorage_Add_Activate(t *testing.T) {
Expect(tenant.Name).To(Equal("My Domain Inc."))
Expect(tenant.Subdomain).To(Equal("mydomain"))
Expect(tenant.Status).To(Equal(models.TenantInactive))
+ Expect(tenant.IsPrivate).To(BeFalse())
err = tenants.Activate(tenant.ID)
Expect(err).To(BeNil())
@@ -35,6 +36,7 @@ func TestTenantStorage_Add_Activate(t *testing.T) {
Expect(tenant.Name).To(Equal("My Domain Inc."))
Expect(tenant.Subdomain).To(Equal("mydomain"))
Expect(tenant.Status).To(Equal(models.TenantActive))
+ Expect(tenant.IsPrivate).To(BeFalse())
}
func TestTenantStorage_SingleTenant_Add(t *testing.T) {
@@ -68,6 +70,19 @@ func TestTenantStorage_Empty_First(t *testing.T) {
Expect(tenant).To(BeNil())
}
+func TestTenantStorage_UpdatePrivacy(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ tenant, _ := tenants.GetByDomain("demo")
+ tenants.SetCurrentTenant(tenant)
+ Expect(tenant.IsPrivate).To(BeFalse())
+
+ tenants.UpdatePrivacy(&models.UpdateTenantPrivacy{IsPrivate: true})
+ tenant, _ = tenants.GetByDomain("demo")
+ Expect(tenant.IsPrivate).To(BeTrue())
+}
+
func TestTenantStorage_GetByDomain_NotFound(t *testing.T) {
SetupDatabaseTest(t)
defer TeardownDatabaseTest()
diff --git a/app/storage/postgres/user_test.go b/app/storage/postgres/user_test.go
index b501f34fe..b6fb779bd 100644
--- a/app/storage/postgres/user_test.go
+++ b/app/storage/postgres/user_test.go
@@ -140,8 +140,8 @@ func TestUserStorage_Register_MultipleProviders(t *testing.T) {
var tenantID int
trx.Get(&tenantID, `
- INSERT INTO tenants (name, subdomain, created_on, status)
- VALUES ('My Domain Inc.','mydomain', now(), 1)
+ INSERT INTO tenants (name, subdomain, created_on, status, is_private)
+ VALUES ('My Domain Inc.','mydomain', now(), 1, false)
RETURNING id
`)
users.SetCurrentTenant(&models.Tenant{
diff --git a/app/storage/storage.go b/app/storage/storage.go
index 567aeecb0..683b1dc2d 100644
--- a/app/storage/storage.go
+++ b/app/storage/storage.go
@@ -63,6 +63,7 @@ type Tenant interface {
Activate(id int) error
GetByDomain(domain string) (*models.Tenant, error)
UpdateSettings(settings *models.UpdateTenantSettings) error
+ UpdatePrivacy(settings *models.UpdateTenantPrivacy) error
IsSubdomainAvailable(subdomain string) (bool, error)
IsCNAMEAvailable(cname string) (bool, error)
SaveVerificationKey(key string, duration time.Duration, request models.NewEmailVerification) error
diff --git a/app/tasks/tasks.go b/app/tasks/tasks.go
index de7d6a78e..4fd626719 100644
--- a/app/tasks/tasks.go
+++ b/app/tasks/tasks.go
@@ -3,7 +3,10 @@ package tasks
import (
"fmt"
"html/template"
+ "strings"
+ "time"
+ "github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/email"
"github.com/getfider/fider/app/pkg/markdown"
@@ -201,3 +204,25 @@ func NotifyAboutStatusChange(idea *models.Idea, response *models.SetResponse) wo
return c.Services().Emailer.BatchSend("change_status", params, c.User().Name, to)
})
}
+
+//SendInvites sends one email to each invited recipient
+func SendInvites(subject, message string, invitations []*models.UserInvitation) worker.Task {
+ return describe("Send invites", func(c *worker.Context) error {
+ to := make([]email.Recipient, len(invitations))
+ for i, invite := range invitations {
+ err := c.Services().Tenants.SaveVerificationKey(invite.VerificationKey, 15*24*time.Hour, invite)
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ url := link(c.BaseURL(), "/invite/verify?k=%s", invite.VerificationKey)
+ toMessage := strings.Replace(message, app.InvitePlaceholder, string(url), -1)
+ to[i] = email.NewRecipient("", invite.Email, email.Params{
+ "message": markdown.Parse(toMessage),
+ })
+ }
+ return c.Services().Emailer.BatchSend("invite_email", email.Params{
+ "subject": subject,
+ }, c.User().Name, to)
+ })
+}
diff --git a/migrations/201804091842_add_is_private.up.sql b/migrations/201804091842_add_is_private.up.sql
new file mode 100644
index 000000000..3eae66f0c
--- /dev/null
+++ b/migrations/201804091842_add_is_private.up.sql
@@ -0,0 +1,5 @@
+ALTER TABLE tenants ADD is_private BOOLEAN NULL;
+
+UPDATE tenants SET is_private = false;
+
+ALTER TABLE tenants ALTER COLUMN is_private SET NOT NULL;
\ No newline at end of file
diff --git a/package-lock.json b/package-lock.json
index eb026c7d5..2c78dad00 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -2423,6 +2423,11 @@
"randombytes": "2.0.6"
}
},
+ "dom-helpers": {
+ "version": "3.3.1",
+ "resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-3.3.1.tgz",
+ "integrity": "sha512-2Sm+JaYn74OiTM2wHvxJOo3roiq/h25Yi69Fqk269cNUwIXsCvATB6CRSFC9Am/20G2b28hGv/+7NiWydIrPvg=="
+ },
"domain-browser": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/domain-browser/-/domain-browser-1.2.0.tgz",
@@ -8098,6 +8103,38 @@
"prop-types": "15.6.0"
}
},
+ "react-toastify": {
+ "version": "4.0.0-rc.2",
+ "resolved": "https://registry.npmjs.org/react-toastify/-/react-toastify-4.0.0-rc.2.tgz",
+ "integrity": "sha512-XakcbL31NoHoHB6ns0+VvWKXSk8PSi9b5qHbbg+G0Jn6c+lFGc5Ve2PGxdiEfHU6IU1nI5X9r8NAfrLwXDddAw==",
+ "requires": {
+ "classnames": "2.2.5",
+ "prop-types": "15.6.0",
+ "react-transition-group": "2.3.1"
+ }
+ },
+ "react-transition-group": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-2.3.1.tgz",
+ "integrity": "sha512-hu4/LAOFSKjWt1+1hgnOv3ldxmt6lvZGTWz4KUkFrqzXrNDIVSu6txIcPszw7PNduR8en9YTN55JLRyd/L1ZiQ==",
+ "requires": {
+ "dom-helpers": "3.3.1",
+ "loose-envify": "1.3.1",
+ "prop-types": "15.6.1"
+ },
+ "dependencies": {
+ "prop-types": {
+ "version": "15.6.1",
+ "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.6.1.tgz",
+ "integrity": "sha512-4ec7bY1Y66LymSUOH/zARVYObB23AT2h8cf6e/O6ZALB/N0sqZFEx7rq6EYPX2MkOdKORuooI/H5k9TlR4q7kQ==",
+ "requires": {
+ "fbjs": "0.8.16",
+ "loose-envify": "1.3.1",
+ "object-assign": "4.1.1"
+ }
+ }
+ }
+ },
"read-chunk": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/read-chunk/-/read-chunk-2.1.0.tgz",
diff --git a/package.json b/package.json
index 29d243e18..17e08a556 100644
--- a/package.json
+++ b/package.json
@@ -8,6 +8,7 @@
"react": "^16.3.1",
"react-dom": "^16.3.1",
"react-textarea-autosize": "^6.1.0",
+ "react-toastify": "^4.0.0-rc.2",
"semantic-ui-css": "2.2.14",
"semantic-ui-react": "^0.79.0"
},
diff --git a/public/assets/styles/main.scss b/public/assets/styles/main.scss
index fc25c9a6d..f43320e14 100644
--- a/public/assets/styles/main.scss
+++ b/public/assets/styles/main.scss
@@ -294,4 +294,8 @@ code {
font-size: 200%;
color: #3b4450;
}
+}
+
+.c-toast {
+ border-radius: 5px !important;
}
\ No newline at end of file
diff --git a/public/components/common/Header.tsx b/public/components/common/Header.tsx
index 07df4662f..5e406ee43 100644
--- a/public/components/common/Header.tsx
+++ b/public/components/common/Header.tsx
@@ -74,6 +74,8 @@ export class Header extends React.Component<HeaderProps, HeaderState> {
</div>
);
+ const showRightMenu = this.props.user || !this.props.tenant.isPrivate;
+
return (
<div className="c-header">
<EnvironmentInfo system={this.props.system} />
@@ -83,15 +85,17 @@ export class Header extends React.Component<HeaderProps, HeaderState> {
<a href="/" className="header item">
{this.props.tenant.name}
</a>
- <div
- onClick={() => this.showModal()}
- className={`ui right simple dropdown item signin ${!this.props.user && "subtitle"}`}
- >
- {this.props.user && <Gravatar user={this.props.user} />}
- {this.state.unreadNotifications > 0 && <div className="unread-dot" />}
- {!this.props.user && "Sign in"} {this.props.user && <i className="dropdown icon" />}
- {items}
- </div>
+ {showRightMenu && (
+ <div
+ onClick={() => this.showModal()}
+ className={`ui right simple dropdown item signin ${!this.props.user && "subtitle"}`}
+ >
+ {this.props.user && <Gravatar user={this.props.user} />}
+ {this.state.unreadNotifications > 0 && <div className="unread-dot" />}
+ {!this.props.user && "Sign in"} {this.props.user && <i className="dropdown icon" />}
+ {items}
+ </div>
+ )}
</div>
</div>
</div>
diff --git a/public/components/common/SignInControl.tsx b/public/components/common/SignInControl.tsx
index 2157046f6..78fe78e59 100644
--- a/public/components/common/SignInControl.tsx
+++ b/public/components/common/SignInControl.tsx
@@ -9,6 +9,7 @@ interface SignInControlState {
interface SignInControlProps {
useEmail: boolean;
+ redirectTo?: string;
onEmailSent?: (email: string) => void;
}
@@ -40,6 +41,7 @@ export class SignInControl extends React.Component<SignInControlProps, SignInCon
if (this.props.onEmailSent) {
this.props.onEmailSent(this.state.email);
}
+ this.setState({ email: "" });
} else if (result.error) {
this.form.setFailure(result.error);
}
@@ -48,17 +50,29 @@ export class SignInControl extends React.Component<SignInControlProps, SignInCon
public render() {
const google = this.settings.providers.google && (
<div className="column">
- <SocialSignInButton oauthEndpoint={this.settings.endpoint} provider="google" />
+ <SocialSignInButton
+ oauthEndpoint={this.settings.endpoint}
+ provider="google"
+ redirectTo={this.props.redirectTo}
+ />
</div>
);
const facebook = this.settings.providers.facebook && (
<div className="column">
- <SocialSignInButton oauthEndpoint={this.settings.endpoint} provider="facebook" />
+ <SocialSignInButton
+ oauthEndpoint={this.settings.endpoint}
+ provider="facebook"
+ redirectTo={this.props.redirectTo}
+ />
</div>
);
const github = this.settings.providers.github && (
<div className="column">
- <SocialSignInButton oauthEndpoint={this.settings.endpoint} provider="github" />
+ <SocialSignInButton
+ oauthEndpoint={this.settings.endpoint}
+ provider="github"
+ redirectTo={this.props.redirectTo}
+ />
</div>
);
const hasOAuth = !!(google || facebook || github);
@@ -87,6 +101,7 @@ export class SignInControl extends React.Component<SignInControlProps, SignInCon
>
<div id="email-signin" className="ui small action fluid input">
<input
+ value={this.state.email}
autoFocus={!device.isTouch()}
onChange={e => this.setState({ email: e.currentTarget.value })}
onKeyDown={this.onEmailKeyDown}
diff --git a/public/components/common/SocialSignInButton.tsx b/public/components/common/SocialSignInButton.tsx
index cf7c62066..26c9083d8 100644
--- a/public/components/common/SocialSignInButton.tsx
+++ b/public/components/common/SocialSignInButton.tsx
@@ -4,6 +4,7 @@ import { Button } from "@fider/components/common";
interface SocialSignInButtonProps {
oauthEndpoint: string;
provider: "google" | "facebook" | "github";
+ redirectTo?: string;
}
const providers = {
@@ -23,7 +24,8 @@ const providers = {
export class SocialSignInButton extends React.Component<SocialSignInButtonProps, {}> {
public render() {
- const href = `${this.props.oauthEndpoint}/oauth/${this.props.provider}?redirect=${location.href}`;
+ const redirectTo = this.props.redirectTo || location.href;
+ const href = `${this.props.oauthEndpoint}/oauth/${this.props.provider}?redirect=${redirectTo}`;
return (
<Button href={href} fluid={true} className={providers[this.props.provider].class}>
diff --git a/public/components/common/Toggle.scss b/public/components/common/Toggle.scss
index 75f6c94b8..bf97a4caf 100644
--- a/public/components/common/Toggle.scss
+++ b/public/components/common/Toggle.scss
@@ -3,6 +3,13 @@
.c-toggle {
cursor: pointer;
+ &.disabled {
+ cursor: not-allowed;
+ label {
+ cursor: not-allowed;
+ }
+ }
+
input {
display: none;
}
diff --git a/public/components/common/Toggle.tsx b/public/components/common/Toggle.tsx
index 9fd570bec..84c8dd096 100644
--- a/public/components/common/Toggle.tsx
+++ b/public/components/common/Toggle.tsx
@@ -4,6 +4,7 @@ import { classSet } from "@fider/services";
interface ToggleProps {
label?: string;
active: boolean;
+ disabled?: boolean;
onToggle: (active: boolean) => Promise<any>;
}
@@ -22,6 +23,10 @@ export class Toggle extends React.Component<ToggleProps, ToggleState> {
}
public toggle = async () => {
+ if (!!this.props.disabled) {
+ return;
+ }
+
this.setState(
state => ({
active: !state.active
@@ -33,8 +38,13 @@ export class Toggle extends React.Component<ToggleProps, ToggleState> {
};
public render() {
+ const className = classSet({
+ "c-toggle": true,
+ disabled: !!this.props.disabled
+ });
+
return (
- <span className="c-toggle" onClick={this.toggle}>
+ <span className={className} onClick={this.toggle}>
<input type="checkbox" checked={this.state.active} readOnly={true} />
<label>
<span className="switch" />
diff --git a/public/index.tsx b/public/index.tsx
index 75229538b..589ff4f99 100644
--- a/public/index.tsx
+++ b/public/index.tsx
@@ -3,6 +3,7 @@ import * as ReactDOM from "react-dom";
import { resolveRootComponent } from "@fider/router";
import { Header, Footer } from "@fider/components/common";
import { analytics } from "@fider/services";
+import { ToastContainer } from "react-toastify";
import "semantic-ui-css/components/reset.min.css";
import "semantic-ui-css/components/site.min.css";
@@ -25,6 +26,7 @@ import "semantic-ui-css/components/icon.min.css";
import "semantic-ui-css/components/message.min.css";
import "semantic-ui-css/components/menu.min.css";
import "semantic-ui-css/components/comment.min.css";
+import "react-toastify/dist/ReactToastify.css";
import "@fider/assets/styles/main.scss";
const w = window as any;
@@ -42,11 +44,12 @@ document.addEventListener("DOMContentLoaded", () => {
if (root) {
const config = resolveRootComponent(location.pathname);
ReactDOM.render(
- <div id={config.id}>
+ <>
+ <ToastContainer position="top-right" toastClassName="c-toast" />
{config.showHeader && React.createElement(Header, w.props)}
{React.createElement(config.component, w.props)}
{React.createElement(Footer, w.props)}
- </div>,
+ </>,
root
);
}
diff --git a/public/models/identity.ts b/public/models/identity.ts
index 9a1e5b9b1..6d6c0cc16 100644
--- a/public/models/identity.ts
+++ b/public/models/identity.ts
@@ -5,6 +5,7 @@ export interface Tenant {
subdomain: string;
invitation: string;
welcomeMessage: string;
+ isPrivate: boolean;
}
export interface User {
diff --git a/public/pages/Administration/components/AdminBasePage.tsx b/public/pages/Administration/components/AdminBasePage.tsx
index 38fd9bcab..85680a29a 100644
--- a/public/pages/Administration/components/AdminBasePage.tsx
+++ b/public/pages/Administration/components/AdminBasePage.tsx
@@ -2,6 +2,7 @@ import * as React from "react";
import { SideMenu } from "./";
export abstract class AdminBasePage<P, S> extends React.Component<P, S> {
+ public abstract id: string;
public abstract name: string;
public abstract icon: string;
public abstract title: string;
@@ -10,7 +11,7 @@ export abstract class AdminBasePage<P, S> extends React.Component<P, S> {
public render() {
return (
- <div className="page ui container">
+ <div id={this.id} className="page ui container">
<h2 className="ui header">
<i className={`circular ${this.icon} icon`} />
<div className="content">
diff --git a/public/pages/Administration/components/SideMenu.tsx b/public/pages/Administration/components/SideMenu.tsx
index 7ae9def30..a1ff1f1b2 100644
--- a/public/pages/Administration/components/SideMenu.tsx
+++ b/public/pages/Administration/components/SideMenu.tsx
@@ -38,8 +38,15 @@ export const SideMenu = (props: SiteMenuProps) => {
return (
<div className="ui vertical menu fluid">
<SideMenuItem name="general" title="General" href="/admin" isActive={activeItem === "general"} />
+ <SideMenuItem name="privacy" title="Privacy" href="/admin/privacy" isActive={activeItem === "privacy"} />
<SideMenuItem name="members" title="Members" href="/admin/members" isActive={activeItem === "members"} />
<SideMenuItem name="tags" title="Tags" href="/admin/tags" isActive={activeItem === "tags"} />
+ <SideMenuItem
+ name="invitations"
+ title="Invitations"
+ href="/admin/invitations"
+ isActive={activeItem === "invitations"}
+ />
</div>
);
};
diff --git a/public/pages/Administration/index.ts b/public/pages/Administration/index.ts
index d20f97aa4..60b442f2a 100644
--- a/public/pages/Administration/index.ts
+++ b/public/pages/Administration/index.ts
@@ -1,3 +1,5 @@
export * from "./pages/GeneralSettings.page";
+export * from "./pages/PrivacySettings.page";
export * from "./pages/ManageTags.page";
+export * from "./pages/Invitations.page";
export * from "./pages/ManageMembers.page";
diff --git a/public/pages/Administration/pages/GeneralSettings.page.tsx b/public/pages/Administration/pages/GeneralSettings.page.tsx
index e26da1934..82866b712 100644
--- a/public/pages/Administration/pages/GeneralSettings.page.tsx
+++ b/public/pages/Administration/pages/GeneralSettings.page.tsx
@@ -20,6 +20,7 @@ interface GeneralSettingsPageState {
}
export class GeneralSettingsPage extends AdminBasePage<GeneralSettingsPageProps, GeneralSettingsPageState> {
+ public id = "p-admin-general";
public name = "general";
public icon = "settings";
public title = "General";
diff --git a/public/pages/Administration/pages/Invitations.page.tsx b/public/pages/Administration/pages/Invitations.page.tsx
new file mode 100644
index 000000000..e9ec22dde
--- /dev/null
+++ b/public/pages/Administration/pages/Invitations.page.tsx
@@ -0,0 +1,168 @@
+import * as React from "react";
+
+import { SystemSettings, CurrentUser, Tenant } from "@fider/models";
+import { Button, ButtonClickEvent, Textarea, DisplayError } from "@fider/components/common";
+import { actions, page, notify, Failure } from "@fider/services";
+import { AdminBasePage } from "../components";
+
+interface InvitationsPageProps {
+ user: CurrentUser;
+ tenant: Tenant;
+}
+
+interface InvitationsPageState {
+ subject: string;
+ message: string;
+ recipients: string[];
+ numOfRecipients: number;
+ rawRecipients: string;
+ error?: Failure;
+}
+
+export class InvitationsPage extends AdminBasePage<InvitationsPageProps, InvitationsPageState> {
+ public id = "p-admin-invitations";
+ public name = "invitations";
+ public icon = "envelope";
+ public title = "Invitations";
+ public subtitle = "Invite people to share their feedback";
+
+ constructor(props: InvitationsPageProps) {
+ super(props);
+
+ this.state = {
+ subject: `Share your ideas and thoughts about ${this.props.tenant.name}`,
+ message: `Hi,
+
+At **${
+ this.props.tenant.name
+ }** we take feedback very seriously, which is why we've launched a space where you can vote, discuss and share your ideas and thoughts about our products and services.
+
+We'd like to extend an invite for you to join this community and raise awareness on topics you care about!
+
+To join, click on the link below.
+
+%invite%
+
+Regards,
+${this.props.user.name} (${this.props.tenant.name})`,
+ recipients: [],
+ numOfRecipients: 0,
+ rawRecipients: ""
+ };
+
+ page.setTitle(`Invitations · Site Settings · ${document.title}`);
+ }
+
+ private setRecipients = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
+ const rawRecipients = e.currentTarget.value;
+ const recipients = rawRecipients.split(/\n|;|,|\s/gm).filter(x => !!x);
+ this.setState({ rawRecipients, recipients, numOfRecipients: recipients.length });
+ };
+
+ private sendSample = async (e: ButtonClickEvent) => {
+ const result = await actions.sendSampleInvite(this.state.subject, this.state.message);
+ if (result.ok) {
+ notify.success(
+ <span>
+ An email message was sent to <strong>{this.props.user.email}</strong>
+ </span>
+ );
+ }
+ this.setState({ error: result.error });
+ };
+
+ private sendInvites = async (e: ButtonClickEvent) => {
+ const result = await actions.sendInvites(this.state.subject, this.state.message, this.state.recipients);
+ if (result.ok) {
+ notify.success("The invites have been sent.");
+ this.setState({ rawRecipients: "", numOfRecipients: 0, recipients: [], error: undefined });
+ } else {
+ this.setState({ error: result.error });
+ }
+ };
+
+ public content() {
+ return (
+ <div className="ui form">
+ <DisplayError fields={["recipients"]} error={this.state.error} />
+ <div className="field">
+ <label htmlFor="recipients">Send invitations to</label>
+ <Textarea
+ id="recipients"
+ rows={1}
+ value={this.state.rawRecipients}
+ minRows={1}
+ onChange={this.setRecipients}
+ />
+ <div className="info">
+ <p>
+ Input the list of all email addresses you wish to invite. Separate each address with either{" "}
+ <strong>semicolon</strong>, <strong>comma</strong>, <strong>whitespace</strong> or{" "}
+ <strong>line break</strong>.
+ </p>
+ <p>You can send this invite to a maximum of 30 recipients each time.</p>
+ </div>
+ </div>
+ <DisplayError fields={["subject"]} error={this.state.error} />
+ <div className="field">
+ <label htmlFor="subject">Subject</label>
+ <input
+ id="subject"
+ value={this.state.subject}
+ type="text"
+ maxLength={70}
+ onChange={e => this.setState({ subject: e.currentTarget.value })}
+ />
+ <p className="info">
+ This is the subject that will be used on the invitation email. Keep it short and sweet.
+ </p>
+ </div>
+ <DisplayError fields={["message"]} error={this.state.error} />
+ <div className="field">
+ <label htmlFor="message">Message</label>
+ <Textarea
+ id="message"
+ value={this.state.message}
+ rows={8}
+ minRows={8}
+ onChange={e => this.setState({ message: e.currentTarget.value })}
+ />
+ <div className="info">
+ <p>
+ This is the content of the invite. Be polite and explain what this invite is for, otherwise there's a high
+ change people will simply ignore your message.
+ </p>
+ <p>
+ You're allowed to write whatever you want as long as you include the invitation link placeholder named{" "}
+ <strong>%invite%</strong>.
+ </p>
+ </div>
+ </div>
+
+ <div className="ui tiny header">Sample Invite</div>
+
+ <div className="field">
+ <p className="info">
+ We highly recommend to send yourself a sample email for you to verify if everything is correct before
+ inviting your list of contacts.
+ </p>
+ {this.props.user.email ? (
+ <Button onClick={this.sendSample}>Send a sample email to {this.props.user.email}</Button>
+ ) : (
+ <Button disabled={true}>Your profile doesn't have an email</Button>
+ )}
+ </div>
+
+ <div className="ui tiny header">Confirmation</div>
+
+ <div className="field">
+ <p className="info">Whenever you're ready, click the following button to send out these invites.</p>
+ <Button onClick={this.sendInvites} color="green" disabled={this.state.numOfRecipients === 0}>
+ Send {this.state.numOfRecipients} {this.state.numOfRecipients === 1 ? "invite" : "invites"}
+ </Button>
+ </div>
+ </div>
+ );
+ }
+}
diff --git a/public/pages/Administration/pages/ManageMembers.page.tsx b/public/pages/Administration/pages/ManageMembers.page.tsx
index 9e9512b16..79f359aee 100644
--- a/public/pages/Administration/pages/ManageMembers.page.tsx
+++ b/public/pages/Administration/pages/ManageMembers.page.tsx
@@ -20,6 +20,7 @@ interface ManageMembersPageProps {
}
export class ManageMembersPage extends AdminBasePage<ManageMembersPageProps, ManageMembersPageState> {
+ public id = "p-admin-members";
public name = "members";
public icon = "users";
public title = "Members";
diff --git a/public/pages/Administration/pages/ManageTags.page.scss b/public/pages/Administration/pages/ManageTags.page.scss
deleted file mode 100644
index d5d7fd474..000000000
--- a/public/pages/Administration/pages/ManageTags.page.scss
+++ /dev/null
@@ -1,13 +0,0 @@
-#p-admin-tags {
- .ui.list {
- .item {
- .content {
- display: inline-block;
- line-height: 26px;
- }
- button.as-link {
- line-height: 26px;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/public/pages/Administration/pages/ManageTags.page.tsx b/public/pages/Administration/pages/ManageTags.page.tsx
index 02dd3dc6d..b0ed8125b 100644
--- a/public/pages/Administration/pages/ManageTags.page.tsx
+++ b/public/pages/Administration/pages/ManageTags.page.tsx
@@ -18,6 +18,7 @@ interface ManageTagsPageState {
}
export class ManageTagsPage extends AdminBasePage<ManageTagsPageProps, ManageTagsPageState> {
+ public id = "p-admin-tags";
public name = "tags";
public icon = "tags";
public title = "Tags";
diff --git a/public/pages/Administration/pages/PrivacySettings.page.scss b/public/pages/Administration/pages/PrivacySettings.page.scss
new file mode 100644
index 000000000..e06e1b806
--- /dev/null
+++ b/public/pages/Administration/pages/PrivacySettings.page.scss
@@ -0,0 +1,5 @@
+#p-admin-privacy {
+ label .c-toggle {
+ margin-left: 10px;
+ }
+}
\ No newline at end of file
diff --git a/public/pages/Administration/pages/PrivacySettings.page.tsx b/public/pages/Administration/pages/PrivacySettings.page.tsx
new file mode 100644
index 000000000..d886ddd68
--- /dev/null
+++ b/public/pages/Administration/pages/PrivacySettings.page.tsx
@@ -0,0 +1,66 @@
+import "./PrivacySettings.page.scss";
+
+import * as React from "react";
+
+import { SystemSettings, CurrentUser, Tenant } from "@fider/models";
+import { Button, ButtonClickEvent, Textarea, DisplayError, Toggle } from "@fider/components/common";
+import { actions, page, notify, Failure } from "@fider/services";
+import { AdminBasePage } from "../components";
+
+interface PrivacySettingsPageProps {
+ user: CurrentUser;
+ tenant: Tenant;
+}
+
+interface PrivacySettingsPageState {
+ isPrivate: boolean;
+}
+
+export class PrivacySettingsPage extends AdminBasePage<PrivacySettingsPageProps, PrivacySettingsPageState> {
+ public id = "p-admin-privacy";
+ public name = "privacy";
+ public icon = "key";
+ public title = "Privacy";
+ public subtitle = "Manage your site privacy";
+
+ constructor(props: PrivacySettingsPageProps) {
+ super(props);
+
+ this.state = {
+ isPrivate: this.props.tenant.isPrivate
+ };
+
+ page.setTitle(`Privacy · Site Settings · ${document.title}`);
+ }
+
+ private toggle = async (active: boolean) => {
+ this.setState(
+ state => ({
+ isPrivate: active
+ }),
+ async () => {
+ const response = await actions.updateTenantPrivacy(this.state.isPrivate);
+ if (response.ok) {
+ notify.success("Your privacy settings have been saved.");
+ }
+ }
+ );
+ };
+
+ public content() {
+ return (
+ <div className="ui form">
+ <div className="field">
+ <label htmlFor="private">
+ Private site
+ <Toggle disabled={!this.props.user.isAdministrator} active={this.state.isPrivate} onToggle={this.toggle} />
+ </label>
+ <p className="info">
+ A private site prevents unauthenticated users from viewing or interacting with its content. <br /> If
+ enabled, only already registered and invited users will be able to sign in to this site.
+ </p>
+ </div>
+ </div>
+ );
+ }
+}
diff --git a/public/pages/CompleteSignInProfile/CompleteSignInProfile.page.tsx b/public/pages/CompleteSignInProfile/CompleteSignInProfile.page.tsx
index 1b6f8fb2e..7e5f3ba91 100644
--- a/public/pages/CompleteSignInProfile/CompleteSignInProfile.page.tsx
+++ b/public/pages/CompleteSignInProfile/CompleteSignInProfile.page.tsx
@@ -1,6 +1,6 @@
import * as React from "react";
-import { HomePage, HomePageProps } from "../";
+import { HomePage, HomePageProps, SignInPage } from "../";
import { Modal, Form, Button } from "@fider/components/common";
import { page, actions } from "@fider/services";
@@ -56,7 +56,9 @@ export class CompleteSignInProfilePage extends React.Component<HomePageProps, Co
</Form>
</Modal.Content>
</Modal.Window>
- {React.createElement(HomePage, this.props)}
+ {this.props.tenant.isPrivate
+ ? React.createElement(SignInPage, this.props)
+ : React.createElement(HomePage, this.props)}
</>
);
}
diff --git a/public/pages/Home/Home.page.tsx b/public/pages/Home/Home.page.tsx
index bd36baaa4..ec274d49a 100644
--- a/public/pages/Home/Home.page.tsx
+++ b/public/pages/Home/Home.page.tsx
@@ -43,7 +43,7 @@ export class HomePage extends React.Component<HomePageProps, HomePageState> {
public render() {
return (
- <div className="page ui container">
+ <div id="p-home" className="page ui container">
<div className="ui grid stackable">
<div className="six wide column">
<MultiLineText
diff --git a/public/pages/MyNotifications/MyNotifications.page.tsx b/public/pages/MyNotifications/MyNotifications.page.tsx
index fd61b9268..a210ed992 100644
--- a/public/pages/MyNotifications/MyNotifications.page.tsx
+++ b/public/pages/MyNotifications/MyNotifications.page.tsx
@@ -57,7 +57,7 @@ export class MyNotificationsPage extends React.Component<MyNotificationsPageProp
public render() {
return (
- <div className="page ui container">
+ <div id="p-my-notifications" className="page ui container">
<h2 className="ui header">
<i className="circular id bell icon" />
<div className="content">
diff --git a/public/pages/MySettings/MySettings.page.tsx b/public/pages/MySettings/MySettings.page.tsx
index 18d8952ae..6e41482de 100644
--- a/public/pages/MySettings/MySettings.page.tsx
+++ b/public/pages/MySettings/MySettings.page.tsx
@@ -58,7 +58,7 @@ export class MySettingsPage extends React.Component<MySettingsPageProps, MySetti
public render() {
return (
- <div className="page ui container">
+ <div id="p-my-settings" className="page ui container">
<Modal.Window isOpen={this.state.showModal} canClose={true} center={true}>
<Modal.Header>Confirm your new email</Modal.Header>
<Modal.Content>
diff --git a/public/pages/ShowIdea/ShowIdea.page.scss b/public/pages/ShowIdea/ShowIdea.page.scss
index 237263294..3fd7105bd 100644
--- a/public/pages/ShowIdea/ShowIdea.page.scss
+++ b/public/pages/ShowIdea/ShowIdea.page.scss
@@ -1,6 +1,11 @@
@import '~@fider/assets/styles/variables.scss';
#p-show-idea {
+
+ .subtitle {
+ margin-top: 1em;
+ }
+
.idea-header {
width: 100%;
h1 {
@@ -12,12 +17,6 @@
height: 24px;
}
}
-
- .page {
- .subtitle {
- margin-top: 1em;
- }
- }
@include tablet {
.header-col,
diff --git a/public/pages/ShowIdea/ShowIdea.page.tsx b/public/pages/ShowIdea/ShowIdea.page.tsx
index a9463cb6e..a63ba6f8e 100644
--- a/public/pages/ShowIdea/ShowIdea.page.tsx
+++ b/public/pages/ShowIdea/ShowIdea.page.tsx
@@ -65,7 +65,7 @@ export class ShowIdeaPage extends React.Component<ShowIdeaPageProps, ShowIdeaPag
public render() {
return (
- <div className="page ui container">
+ <div id="p-show-idea" className="page ui container">
<div className="header-col">
<div className="ui items unstackable">
<div className="item">
diff --git a/public/pages/SignIn/SignIn.page.scss b/public/pages/SignIn/SignIn.page.scss
new file mode 100644
index 000000000..4589a6360
--- /dev/null
+++ b/public/pages/SignIn/SignIn.page.scss
@@ -0,0 +1,16 @@
+@import '~@fider/assets/styles/variables.scss';
+
+#p-signin {
+ margin-top: 50px;
+ max-width: 500px !important;
+
+ .message {
+ max-width: 300px;
+ text-align: center;
+ margin: 0 auto;
+ margin-bottom: 20px;
+ .welcome {
+ font-size: $font-size-big;
+ }
+ }
+}
\ No newline at end of file
diff --git a/public/pages/SignIn/SignIn.page.tsx b/public/pages/SignIn/SignIn.page.tsx
new file mode 100644
index 000000000..83fb4601c
--- /dev/null
+++ b/public/pages/SignIn/SignIn.page.tsx
@@ -0,0 +1,41 @@
+import "./SignIn.page.scss";
+
+import * as React from "react";
+import { SignInControl } from "@fider/components/common";
+import { page, notify } from "@fider/services";
+import { Tenant } from "@fider/models";
+
+interface SignInPageProps {
+ tenant: Tenant;
+}
+
+export class SignInPage extends React.Component<SignInPageProps, {}> {
+ constructor(props: SignInPageProps) {
+ super(props);
+ this.state = {};
+
+ page.setTitle(`Sign in · ${document.title}`);
+ }
+
+ private onEmailSent = (email: string) => {
+ notify.success(
+ <span>
+ We have just sent a confirmation link to <b>{email}</b>. Click the link and you’ll be signed in.
+ </span>
+ );
+ };
+
+ public render() {
+ return (
+ <div id="p-signin" className="page ui container">
+ <div className="message">
+ <p className="welcome">
+ <strong>{this.props.tenant.name}</strong> is a private space and requires an invitation to join it.
+ </p>
+ <p>If you have an account or an invitation, you may use following options to sign in.</p>
+ </div>
+ <SignInControl onEmailSent={this.onEmailSent} useEmail={true} redirectTo={page.getBaseUrl()} />
+ </div>
+ );
+ }
+}
diff --git a/public/pages/SignIn/index.ts b/public/pages/SignIn/index.ts
new file mode 100644
index 000000000..3c59e2054
--- /dev/null
+++ b/public/pages/SignIn/index.ts
@@ -0,0 +1 @@
+export * from "./SignIn.page";
diff --git a/public/pages/SignUp/SignUp.page.scss b/public/pages/SignUp/SignUp.page.scss
index 0601634e2..d3e450792 100644
--- a/public/pages/SignUp/SignUp.page.scss
+++ b/public/pages/SignUp/SignUp.page.scss
@@ -1,8 +1,6 @@
#p-signup {
- .page {
- margin-top: 50px;
- max-width: 500px !important;
- }
+ margin-top: 50px;
+ max-width: 500px !important;
.fdr-avatar {
margin-right: 5px;
diff --git a/public/pages/SignUp/SignUp.page.tsx b/public/pages/SignUp/SignUp.page.tsx
index 1fe79d2b7..8c66f8351 100644
--- a/public/pages/SignUp/SignUp.page.tsx
+++ b/public/pages/SignUp/SignUp.page.tsx
@@ -111,7 +111,7 @@ export class SignUpPage extends React.Component<SignUpPageProps, SignUpPageState
);
return (
- <div className="page ui container">
+ <div id="p-signup" className="page ui container">
{modal}
<img className="logo" src={logo} />
diff --git a/public/pages/index.ts b/public/pages/index.ts
index 37603a26d..46c828e57 100644
--- a/public/pages/index.ts
+++ b/public/pages/index.ts
@@ -1,5 +1,6 @@
export * from "./Home";
export * from "./Administration";
+export * from "./SignIn";
export * from "./SignUp";
export * from "./CompleteSignInProfile";
export * from "./MySettings";
diff --git a/public/router.tsx b/public/router.tsx
index 6fb16403c..a6fdcac9a 100644
--- a/public/router.tsx
+++ b/public/router.tsx
@@ -2,9 +2,12 @@ import * as React from "react";
import {
HomePage,
+ SignInPage,
SignUpPage,
ManageMembersPage,
CompleteSignInProfilePage,
+ PrivacySettingsPage,
+ InvitationsPage,
GeneralSettingsPage,
ManageTagsPage,
ShowIdeaPage,
@@ -13,32 +16,35 @@ import {
} from "@fider/pages";
interface PageConfiguration {
- id: string;
regex: RegExp;
component: any;
showHeader: boolean;
}
-const route = (path: string, component: any, id: string, showHeader: boolean): PageConfiguration => {
+const route = (path: string, component: any, showHeader: boolean = true): PageConfiguration => {
path = path
.replace("/", "/")
.replace(":number", "\\d+")
.replace("*", "/?.*");
const regex = new RegExp(`^${path}$`);
- return { regex, component, id, showHeader };
+ return { regex, component, showHeader };
};
const pathRegex = [
- route("", HomePage, "p-home", true),
- route("/ideas/:number*", ShowIdeaPage, "p-show-idea", true),
- route("/admin/members", ManageMembersPage, "p-admin-members", true),
- route("/admin/tags", ManageTagsPage, "p-admin-tags", true),
- route("/admin", GeneralSettingsPage, "p-admin-general", true),
- route("/signup", SignUpPage, "p-signup", false),
- route("/signin/verify", CompleteSignInProfilePage, "p-complete-signin-profile", true),
- route("/notifications", MyNotificationsPage, "p-my-notifications", true),
- route("/settings", MySettingsPage, "p-my-settings", true)
+ route("", HomePage),
+ route("/ideas/:number*", ShowIdeaPage),
+ route("/admin/members", ManageMembersPage),
+ route("/admin/tags", ManageTagsPage),
+ route("/admin/privacy", PrivacySettingsPage),
+ route("/admin/invitations", InvitationsPage),
+ route("/admin", GeneralSettingsPage),
+ route("/signin", SignInPage),
+ route("/signup", SignUpPage, false),
+ route("/signin/verify", CompleteSignInProfilePage),
+ route("/invite/verify", CompleteSignInProfilePage),
+ route("/notifications", MyNotificationsPage),
+ route("/settings", MySettingsPage)
];
export const resolveRootComponent = (path: string): PageConfiguration => {
diff --git a/public/services/actions/index.ts b/public/services/actions/index.ts
index 850ba750f..5a997c828 100644
--- a/public/services/actions/index.ts
+++ b/public/services/actions/index.ts
@@ -3,4 +3,5 @@ export * from "./tag";
export * from "./idea";
export * from "./tenant";
export * from "./notification";
+export * from "./invite";
export { Failure } from "@fider/services/http";
diff --git a/public/services/actions/invite.ts b/public/services/actions/invite.ts
new file mode 100644
index 000000000..dcec9b046
--- /dev/null
+++ b/public/services/actions/invite.ts
@@ -0,0 +1,9 @@
+import { http, Result } from "@fider/services";
+
+export const sendInvites = async (subject: string, message: string, recipients: string[]): Promise<Result> => {
+ return http.post("/api/admin/invitations/send", { subject, message, recipients }).then(http.event("invite", "send"));
+};
+
+export const sendSampleInvite = async (subject: string, message: string): Promise<Result> => {
+ return http.post("/api/admin/invitations/sample", { subject, message }).then(http.event("invite", "sample"));
+};
diff --git a/public/services/actions/tenant.ts b/public/services/actions/tenant.ts
index 09b36f599..38ac5daf7 100644
--- a/public/services/actions/tenant.ts
+++ b/public/services/actions/tenant.ts
@@ -27,7 +27,7 @@ export const updateTenantSettings = async (
welcomeMessage: string,
cname: string
): Promise<Result> => {
- return await http.post("/api/admin/settings", {
+ return await http.post("/api/admin/settings/general", {
title,
invitation,
welcomeMessage,
@@ -35,6 +35,12 @@ export const updateTenantSettings = async (
});
};
+export const updateTenantPrivacy = async (isPrivate: boolean): Promise<Result> => {
+ return await http.post("/api/admin/settings/privacy", {
+ isPrivate
+ });
+};
+
export const checkAvailability = async (subdomain: string): Promise<Result<CheckAvailabilityResponse>> => {
return await http.get<CheckAvailabilityResponse>(`/api/tenants/${subdomain}/availability`);
};
diff --git a/public/services/index.ts b/public/services/index.ts
index 4fa482b0e..3cb84878f 100644
--- a/public/services/index.ts
+++ b/public/services/index.ts
@@ -3,7 +3,8 @@ export * from "./cache";
export * from "./analytics";
export * from "./jwt";
export * from "./utils";
+import * as notify from "./notify";
import * as device from "./device";
import * as page from "./page";
import * as actions from "./actions";
-export { actions, page, device };
+export { actions, page, device, notify };
diff --git a/public/services/notify.ts b/public/services/notify.ts
new file mode 100644
index 000000000..946fda020
--- /dev/null
+++ b/public/services/notify.ts
@@ -0,0 +1,9 @@
+import { toast } from "react-toastify";
+
+export const success = (message: string | JSX.Element) => {
+ toast.success(message);
+};
+
+export const error = (message: string | JSX.Element) => {
+ toast.error(message);
+};
diff --git a/routes.go b/routes.go
index 5ffdd0e65..b4a3d9694 100644
--- a/routes.go
+++ b/routes.go
@@ -34,11 +34,11 @@ func GetMainEngine(settings *models.SystemSettings) *web.Engine {
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", handlers.SignInByOAuth(oauth.FacebookProvider))
noTenant.Get("/oauth/facebook/callback", handlers.OAuthCallback(oauth.FacebookProvider))
- noTenant.Get("/oauth/google", handlers.SignIn(oauth.GoogleProvider))
+ noTenant.Get("/oauth/google", handlers.SignInByOAuth(oauth.GoogleProvider))
noTenant.Get("/oauth/google/callback", handlers.OAuthCallback(oauth.GoogleProvider))
- noTenant.Get("/oauth/github", handlers.SignIn(oauth.GitHubProvider))
+ noTenant.Get("/oauth/github", handlers.SignInByOAuth(oauth.GitHubProvider))
noTenant.Get("/oauth/github/callback", handlers.OAuthCallback(oauth.GitHubProvider))
}
@@ -50,16 +50,25 @@ func GetMainEngine(settings *models.SystemSettings) *web.Engine {
avatar.Get("/avatars/:size/:id/:name", handlers.Avatar())
}
- verify := r.Group()
+ open := r.Group()
{
- verify.Get("/signup/verify", handlers.VerifySignUpKey())
+ open.Get("/signup/verify", handlers.VerifySignUpKey())
+ open.Use(middlewares.OnlyActiveTenants())
+ open.Get("/signin", handlers.SignInPage())
+ open.Get("/not-invited", handlers.NotInvitedPage())
+ open.Get("/signin/verify", handlers.VerifySignInKey(models.EmailVerificationKindSignIn))
+ open.Get("/invite/verify", handlers.VerifySignInKey(models.EmailVerificationKindUserInvitation))
+ open.Post("/api/signin/complete", handlers.CompleteSignInProfile())
+ open.Post("/api/signin", handlers.SignInByEmail())
}
+ r.Use(middlewares.JwtGetter())
+ r.Use(middlewares.JwtSetter())
+
page := r.Group()
{
- page.Use(middlewares.JwtGetter())
- page.Use(middlewares.JwtSetter())
page.Use(middlewares.OnlyActiveTenants())
+ page.Use(middlewares.CheckTenantPrivacy())
public := page.Group()
{
@@ -68,10 +77,7 @@ func GetMainEngine(settings *models.SystemSettings) *web.Engine {
public.Get("/ideas/:number", handlers.IdeaDetails())
public.Get("/ideas/:number/*all", handlers.IdeaDetails())
public.Get("/signout", handlers.SignOut())
- public.Get("/signin/verify", handlers.VerifySignInKey(models.EmailVerificationKindSignIn))
public.Get("/api/status", handlers.Status(settings))
- public.Post("/api/signin/complete", handlers.CompleteSignInProfile())
- public.Post("/api/signin", handlers.SignInByEmail())
}
private := page.Group()
@@ -98,25 +104,26 @@ func GetMainEngine(settings *models.SystemSettings) *web.Engine {
private.Post("/api/notifications/read-all", handlers.ReadAllNotifications())
private.Get("/api/notifications/unread/total", handlers.TotalUnreadNotifications())
+ private.Use(middlewares.IsAuthorized(models.RoleCollaborator, models.RoleAdministrator))
+
+ private.Get("/admin", handlers.Page())
+ private.Get("/admin/privacy", handlers.Page())
+ private.Get("/admin/invitations", handlers.Page())
+ private.Get("/admin/members", handlers.ManageMembers())
+ private.Get("/admin/tags", handlers.ManageTags())
+ private.Post("/api/admin/invitations/send", handlers.SendInvites())
+ private.Post("/api/admin/invitations/sample", handlers.SendSampleInvite())
+
private.Use(middlewares.IsAuthorized(models.RoleAdministrator))
private.Delete("/api/ideas/:number", handlers.DeleteIdea())
- private.Post("/api/admin/settings", handlers.UpdateSettings())
+ private.Post("/api/admin/settings/general", handlers.UpdateSettings())
+ private.Post("/api/admin/settings/privacy", handlers.UpdatePrivacy())
private.Delete("/api/admin/tags/:slug", handlers.DeleteTag())
private.Post("/api/admin/tags/:slug", handlers.CreateEditTag())
private.Post("/api/admin/tags", handlers.CreateEditTag())
private.Post("/api/admin/users/:user_id/role", handlers.ChangeUserRole())
}
-
- admin := page.Group()
- {
- admin.Use(middlewares.IsAuthenticated())
- admin.Use(middlewares.IsAuthorized(models.RoleCollaborator, models.RoleAdministrator))
-
- admin.Get("/admin", handlers.Page())
- admin.Get("/admin/members", handlers.ManageMembers())
- admin.Get("/admin/tags", handlers.ManageTags())
- }
}
return r
diff --git a/views/403.html b/views/403.html
index bf09d4de0..70b84069e 100644
--- a/views/403.html
+++ b/views/403.html
@@ -14,7 +14,7 @@ Not Authorized &middot; Fider
</p>
{{ if .tenant }}
- <span>Take me back to <a href="{{ .baseURL }}">{{ .tenant.Subdomain }}.fider.io</a> home page.</span>
+ <span>Take me back to <a href="{{ .baseURL }}">{{ .baseURL }}</a> home page.</span>
{{ end }}
</div>
</div>
diff --git a/views/404.html b/views/404.html
index 48c9e0bb5..420cc5c2a 100644
--- a/views/404.html
+++ b/views/404.html
@@ -15,7 +15,7 @@
</p>
{{ if .tenant }}
- <span>Take me back to <a href="{{ .baseURL }}">{{ .tenant.Subdomain }}.fider.io</a> home page.</span>
+ <span>Take me back to <a href="{{ .baseURL }}">{{ .baseURL }}</a> home page.</span>
{{ end }}
</div>
</div>
diff --git a/views/410.html b/views/410.html
index 9f467c722..51da3a8fd 100644
--- a/views/410.html
+++ b/views/410.html
@@ -12,7 +12,7 @@
<p>The link you clicked has expired.</p>
{{ if .tenant }}
- <span>Take me back to <a href="{{ .baseURL }}">{{ .tenant.Subdomain }}.fider.io</a> home page.</span>
+ <span>Take me back to <a href="{{ .baseURL }}">{{ .baseURL }}</a> home page.</span>
{{ end }}
</div>
</div>
diff --git a/views/500.html b/views/500.html
index 7e14e0fa9..28c4760d9 100644
--- a/views/500.html
+++ b/views/500.html
@@ -12,7 +12,7 @@
<p>An error has occurred and we're working to fix the problem! </br> We’ll be up and running shortly.</p>
{{ if .tenant }}
- <span>Take me back to <a href="{{ .baseURL }}">{{ .tenant.Subdomain }}.fider.io</a> home page.</span>
+ <span>Take me back to <a href="{{ .baseURL }}">{{ .baseURL }}</a> home page.</span>
{{ end }}
</div>
</div>
diff --git a/views/not-invited.html b/views/not-invited.html
new file mode 100644
index 000000000..a330c2b8d
--- /dev/null
+++ b/views/not-invited.html
@@ -0,0 +1,21 @@
+{{define "title"}}
+Not Invited &middot; Fider
+{{end}}
+
+{{define "javascript"}}{{end}}
+
+{{define "content"}}
+<div class="ui middle aligned center aligned grid failure-page">
+ <div class="column">
+ <img src="https://getfider.com/images/logo-100x100.png"/>
+ <h1>NOT INVITED</h1>
+ <p>
+ We couldn't find your account for your email address.
+ </p>
+
+ {{ if .tenant }}
+ <span>Take me back to <a href="{{ .baseURL }}/signin">{{ .baseURL }}/signin</a>.</span>
+ {{ end }}
+ </div>
+</div>
+{{end}}
\ No newline at end of file
diff --git a/views/templates/invite_email.tpl b/views/templates/invite_email.tpl
new file mode 100644
index 000000000..ff0a893a7
--- /dev/null
+++ b/views/templates/invite_email.tpl
@@ -0,0 +1,3 @@
+subject: {{ .subject }}
+body:
+{{ .message }}
\ No newline at end of file