Open platform to collect and prioritize feedback
Add change email endpoint (#247)
Guilherme Oenning79a2674350fb
diff --git a/app/actions/actions.go b/app/actions/actions.goindex 7b203f98b..8f3cbf423 100644--- a/app/actions/actions.go+++ b/app/actions/actions.go@@ -9,6 +9,6 @@ import (// Actionable is any action that the user can perform using the web apptype Actionable interface {Initialize() interface{}- Validate(services *app.Services) *validate.Result+ Validate(user *models.User, services *app.Services) *validate.ResultIsAuthorized(user *models.User) bool}diff --git a/app/actions/idea.go b/app/actions/idea.goindex 3e1307e77..419ff15c9 100644--- a/app/actions/idea.go+++ b/app/actions/idea.go@@ -27,7 +27,7 @@ func (input *CreateNewIdea) IsAuthorized(user *models.User) bool {}// Validate is current model is valid-func (input *CreateNewIdea) Validate(services *app.Services) *validate.Result {+func (input *CreateNewIdea) Validate(user *models.User, services *app.Services) *validate.Result {result := validate.Success()if input.Model.Title == "" {@@ -69,7 +69,7 @@ func (input *UpdateIdea) IsAuthorized(user *models.User) bool {}// Validate is current model is valid-func (input *UpdateIdea) Validate(services *app.Services) *validate.Result {+func (input *UpdateIdea) Validate(user *models.User, services *app.Services) *validate.Result {result := validate.Success()idea, err := services.Ideas.GetByNumber(input.Model.Number)@@ -116,7 +116,7 @@ func (input *AddNewComment) IsAuthorized(user *models.User) bool {}// Validate is current model is valid-func (input *AddNewComment) Validate(services *app.Services) *validate.Result {+func (input *AddNewComment) Validate(user *models.User, services *app.Services) *validate.Result {result := validate.Success()if input.Model.Content == "" {@@ -144,7 +144,7 @@ func (input *SetResponse) IsAuthorized(user *models.User) bool {}// Validate is current model is valid-func (input *SetResponse) Validate(services *app.Services) *validate.Result {+func (input *SetResponse) Validate(user *models.User, services *app.Services) *validate.Result {result := validate.Success()if input.Model.Status < models.IdeaOpen || input.Model.Status > models.IdeaDuplicate {diff --git a/app/actions/idea_test.go b/app/actions/idea_test.goindex 481c83fbd..adc9960f2 100644--- a/app/actions/idea_test.go+++ b/app/actions/idea_test.go@@ -28,7 +28,7 @@ func TestCreateNewIdea_InvalidIdeaTitles(t *testing.T) {"my GREAT idea",} {action := &actions.CreateNewIdea{Model: &models.NewIdea{Title: title}}- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectFailed(result, "title")}}@@ -41,7 +41,7 @@ func TestCreateNewIdea_ValidIdeaTitles(t *testing.T) {"this idea is very descriptive",} {action := &actions.CreateNewIdea{Model: &models.NewIdea{Title: title}}- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectSuccess(result)}}diff --git a/app/actions/settings.go b/app/actions/settings.goindex d0dd42df4..a0e1dd8a0 100644--- a/app/actions/settings.go+++ b/app/actions/settings.go@@ -23,7 +23,7 @@ func (input *UpdateUserSettings) IsAuthorized(user *models.User) bool {}// Validate is current model is valid-func (input *UpdateUserSettings) Validate(services *app.Services) *validate.Result {+func (input *UpdateUserSettings) Validate(user *models.User, services *app.Services) *validate.Result {result := validate.Success()if input.Model.Name == "" {diff --git a/app/actions/settings_test.go b/app/actions/settings_test.goindex 17bfdebda..215158507 100644--- a/app/actions/settings_test.go+++ b/app/actions/settings_test.go@@ -17,7 +17,7 @@ func TestInvalidUserNames(t *testing.T) {"123456789012345678901234567890123456789012345678901", // 51 chars} {action := &actions.UpdateUserSettings{Model: &models.UpdateUserSettings{Name: name}}- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectFailed(result, "name")}}@@ -30,7 +30,7 @@ func TestValidUserNames(t *testing.T) {"Arya",} {action := &actions.UpdateUserSettings{Model: &models.UpdateUserSettings{Name: name}}- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectSuccess(result)}}diff --git a/app/actions/signin.go b/app/actions/signin.goindex 38ad8f326..2d8b397ae 100644--- a/app/actions/signin.go+++ b/app/actions/signin.go@@ -27,7 +27,7 @@ func (input *SignInByEmail) IsAuthorized(user *models.User) bool {}// Validate is current model is valid-func (input *SignInByEmail) Validate(services *app.Services) *validate.Result {+func (input *SignInByEmail) Validate(user *models.User, services *app.Services) *validate.Result {result := validate.Success()if input.Model.Email == "" {@@ -64,7 +64,7 @@ func (input *CompleteProfile) IsAuthorized(user *models.User) bool {}// Validate is current model is valid-func (input *CompleteProfile) Validate(services *app.Services) *validate.Result {+func (input *CompleteProfile) Validate(user *models.User, services *app.Services) *validate.Result {result := validate.Success()if input.Model.Name == "" {diff --git a/app/actions/signin_test.go b/app/actions/signin_test.goindex 60ec2d35f..9cd722a93 100644--- a/app/actions/signin_test.go+++ b/app/actions/signin_test.go@@ -14,7 +14,7 @@ func TestSignInByEmail_EmptyEmail(t *testing.T) {RegisterTestingT(t)action := actions.SignInByEmail{Model: &models.SignInByEmail{Email: " "}}- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectFailed(result, "email")}@@ -22,7 +22,7 @@ func TestSignInByEmail_InvalidEmail(t *testing.T) {RegisterTestingT(t)action := actions.SignInByEmail{Model: &models.SignInByEmail{Email: "Hi :)"}}- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectFailed(result, "email")}@@ -33,7 +33,7 @@ func TestSignInByEmail_ShouldHaveVerificationKey(t *testing.T) {action.Initialize()action.Model.Email = "[email protected]"- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectSuccess(result)Expect(action.Model.VerificationKey).NotTo(Equal(""))}@@ -42,7 +42,7 @@ func TestCompleteProfile_EmptyNameAndKey(t *testing.T) {RegisterTestingT(t)action := actions.CompleteProfile{Model: &models.CompleteProfile{}}- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectFailed(result, "name", "key")}@@ -52,14 +52,14 @@ func TestCompleteProfile_LongName(t *testing.T) {action := actions.CompleteProfile{Model: &models.CompleteProfile{Name: "123456789012345678901234567890123456789012345678901", // 51 chars}}- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectFailed(result, "name", "key")}func TestCompleteProfile_UnknownKey(t *testing.T) {RegisterTestingT(t)action := actions.CompleteProfile{Model: &models.CompleteProfile{Name: "Jon Snow", Key: "1234567890"}}- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectFailed(result, "key")}@@ -68,7 +68,7 @@ func TestCompleteProfile_ValidKey(t *testing.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(services)+ result := action.Validate(nil, services)ExpectSuccess(result)Expect(action.Model.Email).To(Equal("[email protected]"))}diff --git a/app/actions/tag.go b/app/actions/tag.goindex 63eb6a555..991834e89 100644--- a/app/actions/tag.go+++ b/app/actions/tag.go@@ -29,7 +29,7 @@ func (input *CreateEditTag) IsAuthorized(user *models.User) bool {}// Validate is current model is valid-func (input *CreateEditTag) Validate(services *app.Services) *validate.Result {+func (input *CreateEditTag) Validate(user *models.User, services *app.Services) *validate.Result {result := validate.Success()if input.Model.Slug != "" {tag, err := services.Tags.GetBySlug(input.Model.Slug)@@ -81,7 +81,7 @@ func (input *DeleteTag) IsAuthorized(user *models.User) bool {}// Validate is current model is valid-func (input *DeleteTag) Validate(services *app.Services) *validate.Result {+func (input *DeleteTag) Validate(user *models.User, services *app.Services) *validate.Result {tag, err := services.Tags.GetBySlug(input.Model.Slug)if err != nil {return validate.Error(err)@@ -110,7 +110,7 @@ func (input *AssignUnassignTag) IsAuthorized(user *models.User) bool {}// Validate is current model is valid-func (input *AssignUnassignTag) Validate(services *app.Services) *validate.Result {+func (input *AssignUnassignTag) Validate(user *models.User, services *app.Services) *validate.Result {idea, err := services.Ideas.GetByNumber(input.Model.Number)if err != nil {return validate.Error(err)diff --git a/app/actions/tenant.go b/app/actions/tenant.goindex cc1211e67..d14c567cf 100644--- a/app/actions/tenant.go+++ b/app/actions/tenant.go@@ -29,7 +29,7 @@ func (input *CreateTenant) IsAuthorized(user *models.User) bool {}// Validate is current model is valid-func (input *CreateTenant) Validate(services *app.Services) *validate.Result {+func (input *CreateTenant) Validate(user *models.User, services *app.Services) *validate.Result {result := validate.Success()var err error@@ -91,7 +91,7 @@ func (input *UpdateTenantSettings) IsAuthorized(user *models.User) bool {}// Validate is current model is valid-func (input *UpdateTenantSettings) Validate(services *app.Services) *validate.Result {+func (input *UpdateTenantSettings) Validate(user *models.User, services *app.Services) *validate.Result {result := validate.Success()if input.Model.Title == "" {diff --git a/app/actions/tenant_test.go b/app/actions/tenant_test.goindex 1f34df7d0..6f0837851 100644--- a/app/actions/tenant_test.go+++ b/app/actions/tenant_test.go@@ -22,7 +22,7 @@ func TestCreateTenant_EmptyToken(t *testing.T) {RegisterTestingT(t)action := actions.CreateTenant{Model: &models.CreateTenant{Token: ""}}- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectFailed(result, "token", "tenantName", "subdomain")}@@ -30,7 +30,7 @@ func TestCreateTenant_EmptyTenantName(t *testing.T) {RegisterTestingT(t)action := actions.CreateTenant{Model: &models.CreateTenant{Token: jonSnowToken, TenantName: ""}}- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectFailed(result, "tenantName", "subdomain")}@@ -38,7 +38,7 @@ func TestCreateTenant_EmptyEmail(t *testing.T) {RegisterTestingT(t)action := actions.CreateTenant{Model: &models.CreateTenant{Name: "Jon Snow", Email: ""}}- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectFailed(result, "email", "tenantName", "subdomain")}@@ -46,7 +46,7 @@ func TestCreateTenant_InvalidEmail(t *testing.T) {RegisterTestingT(t)action := actions.CreateTenant{Model: &models.CreateTenant{Name: "Jon Snow", Email: "jonsnow"}}- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectFailed(result, "email", "tenantName", "subdomain")}@@ -54,7 +54,7 @@ func TestCreateTenant_EmptyName(t *testing.T) {RegisterTestingT(t)action := actions.CreateTenant{Model: &models.CreateTenant{Name: "", Email: "[email protected]"}}- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectFailed(result, "name", "tenantName", "subdomain")}@@ -62,7 +62,7 @@ func TestCreateTenant_EmptySubdomain(t *testing.T) {RegisterTestingT(t)action := actions.CreateTenant{Model: &models.CreateTenant{Token: jonSnowToken, TenantName: "My Company"}}- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectFailed(result, "subdomain")}func TestUpdateTenantSettings_Unauthorized(t *testing.T) {@@ -83,7 +83,7 @@ func TestUpdateTenantSettings_EmptyTitle(t *testing.T) {RegisterTestingT(t)action := actions.UpdateTenantSettings{Model: &models.UpdateTenantSettings{}}- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectFailed(result, "title")}@@ -91,7 +91,7 @@ func TestUpdateTenantSettings_InvalidCNAME(t *testing.T) {RegisterTestingT(t)action := actions.UpdateTenantSettings{Model: &models.UpdateTenantSettings{Title: "Ok", CNAME: "bla"}}- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectFailed(result, "cname")}@@ -99,7 +99,7 @@ func TestUpdateTenantSettings_LargeTitle(t *testing.T) {RegisterTestingT(t)action := actions.UpdateTenantSettings{Model: &models.UpdateTenantSettings{Title: "123456789012345678901234567890123456789012345678901234567890123"}}- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectFailed(result, "title")}@@ -107,6 +107,6 @@ func TestUpdateTenantSettings_LargeInvitation(t *testing.T) {RegisterTestingT(t)action := actions.UpdateTenantSettings{Model: &models.UpdateTenantSettings{Title: "Ok", Invitation: "123456789012345678901234567890123456789012345678901234567890123"}}- result := action.Validate(services)+ result := action.Validate(nil, services)ExpectFailed(result, "invitation")}diff --git a/app/actions/user.go b/app/actions/user.goindex 3c2318c65..980076af3 100644--- a/app/actions/user.go+++ b/app/actions/user.go@@ -1,15 +1,17 @@package actionsimport (+ "strings"+"github.com/getfider/fider/app""github.com/getfider/fider/app/models"+ "github.com/getfider/fider/app/pkg/uuid""github.com/getfider/fider/app/pkg/validate")//ChangeUserRole is the input model change role of an usertype ChangeUserRole struct {- CurrentTenant *models.Tenant- Model *models.ChangeUserRole+ Model *models.ChangeUserRole}// Initialize the model@@ -23,25 +25,78 @@ func (input *ChangeUserRole) IsAuthorized(user *models.User) bool {if user == nil {return false}- input.CurrentTenant = user.Tenantreturn user.IsAdministrator() && user.ID != input.Model.UserID}// Validate is current model is valid-func (input *ChangeUserRole) Validate(services *app.Services) *validate.Result {+func (input *ChangeUserRole) Validate(user *models.User, services *app.Services) *validate.Result {result := validate.Success()if input.Model.Role < models.RoleVisitor || input.Model.Role > models.RoleAdministrator {result.AddFieldFailure("role", "Invalid role")}- user, err := services.Users.GetByID(input.Model.UserID)+ target, err := services.Users.GetByID(input.Model.UserID)if err != nil {if err == app.ErrNotFound {result.AddFieldFailure("user_id", "User not found")} else {return validate.Error(err)}- } else if user.Tenant.ID != input.CurrentTenant.ID {+ } else if target.Tenant.ID != user.Tenant.ID {result.AddFieldFailure("user_id", "User not found")}return result}++//ChangeUserEmail is the action used to change current user's e-mail+type ChangeUserEmail struct {+ Model *models.ChangeUserEmail+}++// Initialize the model+func (input *ChangeUserEmail) Initialize() interface{} {+ input.Model = new(models.ChangeUserEmail)+ input.Model.VerificationKey = strings.Replace(uuid.NewV4().String(), "-", "", 4)+ return input.Model+}++// IsAuthorized returns true if current user is authorized to perform this action+func (input *ChangeUserEmail) IsAuthorized(user *models.User) bool {+ return user != nil+}++// Validate is current model is valid+func (input *ChangeUserEmail) Validate(user *models.User, services *app.Services) *validate.Result {+ result := validate.Success()++ if input.Model.Email == "" {+ result.AddFieldFailure("email", "E-mail is required.")+ return result+ }++ if len(input.Model.Email) > 200 {+ result.AddFieldFailure("email", "E-mail must be less than 200 characters.")+ return result+ }++ if user.Email == input.Model.Email {+ result.AddFieldFailure("email", "Choose a different e-mail.")+ return result+ }++ emailResult := validate.Email(input.Model.Email)+ if !emailResult.Ok {+ result.AddFieldFailure("email", emailResult.Messages...)+ return result+ }++ existing, err := services.Users.GetByEmail(user.Tenant.ID, input.Model.Email)+ if err != nil && err != app.ErrNotFound {+ return validate.Error(err)+ }+ if err == nil && existing.ID != user.ID {+ result.AddFieldFailure("email", "This e-mail is already in use by someone else")+ return result+ }+ input.Model.Requestor = user+ return result+}diff --git a/app/actions/user_test.go b/app/actions/user_test.goindex f80b47a76..b4be0dd97 100644--- a/app/actions/user_test.go+++ b/app/actions/user_test.go@@ -45,7 +45,7 @@ func TestChangeUserRole_InvalidRole(t *testing.T) {action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: targetUser.ID, Role: 4}}action.IsAuthorized(currentUser)- result := action.Validate(services)+ result := action.Validate(currentUser, services)ExpectFailed(result, "role")}@@ -59,7 +59,7 @@ func TestChangeUserRole_InvalidUser(t *testing.T) {action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: 999, Role: models.RoleAdministrator}}action.IsAuthorized(currentUser)- result := action.Validate(services)+ result := action.Validate(currentUser, services)ExpectFailed(result, "user_id")}@@ -79,6 +79,6 @@ func TestChangeUserRole_InvalidUser_Tenant(t *testing.T) {action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: targetUser.ID, Role: models.RoleAdministrator}}action.IsAuthorized(currentUser)- result := action.Validate(services)+ result := action.Validate(currentUser, services)ExpectFailed(result, "user_id")}diff --git a/app/handlers/common.go b/app/handlers/common.goindex e374849dd..20217e32f 100644--- a/app/handlers/common.go+++ b/app/handlers/common.go@@ -1,8 +1,10 @@package handlersimport (+ "net/http""time"+ "github.com/getfider/fider/app""github.com/getfider/fider/app/models""github.com/getfider/fider/app/pkg/web")@@ -26,3 +28,31 @@ func Page() web.HandlerFunc {return c.Page(web.Map{})}}++func validateKey(kind models.EmailVerificationKind, c web.Context) (*models.EmailVerification, error) {+ key := c.QueryParam("k")++ result, err := c.Services().Tenants.FindVerificationByKey(kind, key)+ if err != nil {+ if err == app.ErrNotFound {+ return nil, c.Redirect(http.StatusTemporaryRedirect, c.BaseURL())+ }+ return nil, c.Failure(err)+ }++ //If key has been used, just go back to home page+ if result.VerifiedOn != nil {+ return nil, c.Redirect(http.StatusTemporaryRedirect, c.BaseURL())+ }++ //If key expired, go back to home page+ if time.Now().After(result.ExpiresOn) {+ err = c.Services().Tenants.SetKeyAsVerified(key)+ if err != nil {+ return nil, c.Failure(err)+ }+ return nil, c.Redirect(http.StatusTemporaryRedirect, c.BaseURL())+ }++ return result, nil+}diff --git a/app/handlers/settings.go b/app/handlers/settings.goindex 0589b0877..e93f8a4ca 100644--- a/app/handlers/settings.go+++ b/app/handlers/settings.go@@ -1,10 +1,80 @@package handlersimport (+ "fmt"+ "net/http"+ "time"++ "github.com/getfider/fider/app/models"+"github.com/getfider/fider/app/actions""github.com/getfider/fider/app/pkg/web")+// ChangeUserEmail register the intent of changing user e-mail+func ChangeUserEmail() web.HandlerFunc {+ return func(c web.Context) error {+ input := new(actions.ChangeUserEmail)+ if result := c.BindTo(input); !result.Ok {+ return c.HandleValidation(result)+ }++ err := c.Services().Tenants.SaveVerificationKey(input.Model.VerificationKey, 24*time.Hour, input.Model)+ if err != nil {+ return c.Failure(err)+ }++ subject := "Confirm your new e-mail"+ link := fmt.Sprintf("%s/change-email/verify?k=%s", c.BaseURL(), input.Model.VerificationKey)+ previous := c.User().Email+ if previous == "" {+ previous = "(empty)"+ }+ message := fmt.Sprintf(`+ Hi %s,+ <br /><br />+ Looks like you have requested to change your e-mail from %s to %s.+ <br />+ Click the link below to confirm this operation.+ <br /><br />+ <a href='%s'>%s</a>+ <br /><br />+ <span style="color:#b3b3b1;font-size:11px">This link will expire in 24 hours and can only be used once.</span>+ `, c.User().Name, c.User().Email, input.Model.Email, link, link)+ err = c.Services().Emailer.Send(c.Tenant().Name, input.Model.Email, subject, message)+ if err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{})+ }+}++// VerifyChangeEmailKey checks if key is correct and update user's email+func VerifyChangeEmailKey() web.HandlerFunc {+ return func(c web.Context) error {+ result, err := validateKey(models.EmailVerificationKindChangeEmail, c)+ if err != nil {+ return err+ }++ if result.UserID != c.User().ID {+ return c.Redirect(http.StatusTemporaryRedirect, c.BaseURL())+ }++ err = c.Services().Users.ChangeEmail(result.UserID, result.Email)+ if err != nil {+ return c.Failure(err)+ }++ err = c.Services().Tenants.SetKeyAsVerified(result.Key)+ if err != nil {+ return c.Failure(err)+ }+ return c.Redirect(http.StatusTemporaryRedirect, c.BaseURL()+"/settings")+ }+}+// UpdateUserSettings updates current user settingsfunc UpdateUserSettings() web.HandlerFunc {return func(c web.Context) error {diff --git a/app/handlers/settings_test.go b/app/handlers/settings_test.goindex 6e13232a8..9ae267139 100644--- a/app/handlers/settings_test.go+++ b/app/handlers/settings_test.go@@ -4,7 +4,9 @@ import ("fmt""net/http""testing"+ "time"+ "github.com/getfider/fider/app""github.com/getfider/fider/app/models""github.com/getfider/fider/app/handlers"@@ -53,3 +55,93 @@ func TestChangeRoleHandler_Valid(t *testing.T) {Expect(code).To(Equal(http.StatusOK))Expect(user.Role).To(Equal(models.RoleAdministrator))}++func TestChangeUserEmailHandler_Valid(t *testing.T) {+ RegisterTestingT(t)++ for _, email := range []string{+ "[email protected]",+ "[email protected]",+ } {+ server, _ := mock.NewServer()+ code, _ := server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ ExecutePost(handlers.ChangeUserEmail(), fmt.Sprintf(`{ "email": "%s" }`, email))++ Expect(code).To(Equal(http.StatusOK))+ }+}++func TestChangeUserEmailHandler_Invalid(t *testing.T) {+ RegisterTestingT(t)++ for _, email := range []string{+ "",+ "[email protected]",+ "jon.snow",+ "[email protected]",+ } {+ server, _ := mock.NewServer()+ code, _ := server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ ExecutePost(handlers.ChangeUserEmail(), fmt.Sprintf(`{ "email": "%s" }`, email))++ Expect(code).To(Equal(http.StatusBadRequest))+ }+}++func TestVerifyChangeEmailKeyHandler_Success(t *testing.T) {+ RegisterTestingT(t)++ server, services := mock.NewServer()+ request := &models.ChangeUserEmail{+ Requestor: mock.JonSnow,+ Email: "[email protected]",+ }++ services.Tenants.SaveVerificationKey("th3-s3cr3t", 24*time.Hour, request)+ code, _ := server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ WithURL("/change-email/verify?k=th3-s3cr3t").+ Execute(handlers.VerifyChangeEmailKey())++ Expect(code).To(Equal(http.StatusTemporaryRedirect))+ user, err := services.Users.GetByEmail(mock.DemoTenant.ID, "[email protected]")+ Expect(err).To(BeNil())+ Expect(user.ID).To(Equal(mock.JonSnow.ID))+ Expect(user.Name).To(Equal(mock.JonSnow.Name))+ Expect(user.Email).To(Equal(mock.JonSnow.Email))++ result, err := services.Tenants.FindVerificationByKey(models.EmailVerificationKindChangeEmail, "th3-s3cr3t")+ Expect(err).To(BeNil())+ Expect(result.VerifiedOn).NotTo(BeNil())+}++func TestVerifyChangeEmailKeyHandler_DifferentUser(t *testing.T) {+ RegisterTestingT(t)++ server, services := mock.NewServer()+ request := &models.ChangeUserEmail{+ Requestor: mock.JonSnow,+ Email: "[email protected]",+ }+ services.Tenants.SaveVerificationKey("th3-s3cr3t", 24*time.Hour, request)+ code, _ := server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.AryaStark).+ WithURL("/change-email/verify?k=th3-s3cr3t").+ Execute(handlers.VerifyChangeEmailKey())++ Expect(code).To(Equal(http.StatusTemporaryRedirect))++ _, err := services.Users.GetByEmail(mock.DemoTenant.ID, "[email protected]")+ Expect(err).To(BeNil())+ _, err = services.Users.GetByEmail(mock.DemoTenant.ID, "[email protected]")+ Expect(err).To(BeNil())++ _, err = services.Users.GetByEmail(mock.DemoTenant.ID, "[email protected]")+ Expect(err).To(Equal(app.ErrNotFound))+}diff --git a/app/handlers/signin.go b/app/handlers/signin.goindex 13a2d9245..1257160a2 100644--- a/app/handlers/signin.go+++ b/app/handlers/signin.go@@ -165,28 +165,9 @@ func SignInByEmail() web.HandlerFunc {// VerifySignInKey checks if verify key is correct and sign in userfunc VerifySignInKey(kind models.EmailVerificationKind) web.HandlerFunc {return func(c web.Context) error {- key := c.QueryParam("k")-- result, err := c.Services().Tenants.FindVerificationByKey(kind, key)- if err != nil {- if err == app.ErrNotFound {- return c.Redirect(http.StatusTemporaryRedirect, c.BaseURL())- }- return c.Failure(err)- }-- //If key has been used, just go back to home page- if result.VerifiedOn != nil {- return c.Redirect(http.StatusTemporaryRedirect, c.BaseURL())- }-- //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)- }- return c.Redirect(http.StatusTemporaryRedirect, c.BaseURL())+ result, err := validateKey(kind, c)+ if result == nil {+ return err}var user *models.User@@ -218,7 +199,7 @@ func VerifySignInKey(kind models.EmailVerificationKind) web.HandlerFunc {return c.NotFound()}- err = c.Services().Tenants.SetKeyAsVerified(key)+ err = c.Services().Tenants.SetKeyAsVerified(result.Key)if err != nil {return c.Failure(err)}diff --git a/app/models/identity.go b/app/models/identity.goindex 7c6e589e6..8d0aa264d 100644--- a/app/models/identity.go+++ b/app/models/identity.go@@ -54,6 +54,8 @@ const (EmailVerificationKindSignIn EmailVerificationKind = 1//EmailVerificationKindSignUp is the sign up (create tenant) by name and e-mail processEmailVerificationKindSignUp EmailVerificationKind = 2+ //EmailVerificationKindChangeEmail is the change user e-mail process+ EmailVerificationKindChangeEmail EmailVerificationKind = 3)//HasProvider returns true if current user has registered with given provider@@ -120,6 +122,11 @@ func (e *CreateTenant) GetName() string {return e.Name}+//GetUser returns the current user performing this action+func (e *CreateTenant) GetUser() *User {+ return nil+}+//GetKind returns EmailVerificationKindSignUpfunc (e *CreateTenant) GetKind() EmailVerificationKind {return EmailVerificationKindSignUp@@ -150,15 +157,48 @@ func (e *SignInByEmail) GetName() string {return ""}+//GetUser returns the current user performing this action+func (e *SignInByEmail) GetUser() *User {+ return nil+}+//GetKind returns EmailVerificationKindSignInfunc (e *SignInByEmail) GetKind() EmailVerificationKind {return EmailVerificationKindSignIn}+//ChangeUserEmail is the input model used to change current user's e-mail+type ChangeUserEmail struct {+ Email string `json:"email" format:"lower"`+ VerificationKey string+ Requestor *User+}++//GetEmail returns the email being verified+func (e *ChangeUserEmail) GetEmail() string {+ return e.Email+}++//GetName returns empty for this kind of process+func (e *ChangeUserEmail) GetName() string {+ return ""+}++//GetUser returns the current user performing this action+func (e *ChangeUserEmail) GetUser() *User {+ return e.Requestor+}++//GetKind returns EmailVerificationKindSignIn+func (e *ChangeUserEmail) GetKind() EmailVerificationKind {+ return EmailVerificationKindChangeEmail+}+//NewEmailVerification is used to register a new e-mail verification processtype NewEmailVerification interface {GetEmail() stringGetName() string+ GetUser() *UserGetKind() EmailVerificationKind}@@ -167,6 +207,7 @@ type EmailVerification struct {Email stringName stringKey string+ UserID intKind EmailVerificationKindCreatedOn time.TimeExpiresOn time.Timediff --git a/app/pkg/validate/validation.go b/app/pkg/validate/validation.goindex 88e717067..917a50938 100644--- a/app/pkg/validate/validation.go+++ b/app/pkg/validate/validation.go@@ -7,7 +7,7 @@ import (// Validatable defines which models can be validated against contexttype Validatable interface {- Validate(services *app.Services) *Result+ Validate(user *models.User, services *app.Services) *ResultIsAuthorized(user *models.User) bool}diff --git a/app/pkg/web/context.go b/app/pkg/web/context.goindex 665b73dba..11db6483d 100644--- a/app/pkg/web/context.go+++ b/app/pkg/web/context.go@@ -88,7 +88,7 @@ func (ctx *Context) BindTo(i actions.Actionable) *validate.Result {if !i.IsAuthorized(ctx.User()) {return validate.Unauthorized()}- return i.Validate(ctx.Services())+ return i.Validate(ctx.User(), ctx.Services())}//Logger returns current loggerdiff --git a/app/storage/inmemory/tenant.go b/app/storage/inmemory/tenant.goindex a946b6928..10099a3c9 100644--- a/app/storage/inmemory/tenant.go+++ b/app/storage/inmemory/tenant.go@@ -103,11 +103,16 @@ func (s *TenantStorage) Activate(id int) error {// SaveVerificationKey used by e-mail verificationfunc (s *TenantStorage) SaveVerificationKey(key string, duration time.Duration, request models.NewEmailVerification) error {+ userID := 0+ if request.GetUser() != nil {+ userID = request.GetUser().ID+ }s.verifications = append(s.verifications, &models.EmailVerification{Email: request.GetEmail(),Name: request.GetName(),Kind: request.GetKind(),Key: key,+ UserID: userID,CreatedOn: time.Now(),ExpiresOn: time.Now().Add(duration),VerifiedOn: nil,diff --git a/app/storage/inmemory/user.go b/app/storage/inmemory/user.goindex 561b5fc19..7a705f27d 100644--- a/app/storage/inmemory/user.go+++ b/app/storage/inmemory/user.go@@ -73,35 +73,38 @@ func (s *UserStorage) Register(user *models.User) error {// RegisterProvider adds given provider to userIDfunc (s *UserStorage) RegisterProvider(userID int, provider *models.UserProvider) error {- for _, user := range s.users {- if user.ID == userID {- user.Providers = append(user.Providers, provider)- return nil- }+ user, err := s.GetByID(userID)+ if err == nil {+ user.Providers = append(user.Providers, provider)}- return app.ErrNotFound+ return err}// Update user settingsfunc (s *UserStorage) Update(userID int, settings *models.UpdateUserSettings) error {- for _, user := range s.users {- if user.ID == userID {- user.Name = settings.Name- return nil- }+ user, err := s.GetByID(userID)+ if err == nil {+ user.Name = settings.Name}- return app.ErrNotFound+ return err}// ChangeRole of given userfunc (s *UserStorage) ChangeRole(userID int, role models.Role) error {- for _, user := range s.users {- if user.ID == userID {- user.Role = role- return nil- }+ user, err := s.GetByID(userID)+ if err == nil {+ user.Role = role+ }+ return err+}++// ChangeEmail of given user+func (s *UserStorage) ChangeEmail(userID int, email string) error {+ user, err := s.GetByID(userID)+ if err == nil {+ user.Email = email}- return app.ErrNotFound+ return err}// GetAll return all users of current tenantdiff --git a/app/storage/postgres/tenant.go b/app/storage/postgres/tenant.goindex de0914e8d..8692e2c55 100644--- a/app/storage/postgres/tenant.go+++ b/app/storage/postgres/tenant.go@@ -41,6 +41,7 @@ type dbEmailVerification struct {Email string `db:"email"`Key string `db:"key"`Kind models.EmailVerificationKind `db:"kind"`+ UserID dbx.NullInt `db:"user_id"`CreatedOn time.Time `db:"created_on"`ExpiresOn time.Time `db:"expires_on"`VerifiedOn dbx.NullTime `db:"verified_on"`@@ -61,6 +62,10 @@ func (t *dbEmailVerification) toModel() *models.EmailVerification {model.VerifiedOn = &t.VerifiedOn.Time}+ if t.UserID.Valid {+ model.UserID = int(t.UserID.Int64)+ }+return model}@@ -149,15 +154,19 @@ func (s *TenantStorage) Activate(id int) error {// SaveVerificationKey used by e-mail verification processfunc (s *TenantStorage) SaveVerificationKey(key string, duration time.Duration, request models.NewEmailVerification) error {- query := "INSERT INTO email_verifications (tenant_id, email, created_on, expires_on, key, name, kind) VALUES ($1, $2, $3, $4, $5, $6, $7)"- return s.trx.Execute(query, s.current.ID, request.GetEmail(), time.Now(), time.Now().Add(duration), key, request.GetName(), request.GetKind())+ var userID interface{}+ if request.GetUser() != nil {+ userID = request.GetUser().ID+ }+ query := "INSERT INTO email_verifications (tenant_id, email, created_on, expires_on, key, name, kind, user_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)"+ return s.trx.Execute(query, s.current.ID, request.GetEmail(), time.Now(), time.Now().Add(duration), key, request.GetName(), request.GetKind(), userID)}// FindVerificationByKey based on current tenantfunc (s *TenantStorage) FindVerificationByKey(kind models.EmailVerificationKind, key string) (*models.EmailVerification, error) {verification := dbEmailVerification{}- query := "SELECT id, email, name, key, created_on, verified_on, expires_on, kind FROM email_verifications WHERE key = $1 AND kind = $2 LIMIT 1"+ query := "SELECT id, email, name, key, created_on, verified_on, expires_on, kind, user_id FROM email_verifications WHERE key = $1 AND kind = $2 LIMIT 1"err := s.trx.Get(&verification, query, key, kind)if err != nil {return nil, errdiff --git a/app/storage/postgres/tenant_test.go b/app/storage/postgres/tenant_test.goindex 5acf5c806..3c0e220b1 100644--- a/app/storage/postgres/tenant_test.go+++ b/app/storage/postgres/tenant_test.go@@ -160,6 +160,7 @@ func TestTenantStorage_SaveFindSet_VerificationKey(t *testing.T) {Expect(result.Name).To(Equal("Jon Snow"))Expect(result.Kind).To(Equal(models.EmailVerificationKindSignUp))Expect(result.Key).To(Equal("s3cr3tk3y"))+ Expect(result.UserID).To(Equal(0))Expect(result.ExpiresOn).To(BeTemporally("~", result.CreatedOn.Add(15*time.Minute), 1*time.Second))//Set as verified check values@@ -174,6 +175,7 @@ func TestTenantStorage_SaveFindSet_VerificationKey(t *testing.T) {Expect(result.Email).To(Equal("[email protected]"))Expect(result.Name).To(Equal("Jon Snow"))Expect(result.Key).To(Equal("s3cr3tk3y"))+ Expect(result.UserID).To(Equal(0))Expect(result.ExpiresOn).To(BeTemporally("~", result.CreatedOn.Add(15*time.Minute), 1*time.Second))//Wrong kind should not find it@@ -182,6 +184,34 @@ func TestTenantStorage_SaveFindSet_VerificationKey(t *testing.T) {Expect(result).To(BeNil())}+func TestTenantStorage_SaveFindSet_ChangeEmailVerificationKey(t *testing.T) {+ SetupDatabaseTest(t)+ defer TeardownDatabaseTest()++ tenant, _ := tenants.GetByDomain("demo")+ tenants.SetCurrentTenant(tenant)++ //Save new Key+ request := &models.ChangeUserEmail{+ Email: "[email protected]",+ Requestor: jonSnow,+ }+ err := tenants.SaveVerificationKey("th3-s3cr3t", 15*time.Minute, request)+ Expect(err).To(BeNil())++ //Find and check values+ result, err := tenants.FindVerificationByKey(models.EmailVerificationKindChangeEmail, "th3-s3cr3t")+ Expect(err).To(BeNil())+ Expect(result.CreatedOn).NotTo(Equal(time.Time{}))+ Expect(result.VerifiedOn).To(BeNil())+ Expect(result.Email).To(Equal("[email protected]"))+ Expect(result.Name).To(Equal(""))+ Expect(result.Kind).To(Equal(models.EmailVerificationKindChangeEmail))+ Expect(result.Key).To(Equal("th3-s3cr3t"))+ Expect(result.UserID).To(Equal(jonSnow.ID))+ Expect(result.ExpiresOn).To(BeTemporally("~", result.CreatedOn.Add(15*time.Minute), 1*time.Second))+}+func TestTenantStorage_FindUnknownVerificationKey(t *testing.T) {SetupDatabaseTest(t)defer TeardownDatabaseTest()diff --git a/app/storage/postgres/user.go b/app/storage/postgres/user.goindex 6709b7485..fdaa9d37d 100644--- a/app/storage/postgres/user.go+++ b/app/storage/postgres/user.go@@ -125,6 +125,12 @@ func (s *UserStorage) ChangeRole(userID int, role models.Role) error {return s.trx.Execute(cmd, userID, s.tenant.ID, role)}+// ChangeEmail of given user+func (s *UserStorage) ChangeEmail(userID int, email string) error {+ cmd := "UPDATE users SET email = $3 WHERE id = $1 AND tenant_id = $2"+ return s.trx.Execute(cmd, userID, s.tenant.ID, email)+}+// GetByID returns a user based on given idfunc getUser(trx *dbx.Trx, filter string, args ...interface{}) (*models.User, error) {user := dbUser{}diff --git a/app/storage/postgres/user_test.go b/app/storage/postgres/user_test.goindex 6a5ace9f6..fcd401456 100644--- a/app/storage/postgres/user_test.go+++ b/app/storage/postgres/user_test.go@@ -209,14 +209,31 @@ func TestUserStorage_ChangeRole(t *testing.T) {defer TeardownDatabaseTest()users.SetCurrentTenant(demoTenant)- err := users.ChangeRole(1, models.RoleVisitor)+ err := users.ChangeRole(jonSnow.ID, models.RoleVisitor)Expect(err).To(BeNil())- user, err := users.GetByEmail(1, "[email protected]")+ user, err := users.GetByEmail(jonSnow.Tenant.ID, "[email protected]")Expect(err).To(BeNil())Expect(user.Role).To(Equal(models.RoleVisitor))}+func TestUserStorage_ChangeEmail(t *testing.T) {+ SetupDatabaseTest(t)+ defer TeardownDatabaseTest()++ users.SetCurrentTenant(demoTenant)+ err := users.ChangeEmail(jonSnow.ID, "[email protected]")+ Expect(err).To(BeNil())++ user, err := users.GetByEmail(jonSnow.Tenant.ID, "[email protected]")+ Expect(err).To(BeNil())+ Expect(user.Email).To(Equal("[email protected]"))++ user, err = users.GetByEmail(jonSnow.Tenant.ID, "[email protected]")+ Expect(err).To(Equal(app.ErrNotFound))+ Expect(user).To(BeNil())+}+func TestUserStorage_GetAll(t *testing.T) {SetupDatabaseTest(t)defer TeardownDatabaseTest()diff --git a/app/storage/storage.go b/app/storage/storage.goindex a95adb79e..eb6c17a86 100644--- a/app/storage/storage.go+++ b/app/storage/storage.go@@ -40,6 +40,7 @@ type User interface {Register(user *models.User) errorRegisterProvider(userID int, provider *models.UserProvider) errorUpdate(userID int, settings *models.UpdateUserSettings) error+ ChangeEmail(userID int, email string) errorChangeRole(userID int, role models.Role) errorGetAll() ([]*models.User, error)}diff --git a/public/components/common/SignInControl.tsx b/public/components/common/SignInControl.tsxindex 7662cc7af..6931324f6 100644--- a/public/components/common/SignInControl.tsx+++ b/public/components/common/SignInControl.tsx@@ -42,7 +42,7 @@ export class SignInControl extends React.Component<SignInControlProps, SignInConif (this.state.sent) {return (<div>- <p>We just emailed a confirmation link to <b>{this.state.email}</b>. <br /> Click the link and you’ll be signed in.</p>+ <p>We have just sent a confirmation link to <b>{this.state.email}</b>. <br /> Click the link and you’ll be signed in.</p><p><a href="#" onClick={() => page.hideSignIn()}>OK</a></p></div>);diff --git a/public/pages/signup/SignUpPage.tsx b/public/pages/signup/SignUpPage.tsxindex 9ea9002f0..fd4600ef4 100644--- a/public/pages/signup/SignUpPage.tsx+++ b/public/pages/signup/SignUpPage.tsx@@ -110,7 +110,7 @@ export class SignUpPage extends React.Component<SignUpPageProps, SignUpPageState<div id="submitted-modal" className="ui modal small"><div className="header">Thank you for registering!</div><div className="content">- <p>We just emailed a confirmation link to <b>{this.state.email}</b>. <br /> Click the link to finish your registration.</p>+ <p>We have just sent a confirmation link to <b>{this.state.email}</b>. <br /> Click the link to finish your registration.</p></div></div>);diff --git a/public/pages/site/UserSettingsPage.scss b/public/pages/site/UserSettingsPage.scssnew file mode 100644index 000000000..ba2cd421b--- /dev/null+++ b/public/pages/site/UserSettingsPage.scss@@ -0,0 +1,3 @@+#confirmation-modal {+ text-align: center;+}\ No newline at end of filediff --git a/public/pages/site/UserSettingsPage.tsx b/public/pages/site/UserSettingsPage.tsxindex 7a22a3603..613d95c3d 100644--- a/public/pages/site/UserSettingsPage.tsx+++ b/public/pages/site/UserSettingsPage.tsx@@ -5,8 +5,12 @@ import { Form, DisplayError, Button, Gravatar } from '@fider/components/common';import { CurrentUser } from '@fider/models';import { Failure, actions } from '@fider/services';+import './UserSettingsPage.scss';+interface UserSettingsPageState {name: string;+ newEmail: string;+ changingEmail: boolean;error?: Failure;}@@ -19,6 +23,8 @@ export class UserSettingsPage extends React.Component<UserSettingsPageProps, Useconstructor(props: UserSettingsPageProps) {super(props);this.state = {+ changingEmail: false,+ newEmail: '',name: this.props.user.name};}@@ -32,9 +38,30 @@ export class UserSettingsPage extends React.Component<UserSettingsPageProps, Use}}+ private async submitNewEmail() {+ const result = await actions.changeUserEmail(this.state.newEmail);+ if (result.ok) {+ this.setState({ error: undefined, changingEmail: false }, () => {+ $('#confirmation-modal').modal('show');+ });+ } else if (result.error) {+ this.setState({ error: result.error });+ }+ }+public render() {return (<div className="page ui container">+ <div id="confirmation-modal" className="ui mini modal">+ <div className="header">Confirm your new e-mail</div>+ <div className="content">+ <div>+ <p>We have just sent a confirmation link to <b>{this.state.newEmail}</b>. <br /> Click the link to update your e-mail.</p>+ <p><a href="#" onClick={() => $('#confirmation-modal').modal('hide')}>OK</a></p>+ </div>+ </div>+ </div>+<h2 className="ui header"><i className="circular id badge icon" /><div className="content">@@ -56,16 +83,37 @@ export class UserSettingsPage extends React.Component<UserSettingsPageProps, Use</p></div></div>+ <DisplayError fields={['email']} error={this.state.error} /><div className="field">- <label htmlFor="email">E-mail</label>- <p><b>{this.props.user.email}</b></p>- <div className="info">- {- this.props.user.email- ? <p>Your e-mail is private and will never be displayed to anyone.</p>- : <p>Your account doesn't have an e-mail.</p>- }- </div>+ <label htmlFor="email">E-mail <span className="info">Your e-mail is private and will never be displayed to anyone.</span></label>+ {+ this.state.changingEmail ?+ <>+ <p>+ <input+ id="new-email"+ type="text"+ style={{'max-width': '200px', 'margin-right': '10px'}}+ maxLength={200}+ placeholder={this.props.user.email}+ value={this.state.newEmail}+ onChange={(e) => this.setState({ newEmail: e.currentTarget.value })}+ />+ <Button className="positive" size="mini" onClick={async () => await this.submitNewEmail()}>Confirm</Button>+ <Button size="mini" onClick={async () => this.setState({ changingEmail: false, error: undefined })}>Cancel</Button>+ </p>+ </>+ :+ <p>+ {+ this.props.user.email+ ? <b>{this.props.user.email}</b>+ : <span className="info">Your account doesn't have an e-mail.</span>+ }+ <span className="ui info clickable" onClick={() => this.setState({ changingEmail: true })}>change</span>+ </p>+ }+</div><DisplayError fields={['name']} error={this.state.error} /><div className="field">diff --git a/public/services/actions/user.ts b/public/services/actions/user.tsindex be5b58a03..1c8d61574 100644--- a/public/services/actions/user.ts+++ b/public/services/actions/user.ts@@ -5,3 +5,9 @@ export const updateUserSettings = async (name: string): Promise<Result> => {name,});};++export const changeUserEmail = async (email: string): Promise<Result> => {+ return await http.post('/api/user/change-email', {+ email,+ });+};diff --git a/routes.go b/routes.goindex e69f48129..3670ab414 100644--- a/routes.go+++ b/routes.go@@ -98,6 +98,7 @@ func GetMainEngine(settings *models.AppSettings) *web.Engine {{private.Use(middlewares.IsAuthenticated())private.Get("/settings", handlers.Page())+ private.Get("/change-email/verify", handlers.VerifyChangeEmailKey())private.Get("/api/ideas", handlers.GetIdeas())private.Post("/api/ideas", handlers.PostIdea())@@ -109,6 +110,7 @@ func GetMainEngine(settings *models.AppSettings) *web.Engine {private.Post("/api/ideas/:number/tags/:slug", handlers.AssignTag())private.Delete("/api/ideas/:number/tags/:slug", handlers.UnassignTag())private.Post("/api/user/settings", handlers.UpdateUserSettings())+ private.Post("/api/user/change-email", handlers.ChangeUserEmail())private.Use(middlewares.IsAuthorized(models.RoleAdministrator))