role_command.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright 2016 The etcd Authors
  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. "github.com/coreos/etcd/clientv3"
  18. "github.com/spf13/cobra"
  19. "golang.org/x/net/context"
  20. )
  21. // NewRoleCommand returns the cobra command for "role".
  22. func NewRoleCommand() *cobra.Command {
  23. ac := &cobra.Command{
  24. Use: "role <subcommand>",
  25. Short: "role related command",
  26. }
  27. ac.AddCommand(newRoleAddCommand())
  28. ac.AddCommand(newRoleGrantCommand())
  29. return ac
  30. }
  31. func newRoleAddCommand() *cobra.Command {
  32. return &cobra.Command{
  33. Use: "add <role name>",
  34. Short: "add a new role",
  35. Run: roleAddCommandFunc,
  36. }
  37. }
  38. func newRoleGrantCommand() *cobra.Command {
  39. return &cobra.Command{
  40. Use: "grant <role name> <permission type> <key>",
  41. Short: "grant a key to a role",
  42. Run: roleGrantCommandFunc,
  43. }
  44. }
  45. // roleAddCommandFunc executes the "role add" command.
  46. func roleAddCommandFunc(cmd *cobra.Command, args []string) {
  47. if len(args) != 1 {
  48. ExitWithError(ExitBadArgs, fmt.Errorf("role add command requires role name as its argument."))
  49. }
  50. _, err := mustClientFromCmd(cmd).Auth.RoleAdd(context.TODO(), args[0])
  51. if err != nil {
  52. ExitWithError(ExitError, err)
  53. }
  54. fmt.Printf("Role %s created\n", args[0])
  55. }
  56. // roleGrantCommandFunc executes the "role grant" command.
  57. func roleGrantCommandFunc(cmd *cobra.Command, args []string) {
  58. if len(args) != 3 {
  59. ExitWithError(ExitBadArgs, fmt.Errorf("role grant command requires role name, permission type, and key as its argument."))
  60. }
  61. perm, err := clientv3.StrToPermissionType(args[1])
  62. if err != nil {
  63. ExitWithError(ExitBadArgs, err)
  64. }
  65. _, err = mustClientFromCmd(cmd).Auth.RoleGrant(context.TODO(), args[0], args[2], perm)
  66. if err != nil {
  67. ExitWithError(ExitError, err)
  68. }
  69. fmt.Printf("Role %s updated\n", args[0])
  70. }