Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

chore: add organization member api + cli#13577

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Emyrk merged 6 commits intomainfromstevenmasley/add_orgmember_cli
Jun 20, 2024
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletioncli/organization.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,8 +29,8 @@ func (r *RootCmd) organizations() *serpent.Command {
r.currentOrganization(),
r.switchOrganization(),
r.createOrganization(),
r.organizationRoles(),
r.organizationMembers(),
r.organizationRoles(),
},
}

Expand Down
32 changes: 32 additions & 0 deletionscli/organizationmembers.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@ func (r *RootCmd) organizationMembers() *serpent.Command {
Children: []*serpent.Command{
r.listOrganizationMembers(),
r.assignOrganizationRoles(),
r.addOrganizationMember(),
},
Handler: func(inv *serpent.Invocation) error {
return inv.Command.HelpHandler(inv)
Expand All@@ -28,6 +29,37 @@ func (r *RootCmd) organizationMembers() *serpent.Command {
return cmd
}

func (r *RootCmd) addOrganizationMember() *serpent.Command {
client := new(codersdk.Client)

cmd := &serpent.Command{
Use: "add <username | user_id>",
Short: "Add a new member to the current organization",
Middleware: serpent.Chain(
r.InitClient(client),
serpent.RequireNArgs(1),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
organization, err := CurrentOrganization(r, inv, client)
if err != nil {
return err
}
user := inv.Args[0]

_, err = client.PostOrganizationMember(ctx, organization.ID, user)
if err != nil {
return xerrors.Errorf("could not add member to organization: %w", err)
}

_, _ = fmt.Fprintln(inv.Stdout, "Organization member added")
return nil
},
}

return cmd
}

func (r *RootCmd) assignOrganizationRoles() *serpent.Command {
client := new(codersdk.Client)

Expand Down
38 changes: 38 additions & 0 deletionscli/organizationmembers_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@ import (
"github.com/coder/coder/v2/cli/clitest"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/testutil"
)

Expand All@@ -34,3 +35,40 @@ func TestListOrganizationMembers(t *testing.T) {
require.Contains(t, buf.String(), owner.UserID.String())
})
}

func TestAddOrganizationMembers(t *testing.T) {
t.Parallel()

t.Run("OK", func(t *testing.T) {
t.Parallel()

ownerClient := coderdtest.New(t, &coderdtest.Options{})
owner := coderdtest.CreateFirstUser(t, ownerClient)
_, user := coderdtest.CreateAnotherUser(t, ownerClient, owner.OrganizationID)

ctx := testutil.Context(t, testutil.WaitMedium)
//nolint:gocritic // must be an owner, only owners can create orgs
otherOrg, err := ownerClient.CreateOrganization(ctx, codersdk.CreateOrganizationRequest{
Name: "Other",
DisplayName: "",
Description: "",
Icon: "",
})
require.NoError(t, err, "create another organization")

inv, root := clitest.New(t, "organization", "members", "add", "--organization", otherOrg.ID.String(), user.Username)
//nolint:gocritic // must be an owner
clitest.SetupConfig(t, ownerClient, root)

buf := new(bytes.Buffer)
inv.Stdout = buf
err = inv.WithContext(ctx).Run()
require.NoError(t, err)

//nolint:gocritic // must be an owner
members, err := ownerClient.OrganizationMembers(ctx, otherOrg.ID)
require.NoError(t, err)

require.Len(t, members, 2)
})
}
41 changes: 41 additions & 0 deletionscoderd/apidoc/docs.go
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

37 changes: 37 additions & 0 deletionscoderd/apidoc/swagger.json
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

23 changes: 18 additions & 5 deletionscoderd/coderd.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -845,11 +845,24 @@ func New(options *Options) *API {
})

r.Route("/{user}", func(r chi.Router) {
r.Use(
httpmw.ExtractOrganizationMemberParam(options.Database),
)
r.Put("/roles", api.putMemberRoles)
r.Post("/workspaces", api.postWorkspacesByOrganization)
r.Group(func(r chi.Router) {
r.Use(
// Adding a member requires "read" permission
// on the site user. So limited to owners and user-admins.
// TODO: Allow org-admins to add users via some new permission? Or give them
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

For a future PR: I think a new permission would be nice here, I don't think it's intuitive for developers to know that a read permission on a site user grants them access to add new org members.

Copy link
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

@f0ssel one option is just to not require the read permission to add a user, using the system context to fetch a user.

I agree it is not intuitive at present. Since orgs are still a ways out, I'm not spending too much time on these details atm.

f0ssel reacted with thumbs up emoji
// read on site users.
httpmw.ExtractUserParam(options.Database),
)
r.Post("/", api.postOrganizationMember)
})

r.Group(func(r chi.Router) {
r.Use(
httpmw.ExtractOrganizationMemberParam(options.Database),
)
r.Put("/roles", api.putMemberRoles)
r.Post("/workspaces", api.postWorkspacesByOrganization)
})
})
})
})
Expand Down
47 changes: 47 additions & 0 deletionscoderd/members.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,12 +9,59 @@ import (

"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/db2sdk"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/httpmw"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/codersdk"
)

