Open platform to collect and prioritize feedback
feature: new API to create users (#513)
Guilherme Oenning56330e11ace1
diff --git a/app/actions/user.go b/app/actions/user.goindex 050996026..ffd50eed1 100644--- a/app/actions/user.go+++ b/app/actions/user.go@@ -7,6 +7,50 @@ import ("github.com/getfider/fider/app/pkg/validate")+//CreateUser is the action to create a new user+type CreateUser struct {+ Model *models.CreateUser+}++// Initialize the model+func (input *CreateUser) Initialize() interface{} {+ input.Model = new(models.CreateUser)+ return input.Model+}++// IsAuthorized returns true if current user is authorized to perform this action+func (input *CreateUser) IsAuthorized(user *models.User, services *app.Services) bool {+ return user != nil && user.IsAdministrator()+}++// Validate is current model is valid+func (input *CreateUser) Validate(user *models.User, services *app.Services) *validate.Result {+ result := validate.Success()++ if input.Model.Name == "" {+ result.AddFieldFailure("name", "Name is required.")+ } else if len(input.Model.Name) > 100 {+ result.AddFieldFailure("name", "Name must have less than 100 characters.")+ }++ if input.Model.Email == "" && input.Model.Reference == "" {+ result.AddFieldFailure("", "Either email or reference is required")+ } else {+ if input.Model.Email != "" {+ messages := validate.Email(input.Model.Email)+ if len(messages) > 0 {+ result.AddFieldFailure("email", messages...)+ }+ }++ if len(input.Model.Reference) > 100 {+ result.AddFieldFailure("reference", "Reference must have less than 100 characters.")+ }+ }++ return result+}+//ChangeUserRole is the input model change role of an usertype ChangeUserRole struct {Model *models.ChangeUserRolediff --git a/app/actions/user_test.go b/app/actions/user_test.goindex aeedc124d..3bc2905a0 100644--- a/app/actions/user_test.go+++ b/app/actions/user_test.go@@ -7,8 +7,91 @@ import ("github.com/getfider/fider/app/actions""github.com/getfider/fider/app/models". "github.com/getfider/fider/app/pkg/assert"+ "github.com/getfider/fider/app/pkg/rand")+func TestCreateUser_InvalidInput(t *testing.T) {+ RegisterT(t)++ testCases := []struct {+ expected []string+ message string+ input *models.CreateUser+ }{+ {+ expected: []string{"name"},+ message: "Either email or reference is required",+ input: &models.CreateUser{},+ },+ {+ expected: []string{"email"},+ input: &models.CreateUser{+ Name: "Jon Snow",+ Email: "helloworld",+ },+ },+ {+ expected: []string{"name", "email", "reference"},+ input: &models.CreateUser{+ Name: rand.String(101),+ Email: rand.String(201),+ Reference: rand.String(101),+ },+ },+ }++ for _, testCase := range testCases {+ action := &actions.CreateUser{+ Model: testCase.input,+ }+ result := action.Validate(nil, services)+ ExpectFailed(result, testCase.expected...)+ if testCase.message != "" {+ for k, v := range result.Errors {+ if v.Field == "" {+ Expect(result.Errors[k].Message).Equals(testCase.message)+ }+ }+ }+ }+}++func TestCreateUser_ValidInput(t *testing.T) {+ RegisterT(t)++ testCases := []struct {+ input *models.CreateUser+ }{+ {+ input: &models.CreateUser{+ Name: "John Snow",+ Email: "[email protected]",+ Reference: "812747824",+ },+ },+ {+ input: &models.CreateUser{+ Name: "John Snow",+ Email: "[email protected]",+ },+ },+ {+ input: &models.CreateUser{+ Name: "John Snow",+ Reference: "812747824",+ },+ },+ }++ for _, testCase := range testCases {+ action := &actions.CreateUser{+ Model: testCase.input,+ }+ result := action.Validate(nil, services)+ ExpectSuccess(result)+ }+}+func TestChangeUserRole_Unauthorized(t *testing.T) {RegisterT(t)diff --git a/app/cmd/routes.go b/app/cmd/routes.goindex 4276a8b74..1d91fed6a 100644--- a/app/cmd/routes.go+++ b/app/cmd/routes.go@@ -169,6 +169,7 @@ func routes(r *web.Engine) *web.Engine {//From this step, only Administrators are allowedapi.Use(middlewares.IsAuthorized(models.RoleAdministrator))+ api.Post("/api/v1/users", apiv1.CreateUser())api.Delete("/api/v1/posts/:number", apiv1.DeletePost())api.Post("/api/v1/tags", apiv1.CreateEditTag())api.Put("/api/v1/tags/:slug", apiv1.CreateEditTag())diff --git a/app/handlers/apiv1/user.go b/app/handlers/apiv1/user.goindex 70a4f6ad8..f52616ffd 100644--- a/app/handlers/apiv1/user.go+++ b/app/handlers/apiv1/user.go@@ -1,6 +1,10 @@package apiv1import (+ "github.com/getfider/fider/app"+ "github.com/getfider/fider/app/actions"+ "github.com/getfider/fider/app/models"+ "github.com/getfider/fider/app/pkg/errors""github.com/getfider/fider/app/pkg/web")@@ -15,3 +19,45 @@ func ListUsers() web.HandlerFunc {return c.Ok(users)}}++// CreateUser is used to create new users+func CreateUser() web.HandlerFunc {+ return func(c web.Context) error {+ input := new(actions.CreateUser)+ if result := c.BindTo(input); !result.Ok {+ return c.HandleValidation(result)+ }++ user, err := c.Services().Users.GetByProvider("reference", input.Model.Reference)+ if err != nil && errors.Cause(err) == app.ErrNotFound {+ if input.Model.Email != "" {+ user, err = c.Services().Users.GetByEmail(input.Model.Email)+ }+ if err != nil && errors.Cause(err) == app.ErrNotFound {+ user = &models.User{+ Tenant: c.Tenant(),+ Name: input.Model.Name,+ Email: input.Model.Email,+ }+ err = c.Services().Users.Register(user)+ }+ }++ if err != nil {+ return c.Failure(err)+ }++ if input.Model.Reference != "" && !user.HasProvider("reference") {+ if err := c.Services().Users.RegisterProvider(user.ID, &models.UserProvider{+ Name: "reference",+ UID: input.Model.Reference,+ }); err != nil {+ return c.Failure(err)+ }+ }++ return c.Ok(web.Map{+ "id": user.ID,+ })+ }+}diff --git a/app/handlers/apiv1/user_test.go b/app/handlers/apiv1/user_test.goindex d51de228e..c314cd567 100644--- a/app/handlers/apiv1/user_test.go+++ b/app/handlers/apiv1/user_test.go@@ -24,3 +24,111 @@ func TestListUsersHandler(t *testing.T) {Expect(query.IsArray()).IsTrue()Expect(query.ArrayLength()).Equals(2)}++func TestCreateUser_ExistingEmail(t *testing.T) {+ RegisterT(t)++ server, services := mock.NewServer()+ services.SetCurrentTenant(mock.DemoTenant)+ services.SetCurrentUser(mock.JonSnow)++ status, query := server.+ AsUser(mock.JonSnow).+ OnTenant(mock.DemoTenant).+ ExecutePostAsJSON(apiv1.CreateUser(),+ `{+ "name": "Arya",+ "email": "[email protected]",+ "reference": "AA564645"+ }`)++ Expect(status).Equals(http.StatusOK)+ id := query.Int32("id")+ user, err := services.Users.GetByID(id)+ Expect(err).IsNil()+ Expect(user.ID).Equals(mock.AryaStark.ID)+ Expect(user.Name).Equals("Arya Stark")+ Expect(user.Email).Equals("[email protected]")+ Expect(user.Tenant).Equals(mock.DemoTenant)+ Expect(user.Providers).HasLen(1)+ Expect(user.Providers[0].Name).Equals("reference")+ Expect(user.Providers[0].UID).Equals("AA564645")+}++func TestCreateUser_ExistingEmail_NoReference(t *testing.T) {+ RegisterT(t)++ server, services := mock.NewServer()+ services.SetCurrentTenant(mock.DemoTenant)+ services.SetCurrentUser(mock.JonSnow)++ status, query := server.+ AsUser(mock.JonSnow).+ OnTenant(mock.DemoTenant).+ ExecutePostAsJSON(apiv1.CreateUser(),+ `{+ "name": "Arya",+ "email": "[email protected]"+ }`)++ Expect(status).Equals(http.StatusOK)+ id := query.Int32("id")+ user, err := services.Users.GetByID(id)+ Expect(err).IsNil()+ Expect(user.ID).Equals(mock.AryaStark.ID)+ Expect(user.Name).Equals("Arya Stark")+ Expect(user.Email).Equals("[email protected]")+ Expect(user.Tenant).Equals(mock.DemoTenant)+ Expect(user.Providers).HasLen(0)+}++func TestCreateUser_NewUser(t *testing.T) {+ RegisterT(t)++ server, services := mock.NewServer()+ services.SetCurrentTenant(mock.DemoTenant)+ services.SetCurrentUser(mock.JonSnow)++ status, query := server.+ AsUser(mock.JonSnow).+ OnTenant(mock.DemoTenant).+ ExecutePostAsJSON(apiv1.CreateUser(),+ `{+ "name": "Martin",+ "email": "[email protected]",+ "reference": "89014714"+ }`)++ Expect(status).Equals(http.StatusOK)+ userID := query.Int32("id")+ user, err := services.Users.GetByID(userID)+ Expect(err).IsNil()+ Expect(user.ID).Equals(userID)+ Expect(user.Name).Equals("Martin")+ Expect(user.Email).Equals("[email protected]")+ Expect(user.Tenant).Equals(mock.DemoTenant)+ Expect(user.Providers).HasLen(1)+ Expect(user.Providers[0].Name).Equals("reference")+ Expect(user.Providers[0].UID).Equals("89014714")++ // Try to recreate another user with same reference+ status, query = server.+ AsUser(mock.JonSnow).+ OnTenant(mock.DemoTenant).+ ExecutePostAsJSON(apiv1.CreateUser(),+ `{+ "name": "The Other Martin",+ "reference": "89014714"+ }`)++ Expect(status).Equals(http.StatusOK)+ theOtherUserID := query.Int32("id")+ Expect(theOtherUserID).Equals(userID)+ user, err = services.Users.GetByID(theOtherUserID)+ Expect(err).IsNil()+ Expect(user.Name).Equals("Martin")+ Expect(user.Email).Equals("[email protected]")+ Expect(user.Providers).HasLen(1)+ Expect(user.Providers[0].Name).Equals("reference")+ Expect(user.Providers[0].UID).Equals("89014714")+}diff --git a/app/models/identity.go b/app/models/identity.goindex b9991df44..e45141331 100644--- a/app/models/identity.go+++ b/app/models/identity.go@@ -280,6 +280,13 @@ type UpdateUserSettings struct {Settings map[string]string `json:"settings"`}+// CreateUser is the input model to create a new user+type CreateUser struct {+ Name string `json:"name"`+ Email string `json:"email"`+ Reference string `json:"reference"`+}+// ChangeUserRole is the input model change role of an usertype ChangeUserRole struct {Role Role `route:"role"`