permissions_cleanup.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. from collections import defaultdict
  18. from superset import sm
  19. def cleanup_permissions():
  20. # 1. Clean up duplicates.
  21. pvms = sm.get_session.query(sm.permissionview_model).all()
  22. print('# of permission view menues is: {}'.format(len(pvms)))
  23. pvms_dict = defaultdict(list)
  24. for pvm in pvms:
  25. pvms_dict[(pvm.permission, pvm.view_menu)].append(pvm)
  26. duplicates = [v for v in pvms_dict.values() if len(v) > 1]
  27. len(duplicates)
  28. for pvm_list in duplicates:
  29. first_prm = pvm_list[0]
  30. roles = set(first_prm.role)
  31. for pvm in pvm_list[1:]:
  32. roles = roles.union(pvm.role)
  33. sm.get_session.delete(pvm)
  34. first_prm.roles = list(roles)
  35. sm.get_session.commit()
  36. pvms = sm.get_session.query(sm.permissionview_model).all()
  37. print('STage 1: # of permission view menues is: {}'.format(len(pvms)))
  38. # 2. Clean up None permissions or view menues
  39. pvms = sm.get_session.query(sm.permissionview_model).all()
  40. for pvm in pvms:
  41. if not (pvm.view_menu and pvm.permission):
  42. sm.get_session.delete(pvm)
  43. sm.get_session.commit()
  44. pvms = sm.get_session.query(sm.permissionview_model).all()
  45. print('Stage 2: # of permission view menues is: {}'.format(len(pvms)))
  46. # 3. Delete empty permission view menues from roles
  47. roles = sm.get_session.query(sm.role_model).all()
  48. for role in roles:
  49. role.permissions = [p for p in role.permissions if p]
  50. sm.get_session.commit()
  51. # 4. Delete empty roles from permission view menues
  52. pvms = sm.get_session.query(sm.permissionview_model).all()
  53. for pvm in pvms:
  54. pvm.role = [r for r in pvm.role if r]
  55. sm.get_session.commit()
  56. cleanup_permissions()