github.com/minio/mc@v0.0.0-20240503112107-b471de8d1882/cmd/admin-group-add.go (about)

     1  // Copyright (c) 2015-2022 MinIO, Inc.
     2  //
     3  // This file is part of MinIO Object Storage stack
     4  //
     5  // This program is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Affero General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // This program is distributed in the hope that it will be useful
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13  // GNU Affero General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Affero General Public License
    16  // along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package cmd
    19  
    20  import (
    21  	"fmt"
    22  	"strings"
    23  
    24  	"github.com/fatih/color"
    25  	"github.com/minio/cli"
    26  	json "github.com/minio/colorjson"
    27  	"github.com/minio/madmin-go/v3"
    28  	"github.com/minio/mc/pkg/probe"
    29  	"github.com/minio/pkg/v2/console"
    30  )
    31  
    32  var adminGroupAddCmd = cli.Command{
    33  	Name:         "add",
    34  	Usage:        "add users to a new or existing group",
    35  	Action:       mainAdminGroupAdd,
    36  	OnUsageError: onUsageError,
    37  	Before:       setGlobalsFromContext,
    38  	Flags:        globalFlags,
    39  	CustomHelpTemplate: `NAME:
    40    {{.HelpName}} - {{.Usage}}
    41  
    42  USAGE:
    43    {{.HelpName}} TARGET GROUPNAME MEMBERS...
    44  
    45  FLAGS:
    46    {{range .VisibleFlags}}{{.}}
    47    {{end}}
    48  EXAMPLES:
    49    1. Add users 'fivecent' and 'tencent' to the group 'allcents':
    50       {{.Prompt}} {{.HelpName}} myminio allcents fivecent tencent
    51  
    52    2. Add user "james" to group "staff", then add the "readwrite" policy to the group "staff".
    53       {{.Prompt}} {{.HelpName}} myminio staff james
    54       {{.Prompt}} mc admin policy attach myminio readwrite --group staff
    55  `,
    56  }
    57  
    58  // checkAdminGroupAddSyntax - validate all the passed arguments
    59  func checkAdminGroupAddSyntax(ctx *cli.Context) {
    60  	if len(ctx.Args()) < 3 {
    61  		showCommandHelpAndExit(ctx, 1) // last argument is exit code
    62  	}
    63  }
    64  
    65  // groupMessage container for content message structure
    66  type groupMessage struct {
    67  	op          string
    68  	Status      string   `json:"status"`
    69  	GroupName   string   `json:"groupName,omitempty"`
    70  	Groups      []string `json:"groups,omitempty"`
    71  	Members     []string `json:"members,omitempty"`
    72  	GroupStatus string   `json:"groupStatus,omitempty"`
    73  	GroupPolicy string   `json:"groupPolicy,omitempty"`
    74  }
    75  
    76  func (u groupMessage) String() string {
    77  	switch u.op {
    78  	case "list":
    79  		var s []string
    80  		for _, g := range u.Groups {
    81  			s = append(s, console.Colorize("GroupMessage", g))
    82  		}
    83  		return strings.Join(s, "\n")
    84  	case "disable":
    85  		return console.Colorize("GroupMessage", "Disabled group `"+u.GroupName+"` successfully.")
    86  	case "enable":
    87  		return console.Colorize("GroupMessage", "Enabled group `"+u.GroupName+"` successfully.")
    88  	case "add":
    89  		membersStr := fmt.Sprintf("`%s`", strings.Join(u.Members, ","))
    90  		return console.Colorize("GroupMessage", "Added members "+membersStr+" to group `"+u.GroupName+"` successfully.")
    91  	case "remove":
    92  		if len(u.Members) > 0 {
    93  			membersStr := fmt.Sprintf("{%s}", strings.Join(u.Members, ","))
    94  			return console.Colorize("GroupMessage", "Removed members "+membersStr+" from group "+u.GroupName+" successfully.")
    95  		}
    96  		return console.Colorize("GroupMessage", "Removed group "+u.GroupName+" successfully.")
    97  	case "info":
    98  		return strings.Join([]string{
    99  			console.Colorize("GroupMessage", "Group: "+u.GroupName),
   100  			console.Colorize("GroupMessage", "Status: "+u.GroupStatus),
   101  			console.Colorize("GroupMessage", "Policy: "+u.GroupPolicy),
   102  			console.Colorize("GroupMessage", "Members: "+strings.Join(u.Members, ",")),
   103  		}, "\n")
   104  
   105  	}
   106  	return ""
   107  }
   108  
   109  func (u groupMessage) JSON() string {
   110  	u.Status = "success"
   111  	jsonMessageBytes, e := json.MarshalIndent(u, "", " ")
   112  	fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
   113  
   114  	return string(jsonMessageBytes)
   115  }
   116  
   117  // mainAdminGroupAdd is the handle for "mc admin group add" command.
   118  func mainAdminGroupAdd(ctx *cli.Context) error {
   119  	checkAdminGroupAddSyntax(ctx)
   120  
   121  	console.SetColor("GroupMessage", color.New(color.FgGreen))
   122  
   123  	// Get the alias parameter from cli
   124  	args := ctx.Args()
   125  	aliasedURL := args.Get(0)
   126  
   127  	// Create a new MinIO Admin Client
   128  	client, err := newAdminClient(aliasedURL)
   129  	fatalIf(err, "Unable to initialize admin connection.")
   130  
   131  	members := []string{}
   132  	for i := 2; i < ctx.NArg(); i++ {
   133  		members = append(members, args.Get(i))
   134  	}
   135  	gAddRemove := madmin.GroupAddRemove{
   136  		Group:    args.Get(1),
   137  		Members:  members,
   138  		IsRemove: false,
   139  	}
   140  	fatalIf(probe.NewError(client.UpdateGroupMembers(globalContext, gAddRemove)).Trace(args...), "Unable to add new group")
   141  
   142  	printMsg(groupMessage{
   143  		op:        ctx.Command.Name,
   144  		GroupName: args.Get(1),
   145  		Members:   members,
   146  	})
   147  
   148  	return nil
   149  }