roles.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2019 Yunion
  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 openstack
  15. import (
  16. "fmt"
  17. "net/url"
  18. "yunion.io/x/pkg/errors"
  19. "yunion.io/x/pkg/util/httputils"
  20. "yunion.io/x/cloudmux/pkg/cloudprovider"
  21. )
  22. type SRole struct {
  23. Id string
  24. Name string
  25. }
  26. func (cli *SOpenStackClient) GetRoles(name string) ([]SRole, error) {
  27. resource := "/v3/roles"
  28. query := url.Values{}
  29. if len(name) > 0 {
  30. query.Set("name", name)
  31. }
  32. resp, err := cli.iamRequest(cli.getDefaultRegionName(), httputils.GET, resource, query, nil)
  33. if err != nil {
  34. return nil, errors.Wrap(err, "iamRequest")
  35. }
  36. roles := []SRole{}
  37. err = resp.Unmarshal(&roles, "roles")
  38. if err != nil {
  39. return nil, errors.Wrap(err, "resp.Unmarshal")
  40. }
  41. return roles, nil
  42. }
  43. func (cli *SOpenStackClient) AssignRoleToUserOnProject(userId, projectId, roleName string) error {
  44. if len(roleName) == 0 {
  45. return errors.Error("empty role name")
  46. }
  47. roles, err := cli.GetRoles(roleName)
  48. if err != nil {
  49. return errors.Wrapf(err, "GetRoles(%s)", roleName)
  50. }
  51. if len(roles) == 0 {
  52. return errors.Wrapf(cloudprovider.ErrNotFound, "role %s", roleName)
  53. }
  54. if len(roles) > 1 {
  55. return errors.Wrapf(cloudprovider.ErrDuplicateId, "roles %d for %s", len(roles), roleName)
  56. }
  57. resource := fmt.Sprintf("/v3/projects/%s/users/%s/roles/%s", projectId, userId, roles[0].Id)
  58. _, err = cli.iamRequest(cli.getDefaultRegionName(), httputils.PUT, resource, nil, map[string]string{})
  59. return err
  60. }