From f87d42916f1ec4287daad29d6ffd4145dfc4b5cd Mon Sep 17 00:00:00 2001 From: Joram Wilander Date: Thu, 16 Feb 2017 09:46:55 -0500 Subject: Implement PUT /users/{user_id}/patch endpoint for APIv4 (#5418) --- api4/user.go | 27 +++++++++++++++++++++ api4/user_test.go | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++++ app/user.go | 32 +++++++++++++++++++++---- model/client4.go | 10 ++++++++ model/user.go | 70 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 202 insertions(+), 4 deletions(-) diff --git a/api4/user.go b/api4/user.go index d8d071cd2..e394b9661 100644 --- a/api4/user.go +++ b/api4/user.go @@ -21,6 +21,7 @@ func InitUser() { BaseRoutes.User.Handle("", ApiSessionRequired(getUser)).Methods("GET") BaseRoutes.User.Handle("", ApiSessionRequired(updateUser)).Methods("PUT") + BaseRoutes.User.Handle("/patch", ApiSessionRequired(patchUser)).Methods("PUT") BaseRoutes.User.Handle("", ApiSessionRequired(deleteUser)).Methods("DELETE") BaseRoutes.User.Handle("/roles", ApiSessionRequired(updateUserRoles)).Methods("PUT") BaseRoutes.User.Handle("/password", ApiSessionRequired(updatePassword)).Methods("PUT") @@ -255,6 +256,32 @@ func updateUser(c *Context, w http.ResponseWriter, r *http.Request) { } } +func patchUser(c *Context, w http.ResponseWriter, r *http.Request) { + c.RequireUserId() + if c.Err != nil { + return + } + + patch := model.UserPatchFromJson(r.Body) + if patch == nil { + c.SetInvalidParam("user") + return + } + + if !app.SessionHasPermissionToUser(c.Session, c.Params.UserId) { + c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + return + } + + if ruser, err := app.PatchUser(c.Params.UserId, patch, c.GetSiteURL(), c.IsSystemAdmin()); err != nil { + c.Err = err + return + } else { + c.LogAudit("") + w.Write([]byte(ruser.ToJson())) + } +} + func deleteUser(c *Context, w http.ResponseWriter, r *http.Request) { c.RequireUserId() if c.Err != nil { diff --git a/api4/user_test.go b/api4/user_test.go index 79589bdad..771a53cbe 100644 --- a/api4/user_test.go +++ b/api4/user_test.go @@ -349,6 +349,73 @@ func TestUpdateUser(t *testing.T) { CheckNoError(t, resp) } +func TestPatchUser(t *testing.T) { + th := Setup().InitBasic().InitSystemAdmin() + defer TearDown() + Client := th.Client + + user := th.CreateUser() + Client.Login(user.Email, user.Password) + + patch := &model.UserPatch{} + + patch.Nickname = new(string) + *patch.Nickname = "Joram Wilander" + patch.FirstName = new(string) + *patch.FirstName = "Joram" + patch.LastName = new(string) + *patch.LastName = "Wilander" + patch.Position = new(string) + + ruser, resp := Client.PatchUser(user.Id, patch) + CheckNoError(t, resp) + CheckUserSanitization(t, ruser) + + if ruser.Nickname != "Joram Wilander" { + t.Fatal("Nickname did not update properly") + } + if ruser.FirstName != "Joram" { + t.Fatal("FirstName did not update properly") + } + if ruser.LastName != "Wilander" { + t.Fatal("LastName did not update properly") + } + if ruser.Position != "" { + t.Fatal("Position did not update properly") + } + if ruser.Username != user.Username { + t.Fatal("Username should not have updated") + } + + _, resp = Client.PatchUser("junk", patch) + CheckBadRequestStatus(t, resp) + + ruser.Id = model.NewId() + _, resp = Client.PatchUser(model.NewId(), patch) + CheckForbiddenStatus(t, resp) + + if r, err := Client.DoApiPut("/users/"+user.Id+"/patch", "garbage"); err == nil { + t.Fatal("should have errored") + } else { + if r.StatusCode != http.StatusBadRequest { + t.Log("actual: " + strconv.Itoa(r.StatusCode)) + t.Log("expected: " + strconv.Itoa(http.StatusBadRequest)) + t.Fatal("wrong status code") + } + } + + Client.Logout() + _, resp = Client.PatchUser(user.Id, patch) + CheckUnauthorizedStatus(t, resp) + + th.LoginBasic() + _, resp = Client.PatchUser(user.Id, patch) + CheckForbiddenStatus(t, resp) + + _, resp = th.SystemAdminClient.PatchUser(user.Id, patch) + CheckNoError(t, resp) +} + func TestDeleteUser(t *testing.T) { th := Setup().InitBasic().InitSystemAdmin() Client := th.Client diff --git a/app/user.go b/app/user.go index c34bf87e3..a0cb2a49f 100644 --- a/app/user.go +++ b/app/user.go @@ -858,13 +858,37 @@ func UpdateUserAsUser(user *model.User, siteURL string, asAdmin bool) (*model.Us SanitizeProfile(updatedUser, asAdmin) + sendUpdatedUserEvent(updatedUser) + + return updatedUser, nil +} + +func PatchUser(userId string, patch *model.UserPatch, siteURL string, asAdmin bool) (*model.User, *model.AppError) { + user, err := GetUser(userId) + if err != nil { + return nil, err + } + + user.Patch(patch) + + updatedUser, err := UpdateUser(user, siteURL, true) + if err != nil { + return nil, err + } + + SanitizeProfile(updatedUser, asAdmin) + + sendUpdatedUserEvent(updatedUser) + + return updatedUser, nil +} + +func sendUpdatedUserEvent(user *model.User) { omitUsers := make(map[string]bool, 1) - omitUsers[updatedUser.Id] = true + omitUsers[user.Id] = true message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_USER_UPDATED, "", "", "", omitUsers) - message.Add("user", updatedUser) + message.Add("user", user) go Publish(message) - - return updatedUser, nil } func UpdateUser(user *model.User, siteURL string, sendNotifications bool) (*model.User, *model.AppError) { diff --git a/model/client4.go b/model/client4.go index 5c51026a9..48a88e968 100644 --- a/model/client4.go +++ b/model/client4.go @@ -334,6 +334,16 @@ func (c *Client4) UpdateUser(user *User) (*User, *Response) { } } +// PatchUser partially updates a user in the system. Any missing fields are not updated. +func (c *Client4) PatchUser(userId string, patch *UserPatch) (*User, *Response) { + if r, err := c.DoApiPut(c.GetUserRoute(userId)+"/patch", patch.ToJson()); err != nil { + return nil, &Response{StatusCode: r.StatusCode, Error: err} + } else { + defer closeBody(r) + return UserFromJson(r.Body), BuildResponse(r) + } +} + // UpdateUserPassword updates a user's password. Must be logged in as the user or be a system administrator. func (c *Client4) UpdateUserPassword(userId, currentPassword, newPassword string) (bool, *Response) { requestBody := map[string]string{"current_password": currentPassword, "new_password": newPassword} diff --git a/model/user.go b/model/user.go index 8e02fe1ab..7057ab101 100644 --- a/model/user.go +++ b/model/user.go @@ -61,6 +61,18 @@ type User struct { LastActivityAt int64 `db:"-" json:"last_activity_at,omitempty"` } +type UserPatch struct { + Username *string `json:"username"` + Nickname *string `json:"nickname"` + FirstName *string `json:"first_name"` + LastName *string `json:"last_name"` + Position *string `json:"position"` + Email *string `json:"email"` + Props *StringMap `json:"props,omitempty"` + NotifyProps *StringMap `json:"notify_props,omitempty"` + Locale *string `json:"locale"` +} + // IsValid validates the user and returns an error if it isn't configured // correctly. func (u *User) IsValid() *AppError { @@ -215,6 +227,44 @@ func (user *User) UpdateMentionKeysFromUsername(oldUsername string) { } } +func (u *User) Patch(patch *UserPatch) { + if patch.Username != nil { + u.Username = *patch.Username + } + + if patch.Nickname != nil { + u.Nickname = *patch.Nickname + } + + if patch.FirstName != nil { + u.FirstName = *patch.FirstName + } + + if patch.LastName != nil { + u.LastName = *patch.LastName + } + + if patch.Position != nil { + u.Position = *patch.Position + } + + if patch.Email != nil { + u.Email = *patch.Email + } + + if patch.Props != nil { + u.Props = *patch.Props + } + + if patch.NotifyProps != nil { + u.NotifyProps = *patch.NotifyProps + } + + if patch.Locale != nil { + u.Locale = *patch.Locale + } +} + // ToJson convert a User to a json string func (u *User) ToJson() string { b, err := json.Marshal(u) @@ -225,6 +275,15 @@ func (u *User) ToJson() string { } } +func (u *UserPatch) ToJson() string { + b, err := json.Marshal(u) + if err != nil { + return "" + } else { + return string(b) + } +} + // Generate a valid strong etag so the browser can cache the results func (u *User) Etag(showFullName, showEmail bool) string { return Etag(u.Id, u.UpdateAt, showFullName, showEmail) @@ -419,6 +478,17 @@ func UserFromJson(data io.Reader) *User { } } +func UserPatchFromJson(data io.Reader) *UserPatch { + decoder := json.NewDecoder(data) + var user UserPatch + err := decoder.Decode(&user) + if err == nil { + return &user + } else { + return nil + } +} + func UserMapToJson(u map[string]*User) string { b, err := json.Marshal(u) if err != nil { -- cgit v1.2.3-1-g7c22