Python django.contrib.auth.models.AbstractBaseUser() Examples

The following are 14 code examples of django.contrib.auth.models.AbstractBaseUser(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.contrib.auth.models , or try the search function .
Example #1
Source File: models.py    From elasticsearch-django with MIT License 6 votes vote down vote up
def execute(
        cls,
        search: Search,
        search_terms: str = "",
        user: Optional[AbstractBaseUser] = None,
        reference: Optional[str] = "",
        save: bool = True,
    ) -> SearchQuery:
        """Create a new SearchQuery instance and execute a search against ES."""
        warnings.warn(
            "Deprecated - please use `execute_search` function instead.",
            DeprecationWarning,
        )
        return execute_search(
            search, search_terms=search_terms, user=user, reference=reference, save=save
        ) 
Example #2
Source File: test_checks.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_required_fields_is_list(self):
        """REQUIRED_FIELDS should be a list."""
        class CustomUserNonListRequiredFields(AbstractBaseUser):
            username = models.CharField(max_length=30, unique=True)
            date_of_birth = models.DateField()

            USERNAME_FIELD = 'username'
            REQUIRED_FIELDS = 'date_of_birth'

        errors = checks.run_checks(app_configs=self.apps.get_app_configs())
        self.assertEqual(errors, [
            checks.Error(
                "'REQUIRED_FIELDS' must be a list or tuple.",
                obj=CustomUserNonListRequiredFields,
                id='auth.E001',
            ),
        ]) 
Example #3
Source File: test_checks.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_username_not_in_required_fields(self):
        """USERNAME_FIELD should not appear in REQUIRED_FIELDS."""
        class CustomUserBadRequiredFields(AbstractBaseUser):
            username = models.CharField(max_length=30, unique=True)
            date_of_birth = models.DateField()

            USERNAME_FIELD = 'username'
            REQUIRED_FIELDS = ['username', 'date_of_birth']

        errors = checks.run_checks(self.apps.get_app_configs())
        self.assertEqual(errors, [
            checks.Error(
                "The field named as the 'USERNAME_FIELD' for a custom user model "
                "must not be included in 'REQUIRED_FIELDS'.",
                obj=CustomUserBadRequiredFields,
                id='auth.E002',
            ),
        ]) 
Example #4
Source File: test_checks.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_required_fields_is_list(self):
        """REQUIRED_FIELDS should be a list."""
        class CustomUserNonListRequiredFields(AbstractBaseUser):
            username = models.CharField(max_length=30, unique=True)
            date_of_birth = models.DateField()

            USERNAME_FIELD = 'username'
            REQUIRED_FIELDS = 'date_of_birth'

        errors = checks.run_checks(app_configs=self.apps.get_app_configs())
        self.assertEqual(errors, [
            checks.Error(
                "'REQUIRED_FIELDS' must be a list or tuple.",
                obj=CustomUserNonListRequiredFields,
                id='auth.E001',
            ),
        ]) 
Example #5
Source File: test_checks.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_username_not_in_required_fields(self):
        """USERNAME_FIELD should not appear in REQUIRED_FIELDS."""
        class CustomUserBadRequiredFields(AbstractBaseUser):
            username = models.CharField(max_length=30, unique=True)
            date_of_birth = models.DateField()

            USERNAME_FIELD = 'username'
            REQUIRED_FIELDS = ['username', 'date_of_birth']

        errors = checks.run_checks(self.apps.get_app_configs())
        self.assertEqual(errors, [
            checks.Error(
                "The field named as the 'USERNAME_FIELD' for a custom user model "
                "must not be included in 'REQUIRED_FIELDS'.",
                obj=CustomUserBadRequiredFields,
                id='auth.E002',
            ),
        ]) 
Example #6
Source File: test_autodetector.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_circular_dependency_swappable(self):
        """
        #23322 - The dependency resolver knows to explicitly resolve
        swappable models.
        """
        with isolate_lru_cache(apps.get_swappable_settings_name):
            tenant = ModelState("a", "Tenant", [
                ("id", models.AutoField(primary_key=True)),
                ("primary_address", models.ForeignKey("b.Address", models.CASCADE))],
                bases=(AbstractBaseUser, )
            )
            address = ModelState("b", "Address", [
                ("id", models.AutoField(primary_key=True)),
                ("tenant", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE)),
            ])
            changes = self.get_changes([], [address, tenant])

        # Right number/type of migrations?
        self.assertNumberMigrations(changes, 'a', 2)
        self.assertOperationTypes(changes, 'a', 0, ["CreateModel"])
        self.assertOperationTypes(changes, 'a', 1, ["AddField"])
        self.assertMigrationDependencies(changes, 'a', 0, [])
        self.assertMigrationDependencies(changes, 'a', 1, [('a', 'auto_1'), ('b', 'auto_1')])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, 'b', 1)
        self.assertOperationTypes(changes, 'b', 0, ["CreateModel"])
        self.assertMigrationDependencies(changes, 'b', 0, [('__setting__', 'AUTH_USER_MODEL')]) 
