@Summary Update user profile @ID update-user-profile @Security CoderSessionToken @Accept json @Produce json @Tags Users @Param user path string true "User ID, name, or me" @Param request body codersdk.UpdateUserProfileRequest true "Updated profile" @Success 200 {object} codersdk.User @Router /api/v2
(rw http.ResponseWriter, r *http.Request)
| 867 | // @Success 200 {object} codersdk.User |
| 868 | // @Router /api/v2/users/{user}/profile [put] |
| 869 | func (api *API) putUserProfile(rw http.ResponseWriter, r *http.Request) { |
| 870 | var ( |
| 871 | ctx = r.Context() |
| 872 | user = httpmw.UserParam(r) |
| 873 | auditor = *api.Auditor.Load() |
| 874 | aReq, commitAudit = audit.InitRequest[database.User](rw, &audit.RequestParams{ |
| 875 | Audit: auditor, |
| 876 | Log: api.Logger, |
| 877 | Request: r, |
| 878 | Action: database.AuditActionWrite, |
| 879 | }) |
| 880 | ) |
| 881 | defer commitAudit() |
| 882 | aReq.Old = user |
| 883 | |
| 884 | var params codersdk.UpdateUserProfileRequest |
| 885 | if !httpapi.Read(ctx, rw, r, ¶ms) { |
| 886 | return |
| 887 | } |
| 888 | |
| 889 | // If caller wants to update user's username, they need "update_users" permission. |
| 890 | // This is restricted to user admins only. |
| 891 | if params.Username != user.Username && !api.Authorize(r, policy.ActionUpdate, user) { |
| 892 | httpapi.ResourceNotFound(rw) |
| 893 | return |
| 894 | } |
| 895 | |
| 896 | existentUser, err := api.Database.GetUserByEmailOrUsername(ctx, database.GetUserByEmailOrUsernameParams{ |
| 897 | Username: params.Username, |
| 898 | }) |
| 899 | isDifferentUser := existentUser.ID != user.ID |
| 900 | |
| 901 | if err == nil && isDifferentUser { |
| 902 | responseErrors := []codersdk.ValidationError{{ |
| 903 | Field: "username", |
| 904 | Detail: "This username is already in use.", |
| 905 | }} |
| 906 | httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{ |
| 907 | Message: "A user with this username already exists.", |
| 908 | Validations: responseErrors, |
| 909 | }) |
| 910 | return |
| 911 | } |
| 912 | if !errors.Is(err, sql.ErrNoRows) && isDifferentUser { |
| 913 | httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ |
| 914 | Message: "Internal error fetching user.", |
| 915 | Detail: err.Error(), |
| 916 | }) |
| 917 | return |
| 918 | } |
| 919 | |
| 920 | updatedUserProfile, err := api.Database.UpdateUserProfile(ctx, database.UpdateUserProfileParams{ |
| 921 | ID: user.ID, |
| 922 | Email: user.Email, |
| 923 | Name: params.Name, |
| 924 | AvatarURL: user.AvatarURL, |
| 925 | Username: params.Username, |
| 926 | UpdatedAt: dbtime.Now(), |
nothing calls this directly
no test coverage detected