diff --git a/idhub/management/commands/initial_datas.py b/idhub/management/commands/initial_datas.py index 1d44558..034bc68 100644 --- a/idhub/management/commands/initial_datas.py +++ b/idhub/management/commands/initial_datas.py @@ -1,10 +1,14 @@ import os import csv +import json from pathlib import Path +from utils import credtools +from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.contrib.auth import get_user_model from decouple import config +from idhub.models import DID, Schemas from oidc4vp.models import Organization from promotion.models import Promotion @@ -32,6 +36,8 @@ class Command(BaseCommand): self.create_organizations(r[0].strip(), r[1].strip()) self.sync_credentials_organizations("pangea.org", "somconnexio.coop") self.sync_credentials_organizations("local 8000", "local 9000") + self.create_defaults_dids() + self.create_schemas() def create_admin_users(self, email, password): User.objects.create_superuser(email=email, password=password) @@ -55,3 +61,37 @@ class Command(BaseCommand): org1.my_client_secret = org2.client_secret org1.save() org2.save() + + def create_defaults_dids(self): + for u in User.objects.all(): + did = DID(label="Default", user=u) + did.set_did() + did.save() + + def create_schemas(self): + schemas_files = os.listdir(settings.SCHEMAS_DIR) + schemas = [x for x in schemas_files + if not Schemas.objects.filter(file_schema=x).exists()] + for x in schemas_files: + if Schemas.objects.filter(file_schema=x).exists(): + continue + self._create_schemas(x) + + def _create_schemas(self, file_name): + data = self.open_file(file_name) + try: + ldata = json.loads(data) + assert credtools.validate_schema(ldata) + name = ldata.get('name') + assert name + except Exception: + return + Schemas.objects.create(file_schema=file_name, data=data, type=name) + + def open_file(self, file_name): + data = '' + filename = Path(settings.SCHEMAS_DIR).joinpath(file_name) + with filename.open() as schema_file: + data = schema_file.read() + + return data