validate.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 utils
  15. import (
  16. "context"
  17. "database/sql"
  18. "yunion.io/x/pkg/errors"
  19. api "yunion.io/x/onecloud/pkg/apis/identity"
  20. "yunion.io/x/onecloud/pkg/httperrors"
  21. "yunion.io/x/onecloud/pkg/keystone/models"
  22. "yunion.io/x/onecloud/pkg/mcclient"
  23. )
  24. func ValidateConfig(ctx context.Context, conf api.SIdpAttributeOptions, userCred mcclient.TokenCredential) (api.SIdpAttributeOptions, error) {
  25. if len(conf.DefaultProjectId) > 0 {
  26. obj, err := models.ProjectManager.FetchByIdOrName(ctx, userCred, conf.DefaultProjectId)
  27. if err != nil {
  28. if errors.Cause(err) == sql.ErrNoRows {
  29. return conf, errors.Wrapf(httperrors.ErrResourceNotFound, "project %s", conf.DefaultProjectId)
  30. } else {
  31. return conf, errors.Wrap(err, "FetchProjectById")
  32. }
  33. }
  34. conf.DefaultProjectId = obj.GetId()
  35. }
  36. if len(conf.DefaultRoleId) > 0 {
  37. obj, err := models.RoleManager.FetchByIdOrName(ctx, userCred, conf.DefaultRoleId)
  38. if err != nil {
  39. if errors.Cause(err) == sql.ErrNoRows {
  40. return conf, errors.Wrapf(httperrors.ErrResourceNotFound, "role %s", conf.DefaultRoleId)
  41. } else {
  42. return conf, errors.Wrap(err, "FetchRoleById")
  43. }
  44. }
  45. conf.DefaultRoleId = obj.GetId()
  46. }
  47. if len(conf.DefaultProjectId) > 0 && len(conf.DefaultRoleId) > 0 {
  48. // validate policy
  49. err := models.ValidateJoinProjectRoles(userCred, conf.DefaultProjectId, []string{conf.DefaultRoleId})
  50. if err != nil {
  51. return conf, errors.Wrap(err, "ValidateJoinProjectRoles")
  52. }
  53. }
  54. return conf, nil
  55. }