Skip to content

feat: Add users create and list commands #1111

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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 25, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
90 changes: 90 additions & 0 deletions cli/usercreate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package cli

import (
"fmt"

"github.com/go-playground/validator/v10"
"github.com/spf13/cobra"
"golang.org/x/xerrors"

"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/cryptorand"
)

func userCreate() *cobra.Command {
var (
email string
username string
password string
)
cmd := &cobra.Command{
Use: "create",
RunE: func(cmd *cobra.Command, args []string) error {
client, err := createClient(cmd)
if err != nil {
return err
}
organization, err := currentOrganization(cmd, client)
if err != nil {
return err
}
if username == "" {
username, err = cliui.Prompt(cmd, cliui.PromptOptions{
Text: "Username:",
})
if err != nil {
return err
}
}
if email == "" {
email, err = cliui.Prompt(cmd, cliui.PromptOptions{
Text: "Email:",
Validate: func(s string) error {
err := validator.New().Var(s, "email")
if err != nil {
return xerrors.New("That's not a valid email address!")
}
return err
},
})
if err != nil {
return err
}
}
if password == "" {
password, err = cryptorand.StringCharset(cryptorand.Human, 12)
if err != nil {
return err
}
}

_, err = client.CreateUser(cmd.Context(), codersdk.CreateUserRequest{
Email: email,
Username: username,
Password: password,
OrganizationID: organization.ID,
})
if err != nil {
return err
}
_, _ = fmt.Fprintln(cmd.ErrOrStderr(), `A new user has been created!
Share the instructions below to get them started.
`+cliui.Styles.Placeholder.Render("—————————————————————————————————————————————————")+`
Download the Coder command line for your operating system:
https://github.com/coder/coder/releases

Run `+cliui.Styles.Code.Render("coder login "+client.URL.String())+` to authenticate.

Your email is: `+cliui.Styles.Field.Render(email)+`
Your password is: `+cliui.Styles.Field.Render(password)+`

Create a workspace `+cliui.Styles.Code.Render("coder workspaces create")+`!`)
return nil
},
}
cmd.Flags().StringVarP(&email, "email", "e", "", "Specifies an email address for the new user.")
cmd.Flags().StringVarP(&username, "username", "u", "", "Specifies a username for the new user.")
cmd.Flags().StringVarP(&password, "password", "p", "", "Specifies a password for the new user.")
return cmd
}
42 changes: 42 additions & 0 deletions cli/usercreate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package cli_test

import (
"testing"

"github.com/stretchr/testify/require"

"github.com/coder/coder/cli/clitest"
"github.com/coder/coder/coderd/coderdtest"
"github.com/coder/coder/pty/ptytest"
)

func TestUserCreate(t *testing.T) {
t.Parallel()
t.Run("Prompts", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
coderdtest.CreateFirstUser(t, client)
cmd, root := clitest.New(t, "users", "create")
clitest.SetupConfig(t, client, root)
doneChan := make(chan struct{})
pty := ptytest.New(t)
cmd.SetIn(pty.Input())
cmd.SetOut(pty.Output())
go func() {
defer close(doneChan)
err := cmd.Execute()
require.NoError(t, err)
}()
matches := []string{
"Username", "dean",
"Email", "dean@coder.com",
}
for i := 0; i < len(matches); i += 2 {
match := matches[i]
value := matches[i+1]
pty.ExpectMatch(match)
pty.WriteLine(value)
}
<-doneChan
})
}
46 changes: 46 additions & 0 deletions cli/userlist.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package cli

import (
"fmt"
"sort"
"time"

"github.com/jedib0t/go-pretty/v6/table"
"github.com/spf13/cobra"

"github.com/coder/coder/codersdk"
)

