yunion.io/x/cloudmux@v0.3.10-0-alpha.1/pkg/multicloud/openstack/roles.go (about)

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