groups.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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 models
  15. import (
  16. "context"
  17. "database/sql"
  18. "yunion.io/x/jsonutils"
  19. "yunion.io/x/log"
  20. "yunion.io/x/pkg/errors"
  21. "yunion.io/x/pkg/util/rbacscope"
  22. "yunion.io/x/sqlchemy"
  23. api "yunion.io/x/onecloud/pkg/apis/identity"
  24. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  25. "yunion.io/x/onecloud/pkg/cloudcommon/db/lockman"
  26. "yunion.io/x/onecloud/pkg/cloudcommon/db/quotas"
  27. "yunion.io/x/onecloud/pkg/httperrors"
  28. "yunion.io/x/onecloud/pkg/mcclient"
  29. "yunion.io/x/onecloud/pkg/util/stringutils2"
  30. )
  31. type SGroupManager struct {
  32. SIdentityBaseResourceManager
  33. }
  34. var GroupManager *SGroupManager
  35. func init() {
  36. GroupManager = &SGroupManager{
  37. SIdentityBaseResourceManager: NewIdentityBaseResourceManager(
  38. SGroup{},
  39. "group",
  40. "group",
  41. "groups",
  42. ),
  43. }
  44. GroupManager.SetVirtualObject(GroupManager)
  45. }
  46. /*
  47. +-------------+-------------+------+-----+---------+-------+
  48. | Field | Type | Null | Key | Default | Extra |
  49. +-------------+-------------+------+-----+---------+-------+
  50. | id | varchar(64) | NO | PRI | NULL | |
  51. | domain_id | varchar(64) | NO | MUL | NULL | |
  52. | name | varchar(64) | NO | | NULL | |
  53. | description | text | YES | | NULL | |
  54. | extra | text | YES | | NULL | |
  55. | created_at | datetime | YES | | NULL | |
  56. +-------------+-------------+------+-----+---------+-------+
  57. */
  58. type SGroup struct {
  59. SIdentityBaseResource
  60. // 用户组的显示名称
  61. Displayname string `with:"128" charset:"utf8" nullable:"true" list:"domain" update:"domain" create:"domain_optional"`
  62. }
  63. func (manager *SGroupManager) GetContextManagers() [][]db.IModelManager {
  64. return [][]db.IModelManager{
  65. {UserManager},
  66. {ProjectManager},
  67. }
  68. }
  69. // 用户组列表
  70. func (manager *SGroupManager) ListItemFilter(
  71. ctx context.Context,
  72. q *sqlchemy.SQuery,
  73. userCred mcclient.TokenCredential,
  74. query api.GroupListInput,
  75. ) (*sqlchemy.SQuery, error) {
  76. q, err := manager.SIdentityBaseResourceManager.ListItemFilter(ctx, q, userCred, query.IdentityBaseResourceListInput)
  77. if err != nil {
  78. return nil, err
  79. }
  80. if len(query.Displayname) > 0 {
  81. q = q.Equals("displayname", query.Displayname)
  82. }
  83. userIdStr := query.UserId
  84. if len(userIdStr) > 0 {
  85. user, err := UserManager.FetchById(userIdStr)
  86. if err != nil {
  87. if err == sql.ErrNoRows {
  88. return nil, httperrors.NewResourceNotFoundError2(UserManager.Keyword(), userIdStr)
  89. } else {
  90. return nil, httperrors.NewGeneralError(err)
  91. }
  92. }
  93. subq := UsergroupManager.Query("group_id").Equals("user_id", user.GetId())
  94. q = q.In("id", subq.SubQuery())
  95. }
  96. projIdStr := query.ProjectId
  97. if len(projIdStr) > 0 {
  98. proj, err := ProjectManager.FetchProjectById(projIdStr)
  99. if err != nil {
  100. if err == sql.ErrNoRows {
  101. return nil, httperrors.NewResourceNotFoundError2(ProjectManager.Keyword(), projIdStr)
  102. } else {
  103. return nil, httperrors.NewGeneralError(err)
  104. }
  105. }
  106. subq := AssignmentManager.fetchProjectGroupIdsQuery(proj.Id)
  107. q = q.In("id", subq.SubQuery())
  108. }
  109. if len(query.IdpId) > 0 {
  110. idpObj, err := IdentityProviderManager.FetchByIdOrName(ctx, userCred, query.IdpId)
  111. if err != nil {
  112. if errors.Cause(err) == sql.ErrNoRows {
  113. return nil, errors.Wrapf(httperrors.ErrResourceNotFound, "%s %s", IdentityProviderManager.Keyword(), query.IdpId)
  114. } else {
  115. return nil, errors.Wrap(err, "IdentityProviderManager.FetchByIdOrName")
  116. }
  117. }
  118. subq := IdmappingManager.FetchPublicIdsExcludesQuery(idpObj.GetId(), api.IdMappingEntityGroup, nil)
  119. q = q.In("id", subq.SubQuery())
  120. }
  121. return q, nil
  122. }
  123. func (manager *SGroupManager) OrderByExtraFields(
  124. ctx context.Context,
  125. q *sqlchemy.SQuery,
  126. userCred mcclient.TokenCredential,
  127. query api.GroupListInput,
  128. ) (*sqlchemy.SQuery, error) {
  129. var err error
  130. q, err = manager.SIdentityBaseResourceManager.OrderByExtraFields(ctx, q, userCred, query.IdentityBaseResourceListInput)
  131. if err != nil {
  132. return nil, errors.Wrap(err, "SIdentityBaseResourceManager.OrderByExtraFields")
  133. }
  134. return q, nil
  135. }
  136. func (manager *SGroupManager) QueryDistinctExtraField(q *sqlchemy.SQuery, field string) (*sqlchemy.SQuery, error) {
  137. var err error
  138. q, err = manager.SIdentityBaseResourceManager.QueryDistinctExtraField(q, field)
  139. if err == nil {
  140. return q, nil
  141. }
  142. return q, httperrors.ErrNotFound
  143. }
  144. func (group *SGroup) GetUserCount() (int, error) {
  145. q := UsergroupManager.Query().Equals("group_id", group.Id)
  146. return q.CountWithError()
  147. }
  148. func (group *SGroup) GetProjectCount() (int, error) {
  149. q := AssignmentManager.fetchGroupProjectIdsQuery(group.Id)
  150. return q.CountWithError()
  151. }
  152. func (group *SGroup) ValidateDeleteCondition(ctx context.Context, info jsonutils.JSONObject) error {
  153. if group.IsReadOnly() {
  154. return httperrors.NewForbiddenError("readonly")
  155. }
  156. return group.SIdentityBaseResource.ValidateDeleteCondition(ctx, nil)
  157. }
  158. func (group *SGroup) Delete(ctx context.Context, userCred mcclient.TokenCredential) error {
  159. err := AssignmentManager.projectRemoveAllGroup(ctx, userCred, group)
  160. if err != nil {
  161. return errors.Wrap(err, "AssignmentManager.projectRemoveAllGroup")
  162. }
  163. err = UsergroupManager.delete("", group.Id)
  164. if err != nil {
  165. return errors.Wrap(err, "UsergroupManager.delete")
  166. }
  167. return group.SIdentityBaseResource.Delete(ctx, userCred)
  168. }
  169. func (manager *SGroupManager) FetchCustomizeColumns(
  170. ctx context.Context,
  171. userCred mcclient.TokenCredential,
  172. query jsonutils.JSONObject,
  173. objs []interface{},
  174. fields stringutils2.SSortedStrings,
  175. isList bool,
  176. ) []api.GroupDetails {
  177. rows := make([]api.GroupDetails, len(objs))
  178. identRows := manager.SIdentityBaseResourceManager.FetchCustomizeColumns(ctx, userCred, query, objs, fields, isList)
  179. idList := make([]string, len(rows))
  180. for i := range rows {
  181. rows[i] = api.GroupDetails{
  182. IdentityBaseResourceDetails: identRows[i],
  183. }
  184. group := objs[i].(*SGroup)
  185. idList[i] = group.Id
  186. rows[i].UserCount, _ = group.GetUserCount()
  187. rows[i].ProjectCount, _ = group.GetProjectCount()
  188. }
  189. idpRows := expandIdpAttributes(api.IdMappingEntityGroup, idList, fields)
  190. for i := range rows {
  191. rows[i].IdpResourceInfo = idpRows[i]
  192. }
  193. return rows
  194. }
  195. func (manager *SGroupManager) RegisterExternalGroup(ctx context.Context, idpId string, domainId string, groupId string, groupName string) (*SGroup, error) {
  196. lockman.LockClass(ctx, manager, idpId)
  197. defer lockman.ReleaseClass(ctx, manager, idpId)
  198. pubId, err := IdmappingManager.RegisterIdMap(ctx, idpId, groupId, api.IdMappingEntityGroup)
  199. if err != nil {
  200. return nil, errors.Wrap(err, "IdmappingManager.registerIdMap")
  201. }
  202. group := SGroup{}
  203. group.SetModelManager(manager, &group)
  204. q := manager.RawQuery().Equals("id", pubId)
  205. err = q.First(&group)
  206. if err != nil && err != sql.ErrNoRows {
  207. return nil, errors.Wrap(err, "Query")
  208. }
  209. if err == sql.ErrNoRows {
  210. group.Id = pubId
  211. group.DomainId = domainId
  212. group.Name = groupName
  213. group.Displayname = groupName
  214. err = manager.TableSpec().Insert(ctx, &group)
  215. if err != nil {
  216. return nil, errors.Wrap(err, "Insert")
  217. }
  218. } else {
  219. _, err = db.Update(&group, func() error {
  220. group.DomainId = domainId
  221. group.Name = groupName
  222. group.Displayname = groupName
  223. group.MarkUnDelete()
  224. return nil
  225. })
  226. if err != nil {
  227. return nil, errors.Wrap(err, "update")
  228. }
  229. }
  230. return &group, nil
  231. }
  232. func (group *SGroup) ValidateUpdateCondition(ctx context.Context) error {
  233. // if group.IsReadOnly() {
  234. // return httperrors.NewForbiddenError("readonly")
  235. // }
  236. return group.SIdentityBaseResource.ValidateUpdateCondition(ctx)
  237. }
  238. func (group *SGroup) ValidateUpdateData(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, input api.GroupUpdateInput) (api.GroupUpdateInput, error) {
  239. data := jsonutils.Marshal(input)
  240. if group.IsReadOnly() {
  241. for _, k := range []string{
  242. "name",
  243. "displayname",
  244. } {
  245. if data.Contains(k) {
  246. return input, httperrors.NewForbiddenError("field %s is readonly", k)
  247. }
  248. }
  249. }
  250. var err error
  251. input.IdentityBaseUpdateInput, err = group.SIdentityBaseResource.ValidateUpdateData(ctx, userCred, query, input.IdentityBaseUpdateInput)
  252. if err != nil {
  253. return input, errors.Wrap(err, "SIdentityBaseResource.ValidateUpdateData")
  254. }
  255. return input, nil
  256. }
  257. func (manager *SGroupManager) fetchGroupById(gid string) *SGroup {
  258. obj, _ := GroupManager.FetchById(gid)
  259. if obj != nil {
  260. return obj.(*SGroup)
  261. }
  262. return nil
  263. }
  264. func (manager *SGroupManager) NamespaceScope() rbacscope.TRbacScope {
  265. return rbacscope.ScopeDomain
  266. }
  267. func (group *SGroup) getIdmapping() (*SIdmapping, error) {
  268. return IdmappingManager.FetchFirstEntity(group.Id, api.IdMappingEntityGroup)
  269. }
  270. func (group *SGroup) IsReadOnly() bool {
  271. idmap, _ := group.getIdmapping()
  272. if idmap != nil {
  273. return true
  274. }
  275. return false
  276. }
  277. func (group *SGroup) LinkedWithIdp(idpId string) bool {
  278. idmap, _ := group.getIdmapping()
  279. if idmap != nil && idmap.IdpId == idpId {
  280. return true
  281. }
  282. return false
  283. }
  284. func (manager *SGroupManager) FetchGroupsInDomain(domainId string, excludes []string) ([]SGroup, error) {
  285. q := manager.Query().Equals("domain_id", domainId).NotIn("id", excludes)
  286. grps := make([]SGroup, 0)
  287. err := db.FetchModelObjects(manager, q, &grps)
  288. if err != nil && err != sql.ErrNoRows {
  289. return nil, errors.Wrap(err, "db.FetchModelObjects")
  290. }
  291. return grps, nil
  292. }
  293. func (group *SGroup) UnlinkIdp(idpId string) error {
  294. return IdmappingManager.deleteAny(idpId, api.IdMappingEntityGroup, group.Id)
  295. }
  296. // 组加入项目
  297. func (group *SGroup) PerformJoin(
  298. ctx context.Context,
  299. userCred mcclient.TokenCredential,
  300. query jsonutils.JSONObject,
  301. input api.SJoinProjectsInput,
  302. ) (jsonutils.JSONObject, error) {
  303. err := joinProjects(group, false, ctx, userCred, input)
  304. if err != nil {
  305. return nil, errors.Wrap(err, "joinProjects")
  306. }
  307. return nil, nil
  308. }
  309. // 组退出项目
  310. func (group *SGroup) PerformLeave(
  311. ctx context.Context,
  312. userCred mcclient.TokenCredential,
  313. query jsonutils.JSONObject,
  314. input api.SLeaveProjectsInput,
  315. ) (jsonutils.JSONObject, error) {
  316. err := leaveProjects(group, false, ctx, userCred, input)
  317. if err != nil {
  318. return nil, err
  319. }
  320. return nil, nil
  321. }
  322. func (manager *SGroupManager) FilterByOwner(ctx context.Context, q *sqlchemy.SQuery, man db.FilterByOwnerProvider, userCred mcclient.TokenCredential, owner mcclient.IIdentityProvider, scope rbacscope.TRbacScope) *sqlchemy.SQuery {
  323. if owner != nil && scope == rbacscope.ScopeProject {
  324. // if user has project level privilege, returns all groups in user's project
  325. subq := AssignmentManager.fetchProjectGroupIdsQuery(owner.GetProjectId())
  326. q = q.In("id", subq.SubQuery())
  327. return q
  328. }
  329. return manager.SIdentityBaseResourceManager.FilterByOwner(ctx, q, man, userCred, owner, scope)
  330. }
  331. func (group *SGroup) GetUsages() []db.IUsage {
  332. if group.Deleted {
  333. return nil
  334. }
  335. usage := SIdentityQuota{Group: 1}
  336. usage.SetKeys(quotas.SBaseDomainQuotaKeys{DomainId: group.DomainId})
  337. return []db.IUsage{
  338. &usage,
  339. }
  340. }
  341. func (manager *SGroupManager) ValidateCreateData(
  342. ctx context.Context,
  343. userCred mcclient.TokenCredential,
  344. ownerId mcclient.IIdentityProvider,
  345. query jsonutils.JSONObject,
  346. input api.GroupCreateInput,
  347. ) (api.GroupCreateInput, error) {
  348. var err error
  349. input.IdentityBaseResourceCreateInput, err = manager.SIdentityBaseResourceManager.ValidateCreateData(ctx, userCred, ownerId, query, input.IdentityBaseResourceCreateInput)
  350. if err != nil {
  351. return input, errors.Wrap(err, "SIdentityBaseResourceManager.ValidateCreateData")
  352. }
  353. quota := &SIdentityQuota{
  354. SBaseDomainQuotaKeys: quotas.SBaseDomainQuotaKeys{DomainId: ownerId.GetProjectDomainId()},
  355. Group: 1,
  356. }
  357. err = quotas.CheckSetPendingQuota(ctx, userCred, quota)
  358. if err != nil {
  359. return input, errors.Wrap(err, "CheckSetPendingQuota")
  360. }
  361. return input, nil
  362. }
  363. func (group *SGroup) PostCreate(
  364. ctx context.Context,
  365. userCred mcclient.TokenCredential,
  366. ownerId mcclient.IIdentityProvider,
  367. query jsonutils.JSONObject,
  368. data jsonutils.JSONObject,
  369. ) {
  370. group.SIdentityBaseResource.PostCreate(ctx, userCred, ownerId, query, data)
  371. quota := &SIdentityQuota{
  372. SBaseDomainQuotaKeys: quotas.SBaseDomainQuotaKeys{DomainId: ownerId.GetProjectDomainId()},
  373. Group: 1,
  374. }
  375. err := quotas.CancelPendingUsage(ctx, userCred, quota, quota, true)
  376. if err != nil {
  377. log.Errorf("CancelPendingUsage fail %s", err)
  378. }
  379. }
  380. // 组添加用户
  381. func (group *SGroup) PerformAddUsers(
  382. ctx context.Context,
  383. userCred mcclient.TokenCredential,
  384. query jsonutils.JSONObject,
  385. input api.PerformGroupAddUsersInput,
  386. ) (jsonutils.JSONObject, error) {
  387. users := make([]*SUser, 0)
  388. for _, uid := range input.UserIds {
  389. usr, err := UserManager.FetchByIdOrName(ctx, userCred, uid)
  390. if err != nil {
  391. if errors.Cause(err) == sql.ErrNoRows {
  392. return nil, errors.Wrapf(httperrors.ErrResourceNotFound, "user %s", uid)
  393. } else {
  394. return nil, errors.Wrap(err, "UserManager.FetchByIdOrName")
  395. }
  396. }
  397. users = append(users, usr.(*SUser))
  398. }
  399. for i := range users {
  400. err := UsergroupManager.add(ctx, userCred, users[i], group)
  401. if err != nil {
  402. return nil, errors.Wrap(err, "UsergroupManager.add")
  403. }
  404. }
  405. return nil, nil
  406. }
  407. // 组删除用户
  408. func (group *SGroup) PerformRemoveUsers(
  409. ctx context.Context,
  410. userCred mcclient.TokenCredential,
  411. query jsonutils.JSONObject,
  412. input api.PerformGroupRemoveUsersInput,
  413. ) (jsonutils.JSONObject, error) {
  414. users := make([]*SUser, 0)
  415. for _, uid := range input.UserIds {
  416. usr, err := UserManager.FetchByIdOrName(ctx, userCred, uid)
  417. if err != nil {
  418. if errors.Cause(err) == sql.ErrNoRows {
  419. return nil, errors.Wrapf(httperrors.ErrResourceNotFound, "user %s", uid)
  420. } else {
  421. return nil, errors.Wrap(err, "UserManager.FetchByIdOrName")
  422. }
  423. }
  424. users = append(users, usr.(*SUser))
  425. }
  426. for i := range users {
  427. err := UsergroupManager.remove(ctx, userCred, users[i], group)
  428. if err != nil {
  429. return nil, errors.Wrap(err, "UsergroupManager.add")
  430. }
  431. }
  432. return nil, nil
  433. }