licht-auth 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
LichtAuth/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """
2
+ LichtAuth - autenticação Keycloak multi-tenant para Django + DRF.
3
+
4
+ Adicione "LichtAuth" ao INSTALLED_APPS e siga a documentação no README.
5
+ """
6
+ default_app_config = "LichtAuth.apps.LichtAuthConfig"
7
+
8
+ __version__ = "0.1.0"
LichtAuth/apps.py ADDED
@@ -0,0 +1,8 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class LichtAuthConfig(AppConfig):
5
+ default_auto_field = "django.db.models.BigAutoField"
6
+ name = "LichtAuth"
7
+ verbose_name = "Licht Auth"
8
+ default = True
@@ -0,0 +1,16 @@
1
+ from LichtAuth.conf import licht_settings
2
+
3
+ AUTH_CLASSES = {
4
+ "keycloak": "LichtAuth.auth.keycloak_auth.KeycloakAuthentication",
5
+ "fake": "LichtAuth.auth.fake_auth.FakeAuthentication",
6
+ }
7
+
8
+
9
+ def get_authentication_backend() -> str:
10
+ """Retorna o caminho importável da classe de autenticação ativa.
11
+
12
+ O usuário pode definir ``AUTH_BACKEND`` como "keycloak" ou "fake", ou
13
+ apontar diretamente um caminho importável próprio.
14
+ """
15
+ backend = licht_settings.AUTH_BACKEND
16
+ return AUTH_CLASSES.get(backend, backend)
LichtAuth/auth/base.py ADDED
@@ -0,0 +1,13 @@
1
+ """
2
+ Backward-compat alias.
3
+
4
+ ``LichtAuthentication`` foi renomeado para ``KeycloakAuthentication``;
5
+ mantemos o nome antigo apontando para a nova classe para não quebrar
6
+ projetos que já importavam ``LichtAuth.auth.base.LichtAuthentication``.
7
+ """
8
+ from LichtAuth.auth.keycloak_auth import (
9
+ KeycloakAuthentication as LichtAuthentication,
10
+ )
11
+ from LichtAuth.auth.keycloak_auth import get_or_create_user
12
+
13
+ __all__ = ["LichtAuthentication", "get_or_create_user"]
@@ -0,0 +1,145 @@
1
+ """
2
+ Cliente do serviço de autenticação (Keycloak) com cache Redis opcional.
3
+
4
+ Fluxo de ``validate(token)``:
5
+ 1. Se ``REDIS_ENABLED``: procura o resultado no cache (chave = hash do token).
6
+ 2. Em cache miss: valida o token no Keycloak (userinfo endpoint).
7
+ 3. Se possível, grava o resultado no cache com TTL.
8
+
9
+ Falhas de Redis são tratadas como degradação graciosa: a chamada segue
10
+ direto ao Keycloak, sem quebrar a requisição.
11
+ """
12
+ import hashlib
13
+ import json
14
+ import logging
15
+ from typing import Optional
16
+
17
+ from pydantic import BaseModel, UUID4
18
+ from uuid import UUID as _UUID
19
+
20
+ from LichtAuth.conf import licht_settings, get_redis_config
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ try:
25
+ import redis
26
+ except ImportError: # redis é dependência opcional do pacote
27
+ redis = None
28
+
29
+ try:
30
+ import requests
31
+ except ImportError: # pragma: no cover
32
+ requests = None
33
+
34
+
35
+ class AuthData(BaseModel):
36
+ email: str
37
+ keycloak_id: _UUID
38
+ name: str
39
+
40
+
41
+ class TokenInvalid(Exception):
42
+ """Token rejeitado pelo serviço de autenticação."""
43
+
44
+
45
+ def _get_redis_client():
46
+ if not licht_settings.REDIS_ENABLED or redis is None:
47
+ return None
48
+ return redis.Redis(**get_redis_config())
49
+
50
+
51
+ def _cache_key(token: str) -> str:
52
+ """Gera a chave de cache a partir do hash do token."""
53
+ token_hash = hashlib.sha256(token.encode()).hexdigest()
54
+ return f"{licht_settings.AUTH_CACHE_PREFIX}{token_hash}"
55
+
56
+
57
+ class KeycloakClient:
58
+ """Valida tokens Bearer via userinfo do Keycloak.
59
+
60
+ Endpoint: ``GET {KEYCLOAK_URL}/realms/{REALM}/protocol/openid-connect/userinfo``
61
+ com ``Authorization: Bearer <token>``. Não exige client secret.
62
+ """
63
+
64
+ def __init__(self, timeout: Optional[float] = None):
65
+ self.timeout = timeout or float(licht_settings.KEYCLOAK_TIMEOUT)
66
+
67
+ @property
68
+ def userinfo_url(self) -> str:
69
+ base = licht_settings.KEYCLOAK_URL.rstrip("/")
70
+ realm = licht_settings.KEYCLOAK_REALM
71
+ return f"{base}/realms/{realm}/protocol/openid-connect/userinfo"
72
+
73
+ def fetch(self, token: str) -> AuthData:
74
+ """Consulta o userinfo do Keycloak e devolve ``AuthData``.
75
+
76
+ Levanta ``TokenInvalid`` quando o token é rejeitado.
77
+ """
78
+ response = requests.get(
79
+ self.userinfo_url,
80
+ headers={"Authorization": f"Bearer {token}"},
81
+ timeout=self.timeout,
82
+ )
83
+ if response.status_code in (401, 403):
84
+ raise TokenInvalid("Token rejeitado pelo Keycloak")
85
+ if response.status_code >= 400:
86
+ raise TokenInvalid(
87
+ f"Erro ao validar token no Keycloak: {response.status_code}"
88
+ )
89
+
90
+ payload = response.json()
91
+ try:
92
+ return AuthData(
93
+ email=payload["email"],
94
+ keycloak_id=payload["sub"],
95
+ name=payload.get("name") or payload.get("preferred_username"),
96
+ )
97
+ except (KeyError, ValueError) as exc:
98
+ raise TokenInvalid(f"Payload do Keycloak inválido: {exc}") from exc
99
+
100
+
101
+ class AuthServiceClient:
102
+ """Fachada: valida token com cache Redis quando habilitado."""
103
+
104
+ def __init__(self, backend: Optional[KeycloakClient] = None):
105
+ self.backend = backend or KeycloakClient()
106
+
107
+ def validate(self, token: str) -> AuthData:
108
+ cached = self._read_cache(token)
109
+ if cached is not None:
110
+ return cached
111
+
112
+ auth_data = self.backend.fetch(token)
113
+ self._write_cache(token, auth_data)
114
+ return auth_data
115
+
116
+ # ------------------------------------------------------------------
117
+ # Cache Redis (graceful degradation)
118
+ # ------------------------------------------------------------------
119
+ def _read_cache(self, token: str) -> Optional[AuthData]:
120
+ try:
121
+ r = _get_redis_client()
122
+ if r is None:
123
+ return None
124
+ cached = r.get(_cache_key(token))
125
+ if cached is not None:
126
+ return AuthData.model_validate_json(cached)
127
+ except Exception:
128
+ logger.warning(
129
+ "Redis indisponível para leitura do cache de autenticação, "
130
+ "chamando Keycloak"
131
+ )
132
+ return None
133
+
134
+ def _write_cache(self, token: str, auth_data: AuthData) -> None:
135
+ try:
136
+ r = _get_redis_client()
137
+ if r is None:
138
+ return
139
+ r.setex(
140
+ _cache_key(token),
141
+ int(licht_settings.AUTH_CACHE_TTL),
142
+ auth_data.model_dump_json(),
143
+ )
144
+ except Exception:
145
+ logger.warning("Falha ao gravar cache de autenticação no Redis")
@@ -0,0 +1,127 @@
1
+ """
2
+ Backend de autenticação **fake** — para testes internos e desenvolvimento.
3
+
4
+ Autentica requisições ``Authorization: Bearer <token>`` sem nenhum acesso ao
5
+ Keycloak. Os usuários são definidos na configuração:
6
+
7
+ LICHT_AUTH = {
8
+ "AUTH_BACKEND": "fake",
9
+ "FAKE_USERS": {
10
+ "admin-token": {
11
+ "email": "admin@tenant.com",
12
+ "name": "Admin",
13
+ "keycloak_id": "c0ffee00-0000-4000-8000-000000000001",
14
+ },
15
+ },
16
+ "FAKE_STRICT": False, # se False, "dev" autentica dev@local sempre
17
+ }
18
+
19
+ O comportamento é propositalmente idêntico ao backend Keycloak visto as views:
20
+ ``request.user``, ``request.auth_data`` etc. são populados da mesma forma, e
21
+ o upsert de ``LichtUser`` acontece no banco da aplicação. O que muda é apenas
22
+ a origem da validação (dicionário em memória vs Keycloak).
23
+
24
+ Nota: como os tokens fake não passam pelo Redis (não há serviço externo),
25
+ o pacote não precisa de cache aqui — as validações são O(1) em memória.
26
+ """
27
+ import logging
28
+ import uuid
29
+ from typing import Dict, Optional
30
+
31
+ from rest_framework.authentication import BaseAuthentication
32
+ from rest_framework.exceptions import AuthenticationFailed
33
+
34
+ from LichtAuth.conf import licht_settings
35
+ from LichtAuth.models import LichtUser
36
+ from LichtAuth.auth.client import AuthData
37
+ from LichtAuth.auth.keycloak_auth import (
38
+ KeycloakAuthentication,
39
+ get_or_create_user,
40
+ )
41
+
42
+ logger = logging.getLogger(__name__)
43
+
44
+ FAKE_FALLBACK_TOKEN = "dev"
45
+ FAKE_FALLBACK_EMAIL = "dev@local"
46
+
47
+
48
+ def make_user(
49
+ email: str,
50
+ name: Optional[str] = None,
51
+ keycloak_id: Optional[str] = None,
52
+ ) -> LichtUser:
53
+ """Cria (ou recupera) um ``LichtUser`` direto no banco, sem Keycloak.
54
+
55
+ Útil em fixtures e seeds de teste.
56
+ """
57
+ return LichtUser.objects.get_or_create(
58
+ keycloak_id=keycloak_id or uuid.uuid4(),
59
+ defaults={"email": email, "name": name},
60
+ )[0]
61
+
62
+
63
+ def fake_auth_data(token: str) -> AuthData:
64
+ """Resolve o token fake contra ``FAKE_USERS`` e devolve ``AuthData``."""
65
+ fake_users: Dict[str, dict] = licht_settings.FAKE_USERS or {}
66
+ entry = fake_users.get(token)
67
+
68
+ if entry is None and not licht_settings.FAKE_STRICT and token == FAKE_FALLBACK_TOKEN:
69
+ entry = {
70
+ "email": FAKE_FALLBACK_EMAIL,
71
+ "name": "Dev User",
72
+ "keycloak_id": str(uuid.uuid5(uuid.NAMESPACE_DNS, FAKE_FALLBACK_EMAIL)),
73
+ }
74
+
75
+ if entry is None:
76
+ raise TokenFakeInvalid()
77
+
78
+ try:
79
+ keycloak_id = str(entry["keycloak_id"])
80
+ # garante UUID válido na saída
81
+ return AuthData(
82
+ email=entry["email"],
83
+ keycloak_id=keycloak_id,
84
+ name=entry.get("name") or entry["email"],
85
+ )
86
+ except KeyError as exc:
87
+ raise TokenFakeInvalid(f"FAKE_USERS[{token!r}] incompleto: {exc}") from exc
88
+
89
+
90
+ class TokenFakeInvalid(AuthenticationFailed):
91
+ """AuthenticationFailed com detail do token fake (DRF usa 401)."""
92
+
93
+ def __init__(self, message: str = "Token fake inválido"):
94
+ super().__init__(detail=message)
95
+
96
+
97
+ class FakeAuthentication(KeycloakAuthentication):
98
+ """Autentica via ``Authorization: Bearer <token>`` contra FAKE_USERS."""
99
+
100
+ def __init__(self):
101
+ # pula __init__ da superclasse, que cria o cliente Keycloak
102
+ pass
103
+
104
+ def validate_token(self, token: str) -> AuthData:
105
+ return fake_auth_data(token)
106
+
107
+ def authenticate(self, request):
108
+ auth_header = request.headers.get("Authorization")
109
+ if not auth_header:
110
+ return None
111
+
112
+ parts = auth_header.split(" ")
113
+ if len(parts) != 2 or parts[0].lower() != "bearer":
114
+ raise AuthenticationFailed("Formato de token inválido")
115
+ token = parts[1]
116
+
117
+ try:
118
+ me = self.validate_token(token)
119
+ except TokenFakeInvalid as exc:
120
+ raise AuthenticationFailed(str(exc.detail)) from exc
121
+
122
+ user = get_or_create_user(me.name, me.email, str(me.keycloak_id))
123
+ if not user.is_active:
124
+ raise AuthenticationFailed("Usuário inativo")
125
+
126
+ self.inject_auth_data(request, me, token)
127
+ return (user, token)
@@ -0,0 +1,105 @@
1
+ """
2
+ Backend de autenticação DRF que valida tokens Bearer no Keycloak.
3
+
4
+ Injeta na requisição:
5
+ - ``request.user`` — instância de ``LichtUser`` (upsert por ``keycloak_id``);
6
+ - ``request.auth_data`` — dados validados (dict);
7
+ - ``request._request.auth_data`` — no ``HttpRequest`` subjacente, para
8
+ middlewares Django clássicos.
9
+ """
10
+ import logging
11
+
12
+ from rest_framework.authentication import BaseAuthentication
13
+ from rest_framework.exceptions import AuthenticationFailed
14
+
15
+ from LichtAuth.models import LichtUser
16
+ from LichtAuth.auth.client import AuthServiceClient, AuthData, TokenInvalid
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ def get_or_create_user(name: str, email: str, keycloak_id: str) -> LichtUser:
22
+ """Upsert de usuário local a partir dos dados do Keycloak.
23
+
24
+ Resolve o registro por **e-mail OU keycloak_id** — ambos são unique no
25
+ modelo, e podem divergir quando um usuário foi pré-cadastrado (por
26
+ exemplo, adicionado manualmente como membro de tenant) com um
27
+ ``keycloak_id`` provisório ou inválido. Casos cobertos:
28
+
29
+ - match por ``keycloak_id``: atualiza e-mail/nome se necessário;
30
+ - match por ``email`` apenas: corrige o ``keycloak_id``;
31
+ - sem match: cria o registro.
32
+ """
33
+ from django.db import transaction
34
+
35
+ with transaction.atomic():
36
+ user = (
37
+ LichtUser.objects.select_for_update()
38
+ .filter(keycloak_id=keycloak_id)
39
+ .first()
40
+ )
41
+ if user is None:
42
+ user = (
43
+ LichtUser.objects.select_for_update()
44
+ .filter(email=email)
45
+ .first()
46
+ )
47
+ if user is not None:
48
+ logger.info(
49
+ "LichtUser '%s' reconciliado por e-mail: "
50
+ "keycloak_id %s -> %s",
51
+ email, user.keycloak_id, keycloak_id,
52
+ )
53
+
54
+ if user is not None:
55
+ if str(user.keycloak_id) != str(keycloak_id):
56
+ user.keycloak_id = keycloak_id
57
+ if email and user.email != email:
58
+ user.email = email
59
+ if name and user.name != name:
60
+ user.name = name
61
+ user.save()
62
+ return user
63
+
64
+ return LichtUser.objects.create(
65
+ keycloak_id=keycloak_id, email=email, name=name or None
66
+ )
67
+
68
+
69
+ class KeycloakAuthentication(BaseAuthentication):
70
+ """Autentica via ``Authorization: Bearer <token>`` contra o Keycloak."""
71
+
72
+ def authenticate(self, request):
73
+ auth_header = request.headers.get("Authorization")
74
+ if not auth_header:
75
+ return None
76
+
77
+ parts = auth_header.split(" ")
78
+ if len(parts) != 2 or parts[0].lower() != "bearer":
79
+ raise AuthenticationFailed("Formato de token inválido")
80
+ token = parts[1]
81
+
82
+ try:
83
+ me: AuthData = AuthServiceClient().validate(token)
84
+ except TokenInvalid as exc:
85
+ raise AuthenticationFailed(str(exc)) from exc
86
+
87
+ user = get_or_create_user(me.name, me.email, str(me.keycloak_id))
88
+
89
+ self.inject_auth_data(request, me, token)
90
+ return (user, token)
91
+
92
+ @staticmethod
93
+ def inject_auth_data(request, me: AuthData, token: str) -> None:
94
+ """Anexa dados de autenticação ao request DRF e ao HttpRequest."""
95
+ auth_data = me.model_dump(mode="json")
96
+ request.auth_data = auth_data
97
+ # Propaga para o HttpRequest subjacente para que middlewares
98
+ # Django (ex: OTelEnrichMiddleware) também tenham acesso
99
+ if hasattr(request, "_request"):
100
+ request._request.auth_data = auth_data
101
+
102
+ def authenticate_header(self, request):
103
+ # DRF só emite 401 (e WWW-Authenticate) quando o backend define isso;
104
+ # sem isso, AuthenticationFailed vira 403.
105
+ return 'Bearer realm="licht"'
LichtAuth/conf.py ADDED
@@ -0,0 +1,115 @@
1
+ """
2
+ Centralização das configurações do pacote.
3
+
4
+ Todas as configurações podem ser definidas pelo usuário em um dicionário
5
+ ``LICHT_AUTH`` no ``settings.py`` do projeto. Exemplo:
6
+
7
+ LICHT_AUTH = {
8
+ "KEYCLOAK_URL": "https://keycloak.example.com",
9
+ "KEYCLOAK_REALM": "myrealm",
10
+ "AUTH_CACHE_TTL": 60,
11
+ "AUTH_BACKEND": "fake", # "keycloak" (default) | "fake"
12
+ "REDIS_ENABLED": True,
13
+ "TELEMETRY_EXTRA_ATTRIBUTES": "myapp.telemetry.extra_attrs",
14
+ ...
15
+ }
16
+
17
+ Valores ausentes caem em defaults sensatos (e, quando indicado, em variáveis
18
+ de ambiente), para nunca quebrar o import do settings do usuário.
19
+ """
20
+ import os
21
+ from django.conf import settings
22
+
23
+
24
+ DEFAULTS = {
25
+ # --- Keycloak ---
26
+ "KEYCLOAK_URL": None,
27
+ "KEYCLOAK_REALM": None,
28
+ "KEYCLOAK_CLIENT_ID": None,
29
+ # Timeout (segundos) das chamadas HTTP ao Keycloak
30
+ "KEYCLOAK_TIMEOUT": 5,
31
+
32
+ # --- Backend de autenticação ---
33
+ # "keycloak": valida tokens no serviço real.
34
+ # "fake": aceita tokens simples sem Keycloak (uso em testes/dev).
35
+ "AUTH_BACKEND": "keycloak",
36
+ # Usuários fake: {"<token>": {"email": ..., "name": ..., "keycloak_id": ...}}
37
+ "FAKE_USERS": {},
38
+ # Se True, quando nenhum token fake casar, o 401 é levantado.
39
+ "FAKE_STRICT": True,
40
+
41
+ # --- Cache (Redis) ---
42
+ "REDIS_ENABLED": True,
43
+ "REDIS_HOST": "localhost",
44
+ "REDIS_PORT": 6379,
45
+ "REDIS_DB": 0,
46
+ "REDIS_PASSWORD": None,
47
+ "AUTH_CACHE_TTL": 30,
48
+ # Prefixo das chaves de cache no Redis
49
+ "AUTH_CACHE_PREFIX": "lichtauth:auth:data:",
50
+
51
+ # --- Telemetria ---
52
+ # Nome legível do tracer usado pelo OTelEnrichMiddleware
53
+ "OTEL_TRACER_NAME": "licht",
54
+ # Caminho importável (dot path) para função/callable que devolve
55
+ # atributos extras para os spans. Assinatura aceita:
56
+ # def extra(request, response, span_context: dict) -> dict
57
+ # ou simplesmente extra(request, response) -> dict.
58
+ "TELEMETRY_EXTRA_ATTRIBUTES": None,
59
+ # Atributos padrão para desativar (ex.: ["licht.client_ip"])
60
+ "TELEMETRY_DISABLED_ATTRIBUTES": [],
61
+ }
62
+
63
+
64
+ class LichtSettings:
65
+ """Proxy lazy sobre as settings - lê o dicionário ``LICHT_AUTH``."""
66
+
67
+ @property
68
+ def raw(self) -> dict:
69
+ return getattr(settings, "LICHT_AUTH", {}) or {}
70
+
71
+ def get(self, key: str, default=None):
72
+ # Prioridade: settings.DICIONÁRIO > variável de ambiente > default
73
+ if self.raw.get(key) is not None:
74
+ return self.raw[key]
75
+
76
+ env_key = f"LICHT_AUTH_{key}"
77
+ env_value = os.getenv(env_key)
78
+ if env_value is not None:
79
+ return _coerce(env_value)
80
+
81
+ if key in DEFAULTS:
82
+ return DEFAULTS[key]
83
+
84
+ return default
85
+
86
+ def __getattr__(self, key: str):
87
+ if key.startswith("_"):
88
+ raise AttributeError(key)
89
+ return self.get(key)
90
+
91
+
92
+ def _coerce(value: str):
93
+ """Converte strings de env em bool/int quando fizer sentido."""
94
+ lowered = value.strip().lower()
95
+ if lowered in ("true", "1", "yes", "y", "t"):
96
+ return True
97
+ if lowered in ("false", "0", "no", "n", "f"):
98
+ return False
99
+ if value.lstrip("-").isdigit():
100
+ return int(value)
101
+ return value
102
+
103
+
104
+ licht_settings = LichtSettings()
105
+
106
+
107
+ def get_redis_config() -> dict:
108
+ """Monta os parâmetros do cliente Redis de cache de autenticação."""
109
+ return {
110
+ "host": licht_settings.get("REDIS_HOST", "localhost"),
111
+ "port": int(licht_settings.get("REDIS_PORT", 6379)),
112
+ "db": int(licht_settings.get("REDIS_DB", 0)),
113
+ "password": licht_settings.get("REDIS_PASSWORD"),
114
+ "decode_responses": True,
115
+ }
File without changes
File without changes
@@ -0,0 +1,119 @@
1
+ """
2
+ Criação de tenants via linha de comando, à la ``createsuperuser``::
3
+
4
+ python manage.py createtenant --slug meu-projeto --expire-date 2030-12-31 \\
5
+ --description "Tenant do projeto X" \\
6
+ --admin-email admin@exemplo.com --admin-name "Admin X"
7
+
8
+ Se ``--admin-email`` for informado, o usuário é criado (ou recuperado por
9
+ keycloak_id/email) e vinculado como admin do novo tenant.
10
+ """
11
+ import uuid
12
+ from datetime import date
13
+
14
+ from django.core.management.base import BaseCommand, CommandError
15
+
16
+ from LichtAuth.models import LichtUser, Tenant, TenantUser, validate_slug
17
+
18
+
19
+ class Command(BaseCommand):
20
+ help = "Cria um tenant e, opcionalmente, vincula um usuário admin."
21
+
22
+ def add_arguments(self, parser):
23
+ parser.add_argument(
24
+ "--slug", required=True, help="Slug único do tenant (30 chars)."
25
+ )
26
+ parser.add_argument(
27
+ "--expire-date",
28
+ required=True,
29
+ help="Data de expiração, formato YYYY-MM-DD.",
30
+ )
31
+ parser.add_argument(
32
+ "--description", default=None, help="Descrição livre do tenant."
33
+ )
34
+ parser.add_argument(
35
+ "--admin-email", default=None, help="Email do admin inicial."
36
+ )
37
+ parser.add_argument(
38
+ "--admin-name", default=None, help="Nome do admin inicial."
39
+ )
40
+ parser.add_argument(
41
+ "--admin-keycloak-id",
42
+ default=None,
43
+ help="Keycloak ID do admin (gerado se ausente).",
44
+ )
45
+ parser.add_argument(
46
+ "--inactive", action="store_true", help="Cria o tenant inativo."
47
+ )
48
+
49
+ def handle(self, *args, **options):
50
+ slug = options["slug"]
51
+ try:
52
+ validate_slug(slug)
53
+ except Exception as exc:
54
+ raise CommandError(f"Slug inválido: {exc}")
55
+
56
+ try:
57
+ expire_date = date.fromisoformat(options["expire_date"])
58
+ except ValueError:
59
+ raise CommandError(
60
+ "--expire-date inválida. Use o formato YYYY-MM-DD."
61
+ )
62
+
63
+ if Tenant.objects.filter(slug=slug).exists():
64
+ raise CommandError(f"Tenant com slug '{slug}' já existe.")
65
+
66
+ admin_user = None
67
+ if options["admin_email"]:
68
+ admin_user = self._get_or_create_admin(options)
69
+
70
+ tenant = Tenant.objects.create(
71
+ slug=slug,
72
+ description=options["description"],
73
+ active=not options["inactive"],
74
+ expire_date=expire_date,
75
+ )
76
+
77
+ if admin_user is not None:
78
+ TenantUser.objects.create(
79
+ tenant=tenant, user=admin_user, admin=True
80
+ )
81
+
82
+ self.stdout.write(
83
+ self.style.SUCCESS(
84
+ f"Tenant '{tenant.slug}' criado com sucesso "
85
+ f"(id={tenant.id}, expire_date={tenant.expire_date})"
86
+ )
87
+ )
88
+ if admin_user is not None:
89
+ self.stdout.write(
90
+ self.style.SUCCESS(
91
+ f"Admin '{admin_user.email}' vinculado ao tenant "
92
+ f"(keycloak_id={admin_user.keycloak_id})"
93
+ )
94
+ )
95
+ self.stdout.write(
96
+ f"Use no header das requisições: X-Tenant-ID: {tenant.id}"
97
+ )
98
+
99
+ def _get_or_create_admin(self, options) -> LichtUser:
100
+ email = options["admin_email"]
101
+ keycloak_id = options["admin_keycloak_id"] or str(uuid.uuid4())
102
+
103
+ user = LichtUser.objects.filter(email=email).first()
104
+ if user is None:
105
+ user = LichtUser.objects.filter(keycloak_id=keycloak_id).first()
106
+ if user is None:
107
+ user = LichtUser.objects.create(
108
+ id=uuid.uuid4(),
109
+ email=email,
110
+ name=options["admin_name"],
111
+ keycloak_id=keycloak_id,
112
+ )
113
+ # senha inutilizável
114
+ user.set_unusable_password()
115
+ user.save(update_fields=["password"])
116
+ self.stdout.write(f"Usuário '{email}' criado.")
117
+ else:
118
+ self.stdout.write(f"Usuário '{email}' recuperado do banco.")
119
+ return user
@@ -0,0 +1,3 @@
1
+ from LichtAuth.middleware.tenant import TenantMiddleware
2
+
3
+ __all__ = ["TenantMiddleware"]