Example #7
Source File: test_autodetector.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_circular_dependency_swappable2(self):
        """
        #23322 - The dependency resolver knows to explicitly resolve
        swappable models but with the swappable not being the first migrated
        model.
        """
        with isolate_lru_cache(apps.get_swappable_settings_name):
            address = ModelState("a", "Address", [
                ("id", models.AutoField(primary_key=True)),
                ("tenant", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE)),
            ])
            tenant = ModelState("b", "Tenant", [
                ("id", models.AutoField(primary_key=True)),
                ("primary_address", models.ForeignKey("a.Address", models.CASCADE))],
                bases=(AbstractBaseUser, )
            )
            changes = self.get_changes([], [address, tenant])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, 'a', 2)
        self.assertOperationTypes(changes, 'a', 0, ["CreateModel"])
        self.assertOperationTypes(changes, 'a', 1, ["AddField"])
        self.assertMigrationDependencies(changes, 'a', 0, [])
        self.assertMigrationDependencies(changes, 'a', 1, [('__setting__', 'AUTH_USER_MODEL'), ('a', 'auto_1')])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, 'b', 1)
        self.assertOperationTypes(changes, 'b', 0, ["CreateModel"])
        self.assertMigrationDependencies(changes, 'b', 0, [('a', 'auto_1')]) 
Example #8
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_circular_dependency_swappable(self):
        """
        #23322 - The dependency resolver knows to explicitly resolve
        swappable models.
        """
        with isolate_lru_cache(apps.get_swappable_settings_name):
            tenant = ModelState("a", "Tenant", [
                ("id", models.AutoField(primary_key=True)),
                ("primary_address", models.ForeignKey("b.Address", models.CASCADE))],
                bases=(AbstractBaseUser,)
            )
            address = ModelState("b", "Address", [
                ("id", models.AutoField(primary_key=True)),
                ("tenant", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE)),
            ])
            changes = self.get_changes([], [address, tenant])

        # Right number/type of migrations?
        self.assertNumberMigrations(changes, 'a', 2)
        self.assertOperationTypes(changes, 'a', 0, ["CreateModel"])
        self.assertOperationTypes(changes, 'a', 1, ["AddField"])
        self.assertMigrationDependencies(changes, 'a', 0, [])
        self.assertMigrationDependencies(changes, 'a', 1, [('a', 'auto_1'), ('b', 'auto_1')])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, 'b', 1)
        self.assertOperationTypes(changes, 'b', 0, ["CreateModel"])
        self.assertMigrationDependencies(changes, 'b', 0, [('__setting__', 'AUTH_USER_MODEL')]) 
Example #9
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_circular_dependency_swappable2(self):
        """
        #23322 - The dependency resolver knows to explicitly resolve
        swappable models but with the swappable not being the first migrated
        model.
        """
        with isolate_lru_cache(apps.get_swappable_settings_name):
            address = ModelState("a", "Address", [
                ("id", models.AutoField(primary_key=True)),
                ("tenant", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE)),
            ])
            tenant = ModelState("b", "Tenant", [
                ("id", models.AutoField(primary_key=True)),
                ("primary_address", models.ForeignKey("a.Address", models.CASCADE))],
                bases=(AbstractBaseUser,)
            )
            changes = self.get_changes([], [address, tenant])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, 'a', 2)
        self.assertOperationTypes(changes, 'a', 0, ["CreateModel"])
        self.assertOperationTypes(changes, 'a', 1, ["AddField"])
        self.assertMigrationDependencies(changes, 'a', 0, [])
        self.assertMigrationDependencies(changes, 'a', 1, [('__setting__', 'AUTH_USER_MODEL'), ('a', 'auto_1')])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, 'b', 1)
        self.assertOperationTypes(changes, 'b', 0, ["CreateModel"])
        self.assertMigrationDependencies(changes, 'b', 0, [('a', 'auto_1')]) 
Example #10
Source File: test_checks.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_is_anonymous_authenticated_methods(self):
        """
        <User Model>.is_anonymous/is_authenticated must not be methods.
        """
        class BadUser(AbstractBaseUser):
            username = models.CharField(max_length=30, unique=True)
            USERNAME_FIELD = 'username'

            def is_anonymous(self):
                return True

            def is_authenticated(self):
                return True

        errors = checks.run_checks(app_configs=self.apps.get_app_configs())
        self.assertEqual(errors, [
            checks.Critical(
                '%s.is_anonymous must be an attribute or property rather than '
                'a method. Ignoring this is a security issue as anonymous '
                'users will be treated as authenticated!' % BadUser,
                obj=BadUser,
                id='auth.C009',
            ),
            checks.Critical(
                '%s.is_authenticated must be an attribute or property rather '
                'than a method. Ignoring this is a security issue as anonymous '
                'users will be treated as authenticated!' % BadUser,
                obj=BadUser,
                id='auth.C010',
            ),
        ]) 