func userList() *cobra.Command {
return &cobra.Command{
Use: "list",
Aliases: []string{"ls"},
RunE: func(cmd *cobra.Command, args []string) error {
client, err := createClient(cmd)
if err != nil {
return err
}
users, err := client.Users(cmd.Context(), codersdk.UsersRequest{})
if err != nil {
return err
}
sort.Slice(users, func(i, j int) bool {
return users[i].Username < users[j].Username
})

tableWriter := table.NewWriter()
tableWriter.SetStyle(table.StyleLight)
tableWriter.Style().Options.SeparateColumns = false
tableWriter.AppendHeader(table.Row{"Username", "Email", "Created At"})
Comment on lines +31 to +34
Copy link
Contributor

Choose a reason for hiding this comment

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

Might be nice to have a central location for table styles so everything is consistent.

Copy link
Member Author

Choose a reason for hiding this comment

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

Agreed. I shall follow up

for _, user := range users {
tableWriter.AppendRow(table.Row{
user.Username,
user.Email,
user.CreatedAt.Format(time.Stamp),
})
}
_, err = fmt.Fprintln(cmd.OutOrStdout(), tableWriter.Render())
return err
},
}
}
30 changes: 30 additions & 0 deletions cli/userlist_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package cli_test

import (
"testing"

"github.com/stretchr/testify/require"

"github.com/coder/coder/cli/clitest"
"github.com/coder/coder/coderd/coderdtest"
"github.com/coder/coder/pty/ptytest"
)

func TestUserList(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
coderdtest.CreateFirstUser(t, client)
cmd, root := clitest.New(t, "users", "list")
clitest.SetupConfig(t, client, root)
doneChan := make(chan struct{})
pty := ptytest.New(t)
cmd.SetIn(pty.Input())
cmd.SetOut(pty.Output())
go func() {
defer close(doneChan)
err := cmd.Execute()
require.NoError(t, err)
}()
pty.ExpectMatch("coder.com")
<-doneChan
}
1 change: 1 addition & 0 deletions cli/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ func users() *cobra.Command {
cmd := &cobra.Command{
Use: "users",
}
cmd.AddCommand(userCreate(), userList())
return cmd
}
5 changes: 0 additions & 5 deletions coderd/database/databasefake/databasefake.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,8 +207,6 @@ func (q *fakeQuerier) GetUsers(_ context.Context, params database.GetUsersParams
tmp = append(tmp, users[i])
} else if strings.Contains(user.Username, params.Search) {
tmp = append(tmp, users[i])
} else if strings.Contains(user.Name, params.Search) {
tmp = append(tmp, users[i])
}
}
users = tmp
Expand Down Expand Up @@ -1116,8 +1114,6 @@ func (q *fakeQuerier) InsertUser(_ context.Context, arg database.InsertUserParam
user := database.User{
ID: arg.ID,
Email: arg.Email,
Name: arg.Name,
LoginType: arg.LoginType,
HashedPassword: arg.HashedPassword,
CreatedAt: arg.CreatedAt,
UpdatedAt: arg.UpdatedAt,
Expand All @@ -1135,7 +1131,6 @@ func (q *fakeQuerier) UpdateUserProfile(_ context.Context, arg database.UpdateUs
if user.ID != arg.ID {
continue
}
user.Name = arg.Name
user.Email = arg.Email
user.Username = arg.Username
q.users[index] = user
Expand Down
7 changes: 2 additions & 5 deletions coderd/database/dump.sql

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

5 changes: 1 addition & 4 deletions coderd/database/migrations/000001_base.up.sql
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,10 @@ CREATE TYPE login_type AS ENUM (
CREATE TABLE IF NOT EXISTS users (
id uuid NOT NULL,
email text NOT NULL,
name text NOT NULL,
revoked boolean NOT NULL,
login_type login_type NOT NULL,
username text DEFAULT ''::text NOT NULL,
hashed_password bytea NOT NULL,
created_at timestamp with time zone NOT NULL,
updated_at timestamp with time zone NOT NULL,
username text DEFAULT ''::text NOT NULL,
PRIMARY KEY (id)
);

Expand Down
5 changes: 1 addition & 4 deletions coderd/database/models.go

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

Loading