example_auth_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 clientv3_test
  15. import (
  16. "fmt"
  17. "log"
  18. "github.com/coreos/etcd/clientv3"
  19. "golang.org/x/net/context"
  20. )
  21. func ExampleAuth() {
  22. cli, err := clientv3.New(clientv3.Config{
  23. Endpoints: endpoints,
  24. DialTimeout: dialTimeout,
  25. })
  26. if err != nil {
  27. log.Fatal(err)
  28. }
  29. defer cli.Close()
  30. if _, err = cli.RoleAdd(context.TODO(), "root"); err != nil {
  31. log.Fatal(err)
  32. }
  33. if _, err = cli.RoleGrantPermission(
  34. context.TODO(),
  35. "root", // role name
  36. "foo", // key
  37. "zoo", // range end
  38. clientv3.PermissionType(clientv3.PermReadWrite),
  39. ); err != nil {
  40. log.Fatal(err)
  41. }
  42. if _, err = cli.UserAdd(context.TODO(), "root", "123"); err != nil {
  43. log.Fatal(err)
  44. }
  45. if _, err = cli.UserGrantRole(context.TODO(), "root", "root"); err != nil {
  46. log.Fatal(err)
  47. }
  48. if _, err = cli.AuthEnable(context.TODO()); err != nil {
  49. log.Fatal(err)
  50. }
  51. cliAuth, err := clientv3.New(clientv3.Config{
  52. Endpoints: endpoints,
  53. DialTimeout: dialTimeout,
  54. Username: "root",
  55. Password: "123",
  56. })
  57. if err != nil {
  58. log.Fatal(err)
  59. }
  60. defer cliAuth.Close()
  61. if _, err = cliAuth.Put(context.TODO(), "foo1", "bar"); err != nil {
  62. log.Fatal(err)
  63. }
  64. _, err = cliAuth.Txn(context.TODO()).
  65. If(clientv3.Compare(clientv3.Value("zoo1"), ">", "abc")).
  66. Then(clientv3.OpPut("zoo1", "XYZ")).
  67. Else(clientv3.OpPut("zoo1", "ABC")).
  68. Commit()
  69. fmt.Println(err)
  70. // now check the permission
  71. resp, err := cliAuth.RoleGet(context.TODO(), "root")
  72. if err != nil {
  73. log.Fatal(err)
  74. }
  75. fmt.Printf("root user permission: key %q, range end %q\n", resp.Perm[0].Key, resp.Perm[0].RangeEnd)
  76. if _, err = cliAuth.AuthDisable(context.TODO()); err != nil {
  77. log.Fatal(err)
  78. }
  79. // Output: etcdserver: permission denied
  80. // root user permission: key "foo", range end "zoo"
  81. }