init.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 saml
  15. import (
  16. "os"
  17. "yunion.io/x/pkg/errors"
  18. "yunion.io/x/pkg/util/samlutils"
  19. "yunion.io/x/onecloud/pkg/appsrv"
  20. "yunion.io/x/onecloud/pkg/cloudid/models"
  21. "yunion.io/x/onecloud/pkg/cloudid/options"
  22. "yunion.io/x/onecloud/pkg/httperrors"
  23. "yunion.io/x/onecloud/pkg/util/samlutils/idp"
  24. "yunion.io/x/onecloud/pkg/util/seclib2"
  25. )
  26. var (
  27. saml *samlutils.SSAMLInstance
  28. idpInstance *idp.SSAMLIdpInstance
  29. )
  30. func initSAMLInstance() error {
  31. certfile := options.Options.SslCertfile
  32. if len(options.Options.SslCaCerts) > 0 {
  33. var err error
  34. certfile, err = seclib2.MergeCaCertFiles(options.Options.SslCaCerts, options.Options.SslCertfile)
  35. if err != nil {
  36. return errors.Wrapf(httperrors.ErrInputParameter, "fail to merge ca+cert content: %s", err)
  37. }
  38. defer os.Remove(certfile)
  39. }
  40. if len(certfile) == 0 {
  41. return errors.Wrap(httperrors.ErrInputParameter, "Missing ssl-certfile")
  42. }
  43. if len(options.Options.SslKeyfile) == 0 {
  44. return errors.Wrap(httperrors.ErrInputParameter, "Missing ssl-keyfile")
  45. }
  46. var err error
  47. saml, err = samlutils.NewSAMLInstance(options.Options.ApiServer, certfile, options.Options.SslKeyfile)
  48. if err != nil {
  49. return errors.Wrap(err, "samlutils.NewSAMLInstance")
  50. }
  51. models.SamlIdpInstance = SAMLIdpInstance
  52. return nil
  53. }
  54. func SAMLInstance() *samlutils.SSAMLInstance {
  55. if saml.GetEntityId() != options.Options.ApiServer {
  56. saml.SetEntityId(options.Options.ApiServer)
  57. }
  58. return saml
  59. }
  60. func SAMLIdpInstance() *idp.SSAMLIdpInstance {
  61. return idpInstance
  62. }
  63. func IsSAMLEnabled() bool {
  64. return saml != nil
  65. }
  66. func InitSAML(app *appsrv.Application, prefix string) error {
  67. err := initSAMLInstance()
  68. if err != nil {
  69. return errors.Wrap(err, "initSAMLInstance")
  70. }
  71. err = initSAMLIdp(app, prefix)
  72. if err != nil {
  73. return errors.Wrap(err, "initSAMLIdp")
  74. }
  75. return nil
  76. }