// UpdateOrgUser updates the user specified by uid within the organization specified by oid
// It reflects PATCH /api/orgs/:orgId/users/:userId API call.
164842
func (r *Client) UpdateOrgUser(user UserRole, oid, uid uint) (StatusMessage, error) {
	var (
		raw   []byte
		reply StatusMessage
		err   error
	)
	if raw, err = json.Marshal(user); err != nil {
		return StatusMessage{}, err
	}
	if raw, _, err = r.patch(fmt.Sprintf("api/orgs/%d/users/%d", oid, uid), nil, raw); err != nil {
		return StatusMessage{}, err
	}
	err = json.Unmarshal(raw, &reply)
	return reply, err
}
189108
func UpdateOrgUserForCurrentOrg(c *m.ReqContext, cmd m.UpdateOrgUserCommand) Response {
	cmd.OrgId = c.OrgId
	cmd.UserId = c.ParamsInt64(":userId")
	return updateOrgUserHelper(cmd)
}
161701
func (c *FakeUserIdentityMappings) Update(userIdentityMapping *user.UserIdentityMapping) (result *user.UserIdentityMapping, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootUpdateAction(useridentitymappingsResource, userIdentityMapping), &user.UserIdentityMapping{})
	if obj == nil {
		return nil, err
	}
	return obj.(*user.UserIdentityMapping), err
}
337881
func (s *Service) UpdateOrganization(w http.ResponseWriter, r *http.Request) {
	var req organizationRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		invalidJSON(w, s.Logger)
		return
	}

	if err := req.ValidUpdate(); err != nil {
		invalidData(w, err, s.Logger)
		return
	}

	ctx := r.Context()
	id := httprouter.GetParamFromContext(ctx, "oid")

	org, err := s.Store.Organizations(ctx).Get(ctx, chronograf.OrganizationQuery{ID: &id})
	if err != nil {
		Error(w, http.StatusBadRequest, err.Error(), s.Logger)
		return
	}

	if req.Name != "" {
		org.Name = req.Name
	}

	if req.DefaultRole != "" {
		org.DefaultRole = req.DefaultRole
	}

	err = s.Store.Organizations(ctx).Update(ctx, org)
	if err != nil {
		Error(w, http.StatusBadRequest, err.Error(), s.Logger)
		return
	}

	res := newOrganizationResponse(org)
	location(w, res.Links.Self)
	encodeJSON(w, http.StatusOK, res, s.Logger)

}
16753
func (f *Facade) UpdateUser(ctx datastore.Context, user userdomain.User) error {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.UpdateUser"))
	var err error
	logger := plog.WithField("userName", user.Name)
	logger.Debug("Started Facade.UpdateUser")
	defer logger.WithError(err).Debug("Finished Facade.UpdateUser")

	id := strings.TrimSpace(user.Name)
	if id == "" {
		err = errors.New("empty User.Name not allowed")
		return err
	}

	user.Name = id
	user.Password = hashPassword(user.Password)
	err = f.userStore.Put(ctx, userdomain.Key(user.Name), &user)
	return err
}
903171
func UpdateUser(c *m.ReqContext, cmd m.UpdateUserCommand) Response {
	cmd.UserId = c.ParamsInt64(":id")
	return handleUpdateUser(cmd)
}
574374
func (s *witServiceImpl) UpdateUser(ctx context.Context, updatePayload *app.UpdateUsersPayload, identityID string) error {
	// Using the UpdateUserPayload because it also describes which attribtues are being updated and which are not.
	updateUserPayload := &witservice.UpdateUserAsServiceAccountUsersPayload{
		Data: &witservice.UpdateUserData{
			Attributes: &witservice.UpdateIdentityDataAttributes{
				Bio:                   updatePayload.Data.Attributes.Bio,
				Company:               updatePayload.Data.Attributes.Company,
				ContextInformation:    updatePayload.Data.Attributes.ContextInformation,
				Email:                 updatePayload.Data.Attributes.Email,
				FullName:              updatePayload.Data.Attributes.FullName,
				ImageURL:              updatePayload.Data.Attributes.ImageURL,
				RegistrationCompleted: updatePayload.Data.Attributes.RegistrationCompleted,
				URL:                   updatePayload.Data.Attributes.URL,
				Username:              updatePayload.Data.Attributes.Username,
			},
			Type: updatePayload.Data.Type,
		},
	}

	remoteWITService, err := s.createClientWithContextSigner(ctx)

	if err != nil {
		return err
	}

	remoteUpdateUserAPIPath := witservice.UpdateUserAsServiceAccountUsersPath(identityID)
	res, err := remoteWITService.UpdateUserAsServiceAccountUsers(goasupport.ForwardContextRequestID(ctx), remoteUpdateUserAPIPath, updateUserPayload)
	if err != nil {
		return err
	}
	defer rest.CloseResponse(res)
	bodyString := rest.ReadBody(res.Body) // To prevent FDs leaks
	if res.StatusCode != http.StatusOK {
		log.Error(ctx, map[string]interface{}{
			"identity_id":     identityID,
			"username":        updatePayload.Data.Attributes.Username,
			"response_status": res.Status,
			"response_body":   bodyString,
		}, "unable to update user in WIT")
		return errors.Errorf("unable to update user in WIT. Response status: %s. Response body: %s", res.Status, bodyString)
	}
	return nil
}
198475
func (c oauthClient) UpdateUser(user wl.User) (wl.User, error) {
	body := []byte(fmt.Sprintf(`{"revision":%d,"name":"%s"}`, user.Revision, user.Name))
	url := fmt.Sprintf("%s/user", c.apiURL)

	req, err := c.newPutRequest(url, body)
	if err != nil {
		return wl.User{}, err
	}

	resp, err := c.do(req)
	if err != nil {
		return wl.User{}, err
	}

	if resp.StatusCode != http.StatusOK {
		return wl.User{}, fmt.Errorf("Unexpected response code %d - expected %d", resp.StatusCode, http.StatusOK)
	}

	returnedUser := wl.User{}
	err = json.NewDecoder(resp.Body).Decode(&returnedUser)
	if err != nil {
		return wl.User{}, err
	}

	return returnedUser, nil
}
810048
func (c *UsersClient) Update(ctx context.Context, id ID, updateUser *UpdateUser) (*User, error) {
	idBytes, err := id.MarshalText()
	if err != nil {
		return nil, err
	}

	p := fmt.Sprintf("/users/%s", string(idBytes))

	req, err := c.backend.NewRequest(http.MethodPatch, p, nil, updateUser)
	if err != nil {
		return nil, err
	}

	var resp User
	_, err = c.backend.Do(ctx, req, &resp, func(code int) error {
		return &Error{}
	})
	if err != nil {
		return nil, err
	}

	return &resp, nil
}
363152
func (s *userService) UpdateUsername(id int64, newUsername string) (datamodels.User, error) {
	return s.Update(id, datamodels.User{
		Username: newUsername,
	})
}
131090
func (s *OrganizationService) UpdateOrganization(ctx context.Context, id platform.ID, upd platform.OrganizationUpdate) (*platform.Organization, error) {
	u, err := newURL(s.Addr, organizationIDPath(id))
	if err != nil {
		return nil, err
	}

	octets, err := json.Marshal(upd)
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest("PATCH", u.String(), bytes.NewReader(octets))
	if err != nil {
		return nil, err
	}

	req.Header.Set("Content-Type", "application/json")
	SetToken(s.Token, req)

	hc := newClient(u.Scheme, s.InsecureSkipVerify)

	resp, err := hc.Do(req)
	if err != nil {
		return nil, err
	}

	if err := CheckError(resp, true); err != nil {
		return nil, err
	}

	var o platform.Organization
	if err := json.NewDecoder(resp.Body).Decode(&o); err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	return &o, nil
}
455666
func (api OrganizationsAPI) UpdateUserGrant(w http.ResponseWriter, r *http.Request) {
	globalid := mux.Vars(r)["globalid"]

	body := struct {
		Username string       `json:"username"`
		OldGrant grants.Grant `json:"oldgrant"`
		NewGrant grants.Grant `json:"newgrant"`
	}{}
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		log.Debug("Error decoding create grant body:", err)
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	if err := body.OldGrant.Validate(); err != nil {
		log.Debug("Invalid grant: ", err)
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	if err := body.NewGrant.Validate(); err != nil {
		log.Debug("Invalid grant: ", err)
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	userObj, err := SearchUser(r, body.Username)
	if err != nil && !db.IsNotFound(err) {
		log.Error("Failed to look up user identifier: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	if err != nil {
		// We can't give a grant to a user that doesn't exist
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	hasAuth, err := hasAuthorization(r, userObj.Username, globalid)
	if handleServerError(w, "checking if user has an authorization for the organization", err) {
		return
	}
	if !hasAuth {
		log.Debug("Refusing to update grant for user without authorization")
		w.WriteHeader(http.StatusForbidden)
		w.Write([]byte("User does not have an authorization for this organzation"))
		return
	}

	grantMgr := grants.NewManager(r)
	savedGrants, err := grantMgr.GetGrantsForUser(userObj.Username, globalid)
	if err != nil && !db.IsNotFound(err) {
		log.Error("Failed to get user grants: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	if db.IsNotFound(err) {
		log.Debug("Can't update grants if user doesn't have any")
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}
	found := false
	for _, grant := range savedGrants.Grants {
		if grant == body.OldGrant {
			found = true
			break
		}
	}

	if !found {
		log.Debug("Can't update grant if user doesn't have it")
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	err = grantMgr.UpdateGrant(userObj.Username, globalid, body.OldGrant, body.NewGrant)
	if err != nil {
		log.Error("Failed to update user grant: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	grantObj, err := grantMgr.GetGrantsForUser(userObj.Username, globalid)
	if err != nil {
		log.Error("Failed to look up user grants: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(grantObj.Grants)
}
615075
func (s *Service) UpdateSourceUser(w http.ResponseWriter, r *http.Request) {
	var req sourceUserRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		invalidJSON(w, s.Logger)
		return
	}
	if err := req.ValidUpdate(); err != nil {
		invalidData(w, err, s.Logger)
		return
	}

	ctx := r.Context()
	uid := httprouter.GetParamFromContext(ctx, "uid")
	srcID, ts, err := s.sourcesSeries(ctx, w, r)
	if err != nil {
		return
	}

	user := &chronograf.User{
		Name:        uid,
		Passwd:      req.Password,
		Permissions: req.Permissions,
		Roles:       req.Roles,
	}
	store := ts.Users(ctx)

	if err := store.Update(ctx, user); err != nil {
		Error(w, http.StatusBadRequest, err.Error(), s.Logger)
		return
	}

	u, err := store.Get(ctx, chronograf.UserQuery{Name: &uid})
	if err != nil {
		Error(w, http.StatusBadRequest, err.Error(), s.Logger)
		return
	}

	res := newSourceUserResponse(srcID, u.Name).WithPermissions(u.Permissions)
	if _, hasRoles := s.hasRoles(ctx, ts); hasRoles {
		res.WithRoles(srcID, u.Roles)
	}
	location(w, res.Links.Self)
	encodeJSON(w, http.StatusOK, res, s.Logger)
}
219140
func (s *UserStorage) Update(c model.User) error {
	_, exists := s.users[c.ID]
	if !exists {
		return fmt.Errorf("User with id %s does not exist", c.ID)
	}
	s.users[c.ID] = &c

	return nil
}
587855
func UpdateUserPreferences(c *m.ReqContext, dtoCmd dtos.UpdatePrefsCmd) Response {
	return updatePreferencesFor(c.OrgId, c.UserId, 0, &dtoCmd)
}
647238
func (s *OrgService) UpdateOrganization(ctx context.Context, id influxdb.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) {
	if err := authorizeWriteOrg(ctx, id); err != nil {
		return nil, err
	}

	return s.s.UpdateOrganization(ctx, id, upd)
}
983032
func (u *UsersClient) Update(ctx context.Context, delta apitypes.ProfileUpdate) (envelope.UserInf, error) {
	e := envelope.Unsigned{}
	err := u.client.DaemonRoundTrip(ctx, "PATCH", "/self", nil, &delta, &e, nil)
	if err != nil {
		return nil, err
	}

	return envelope.ConvertUser(&e)
}