user_command.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright 2016 Nippon Telegraph and Telephone Corporation.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package command
  15. import (
  16. "fmt"
  17. "strings"
  18. "github.com/bgentry/speakeasy"
  19. "github.com/spf13/cobra"
  20. "golang.org/x/net/context"
  21. )
  22. // NewUserCommand returns the cobra command for "user".
  23. func NewUserCommand() *cobra.Command {
  24. ac := &cobra.Command{
  25. Use: "user <subcommand>",
  26. Short: "user related command",
  27. }
  28. ac.AddCommand(NewUserAddCommand())
  29. return ac
  30. }
  31. var (
  32. passwordInteractive bool
  33. )
  34. func NewUserAddCommand() *cobra.Command {
  35. cmd := cobra.Command{
  36. Use: "add <user name>",
  37. Short: "add a new user",
  38. Run: userAddCommandFunc,
  39. }
  40. cmd.Flags().BoolVar(&passwordInteractive, "interactive", true, "read password from stdin instead of interactive terminal")
  41. return &cmd
  42. }
  43. // userAddCommandFunc executes the "user add" command.
  44. func userAddCommandFunc(cmd *cobra.Command, args []string) {
  45. if len(args) != 1 {
  46. ExitWithError(ExitBadArgs, fmt.Errorf("user add command requires user name as its argument."))
  47. }
  48. var password string
  49. if !passwordInteractive {
  50. fmt.Scanf("%s", &password)
  51. } else {
  52. prompt1 := fmt.Sprintf("Password of %s: ", args[0])
  53. password1, err1 := speakeasy.Ask(prompt1)
  54. if err1 != nil {
  55. ExitWithError(ExitBadArgs, fmt.Errorf("failed to ask password: %s.", err1))
  56. }
  57. if len(password1) == 0 {
  58. ExitWithError(ExitBadArgs, fmt.Errorf("empty password"))
  59. }
  60. prompt2 := fmt.Sprintf("Type password of %s again for confirmation: ", args[0])
  61. password2, err2 := speakeasy.Ask(prompt2)
  62. if err2 != nil {
  63. ExitWithError(ExitBadArgs, fmt.Errorf("failed to ask password: %s.", err2))
  64. }
  65. if strings.Compare(password1, password2) != 0 {
  66. ExitWithError(ExitBadArgs, fmt.Errorf("given passwords are different."))
  67. }
  68. password = password1
  69. }
  70. _, err := mustClientFromCmd(cmd).Auth.UserAdd(context.TODO(), args[0], password)
  71. if err != nil {
  72. ExitWithError(ExitError, err)
  73. }
  74. }