Open platform to collect and prioritize feedback
allow users to change their names (#130)
Guilherme Oenninged9174e42687
diff --git a/app/actions/settings.go b/app/actions/settings.gonew file mode 100644index 000000000..52d2ed807--- /dev/null+++ b/app/actions/settings.go@@ -0,0 +1,41 @@+package actions++import (+ "strings"++ "github.com/getfider/fider/app"+ "github.com/getfider/fider/app/models"+ "github.com/getfider/fider/app/pkg/validate"+)++// UpdateUserSettings happens when users updates their settings+type UpdateUserSettings struct {+ Model *models.UpdateUserSettings+}++// Initialize the model+func (input *UpdateUserSettings) Initialize() interface{} {+ input.Model = new(models.UpdateUserSettings)+ return input.Model+}++// IsAuthorized returns true if current user is authorized to perform this action+func (input *UpdateUserSettings) IsAuthorized(user *models.User) bool {+ return user != nil+}++// Validate is current model is valid+func (input *UpdateUserSettings) Validate(services *app.Services) *validate.Result {+ result := validate.Success()+ input.Model.Name = strings.Trim(input.Model.Name, " ")++ if input.Model.Name == "" {+ result.AddFieldFailure("name", "Name is required.")+ }++ if len(input.Model.Name) > 50 {+ result.AddFieldFailure("name", "Name must be less than 50 characters.")+ }++ return result+}diff --git a/app/actions/settings_test.go b/app/actions/settings_test.gonew file mode 100644index 000000000..28753f11d--- /dev/null+++ b/app/actions/settings_test.go@@ -0,0 +1,37 @@+package actions_test++import (+ "testing"++ "github.com/getfider/fider/app/actions"+ "github.com/getfider/fider/app/models"++ . "github.com/onsi/gomega"+)++func TestInvalidUserNames(t *testing.T) {+ RegisterTestingT(t)++ for _, name := range []string{+ "",+ " ",+ "123456789012345678901234567890123456789012345678901", // 51 chars+ } {+ action := &actions.UpdateUserSettings{Model: &models.UpdateUserSettings{Name: name}}+ result := action.Validate(services)+ ExpectFailed(result, "name")+ }+}++func TestValidUserNames(t *testing.T) {+ RegisterTestingT(t)++ for _, name := range []string{+ "Jon Snow",+ "Arya",+ } {+ action := &actions.UpdateUserSettings{Model: &models.UpdateUserSettings{Name: name}}+ result := action.Validate(services)+ ExpectSuccess(result)+ }+}diff --git a/app/actions/signin.go b/app/actions/signin.goindex 164e41a77..d008bc1aa 100644--- a/app/actions/signin.go+++ b/app/actions/signin.go@@ -36,6 +36,10 @@ func (input *SignInByEmail) Validate(services *app.Services) *validate.Result {return result}+ if len(input.Model.Email) > 200 {+ result.AddFieldFailure("email", "E-mail must be less than 200 characters.")+ }+emailResult := validate.Email(input.Model.Email)if !emailResult.Ok {result.AddFieldFailure("email", emailResult.Messages...)@@ -44,7 +48,7 @@ func (input *SignInByEmail) Validate(services *app.Services) *validate.Result {return result}-// CompleteProfile happens when user completes his profile during first time sign in+// CompleteProfile happens when users completes their profile during first time sign intype CompleteProfile struct {Model *models.CompleteProfile}@@ -70,6 +74,10 @@ func (input *CompleteProfile) Validate(services *app.Services) *validate.Resultresult.AddFieldFailure("name", "Name is required.")}+ if len(input.Model.Name) > 50 {+ result.AddFieldFailure("name", "Name must be less than 50 characters.")+ }+if input.Model.Key == "" {result.AddFieldFailure("key", "Key is required.")} else {diff --git a/app/actions/signin_test.go b/app/actions/signin_test.goindex 2fdc099af..fd612b2c8 100644--- a/app/actions/signin_test.go+++ b/app/actions/signin_test.go@@ -46,6 +46,17 @@ func TestCompleteProfile_EmptyNameAndKey(t *testing.T) {ExpectFailed(result, "key")}+func TestCompleteProfile_LongName(t *testing.T) {+ RegisterTestingT(t)++ action := actions.CompleteProfile{Model: &models.CompleteProfile{+ Name: "123456789012345678901234567890123456789012345678901", // 51 chars+ }}+ result := action.Validate(services)+ ExpectFailed(result, "name")+ ExpectFailed(result, "key")+}+func TestCompleteProfile_UnknownKey(t *testing.T) {RegisterTestingT(t)action := actions.CompleteProfile{Model: &models.CompleteProfile{Name: "Jon Snow", Key: "1234567890"}}diff --git a/app/handlers/settings.go b/app/handlers/settings.gonew file mode 100644index 000000000..3354b11d9--- /dev/null+++ b/app/handlers/settings.go@@ -0,0 +1,23 @@+package handlers++import (+ "github.com/getfider/fider/app/actions"+ "github.com/getfider/fider/app/pkg/web"+)++// UpdateUserSettings updates current user settings+func UpdateUserSettings() web.HandlerFunc {+ return func(c web.Context) error {+ input := new(actions.UpdateUserSettings)+ if result := c.BindTo(input); !result.Ok {+ return c.HandleValidation(result)+ }++ err := c.Services().Users.Update(c.User().ID, input.Model)+ if err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{})+ }+}diff --git a/app/handlers/settings_test.go b/app/handlers/settings_test.gonew file mode 100644index 000000000..f91e7be0d--- /dev/null+++ b/app/handlers/settings_test.go@@ -0,0 +1,36 @@+package handlers_test++import (+ "net/http"+ "testing"++ "github.com/getfider/fider/app/handlers"+ "github.com/getfider/fider/app/pkg/mock"+ . "github.com/onsi/gomega"+)++func TestUpdateUserSettingsHandler_EmptyInput(t *testing.T) {+ RegisterTestingT(t)++ server, _ := mock.NewServer()+ code, _ := server.+ AsUser(mock.JonSnow).+ ExecutePost(handlers.UpdateUserSettings(), `{ }`)++ Expect(code).To(Equal(http.StatusBadRequest))+}++func TestUpdateUserSettingsHandler_ValidName(t *testing.T) {+ RegisterTestingT(t)++ server, services := mock.NewServer()+ code, _ := server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ ExecutePost(handlers.UpdateUserSettings(), `{ "name": "Jon Stark" }`)++ user, _ := services.Users.GetByEmail(mock.DemoTenant.ID, "[email protected]")++ Expect(code).To(Equal(http.StatusOK))+ Expect(user.Name).To(Equal("Jon Stark"))+}diff --git a/app/models/identity.go b/app/models/identity.goindex 09e039290..1ba7d359d 100644--- a/app/models/identity.go+++ b/app/models/identity.go@@ -110,3 +110,8 @@ type CompleteProfile struct {Name string `json:"name"`Email string}++// UpdateUserSettings is the model used to update user's settings+type UpdateUserSettings struct {+ Name string `json:"name"`+}diff --git a/app/storage/inmemory/user.go b/app/storage/inmemory/user.goindex 8d5937205..42fde3921 100644--- a/app/storage/inmemory/user.go+++ b/app/storage/inmemory/user.go@@ -69,3 +69,14 @@ func (s *UserStorage) RegisterProvider(userID int, provider *models.UserProvider}return app.ErrNotFound}++// Update user settings+func (s *UserStorage) Update(userID int, settings *models.UpdateUserSettings) error {+ for _, user := range s.users {+ if user.ID == userID {+ user.Name = settings.Name+ return nil+ }+ }+ return app.ErrNotFound+}diff --git a/app/storage/postgres/user.go b/app/storage/postgres/user.goindex a17a767cb..f24d6e5ad 100644--- a/app/storage/postgres/user.go+++ b/app/storage/postgres/user.go@@ -104,6 +104,12 @@ func (s *UserStorage) RegisterProvider(userID int, provider *models.UserProviderreturn s.trx.Execute(cmd, userID, provider.Name, provider.UID, time.Now())}+// Update user settings+func (s *UserStorage) Update(userID int, settings *models.UpdateUserSettings) error {+ cmd := "UPDATE users SET name = $2 WHERE id = $1"+ return s.trx.Execute(cmd, userID, settings.Name)+}+// 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 6b6a4a642..6fb0a5bfc 100644--- a/app/storage/postgres/user_test.go+++ b/app/storage/postgres/user_test.go@@ -226,3 +226,20 @@ func TestUserStorage_RegisterProvider(t *testing.T) {Expect(user.Providers[1].UID).To(Equal("GO1234"))Expect(user.Providers[1].Name).To(Equal("google"))}++func TestUserStorage_UpdateSettings(t *testing.T) {+ RegisterTestingT(t)+ db, _ := dbx.New()+ db.Seed()+ defer db.Close()++ trx, _ := db.Begin()+ defer trx.Rollback()++ users := postgres.NewUserStorage(trx)+ err := users.Update(1, &models.UpdateUserSettings{Name: "Jon Stark"})+ Expect(err).To(BeNil())++ user, err := users.GetByEmail(1, "[email protected]")+ Expect(user.Name).To(Equal("Jon Stark"))+}diff --git a/app/storage/storage.go b/app/storage/storage.goindex 3188926a2..7d05f8eba 100644--- a/app/storage/storage.go+++ b/app/storage/storage.go@@ -24,6 +24,7 @@ type User interface {GetByProvider(tenantID int, provider string, uid string) (*models.User, error)Register(user *models.User) errorRegisterProvider(userID int, provider *models.UserProvider) error+ Update(userID int, settings *models.UpdateUserSettings) error}// Tenant contains read and write operations for tenantsdiff --git a/public/di.ts b/public/di.tsindex 8ca9bc569..ab4abafef 100644--- a/public/di.ts+++ b/public/di.ts@@ -14,6 +14,7 @@ const {const injectables = {Session: Symbol('Session'),IdeaService: Symbol('IdeaService'),+ UserService: Symbol('UserService'),TenantService: Symbol('TenantService'),};diff --git a/public/index.tsx b/public/index.tsxindex 6659515c5..cc2f323ac 100644--- a/public/index.tsx+++ b/public/index.tsx@@ -15,7 +15,9 @@ import {IdeaService,HttpIdeaService,TenantService,- HttpTenantService+ HttpTenantService,+ UserService,+ HttpUserService} from '@fider/services';import '@fider/assets/styles/main.scss';@@ -23,6 +25,7 @@ import '@fider/assets/styles/main.scss';container.bind<Session>(injectables.Session).toConstantValue(new BrowserSession(window));container.bind<IdeaService>(injectables.IdeaService).to(HttpIdeaService);container.bind<TenantService>(injectables.TenantService).to(HttpTenantService);+container.bind<UserService>(injectables.UserService).to(HttpUserService);interface PageConfiguration {id: string;diff --git a/public/pages/site/UserSettingsPage.tsx b/public/pages/site/UserSettingsPage.tsxindex 2c442d44b..b269375f0 100644--- a/public/pages/site/UserSettingsPage.tsx+++ b/public/pages/site/UserSettingsPage.tsx@@ -4,7 +4,7 @@ import { inject, injectables } from '@fider/di';import { Footer, Header, Form, DisplayError, Button, Gravatar } from '@fider/components/common';import { CurrentUser } from '@fider/models';-import { Session, Failure } from '@fider/services';+import { Session, Failure, UserService } from '@fider/services';interface UserSettingsPageState {name: string;@@ -17,6 +17,9 @@ export class UserSettingsPage extends React.Component<{}, UserSettingsPageState>@inject(injectables.Session)private session: Session;+ @inject(injectables.UserService)+ private userService: UserService;+constructor(props: {}) {super(props);this.user = this.session.getCurrentUser()!;@@ -26,7 +29,12 @@ export class UserSettingsPage extends React.Component<{}, UserSettingsPageState>}private async confirm() {- console.log('Done!');+ const result = await this.userService.updateSettings(this.state.name);+ if (result.ok) {+ location.reload();+ } else if (result.error) {+ this.setState({ error: result.error });+ }}public render() {@@ -40,7 +48,7 @@ export class UserSettingsPage extends React.Component<{}, UserSettingsPageState><div className="ui form"><div className="field"><label htmlFor="email">Avatar</label>- <p><Gravatar hash={ this.user.gravatar } name={ this.state.name } /></p>+ <p><Gravatar hash={ this.user.gravatar } name={ this.user.name } /></p><p className="info"><p>We use <a href="https://en.gravatar.com/" target="blank">Gravatar</a> to display profile avatars. <br/>@@ -63,11 +71,13 @@ export class UserSettingsPage extends React.Component<{}, UserSettingsPageState><label htmlFor="name">Name</label><input id="name"type="text"- disabledmaxLength={100}value={ this.state.name }onChange={(e) => this.setState({ name: e.currentTarget.value })}/></div>+ <div className="field">+ <Button className="positive" size="tiny" onClick={async () => await this.confirm()}>Confirm</Button>+ </div></div></div></div>diff --git a/public/services/UserService.ts b/public/services/UserService.tsnew file mode 100644index 000000000..791487226--- /dev/null+++ b/public/services/UserService.ts@@ -0,0 +1,16 @@+import { get, post, Result } from '@fider/services/http';+import { injectable } from '@fider/di';+import { Tenant } from '@fider/models';++export interface UserService {+ updateSettings(name: string): Promise<Result>;+}++@injectable()+export class HttpUserService implements UserService {+ public async updateSettings(name: string): Promise<Result> {+ return await post('/api/user/settings', {+ name,+ });+ }+}diff --git a/public/services/index.ts b/public/services/index.tsindex d06ee4796..7aee161d3 100644--- a/public/services/index.ts+++ b/public/services/index.ts@@ -1,4 +1,5 @@export * from './Session';export * from './IdeaService';export * from './TenantService';+export * from './UserService';export { Failure } from './http';diff --git a/router.go b/router.goindex 2d4f96d81..4bef5c4f4 100644--- a/router.go+++ b/router.go@@ -109,6 +109,7 @@ func GetMainEngine(settings *models.AppSettings) *web.Engine {private.Post("/api/ideas/:number/status", handlers.SetResponse())private.Post("/api/ideas/:number/support", handlers.AddSupporter())private.Post("/api/ideas/:number/unsupport", handlers.RemoveSupporter())+ private.Post("/api/user/settings", handlers.UpdateUserSettings())private.Use(middlewares.IsAuthorized(models.RoleMember, models.RoleAdministrator))