diff --git a/apiserver/plane/license/api/views/instance.py b/apiserver/plane/license/api/views/instance.py index b43586509..309b2b9da 100644 --- a/apiserver/plane/license/api/views/instance.py +++ b/apiserver/plane/license/api/views/instance.py @@ -1,10 +1,14 @@ +# Python imports +import json +import os +import requests + # Django imports from django.utils import timezone # Third party imports from rest_framework import status from rest_framework.response import Response -from rest_framework.permissions import AllowAny # Module imports from plane.api.views import BaseAPIView @@ -23,16 +27,85 @@ from plane.db.models import User class InstanceEndpoint(BaseAPIView): def get_permissions(self): - if self.request.method == "GET": - self.permission_classes = [ - AllowAny, - ] - else: + if self.request.method in ["POST", "PATCH"]: self.permission_classes = [ InstanceOwnerPermission, ] + else: + self.permission_classes = [ + InstanceAdminPermission, + ] return super(InstanceEndpoint, self).get_permissions() + def post(self, request): + # Check if the instance is registered + instance = Instance.objects.first() + + # If instance is None then register this instance + if instance is None: + with open("package.json", "r") as file: + # Load JSON content from the file + data = json.load(file) + + license_engine_base_url = os.environ.get("LICENSE_ENGINE_BASE_URL") + + if not license_engine_base_url: + raise Response( + {"error": "LICENSE_ENGINE_BASE_URL is required"}, + status=status.HTTP_400_BAD_REQUEST, + ) + + headers = {"Content-Type": "application/json"} + + payload = { + "email": request.user.email, + "version": data.get("version", 0.1), + } + + response = requests.post( + f"{license_engine_base_url}/api/instances", + headers=headers, + data=json.dumps(payload), + ) + + if response.status_code == 201: + data = response.json() + # Create instance + instance = Instance.objects.create( + instance_name="Plane Free", + instance_id=data.get("id"), + license_key=data.get("license_key"), + api_key=data.get("api_key"), + version=data.get("version"), + primary_email=data.get("email"), + primary_owner=request.user, + last_checked_at=timezone.now(), + ) + # Create instance admin + _ = InstanceAdmin.objects.create( + user=request.user, + instance=instance, + role=20, + ) + + return Response( + { + "message": f"Instance succesfully registered with owner: {instance.primary_owner.email}" + }, + status=status.HTTP_201_CREATED, + ) + return Response( + {"error": "Instance could not be registered"}, + status=status.HTTP_400_BAD_REQUEST, + ) + else: + return Response( + { + "message": f"Instance already registered with instance owner: {instance.primary_owner.email}" + }, + status=status.HTTP_200_OK, + ) + def get(self, request): instance = Instance.objects.first() # get the instance