github.com/mook-as/cf-cli@v7.0.0-beta.28.0.20200120190804-b91c115fae48+incompatible/cf/commands/user/create_user.go (about) 1 package user 2 3 import ( 4 "fmt" 5 6 "code.cloudfoundry.org/cli/cf" 7 "code.cloudfoundry.org/cli/cf/api" 8 "code.cloudfoundry.org/cli/cf/commandregistry" 9 "code.cloudfoundry.org/cli/cf/configuration/coreconfig" 10 "code.cloudfoundry.org/cli/cf/errors" 11 "code.cloudfoundry.org/cli/cf/flags" 12 . "code.cloudfoundry.org/cli/cf/i18n" 13 "code.cloudfoundry.org/cli/cf/requirements" 14 "code.cloudfoundry.org/cli/cf/terminal" 15 ) 16 17 type CreateUser struct { 18 ui terminal.UI 19 config coreconfig.Reader 20 userRepo api.UserRepository 21 } 22 23 func init() { 24 commandregistry.Register(&CreateUser{}) 25 } 26 27 func (cmd *CreateUser) MetaData() commandregistry.CommandMetadata { 28 return commandregistry.CommandMetadata{ 29 Name: "create-user", 30 Description: T("Create a new user"), 31 Usage: []string{ 32 T("CF_NAME create-user USERNAME PASSWORD"), 33 }, 34 } 35 } 36 37 func (cmd *CreateUser) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) { 38 if len(fc.Args()) != 2 { 39 usage := commandregistry.Commands.CommandUsage("create-user") 40 cmd.ui.Failed(T("Incorrect Usage. Requires arguments\n\n") + usage) 41 return nil, fmt.Errorf("Incorrect usage: %d arguments of %d required", len(fc.Args()), 2) 42 } 43 44 reqs := []requirements.Requirement{ 45 requirementsFactory.NewLoginRequirement(), 46 } 47 48 return reqs, nil 49 } 50 51 func (cmd *CreateUser) SetDependency(deps commandregistry.Dependency, pluginCall bool) commandregistry.Command { 52 cmd.ui = deps.UI 53 cmd.config = deps.Config 54 cmd.userRepo = deps.RepoLocator.GetUserRepository() 55 return cmd 56 } 57 58 func (cmd *CreateUser) Execute(c flags.FlagContext) error { 59 username := c.Args()[0] 60 password := c.Args()[1] 61 62 cmd.ui.Say(T("Creating user {{.TargetUser}}...", 63 map[string]interface{}{ 64 "TargetUser": terminal.EntityNameColor(username), 65 "CurrentUser": terminal.EntityNameColor(cmd.config.Username()), 66 })) 67 68 err := cmd.userRepo.Create(username, password) 69 switch err.(type) { 70 case nil: 71 case *errors.ModelAlreadyExistsError: 72 cmd.ui.Warn("%s", err.Error()) 73 default: 74 return errors.New(T("Error creating user {{.TargetUser}}.\n{{.Error}}", 75 map[string]interface{}{ 76 "TargetUser": terminal.EntityNameColor(username), 77 "Error": err.Error(), 78 })) 79 } 80 81 cmd.ui.Ok() 82 cmd.ui.Say(T("\nTIP: Assign roles with '{{.CurrentUser}} set-org-role' and '{{.CurrentUser}} set-space-role'", map[string]interface{}{"CurrentUser": cf.Name})) 83 return nil 84 }