// @Summary Add organization member
// @ID add-organization-member
// @Security CoderSessionToken
// @Produce json
// @Tags Members
// @Param organization path string true "Organization ID"
// @Param user path string true "User ID, name, or me"
// @Success 200 {object} codersdk.OrganizationMember
// @Router /organizations/{organization}/members/{user} [post]
func (api *API) postOrganizationMember(rw http.ResponseWriter, r *http.Request) {
var (
ctx = r.Context()
organization = httpmw.OrganizationParam(r)
user = httpmw.UserParam(r)
)

member, err := api.Database.InsertOrganizationMember(ctx, database.InsertOrganizationMemberParams{
OrganizationID: organization.ID,
UserID: user.ID,
CreatedAt: dbtime.Now(),
UpdatedAt: dbtime.Now(),
Roles: []string{},
})
if httpapi.Is404Error(err) {
httpapi.ResourceNotFound(rw)
return
}
if err != nil {
httpapi.InternalServerError(rw, err)
return
}

resp, err := convertOrganizationMembers(ctx, api.Database, []database.OrganizationMember{member})
if err != nil {
httpapi.InternalServerError(rw, err)
return
}

if len(resp) == 0 {
httpapi.InternalServerError(rw, xerrors.Errorf("marshal member"))
return
}

httpapi.Write(ctx, rw, http.StatusOK, resp[0])
}

// @Summary List organization members
// @ID list-organization-members
// @Security CoderSessionToken
Expand Down
59 changes: 59 additions & 0 deletionscoderd/members_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,65 @@ import (
"github.com/coder/coder/v2/testutil"
)

func TestAddMember(t *testing.T) {
t.Parallel()

t.Run("OK", func(t *testing.T) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

I think testing to error cases like missing user and org 404, etc for posterity could be good as well

Emyrk reacted with thumbs up emoji
t.Parallel()
owner := coderdtest.New(t, nil)
first := coderdtest.CreateFirstUser(t, owner)
ctx := testutil.Context(t, testutil.WaitMedium)
org, err := owner.CreateOrganization(ctx, codersdk.CreateOrganizationRequest{
Name: "other",
DisplayName: "",
Description: "",
Icon: "",
})
require.NoError(t, err)

// Make a user not in the second organization
_, user := coderdtest.CreateAnotherUser(t, owner, first.OrganizationID)

members, err := owner.OrganizationMembers(ctx, org.ID)
require.NoError(t, err)
require.Len(t, members, 1) // Verify just the 1 member

// Add user to org
_, err = owner.PostOrganizationMember(ctx, org.ID, user.Username)
require.NoError(t, err)

members, err = owner.OrganizationMembers(ctx, org.ID)
require.NoError(t, err)
// Owner + new member
require.Len(t, members, 2)
require.ElementsMatch(t,
[]uuid.UUID{first.UserID, user.ID},
db2sdk.List(members, onlyIDs))
})

t.Run("UserNotExists", func(t *testing.T) {
t.Parallel()
owner := coderdtest.New(t, nil)
_ = coderdtest.CreateFirstUser(t, owner)
ctx := testutil.Context(t, testutil.WaitMedium)

org, err := owner.CreateOrganization(ctx, codersdk.CreateOrganizationRequest{
Name: "other",
DisplayName: "",
Description: "",
Icon: "",
})
require.NoError(t, err)

// Add user to org
_, err = owner.PostOrganizationMember(ctx, org.ID, uuid.NewString())
require.Error(t, err)
var apiErr *codersdk.Error
require.ErrorAs(t, err, &apiErr)
require.Contains(t, apiErr.Message, "must be an existing")
})
}

func TestListMembers(t *testing.T) {
t.Parallel()

Expand Down
14 changes: 14 additions & 0 deletionscodersdk/users.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -379,6 +379,20 @@ func (c *Client) UpdateUserPassword(ctx context.Context, user string, req Update
return nil
}

// PostOrganizationMember adds a user to an organization
func (c *Client) PostOrganizationMember(ctx context.Context, organizationID uuid.UUID, user string) (OrganizationMember, error) {
res, err := c.Request(ctx, http.MethodPost, fmt.Sprintf("/api/v2/organizations/%s/members/%s", organizationID, user), nil)
if err != nil {
return OrganizationMember{}, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return OrganizationMember{}, ReadBodyAsError(res)
}
var member OrganizationMember
return member, json.NewDecoder(res.Body).Decode(&member)
}

// OrganizationMembers lists all members in an organization
func (c *Client) OrganizationMembers(ctx context.Context, organizationID uuid.UUID) ([]OrganizationMemberWithName, error) {
res, err := c.Request(ctx, http.MethodGet, fmt.Sprintf("/api/v2/organizations/%s/members/", organizationID), nil)
Expand Down
Loading
Loading

[8]ページ先頭

©2009-2025 Movatter.jp