Skip to content

Development Helpers and Tools

country_workspace.security.backends.AnyUserAuthBackend

DEBUG Only smart auth backend auto-create users

Source code in src/country_workspace/security/backends.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class AnyUserAuthBackend(ModelBackend):
    """DEBUG Only smart auth backend  auto-create users"""

    def authenticate(
        self,
        request: "Optional[HttpRequest]",
        username: str | None = None,
        password: str | None = None,
        **kwargs: Any,
    ) -> "AbstractBaseUser | None":
        countries = Office.objects.values_list("slug", flat=True)

        if settings.DEBUG:
            if username in countries:
                user, __ = get_user_model().objects.update_or_create(
                    username=username,
                    defaults=dict(is_staff=True, is_active=True, is_superuser=False),
                )
                office = Office.objects.get(slug=username)
                g = Group.objects.get(name=settings.ANALYST_GROUP_NAME)
                UserRole.objects.get_or_create(user=user, country_office=office, group=g)
                return user
            elif username in ["admin", "superuser", "administrator", "sax"]:
                user, __ = get_user_model().objects.update_or_create(
                    username=username,
                    defaults=dict(is_staff=True, is_active=True, is_superuser=True),
                )
                return user
        return None