Skip to content

Commit

Permalink
restructure user command/api
Browse files Browse the repository at this point in the history
Signed-off-by: Kristoffer Dalby <[email protected]>
  • Loading branch information
kradalby committed Nov 29, 2024
1 parent 7512e23 commit e3c6d94
Show file tree
Hide file tree
Showing 18 changed files with 1,610 additions and 3,413 deletions.
84 changes: 72 additions & 12 deletions cmd/headscale/cli/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,41 @@ import (
"google.golang.org/grpc/status"
)

func usernameAndIDFlag(cmd *cobra.Command) {
cmd.Flags().Int64P("identifier", "i", -1, "User identifier (ID)")
cmd.Flags().StringP("name", "n", "", "Username")
}

// usernameAndIDFromFlag returns the username and ID from the flags of the command.
// If both are empty, it will exit the program with an error.
func usernameAndIDFromFlag(cmd *cobra.Command) (uint64, string) {
username, _ := cmd.Flags().GetString("name")
identifier, _ := cmd.Flags().GetInt64("identifier")
if username == "" && identifier < 0 {
err := errors.New("--name or --identifier flag is required")
ErrorOutput(
err,
fmt.Sprintf(
"Cannot rename user: %s",
status.Convert(err).Message(),
),
"",
)
}

return uint64(identifier), username
}

func init() {
rootCmd.AddCommand(userCmd)
userCmd.AddCommand(createUserCmd)
userCmd.AddCommand(listUsersCmd)
usernameAndIDFlag(listUsersCmd)
listUsersCmd.Flags().StringP("email", "e", "", "Email")
userCmd.AddCommand(destroyUserCmd)
usernameAndIDFlag(destroyUserCmd)
userCmd.AddCommand(renameUserCmd)
usernameAndIDFlag(renameUserCmd)
}

var errMissingParameter = errors.New("missing parameters")
Expand Down Expand Up @@ -70,7 +99,7 @@ var createUserCmd = &cobra.Command{
}

var destroyUserCmd = &cobra.Command{
Use: "destroy NAME",
Use: "destroy --identifier ID or --name NAME",
Short: "Destroys a user",
Aliases: []string{"delete"},
Args: func(cmd *cobra.Command, args []string) error {
Expand All @@ -83,17 +112,17 @@ var destroyUserCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
output, _ := cmd.Flags().GetString("output")

userName := args[0]

request := &v1.GetUserRequest{
Name: userName,
id, username := usernameAndIDFromFlag(cmd)
request := &v1.ListUsersRequest{
Name: username,
Id: id,
}

ctx, client, conn, cancel := newHeadscaleCLIWithConfig()
defer cancel()
defer conn.Close()

_, err := client.GetUser(ctx, request)
users, err := client.ListUsers(ctx, request)
if err != nil {
ErrorOutput(
err,
Expand All @@ -102,13 +131,24 @@ var destroyUserCmd = &cobra.Command{
)
}

if len(users.GetUsers()) != 1 {
err := fmt.Errorf("Unable to determine user to delete, query returned multiple users, use ID")
ErrorOutput(
err,
fmt.Sprintf("Error: %s", status.Convert(err).Message()),
output,
)
}

user := users.GetUsers()[0]

confirm := false
force, _ := cmd.Flags().GetBool("force")
if !force {
prompt := &survey.Confirm{
Message: fmt.Sprintf(
"Do you want to remove the user '%s' and any associated preauthkeys?",
userName,
"Do you want to remove the user %q (%d) and any associated preauthkeys?",
user.GetName(), user.GetId(),
),
}
err := survey.AskOne(prompt, &confirm)
Expand All @@ -118,7 +158,7 @@ var destroyUserCmd = &cobra.Command{
}

if confirm || force {
request := &v1.DeleteUserRequest{Name: userName}
request := &v1.DeleteUserRequest{Id: user.GetId()}

response, err := client.DeleteUser(ctx, request)
if err != nil {
Expand Down Expand Up @@ -151,6 +191,23 @@ var listUsersCmd = &cobra.Command{

request := &v1.ListUsersRequest{}

id, _ := cmd.Flags().GetInt64("identifier")
username, _ := cmd.Flags().GetString("name")
email, _ := cmd.Flags().GetString("email")

// filter by one param at most
switch {
case id > 0:
request.Id = uint64(id)
break
case username != "":
request.Name = username
break
case email != "":
request.Email = email
break
}

response, err := client.ListUsers(ctx, request)
if err != nil {
ErrorOutput(
Expand All @@ -169,7 +226,7 @@ var listUsersCmd = &cobra.Command{
tableData = append(
tableData,
[]string{
user.GetId(),
fmt.Sprintf("%d", user.GetId()),
user.GetDisplayName(),
user.GetName(),
user.GetEmail(),
Expand All @@ -189,7 +246,7 @@ var listUsersCmd = &cobra.Command{
}

var renameUserCmd = &cobra.Command{
Use: "rename OLD_NAME NEW_NAME",
Use: "rename --identifier ID NEW_NAME",
Short: "Renames a user",
Aliases: []string{"mv"},
Args: func(cmd *cobra.Command, args []string) error {
Expand All @@ -207,8 +264,11 @@ var renameUserCmd = &cobra.Command{
defer cancel()
defer conn.Close()

id, username := usernameAndIDFromFlag(cmd)

request := &v1.RenameUserRequest{
OldName: args[0],
OldId: id,
OldName: username,
NewName: args[1],
}

Expand Down
23 changes: 20 additions & 3 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -41,22 +41,38 @@

protoc-gen-grpc-gateway = buildGo rec {
pname = "grpc-gateway";
version = "2.22.0";
version = "2.24.0";

src = pkgs.fetchFromGitHub {
owner = "grpc-ecosystem";
repo = "grpc-gateway";
rev = "v${version}";
sha256 = "sha256-I1w3gfV06J8xG1xJ+XuMIGkV2/Ofszo7SCC+z4Xb6l4=";
sha256 = "sha256-lUEoqXJF1k4/il9bdDTinkUV5L869njZNYqObG/mHyA=";
};

vendorHash = "sha256-S4hcD5/BSGxM2qdJHMxOkxsJ5+Ks6m4lKHSS9+yZ17c=";
vendorHash = "sha256-Ttt7bPKU+TMKRg5550BS6fsPwYp0QJqcZ7NLrhttSdw=";

nativeBuildInputs = [pkgs.installShellFiles];

subPackages = ["protoc-gen-grpc-gateway" "protoc-gen-openapiv2"];
};

protobuf-language-server = buildGo rec {
pname = "protobuf-language-server";
version = "2546944";

src = pkgs.fetchFromGitHub {
owner = "lasorda";
repo = "protobuf-language-server";
rev = "${version}";
sha256 = "sha256-Cbr3ktT86RnwUntOiDKRpNTClhdyrKLTQG2ZEd6fKDc=";
};

vendorHash = "sha256-PfT90dhfzJZabzLTb1D69JCO+kOh2khrlpF5mCDeypk=";

subPackages = ["."];
};

# Upstream does not override buildGoModule properly,
# importing a specific module, so comment out for now.
# golangci-lint = prev.golangci-lint.override {
Expand Down Expand Up @@ -115,6 +131,7 @@
protoc-gen-grpc-gateway
buf
clang-tools # clang-format
protobuf-language-server
];

# Add entry to build a docker image with headscale
Expand Down
Loading

0 comments on commit e3c6d94

Please sign in to comment.