Example #11
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_circular_dependency_swappable2(self):
        """
        #23322 - The dependency resolver knows to explicitly resolve
        swappable models but with the swappable not being the first migrated
        model.
        """
        with isolate_lru_cache(apps.get_swappable_settings_name):
            address = ModelState("a", "Address", [
                ("id", models.AutoField(primary_key=True)),
                ("tenant", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE)),
            ])
            tenant = ModelState("b", "Tenant", [
                ("id", models.AutoField(primary_key=True)),
                ("primary_address", models.ForeignKey("a.Address", models.CASCADE))],
                bases=(AbstractBaseUser,)
            )
            changes = self.get_changes([], [address, tenant])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, 'a', 2)
        self.assertOperationTypes(changes, 'a', 0, ["CreateModel"])
        self.assertOperationTypes(changes, 'a', 1, ["AddField"])
        self.assertMigrationDependencies(changes, 'a', 0, [])
        self.assertMigrationDependencies(changes, 'a', 1, [('__setting__', 'AUTH_USER_MODEL'), ('a', 'auto_1')])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, 'b', 1)
        self.assertOperationTypes(changes, 'b', 0, ["CreateModel"])
        self.assertMigrationDependencies(changes, 'b', 0, [('a', 'auto_1')]) 
Example #12
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_swappable_circular_multi_mti(self):
        with isolate_lru_cache(apps.get_swappable_settings_name):
            parent = ModelState('a', 'Parent', [
                ('user', models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE))
            ])
            child = ModelState('a', 'Child', [], bases=('a.Parent',))
            user = ModelState('a', 'User', [], bases=(AbstractBaseUser, 'a.Child'))
            changes = self.get_changes([], [parent, child, user])
        self.assertNumberMigrations(changes, 'a', 1)
        self.assertOperationTypes(changes, 'a', 0, ['CreateModel', 'CreateModel', 'CreateModel', 'AddField']) 
Example #13
Source File: test_checks.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_is_anonymous_authenticated_methods(self):
        """
        <User Model>.is_anonymous/is_authenticated must not be methods.
        """
        class BadUser(AbstractBaseUser):
            username = models.CharField(max_length=30, unique=True)
            USERNAME_FIELD = 'username'

            def is_anonymous(self):
                return True

            def is_authenticated(self):
                return True

        errors = checks.run_checks(app_configs=self.apps.get_app_configs())
        self.assertEqual(errors, [
            checks.Critical(
                '%s.is_anonymous must be an attribute or property rather than '
                'a method. Ignoring this is a security issue as anonymous '
                'users will be treated as authenticated!' % BadUser,
                obj=BadUser,
                id='auth.C009',
            ),
            checks.Critical(
                '%s.is_authenticated must be an attribute or property rather '
                'than a method. Ignoring this is a security issue as anonymous '
                'users will be treated as authenticated!' % BadUser,
                obj=BadUser,
                id='auth.C010',
            ),
        ]) 
Example #14
Source File: models.py    From elasticsearch-django with MIT License 4 votes vote down vote up
def execute_search(
    search: Search,
    search_terms: str = "",
    user: Optional[AbstractBaseUser] = None,
    reference: Optional[str] = "",
    save: bool = True,
    query_type: str = SearchQuery.QUERY_TYPE_SEARCH,
) -> SearchQuery:
    """
    Create a new SearchQuery instance and execute a search against ES.

    Args:
        search: elasticsearch.search.Search object, that internally contains
            the connection and query; this is the query that is executed. All
            we are doing is logging the input and parsing the output.
        search_terms: raw end user search terms input - what they typed into the search
            box.
        user: Django User object, the person making the query - used for logging
            purposes. Can be null.
        reference: string, can be anything you like, used for identification,
            grouping purposes.
        save: bool, if True then save the new object immediately, can be
            overridden to False to prevent logging absolutely everything.
            Defaults to True
        query_type: string, used to determine whether to run a search query or
            a count query (returns hit count, but no results).

    """
    start = time.time()
    if query_type == SearchQuery.QUERY_TYPE_SEARCH:
        response = search.execute()
        hits = [h.meta.to_dict() for h in response.hits]
        total_hits = response.hits.total
    elif query_type == SearchQuery.QUERY_TYPE_COUNT:
        response = total_hits = search.count()
        hits = []
    else:
        raise ValueError(f"Invalid SearchQuery.query_type value: '{query_type}'")
    duration = time.time() - start
    search_query = SearchQuery(
        user=user,
        search_terms=search_terms,
        index=", ".join(search._index or ["_all"])[:100],  # field length restriction
        query=search.to_dict(),
        query_type=query_type,
        hits=hits,
        total_hits=total_hits,
        reference=reference or "",
        executed_at=tz_now(),
        duration=duration,
    )
    search_query.response = response
    return search_query.save() if save else search_query