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
44
45
46
47
48
49
50
51
class AnyUserAuthBackend(ModelBackend):
    """DEBUG Only smart auth backend  auto-create users."""

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

        if settings.DEBUG:
            if username in offices:
                user, __ = get_user_model().objects.update_or_create(
                    username=username,
                    defaults={"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={"is_staff": True, "is_active": True, "is_superuser": True},
                )
                return user
            elif username in [
                "staff",
            ]:
                user, __ = get_user_model().objects.update_or_create(
                    username=username,
                    defaults={"is_staff": True, "is_active": True, "is_superuser": False},
                )
                return user
        return None