2022-04-20 13:33:41 +02:00
|
|
|
import requests
|
2020-08-14 11:23:55 +02:00
|
|
|
from django.conf import settings
|
|
|
|
from django.db.models import QuerySet
|
2021-04-14 17:45:39 +02:00
|
|
|
from rest_framework import mixins, serializers, viewsets
|
2020-08-14 11:23:55 +02:00
|
|
|
|
2022-04-20 13:33:41 +02:00
|
|
|
from ee.models.license import License, LicenseError
|
2020-08-14 11:23:55 +02:00
|
|
|
|
|
|
|
|
|
|
|
class LicenseSerializer(serializers.ModelSerializer):
|
|
|
|
class Meta:
|
|
|
|
model = License
|
|
|
|
fields = [
|
2021-04-14 17:45:39 +02:00
|
|
|
"id",
|
2020-08-14 11:23:55 +02:00
|
|
|
"key",
|
2021-04-14 17:45:39 +02:00
|
|
|
"plan",
|
2020-08-14 11:23:55 +02:00
|
|
|
"valid_until",
|
2021-04-14 17:45:39 +02:00
|
|
|
"max_users",
|
|
|
|
"created_at",
|
2020-08-14 11:23:55 +02:00
|
|
|
]
|
2021-04-14 17:45:39 +02:00
|
|
|
read_only_fields = ["plan", "valid_until", "max_users"]
|
2020-08-14 11:23:55 +02:00
|
|
|
|
2022-04-20 13:33:41 +02:00
|
|
|
def validate(self, data):
|
|
|
|
validation = requests.post("https://license.posthog.com/licenses/activate", data={"key": data["key"]})
|
|
|
|
resp = validation.json()
|
|
|
|
if not validation.ok:
|
|
|
|
raise LicenseError(resp["code"], resp["detail"])
|
|
|
|
data["valid_until"] = resp["valid_until"]
|
|
|
|
data["plan"] = resp["plan"]
|
|
|
|
data["max_users"] = resp.get("max_users", 0)
|
|
|
|
return data
|
2020-08-14 11:23:55 +02:00
|
|
|
|
2021-04-14 17:45:39 +02:00
|
|
|
|
|
|
|
class LicenseViewSet(
|
|
|
|
mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet,
|
|
|
|
):
|
2020-08-14 11:23:55 +02:00
|
|
|
queryset = License.objects.all()
|
|
|
|
serializer_class = LicenseSerializer
|
|
|
|
|
|
|
|
def get_queryset(self) -> QuerySet:
|
2020-09-28 13:21:03 +02:00
|
|
|
if getattr(settings, "MULTI_TENANCY", False):
|
2020-08-14 11:23:55 +02:00
|
|
|
return License.objects.none()
|
|
|
|
|
|
|
|
return super().get_queryset()
|