sql.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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 sql
  15. import (
  16. "context"
  17. "fmt"
  18. "time"
  19. "github.com/pkg/errors"
  20. "yunion.io/x/jsonutils"
  21. "yunion.io/x/log"
  22. "yunion.io/x/pkg/util/sets"
  23. api "yunion.io/x/onecloud/pkg/apis/identity"
  24. noapi "yunion.io/x/onecloud/pkg/apis/notify"
  25. "yunion.io/x/onecloud/pkg/cloudcommon/notifyclient"
  26. "yunion.io/x/onecloud/pkg/httperrors"
  27. "yunion.io/x/onecloud/pkg/keystone/driver"
  28. "yunion.io/x/onecloud/pkg/keystone/models"
  29. o "yunion.io/x/onecloud/pkg/keystone/options"
  30. "yunion.io/x/onecloud/pkg/mcclient"
  31. "yunion.io/x/onecloud/pkg/mcclient/modules/notify"
  32. )
  33. type SSQLDriver struct {
  34. driver.SBaseIdentityDriver
  35. }
  36. func NewSQLDriver(idpId, idpName, template, targetDomainId string, conf api.TConfigs) (driver.IIdentityBackend, error) {
  37. base, err := driver.NewBaseIdentityDriver(idpId, idpName, template, targetDomainId, conf)
  38. if err != nil {
  39. return nil, err
  40. }
  41. drv := SSQLDriver{base}
  42. drv.SetVirtualObject(&drv)
  43. return &drv, nil
  44. }
  45. func (sql *SSQLDriver) GetSsoRedirectUri(ctx context.Context, callbackUrl, state string) (string, error) {
  46. return "", errors.Wrap(httperrors.ErrNotSupported, "not a SSO driver")
  47. }
  48. func (sql *SSQLDriver) Authenticate(ctx context.Context, ident mcclient.SAuthenticationIdentity) (*api.SUserExtended, error) {
  49. usrExt, err := models.UserManager.FetchUserExtended(
  50. ident.Password.User.Id,
  51. ident.Password.User.Name,
  52. ident.Password.User.Domain.Id,
  53. ident.Password.User.Domain.Name,
  54. )
  55. if err != nil {
  56. return nil, errors.Wrap(err, "UserManager.FetchUserExtended")
  57. }
  58. localUser, err := models.LocalUserManager.FetchLocalUserById(usrExt.LocalId)
  59. if err != nil {
  60. return nil, errors.Wrap(err, "LocalUserManager.FetchLocalUser")
  61. }
  62. err = models.VerifyPassword(usrExt, ident.Password.User.Password)
  63. if err != nil {
  64. localUser.SaveFailedAuth()
  65. if o.Options.PasswordErrorLockCount > 0 && localUser.FailedAuthCount > o.Options.PasswordErrorLockCount && !usrExt.IsSystemAccount {
  66. // do not lock system account!!!
  67. models.UserManager.LockUser(usrExt.Id, "too many failed auth attempts")
  68. data := jsonutils.NewDict()
  69. data.Set("name", jsonutils.NewString(usrExt.Name))
  70. notifyclient.SystemEventNotify(ctx, noapi.ActionLock, noapi.TOPIC_RESOURCE_USER, data)
  71. return nil, errors.Wrap(httperrors.ErrTooManyAttempts, "user locked")
  72. }
  73. return nil, errors.Wrap(err, "usrExt.VerifyPassword")
  74. }
  75. localUser.ClearFailedAuth()
  76. usrExt.AuditIds = []string{fmt.Sprintf("%d", localUser.Id)}
  77. return usrExt, nil
  78. }
  79. func (sql *SSQLDriver) alertNotify(ctx context.Context, uext *api.SUserExtended, triggerTime time.Time) {
  80. // users
  81. data := jsonutils.NewDict()
  82. data.Set("user", jsonutils.NewString(uext.Name))
  83. data.Set("domain", jsonutils.NewString(uext.DomainName))
  84. metadata := map[string]interface{}{
  85. "trigger_time": triggerTime,
  86. }
  87. p := notifyclient.SNotifyParams{
  88. RecipientId: []string{uext.Id},
  89. Priority: notify.NotifyPriorityCritical,
  90. Event: notifyclient.USER_LOGIN_EXCEPTION,
  91. Data: data,
  92. Tag: noapi.NOTIFICATION_TAG_ALERT,
  93. Metadata: metadata,
  94. IgnoreNonexistentReceiver: true,
  95. }
  96. notifyclient.NotifyWithTag(ctx, p)
  97. // admin user
  98. daUserIds, err := getDomainAdminUserIds(uext.DomainName)
  99. if err != nil {
  100. log.Errorf("unable to get user with role domainadmin in domain %s: %v", uext.DomainName, err)
  101. }
  102. aUserIds, err := getAdminUserIds()
  103. if err != nil {
  104. log.Errorf("unable to get user with role admin: %v", err)
  105. }
  106. userSet := sets.NewString(daUserIds...)
  107. userSet.Insert(aUserIds...)
  108. data.Set("admin", jsonutils.JSONTrue)
  109. // prevent duplicate messages
  110. userSet.Delete(uext.Id)
  111. p.RecipientId = userSet.UnsortedList()
  112. p.Data = data
  113. notifyclient.NotifyWithTag(ctx, p)
  114. }
  115. func fetchRoleId(name string) (string, error) {
  116. id := struct {
  117. Id string
  118. }{}
  119. q := models.RoleManager.Query().Equals("name", name)
  120. err := q.First(&id)
  121. if err != nil {
  122. return "", err
  123. }
  124. return id.Id, nil
  125. }
  126. func getAdminUserIds() ([]string, error) {
  127. return getUserIdsWithRole(o.Options.AdminRoleToNotify, "")
  128. }
  129. func getUserIdsWithRole(roleName string, domainId string) ([]string, error) {
  130. roleId, err := fetchRoleId(roleName)
  131. if err != nil {
  132. return nil, errors.Wrapf(err, "unable to fetch roleid of %s", roleName)
  133. }
  134. ras, _, err := models.AssignmentManager.FetchAll("", "", roleId, "", "", "", []string{}, []string{}, []string{}, []string{}, []string{}, []string{domainId}, false, true, false, false, false, 0, 0)
  135. if err != nil {
  136. return nil, err
  137. }
  138. userIds := make([]string, 0, len(ras))
  139. for i := range ras {
  140. userIds = append(userIds, ras[i].User.Id)
  141. }
  142. log.Infof("%s User: %v", roleName, userIds)
  143. return userIds, nil
  144. }
  145. func getDomainAdminUserIds(domainId string) ([]string, error) {
  146. return getUserIdsWithRole(o.Options.DomainAdminRoleToNotify, domainId)
  147. }
  148. func (sql *SSQLDriver) Sync(ctx context.Context) error {
  149. return nil
  150. }
  151. func (sql *SSQLDriver) Probe(ctx context.Context) error {
  152. return nil
  153. }