Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

__init__.py 4.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. """
  2. Creates permissions for all installed apps that need permissions.
  3. """
  4. import getpass
  5. import unicodedata
  6. from django.apps import apps as global_apps
  7. from django.contrib.auth import get_permission_codename
  8. from django.core import exceptions
  9. from django.db import DEFAULT_DB_ALIAS, router
  10. def _get_all_permissions(opts):
  11. """
  12. Return (codename, name) for all permissions in the given opts.
  13. """
  14. builtin = _get_builtin_permissions(opts)
  15. custom = list(opts.permissions)
  16. return builtin + custom
  17. def _get_builtin_permissions(opts):
  18. """
  19. Return (codename, name) for all autogenerated permissions.
  20. By default, this is ('add', 'change', 'delete', 'view')
  21. """
  22. perms = []
  23. for action in opts.default_permissions:
  24. perms.append((
  25. get_permission_codename(action, opts),
  26. 'Can %s %s' % (action, opts.verbose_name_raw)
  27. ))
  28. return perms
  29. def create_permissions(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, apps=global_apps, **kwargs):
  30. if not app_config.models_module:
  31. return
  32. app_label = app_config.label
  33. try:
  34. app_config = apps.get_app_config(app_label)
  35. ContentType = apps.get_model('contenttypes', 'ContentType')
  36. Permission = apps.get_model('auth', 'Permission')
  37. except LookupError:
  38. return
  39. if not router.allow_migrate_model(using, Permission):
  40. return
  41. # This will hold the permissions we're looking for as
  42. # (content_type, (codename, name))
  43. searched_perms = []
  44. # The codenames and ctypes that should exist.
  45. ctypes = set()
  46. for klass in app_config.get_models():
  47. # Force looking up the content types in the current database
  48. # before creating foreign keys to them.
  49. ctype = ContentType.objects.db_manager(using).get_for_model(klass)
  50. ctypes.add(ctype)
  51. for perm in _get_all_permissions(klass._meta):
  52. searched_perms.append((ctype, perm))
  53. # Find all the Permissions that have a content_type for a model we're
  54. # looking for. We don't need to check for codenames since we already have
  55. # a list of the ones we're going to create.
  56. all_perms = set(Permission.objects.using(using).filter(
  57. content_type__in=ctypes,
  58. ).values_list(
  59. "content_type", "codename"
  60. ))
  61. perms = [
  62. Permission(codename=codename, name=name, content_type=ct)
  63. for ct, (codename, name) in searched_perms
  64. if (ct.pk, codename) not in all_perms
  65. ]
  66. Permission.objects.using(using).bulk_create(perms)
  67. if verbosity >= 2:
  68. for perm in perms:
  69. print("Adding permission '%s'" % perm)
  70. def get_system_username():
  71. """
  72. Return the current system user's username, or an empty string if the
  73. username could not be determined.
  74. """
  75. try:
  76. result = getpass.getuser()
  77. except (ImportError, KeyError):
  78. # KeyError will be raised by os.getpwuid() (called by getuser())
  79. # if there is no corresponding entry in the /etc/passwd file
  80. # (a very restricted chroot environment, for example).
  81. return ''
  82. return result
  83. def get_default_username(check_db=True):
  84. """
  85. Try to determine the current system user's username to use as a default.
  86. :param check_db: If ``True``, requires that the username does not match an
  87. existing ``auth.User`` (otherwise returns an empty string).
  88. :returns: The username, or an empty string if no username can be
  89. determined.
  90. """
  91. # This file is used in apps.py, it should not trigger models import.
  92. from django.contrib.auth import models as auth_app
  93. # If the User model has been swapped out, we can't make any assumptions
  94. # about the default user name.
  95. if auth_app.User._meta.swapped:
  96. return ''
  97. default_username = get_system_username()
  98. try:
  99. default_username = (
  100. unicodedata.normalize('NFKD', default_username)
  101. .encode('ascii', 'ignore').decode('ascii')
  102. .replace(' ', '').lower()
  103. )
  104. except UnicodeDecodeError:
  105. return ''
  106. # Run the username validator
  107. try:
  108. auth_app.User._meta.get_field('username').run_validators(default_username)
  109. except exceptions.ValidationError:
  110. return ''
  111. # Don't return the default username if it is already taken.
  112. if check_db and default_username:
  113. try:
  114. auth_app.User._default_manager.get(username=default_username)
  115. except auth_app.User.DoesNotExist:
  116. pass
  117. else:
  118. return ''
  119. return default_username