@Summary Assign role to user @ID assign-role-to-user @Security CoderSessionToken @Accept json @Produce json @Tags Users @Param user path string true "User ID, name, or me" @Param request body codersdk.UpdateRoles true "Update roles request" @Success 200 {object} codersdk.User @Router /api/v2/users/{
(rw http.ResponseWriter, r *http.Request)
| 1774 | // @Success 200 {object} codersdk.User |
| 1775 | // @Router /api/v2/users/{user}/roles [put] |
| 1776 | func (api *API) putUserRoles(rw http.ResponseWriter, r *http.Request) { |
| 1777 | var ( |
| 1778 | ctx = r.Context() |
| 1779 | // User is the user to modify. |
| 1780 | user = httpmw.UserParam(r) |
| 1781 | apiKey = httpmw.APIKey(r) |
| 1782 | auditor = *api.Auditor.Load() |
| 1783 | aReq, commitAudit = audit.InitRequest[database.User](rw, &audit.RequestParams{ |
| 1784 | Audit: auditor, |
| 1785 | Log: api.Logger, |
| 1786 | Request: r, |
| 1787 | Action: database.AuditActionWrite, |
| 1788 | }) |
| 1789 | ) |
| 1790 | defer commitAudit() |
| 1791 | aReq.Old = user |
| 1792 | |
| 1793 | if user.LoginType == database.LoginTypeOIDC && api.IDPSync.SiteRoleSyncEnabled() { |
| 1794 | httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 1795 | Message: "Cannot modify roles for OIDC users when role sync is enabled.", |
| 1796 | Detail: "'User Role Field' is set in the OIDC configuration. All role changes must come from the oidc identity provider.", |
| 1797 | }) |
| 1798 | return |
| 1799 | } |
| 1800 | |
| 1801 | if apiKey.UserID == user.ID { |
| 1802 | httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 1803 | Message: "You cannot change your own roles.", |
| 1804 | }) |
| 1805 | return |
| 1806 | } |
| 1807 | |
| 1808 | var params codersdk.UpdateRoles |
| 1809 | if !httpapi.Read(ctx, rw, r, ¶ms) { |
| 1810 | return |
| 1811 | } |
| 1812 | |
| 1813 | updatedUser, err := api.Database.UpdateUserRoles(ctx, database.UpdateUserRolesParams{ |
| 1814 | GrantedRoles: params.Roles, |
| 1815 | ID: user.ID, |
| 1816 | }) |
| 1817 | if dbauthz.IsNotAuthorizedError(err) { |
| 1818 | httpapi.Forbidden(rw) |
| 1819 | return |
| 1820 | } |
| 1821 | if err != nil { |
| 1822 | httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 1823 | Message: err.Error(), |
| 1824 | }) |
| 1825 | return |
| 1826 | } |
| 1827 | aReq.New = updatedUser |
| 1828 | |
| 1829 | organizationIDs, err := userOrganizationIDs(ctx, api, user) |
| 1830 | if err != nil { |
| 1831 | httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ |
| 1832 | Message: "Internal error fetching user's organizations.", |
| 1833 | Detail: err.Error(), |
nothing calls this directly
no test coverage detected