def post_migrate( self, app_config: django.apps.AppConfig, verbosity: int, interactive: bool, using: str, **kwargs, ) -> None: from django.conf import settings # noqa super().post_migrate(app_config, verbosity, interactive, using, **kwargs) # Ensure presence of an OTP YubiKey default config apps.get_model( "otp_yubikey", "ValidationService").objects.using(using).update_or_create( name="default", defaults={ "use_ssl": True, "param_sl": "", "param_timeout": "" }) # Ensure that default Favicon object exists for name, default in settings.DEFAULT_FAVICON_PATHS.items(): get_or_create_favicon(name, default, is_favicon=name == "favicon")
def adjust_roles(apps, role_prefix, desired_roles, verbosity=1): """ Adjust all roles with a given prefix. Args: apps (django.apps.registry.Apps): Django app registry role_prefix (str): Common prefix of roles to adjust desired_roles (dict): Dictionary of desired state of roles, where each entry is either a list of permissions, or a dict with "description" and "permissions" as keys. """ assert all((key.startswith(role_prefix) for key in desired_roles)) try: Role = apps.get_model("core", "Role") Permission = apps.get_model("auth", "Permission") except LookupError: # The signal might have been triggered on an old migration if verbosity >= 1: print(_("Role model does not exist. Skipping initialization.")) return def _get_permission(perm): app_label, codename = perm.split(".", maxsplit=2) return Permission.objects.get(content_type__app_label=app_label, codename=codename) # Remove obsolete roles Role.objects.filter( name__startswith=role_prefix, locked=True).exclude(name__in=desired_roles.keys()).delete() # Create / update desired roles for name, desired_role in desired_roles.items(): if isinstance(desired_role, dict): description = desired_role.get("description") permissions = desired_role["permissions"] elif isinstance(desired_role, list): description = None permissions = desired_role else: raise RuntimeError( _("Locked role definition for {name} is incompatible.").format( name=name)) permissions = [_get_permission(perm) for perm in permissions] role, created = Role.objects.get_or_create(name=name, locked=True, defaults={ "name": name, "locked": True }) role.description = description role.save() role.permissions.set(permissions)
def _populate_access_policies(sender, apps, verbosity, **kwargs): from pulpcore.app.util import get_view_urlpattern try: AccessPolicy = apps.get_model("core", "AccessPolicy") except LookupError: if verbosity >= 1: print( _("AccessPolicy model does not exist. Skipping initialization." )) return for viewset_batch in sender.named_viewsets.values(): for viewset in viewset_batch: access_policy = getattr(viewset, "DEFAULT_ACCESS_POLICY", None) if access_policy is not None: viewset_name = get_view_urlpattern(viewset) _rename_permissions_assignment_workaround( access_policy, viewset) db_access_policy, created = AccessPolicy.objects.get_or_create( viewset_name=viewset_name, defaults=access_policy) if created: if verbosity >= 1: print( _("Access policy for {viewset_name} created."). format(viewset_name=viewset_name)) if not created and not db_access_policy.customized: for key, value in access_policy.items(): setattr(db_access_policy, key, value) db_access_policy.save() if verbosity >= 1: print( _("Access policy for {viewset_name} updated."). format(viewset_name=viewset_name))
def _populate_access_policies(sender, **kwargs): print(f"Initialize missing access policies for {sender.label}.") apps = kwargs.get("apps") if apps is None: from django.apps import apps AccessPolicy = apps.get_model("core", "AccessPolicy") for viewset_batch in sender.named_viewsets.values(): for viewset in viewset_batch: access_policy = getattr(viewset, "DEFAULT_ACCESS_POLICY", None) if access_policy is not None: AccessPolicy.objects.get_or_create( viewset_name=viewset.urlpattern(), defaults=access_policy)
def log_gather_history(model_name, message, no_people, no_groups, no_identifiers, status=GatherHistory.COMPLETED): history = apps.get_model(model_name) store, created = history.objects.create(message=message, no_groups=no_groups, no_people=no_people, no_identifiers=no_identifiers, import_status=status) store.save()
def add_permission(request, app_label, module_name, pk, approved=False, template_name='authority/permission_form.html', extra_context=None, form_class=UserPermissionForm): codename = request.POST.get('codename', None) model = apps.get_model(app_label, module_name) if model is None: return permission_denied(request) obj = get_object_or_404(model, pk=pk) next = get_next(request, obj) if approved: if not request.user.has_perm('authority.add_permission'): return HttpResponseRedirect( url_for_obj('authority-add-permission-request', obj)) view_name = 'authority-add-permission' else: view_name = 'authority-add-permission-request' if request.method == 'POST': if codename is None: return HttpResponseForbidden(next) form = form_class(data=request.POST, obj=obj, approved=approved, perm=codename, initial=dict(codename=codename)) if not approved: # Limit permission request to current user form.data['user'] = request.user if form.is_valid(): form.save(request) request.user.message_set.create( message=_('You added a permission request.')) return HttpResponseRedirect(next) else: form = form_class(obj=obj, approved=approved, perm=codename, initial=dict(codename=codename)) context = { 'form': form, 'form_url': url_for_obj(view_name, obj), 'next': next, 'perm': codename, 'approved': approved, } if extra_context: context.update(extra_context) return render_to_response(template_name, context, context_instance=RequestContext(request))
def _populate_access_policies(sender, **kwargs): from pulpcore.app.util import get_view_urlpattern apps = kwargs.get("apps") if apps is None: from django.apps import apps AccessPolicy = apps.get_model("core", "AccessPolicy") for viewset_batch in sender.named_viewsets.values(): for viewset in viewset_batch: access_policy = getattr(viewset, "DEFAULT_ACCESS_POLICY", None) if access_policy is not None: viewset_name = get_view_urlpattern(viewset) db_access_policy, created = AccessPolicy.objects.get_or_create( viewset_name=viewset_name, defaults=access_policy) if created: print(f"Access policy for {viewset_name} created.") if not created and not db_access_policy.customized: for key, value in access_policy.items(): setattr(db_access_policy, key, value) db_access_policy.save() print(f"Access policy for {viewset_name} updated.")
def create_proxy_permissions(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs): if not app_config.models_module: return # print(app_config) try: Permission = apps.get_model('auth', 'Permission') except LookupError: return if not router.allow_migrate_model(using, Permission): return from django.contrib.contenttypes.models import ContentType permission_name_max_length = Permission._meta.get_field('name').max_length # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = list() # The codenames and ctypes that should exist. ctypes = set() for klass in list(app_config.get_models()): opts = klass._meta permissions = ( ("list_" + opts.model_name, string_concat(_('Visualizaçao da lista de'), ' ', opts.verbose_name_plural)), ("detail_" + opts.model_name, string_concat(_('Visualização dos detalhes de'), ' ', opts.verbose_name_plural)), ) opts.permissions = tuple( set(list(permissions) + list(opts.permissions))) if opts.proxy: # Force looking up the content types in the current database # before creating foreign keys to them. app_label, model = opts.app_label, opts.model_name try: ctype = ContentType.objects.db_manager( using).get_by_natural_key(app_label, model) except: ctype = ContentType.objects.db_manager(using).create( app_label=app_label, model=model) else: ctype = ContentType.objects.db_manager(using).get_for_model(klass) ctypes.add(ctype) for perm in _get_all_permissions(klass._meta, ctype): searched_perms.append((ctype, perm)) # Find all the Permissions that have a content_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_perms = set( Permission.objects.using(using).filter( content_type__in=ctypes, ).values_list("content_type", "codename")) perms = [ Permission(codename=codename, name=name, content_type=ct) for ct, (codename, name) in searched_perms if (ct.pk, codename) not in all_perms ] # Validate the permissions before bulk_creation to avoid cryptic database # error when the name is longer than 255 characters for perm in perms: if len(perm.name) > permission_name_max_length: raise exceptions.ValidationError('The permission name %s of %s.%s ' 'is longer than %s characters' % ( perm.name, perm.content_type.app_label, perm.content_type.model, permission_name_max_length, )) Permission.objects.using(using).bulk_create(perms) if verbosity >= 2: for perm in perms: print("Adding permission '%s'" % perm)
def model_classes(self): return [apps.get_model(n) for n in self.models]
def get_sms_template_model(): return get_model(*getattr(settings, 'ATS_SMS_TEMPLATE_MODEL').split('.'))
def get_output_sms_model(): return get_model(*getattr(settings, 'ATS_OUTPUT_SMS_MODEL').split('.'))
def model(self): return apps.get_model(app_label=str(self.kwargs['app_label']), model_name=str(self.kwargs['model_name']))
def handle(self, *args, **options): if args: raise CommandError("Command doesn't accept any arguments") Entry = get_entry_model() CategoryM2M = Entry.categories.through old_fk = CategoryM2M._meta.get_field('category') CurrentModel = old_fk.rel.to self.stdout.write("Current Entry.categories model: <{0}.{1}>".format( CurrentModel._meta.app_label, CurrentModel._meta.object_name)) old = options['from'] new = options['to'] if not old or not new: raise CommandError("Expected --from and --to options") if old.lower( ) == 'categories.category' and 'categories' not in settings.INSTALLED_APPS: # Can't import it in a Django 1.8+ project. OldModel = DummyCategoryBase else: try: OldModel = apps.get_model(old) except LookupError as e: raise CommandError("Invalid --from value: {0}".format(e)) if not issubclass(OldModel, MPTTModel): raise CommandError("Expected MPTT model for --from value") try: NewModel = apps.get_model(new) except LookupError as e: raise CommandError("Invalid --to value: {0}".format(e)) if not issubclass(NewModel, MPTTModel): raise CommandError("Expected MPTT model for --to value") if NewModel.objects.all().exists(): raise CommandError( "New model already has records, it should be an empty table!") old_i18n = issubclass(OldModel, TranslatableModel) new_i18n = issubclass(NewModel, TranslatableModel) old_title = _detect_title_field(OldModel) new_title = _detect_title_field(NewModel) mptt_fields = "lft, rght, tree_id, level, parent_id" with transaction.atomic(): if not old_i18n and not new_i18n: # Untranslated to untranslated self.stdout.write("* Copying category fields...") with connection.cursor() as cursor: cursor.execute( 'INSERT INTO {new_model}(id, slug, {new_title}, {mptt_fields}})' ' SELECT id, slug, {old_title}, {mptt_fields} FROM {old_model}' .format( new_model=NewModel._meta.db_table, new_title=new_title, old_model=OldModel._meta.db_table, old_title=old_title, mptt_fields=mptt_fields, )) elif not old_i18n and new_i18n: # Untranslated to translated # - base table fields with connection.cursor() as cursor: self.stdout.write("* Copying category base fields...") cursor.execute( 'INSERT INTO {new_model}(id, {mptt_fields})' ' SELECT id, {mptt_fields} FROM {old_model}'.format( new_model=NewModel._meta.db_table, old_model=OldModel._meta.db_table, mptt_fields=mptt_fields, )) # - create translations on fallback language self.stdout.write("* Creating category translations...") cursor.execute( 'INSERT INTO {new_translations}(master_id, language_code, slug, {new_title})' ' SELECT id, %s, slug, {old_title} FROM {old_model}'. format( new_translations=NewModel._parler_meta.root_model. _meta.db_table, new_title=new_title, old_model=OldModel._meta.db_table, old_title=old_title, ), [appsettings.FLUENT_BLOGS_DEFAULT_LANGUAGE_CODE]) elif old_i18n and not new_i18n: # Reverse, translated to untranslated. Take fallback only # Convert all fields back to the single-language table. self.stdout.write( "* Copying category fields and fallback language fields..." ) for old_category in OldModel.objects.all(): translations = old_category.translations.all() try: # Try default translation old_translation = translations.get( language_code=appsettings. FLUENT_BLOGS_DEFAULT_LANGUAGE_CODE) except ObjectDoesNotExist: try: # Try internal fallback old_translation = translations.get( language_code__in=('en-us', 'en')) except ObjectDoesNotExist: # Hope there is a single translation old_translation = translations.get() fields = dict( id=old_category.id, lft=old_category.lft, rght=old_category.rght, tree_id=old_category.tree_id, level=old_category.level, # parler fields _language_code=old_translation.language_code, slug=old_category.slug) fields[new_title] = getattr(old_translation, old_title) NewModel.objects.create(**fields) elif old_i18n and new_i18n: # Translated to translated # - base table with connection.cursor() as cursor: self.stdout.write("* Copying category base fields...") cursor.execute( 'INSERT INTO {new_model}(id, {mptt_fields})' ' SELECT id, {mptt_fields} FROM {old_model}'.format( new_model=NewModel._meta.db_table, old_model=OldModel._meta.db_table, mptt_fields=mptt_fields, )) # - all translations self.stdout.write("* Copying category translations...") cursor.execute( 'INSERT INTO {new_translations}(master_id, language_code, slug, {new_title})' ' SELECT id, languag_code, slug, {old_title} FROM {old_translations}' .format( new_translations=NewModel._parler_meta.root_model. _meta.db_table, new_title=new_title, old_translations=OldModel._parler_meta.root_model. _meta.db_table, old_title=old_title, ), [appsettings.FLUENT_BLOGS_DEFAULT_LANGUAGE_CODE]) else: raise NotImplementedError() # impossible combination self.stdout.write("* Switching M2M foreign key constraints...") __, __, __, kwargs = old_fk.deconstruct() kwargs['to'] = NewModel new_fk = models.ForeignKey(**kwargs) new_fk.set_attributes_from_name(old_fk.name) with connection.schema_editor() as schema_editor: schema_editor.alter_field(CategoryM2M, old_fk, new_fk) self.stdout.write("Done.\n") self.stdout.write( "You may now remove the old category app from your project, INSTALLED_APPS and database.\n" )