IdHub/idhub/models.py

874 lines
27 KiB
Python
Raw Normal View History

2023-10-26 11:33:13 +00:00
import json
import ujson
2023-11-15 10:52:19 +00:00
import pytz
import hashlib
2023-11-14 16:45:08 +00:00
import datetime
from collections import OrderedDict
from django.db import models
2023-11-20 18:18:00 +00:00
from django.conf import settings
2024-06-06 09:40:26 +00:00
from django.urls import reverse
2023-11-15 10:43:13 +00:00
from django.template.loader import get_template
2023-10-16 17:08:18 +00:00
from django.utils.translation import gettext_lazy as _
2024-06-06 09:40:26 +00:00
from pyvckit.did import (
generate_keys,
generate_did,
gen_did_document,
get_signing_key
2023-11-14 17:12:34 +00:00
)
2024-06-06 09:40:26 +00:00
from pyvckit.sign_vc import sign
from pyvckit.verify import verify_vc
2024-02-23 15:50:31 +00:00
from oidc4vp.models import Organization
2023-10-25 15:49:17 +00:00
from idhub_auth.models import User
2023-09-28 09:01:14 +00:00
2023-11-09 16:58:06 +00:00
class Event(models.Model):
class Types(models.IntegerChoices):
EV_USR_REGISTERED = 1, "User registered"
EV_USR_WELCOME = 2, "User welcomed"
EV_DATA_UPDATE_REQUESTED_BY_USER = 3, "Data update requested by user"
EV_DATA_UPDATE_REQUESTED = 4, "Data update requested. Pending approval by administrator"
EV_USR_UPDATED_BY_ADMIN = 5, "User's data updated by admin"
EV_USR_UPDATED = 6, "Your data updated by admin"
EV_USR_DELETED_BY_ADMIN = 7, "User deactivated by admin"
EV_DID_CREATED_BY_USER = 8, "DID created by user"
EV_DID_CREATED = 9, "DID created"
EV_DID_DELETED = 10, "DID deleted"
EV_CREDENTIAL_DELETED_BY_USER = 11, "Credential deleted by user"
EV_CREDENTIAL_DELETED_BY_ADMIN = 12, "Credential deleted by admin"
EV_CREDENTIAL_DELETED = 13, "Credential deleted"
EV_CREDENTIAL_ISSUED_FOR_USER = 14, "Credential issued for user"
EV_CREDENTIAL_ISSUED = 15, "Credential issued"
EV_CREDENTIAL_PRESENTED_BY_USER = 16, "Credential presented by user"
EV_CREDENTIAL_PRESENTED = 17, "Credential presented"
EV_CREDENTIAL_ENABLED = 18, "Credential enabled"
EV_CREDENTIAL_CAN_BE_REQUESTED = 19, "Credential available"
EV_CREDENTIAL_REVOKED_BY_ADMIN = 20, "Credential revoked by admin"
EV_CREDENTIAL_REVOKED = 21, "Credential revoked"
EV_ROLE_CREATED_BY_ADMIN = 22, "Role created by admin"
EV_ROLE_MODIFIED_BY_ADMIN = 23, "Role modified by admin"
EV_ROLE_DELETED_BY_ADMIN = 24, "Role deleted by admin"
EV_SERVICE_CREATED_BY_ADMIN = 25, "Service created by admin"
EV_SERVICE_MODIFIED_BY_ADMIN = 26, "Service modified by admin"
EV_SERVICE_DELETED_BY_ADMIN = 27, "Service deleted by admin"
EV_ORG_DID_CREATED_BY_ADMIN = 28, "Organisational DID created by admin"
EV_ORG_DID_DELETED_BY_ADMIN = 29, "Organisational DID deleted by admin"
EV_USR_DEACTIVATED_BY_ADMIN = 30, "User deactivated"
EV_USR_ACTIVATED_BY_ADMIN = 31, "User activated"
EV_USR_SEND_VP = 32, "User send Verificable Presentation"
2024-02-27 18:33:40 +00:00
EV_USR_SEND_CREDENTIAL = 33, "User send credential"
2023-09-28 09:01:14 +00:00
2023-12-14 16:15:22 +00:00
created = models.DateTimeField(_("Date"), auto_now=True)
message = models.CharField(_("Description"), max_length=350)
2023-11-09 16:58:06 +00:00
type = models.PositiveSmallIntegerField(
2023-12-14 16:15:22 +00:00
_("Event"),
2023-11-09 16:58:06 +00:00
choices=Types.choices,
)
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='events',
null=True,
)
2023-09-28 09:01:14 +00:00
def get_type_name(self):
2023-11-09 16:58:06 +00:00
return self.Types(self.type).label
@classmethod
def set_EV_USR_REGISTERED(cls, user):
2023-11-10 15:22:41 +00:00
msg = _("The user {username} was registered: name: {first_name}, last name: {last_name}").format(
username=user.username,
first_name=user.first_name,
last_name=user.last_name
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_USR_REGISTERED,
message=msg
)
@classmethod
def set_EV_USR_WELCOME(cls, user):
2023-11-10 15:22:41 +00:00
msg = _("Welcome. You has been registered: name: {first_name}, last name: {last_name}").format(
first_name=user.first_name,
last_name=user.last_name
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_USR_WELCOME,
message=msg,
user=user
)
# Is required?
@classmethod
def set_EV_DATA_UPDATE_REQUESTED_BY_USER(cls, user):
2023-11-10 15:22:41 +00:00
msg = _("The user '{username}' has request the update of the following information: ")
msg += "['field1':'value1', 'field2':'value2'>,...]"
msg = msg.format(username=user.username)
2023-11-09 16:58:06 +00:00
cls.objects.create(
type=cls.Types.EV_DATA_UPDATE_REQUESTED_BY_USER,
message=msg,
)
# Is required?
@classmethod
def set_EV_DATA_UPDATE_REQUESTED(cls, user):
2023-11-10 15:22:41 +00:00
msg = _("You have requested the update of the following information: ")
2023-11-09 16:58:06 +00:00
msg += "['field1':'value1', 'field2':'value2'>,...]"
cls.objects.create(
type=cls.Types.EV_DATA_UPDATE_REQUESTED,
message=msg,
user=user
)
@classmethod
def set_EV_USR_UPDATED_BY_ADMIN(cls, user):
msg = "The admin has updated the following user 's information: "
2023-11-10 15:22:41 +00:00
msg += "name: {first_name}, last name: {last_name}"
msg = _(msg).format(
first_name=user.first_name,
last_name=user.last_name
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_USR_UPDATED_BY_ADMIN,
message=msg
)
@classmethod
def set_EV_USR_UPDATED(cls, user):
msg = "The admin has updated your personal information: "
2023-11-10 15:22:41 +00:00
msg += "name: {first_name}, last name: {last_name}"
msg = _(msg).format(
first_name=user.first_name,
last_name=user.last_name
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_USR_UPDATED,
message=msg,
user=user
)
@classmethod
def set_EV_USR_DELETED_BY_ADMIN(cls, user):
2023-11-10 15:22:41 +00:00
msg = _("The admin has deleted the user: username: {username}").format(
username=user.username,
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_USR_DELETED_BY_ADMIN,
message=msg
)
@classmethod
def set_EV_DID_CREATED_BY_USER(cls, did):
2023-11-10 15:22:41 +00:00
msg = _("New DID with DID-ID: '{did}' created by user '{username}'").format(
did=did.did,
username=did.user.username
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_DID_CREATED_BY_USER,
message=msg,
)
@classmethod
def set_EV_DID_CREATED(cls, did):
2023-11-10 15:22:41 +00:00
msg = _("New DID with label: '{label}' and DID-ID: '{did}' was created'").format(
label=did.label,
did=did.did
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_DID_CREATED,
message=msg,
user=did.user
)
@classmethod
def set_EV_DID_DELETED(cls, did):
2023-11-10 15:22:41 +00:00
msg = _("The DID with label '{label}' and DID-ID: '{did}' was deleted from your wallet").format(
label=did.label,
did=did.did
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_DID_DELETED,
message=msg,
user=did.user
)
@classmethod
def set_EV_CREDENTIAL_DELETED_BY_ADMIN(cls, cred):
2023-11-10 15:22:41 +00:00
msg = _("The credential of type '{type}' and ID: '{id}' was deleted").format(
2024-01-24 15:10:10 +00:00
type=cred.type,
2023-11-10 15:22:41 +00:00
id=cred.id,
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_CREDENTIAL_DELETED_BY_ADMIN,
message=msg,
)
@classmethod
def set_EV_CREDENTIAL_DELETED(cls, cred):
2023-11-10 15:22:41 +00:00
msg = _("The credential of type '{type}' and ID: '{id}' was deleted from your wallet").format(
2024-01-24 15:10:10 +00:00
type=cred.type,
2023-11-10 15:22:41 +00:00
id=cred.id
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_CREDENTIAL_DELETED,
message=msg,
user=cred.user
)
@classmethod
def set_EV_CREDENTIAL_ISSUED_FOR_USER(cls, cred):
2023-11-10 15:22:41 +00:00
msg = _("The credential of type '{type}' and ID: '{id}' was issued for user {username}").format(
2024-01-24 15:10:10 +00:00
type=cred.type,
2023-11-10 15:22:41 +00:00
id=cred.id,
username=cred.user.username
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_CREDENTIAL_ISSUED_FOR_USER,
message=msg,
)
@classmethod
def set_EV_CREDENTIAL_ISSUED(cls, cred):
2023-11-10 15:22:41 +00:00
msg = _("The credential of type '{type}' and ID: '{id}' was issued and stored in your wallet").format(
2024-01-24 15:10:10 +00:00
type=cred.type,
2023-11-10 15:22:41 +00:00
id=cred.id
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_CREDENTIAL_ISSUED,
message=msg,
user=cred.user
)
@classmethod
def set_EV_CREDENTIAL_PRESENTED_BY_USER(cls, cred, verifier):
2023-11-10 15:22:41 +00:00
msg = "The credential of type '{type}' and ID: '{id}' "
msg += "was presented by user {username} to verifier '{verifier}"
msg = _(msg).format(
2024-01-24 15:10:10 +00:00
type=cred.type,
2023-11-10 15:22:41 +00:00
id=cred.id,
username=cred.user.username,
verifier=verifier
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_CREDENTIAL_PRESENTED_BY_USER,
message=msg,
)
@classmethod
def set_EV_CREDENTIAL_PRESENTED(cls, cred, verifier):
2023-11-10 15:22:41 +00:00
msg = "The credential of type '{type}' and ID: '{id}' "
msg += "was presented to verifier '{verifier}'"
msg = _(msg).format(
2024-01-24 15:10:10 +00:00
type=cred.type,
2023-11-10 15:22:41 +00:00
id=cred.id,
verifier=verifier
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_CREDENTIAL_PRESENTED,
message=msg,
user=cred.user
)
@classmethod
def set_EV_CREDENTIAL_ENABLED(cls, cred):
2023-11-10 15:22:41 +00:00
msg = _("The credential of type '{type}' was enabled for user {username}").format(
2024-01-24 15:10:10 +00:00
type=cred.type,
2023-11-10 15:22:41 +00:00
username=cred.user.username
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_CREDENTIAL_ENABLED,
message=msg,
)
@classmethod
def set_EV_CREDENTIAL_CAN_BE_REQUESTED(cls, cred):
2023-11-10 15:22:41 +00:00
msg = _("You can request the '{type}' credential").format(
2024-01-24 15:10:10 +00:00
type=cred.type
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_CREDENTIAL_CAN_BE_REQUESTED,
message=msg,
user=cred.user
)
@classmethod
def set_EV_CREDENTIAL_REVOKED_BY_ADMIN(cls, cred):
2023-11-10 15:22:41 +00:00
msg = _("The credential of type '{type}' and ID: '{id}' was revoked for ").format(
2024-01-24 15:10:10 +00:00
type=cred.type,
2023-11-10 15:22:41 +00:00
id=cred.id
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_CREDENTIAL_REVOKED_BY_ADMIN,
message=msg,
)
@classmethod
def set_EV_CREDENTIAL_REVOKED(cls, cred):
2023-11-10 15:22:41 +00:00
msg = _("The credential of type '{type}' and ID: '{id}' was revoked by admin").format(
2024-01-24 15:10:10 +00:00
type=cred.type,
2023-11-10 15:22:41 +00:00
id=cred.id
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_CREDENTIAL_REVOKED,
message=msg,
user=cred.user
)
@classmethod
def set_EV_ROLE_CREATED_BY_ADMIN(cls):
2023-11-10 15:22:41 +00:00
msg = _('A new role was created by admin')
2023-11-09 16:58:06 +00:00
cls.objects.create(
type=cls.Types.EV_ROLE_CREATED_BY_ADMIN,
message=msg,
)
@classmethod
def set_EV_ROLE_MODIFIED_BY_ADMIN(cls):
2023-11-10 15:22:41 +00:00
msg = _('The role was modified by admin')
2023-11-09 16:58:06 +00:00
cls.objects.create(
type=cls.Types.EV_ROLE_MODIFIED_BY_ADMIN,
message=msg,
)
@classmethod
def set_EV_ROLE_DELETED_BY_ADMIN(cls):
2023-11-10 15:22:41 +00:00
msg = _('The role was removed by admin')
2023-11-09 16:58:06 +00:00
cls.objects.create(
type=cls.Types.EV_ROLE_DELETED_BY_ADMIN,
message=msg,
)
@classmethod
def set_EV_SERVICE_CREATED_BY_ADMIN(cls):
2023-11-10 15:22:41 +00:00
msg = _('A new service was created by admin')
2023-11-09 16:58:06 +00:00
cls.objects.create(
type=cls.Types.EV_SERVICE_CREATED_BY_ADMIN,
message=msg,
)
@classmethod
def set_EV_SERVICE_MODIFIED_BY_ADMIN(cls):
2023-11-10 15:22:41 +00:00
msg = _('The service was modified by admin')
2023-11-09 16:58:06 +00:00
cls.objects.create(
type=cls.Types.EV_SERVICE_MODIFIED_BY_ADMIN,
message=msg,
)
@classmethod
def set_EV_SERVICE_DELETED_BY_ADMIN(cls):
2023-11-10 15:22:41 +00:00
msg = _('The service was removed by admin')
2023-11-09 16:58:06 +00:00
cls.objects.create(
type=cls.Types.EV_SERVICE_DELETED_BY_ADMIN,
message=msg,
)
@classmethod
def set_EV_ORG_DID_CREATED_BY_ADMIN(cls, did):
2023-11-10 15:22:41 +00:00
msg = _("New Organisational DID with label: '{label}' and DID-ID: '{did}' was created").format(
label=did.label,
did=did.did
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_ORG_DID_CREATED_BY_ADMIN,
message=msg,
)
@classmethod
def set_EV_ORG_DID_DELETED_BY_ADMIN(cls, did):
2023-11-10 15:22:41 +00:00
msg = _("Organisational DID with label: '{label}' and DID-ID: '{did}' was removed").format(
label=did.label,
did=did.did
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_ORG_DID_DELETED_BY_ADMIN,
message=msg,
)
@classmethod
def set_EV_USR_DEACTIVATED_BY_ADMIN(cls, user):
2023-11-10 15:22:41 +00:00
msg = "The user '{username}' was temporarily deactivated: "
msg += "[name:'{first_name}', last name:'{last_name}']"
msg = _(msg).format(
username=user.username,
first_name=user.first_name,
last_name=user.last_name
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_USR_DEACTIVATED_BY_ADMIN,
message=msg,
)
@classmethod
def set_EV_USR_ACTIVATED_BY_ADMIN(cls, user):
2023-11-10 15:22:41 +00:00
msg = "The user '{username}' was activated: "
msg += "name:'{first_name}', last name:'{last_name}']"
msg = _(msg).format(
username=user.username,
first_name=user.first_name,
last_name=user.last_name
2023-11-09 16:58:06 +00:00
)
cls.objects.create(
type=cls.Types.EV_USR_ACTIVATED_BY_ADMIN,
message=msg,
)
2024-01-21 12:45:34 +00:00
@classmethod
def set_EV_USR_SEND_VP(cls, msg, user):
cls.objects.create(
type=cls.Types.EV_USR_SEND_VP,
message=msg,
user=user
)
2023-11-09 16:58:06 +00:00
2024-02-27 18:33:40 +00:00
@classmethod
def set_EV_USR_SEND_CREDENTIAL(cls, msg):
cls.objects.create(
type=cls.Types.EV_USR_SEND_CREDENTIAL,
message=msg,
)
2023-09-28 09:01:14 +00:00
class DID(models.Model):
2024-01-16 13:00:05 +00:00
class Types(models.IntegerChoices):
2024-02-23 18:17:56 +00:00
WEB = 1, "Web"
KEY = 2, "Key"
2024-01-16 13:00:05 +00:00
type = models.PositiveSmallIntegerField(
_("Type"),
choices=Types.choices,
)
2023-10-26 16:06:52 +00:00
created_at = models.DateTimeField(auto_now=True)
2023-12-14 16:15:22 +00:00
label = models.CharField(_("Label"), max_length=50)
2023-11-14 17:12:34 +00:00
did = models.CharField(max_length=250)
# In JWK format. Must be stored as-is and passed whole to library functions.
# Example key material:
# '{"kty":"OKP","crv":"Ed25519","x":"oB2cPGFx5FX4dtS1Rtep8ac6B__61HAP_RtSzJdPxqs","d":"OJw80T1CtcqV0hUcZdcI-vYNBN1dlubrLaJa0_se_gU"}'
2024-01-10 12:53:43 +00:00
key_material = models.TextField()
eidas1 = models.BooleanField(default=False)
2023-10-16 17:08:18 +00:00
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='dids',
2023-10-26 11:33:13 +00:00
null=True,
2023-10-16 17:08:18 +00:00
)
# JSON-serialized DID document
2024-01-15 09:34:42 +00:00
didweb_document = models.TextField()
2023-09-28 09:01:14 +00:00
2023-10-26 16:09:07 +00:00
@property
def is_organization_did(self):
if not self.user:
return True
return False
2024-02-23 15:50:31 +00:00
def get_key_material(self):
user = self.user or self.get_organization()
return user.decrypt_data(self.key_material)
def set_key_material(self, value):
user = self.user or self.get_organization()
if not user.encrypted_sensitive_data:
user.set_encrypted_sensitive_data()
user.save()
self.key_material = user.encrypt_data(value)
def set_did(self):
2024-06-06 09:40:26 +00:00
new_key_material = generate_keys()
self.set_key_material(new_key_material)
2023-11-14 08:48:36 +00:00
2024-01-16 13:00:05 +00:00
if self.type == self.Types.KEY:
2024-06-06 09:40:26 +00:00
self.did = generate_did(new_key_material)
2024-01-16 13:00:05 +00:00
elif self.type == self.Types.WEB:
2024-06-06 09:40:26 +00:00
url = "https://{}".format(settings.DOMAIN)
path = reverse("idhub:serve_did", args=["a"])
if path:
path = path.split("/a/did.json")[0]
url = "https://{}/{}".format(settings.DOMAIN, path)
self.did = generate_did(new_key_material, url)
key = json.loads(new_key_material)
url, self.didweb_document = gen_did_document(self.did, key)
2023-11-14 08:48:36 +00:00
def get_key(self):
return json.loads(self.key_material)
2024-02-23 15:50:31 +00:00
def get_organization(self):
2024-02-27 08:27:55 +00:00
return Organization.objects.get(main=True)
2024-02-23 15:50:31 +00:00
2023-10-25 15:49:17 +00:00
class Schemas(models.Model):
2023-11-29 16:29:31 +00:00
type = models.CharField(max_length=250)
2024-03-20 10:40:55 +00:00
file_schema = models.CharField(_('Schema'), max_length=250)
2023-10-25 15:49:17 +00:00
data = models.TextField()
2024-03-20 12:02:50 +00:00
created_at = models.DateTimeField(_("Date"), auto_now=True)
2024-03-20 10:40:55 +00:00
_name = models.TextField(_("Name"), null=True, db_column='name')
2024-03-20 12:02:50 +00:00
_description = models.CharField(_("Description"), max_length=250, null=True, db_column='description')
2023-12-19 17:33:09 +00:00
template_description = models.TextField(null=True)
2023-10-25 15:49:17 +00:00
2023-10-26 11:33:13 +00:00
@property
def get_schema(self):
if not self.data:
return {}
return json.loads(self.data)
def _update_and_get_field(self, field_attr, schema_key, is_json=False):
field_value = getattr(self, field_attr)
if not field_value:
field_value = self.get_schema.get(schema_key, [] if is_json else '')
self._update_model_field(field_attr, field_value)
2024-01-22 17:13:06 +00:00
try:
if is_json:
return json.loads(field_value)
2024-01-29 11:05:07 +00:00
except Exception:
pass
2024-01-22 17:13:06 +00:00
return field_value
2023-10-26 11:33:13 +00:00
def _update_model_field(self, field_attr, field_value):
if field_value:
setattr(self, field_attr, field_value)
self.save(update_fields=[field_attr])
2023-10-26 11:33:13 +00:00
@property
def name(self, request=None):
names = self._update_and_get_field('_name', 'name',
is_json=True)
language_code = self._get_language_code(request)
name = self._get_name_by_language(names, language_code)
return name
2024-02-29 12:00:59 +00:00
@property
2024-03-01 08:31:43 +00:00
def has_credentials(self):
2024-02-29 12:00:59 +00:00
return self.vcredentials.filter(
status=VerificableCredential.Status.ISSUED).exists()
def _get_language_code(self, request=None):
language_code = settings.LANGUAGE_CODE
if request:
language_code = request.LANGUAGE_CODE
if self._is_catalan_code(language_code):
2024-03-19 10:00:06 +00:00
language_code = 'ca_ES'
return language_code
def _get_name_by_language(self, names, lang_code):
for name in names:
if name.get('lang') == lang_code:
return name.get('value')
return None
def _is_catalan_code(self, language_code):
2024-03-19 10:00:06 +00:00
return language_code == 'ca'
@name.setter
def name(self, value):
self._name = json.dumps(value)
@property
def description(self):
return self._update_and_get_field('_description', 'description')
@description.setter
def description(self, value):
self._description = value
2023-10-25 15:49:17 +00:00
2024-02-15 17:59:57 +00:00
def get_credential_subject_schema(self):
sc = self.get_data()
properties = sc["allOf"][1]["properties"]["credentialSubject"]["properties"]
required = sc["allOf"][1]["properties"]["credentialSubject"]["required"]
if "id" in required:
required.remove("id")
schema = {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": properties,
"required": required,
"additionalProperties": False
}
return schema
def get_data(self):
return json.loads(self.data)
2023-10-30 12:53:19 +00:00
class VerificableCredential(models.Model):
2023-10-26 11:33:13 +00:00
"""
Definition of Verificable Credentials
"""
class Status(models.IntegerChoices):
2023-10-31 16:07:43 +00:00
ENABLED = 1, _("Enabled")
2023-11-02 13:17:07 +00:00
ISSUED = 2, _("Issued")
REVOKED = 3, _("Revoked")
EXPIRED = 4, _("Expired")
2023-10-26 11:33:13 +00:00
2024-03-20 12:02:50 +00:00
type = models.CharField(_("Type"), max_length=250)
2023-09-28 09:01:14 +00:00
id_string = models.CharField(max_length=250)
verified = models.BooleanField()
2023-10-25 10:18:42 +00:00
created_on = models.DateTimeField(auto_now=True)
2024-03-20 12:02:50 +00:00
issued_on = models.DateTimeField(_("Issued on"), null=True)
2023-10-26 11:33:13 +00:00
data = models.TextField()
2023-11-14 17:50:23 +00:00
csv_data = models.TextField()
hash = models.CharField(max_length=260)
2023-10-26 11:33:13 +00:00
status = models.PositiveSmallIntegerField(
2024-03-20 12:02:50 +00:00
_("Status"),
2023-10-26 11:33:13 +00:00
choices=Status.choices,
2023-10-31 16:07:43 +00:00
default=Status.ENABLED
2023-10-26 11:33:13 +00:00
)
2023-10-16 17:08:18 +00:00
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='vcredentials',
2024-03-20 12:02:50 +00:00
verbose_name=_("User")
2023-10-16 17:08:18 +00:00
)
2023-12-01 18:31:09 +00:00
subject_did = models.ForeignKey(
DID,
on_delete=models.CASCADE,
related_name='subject_credentials',
2023-12-04 08:51:08 +00:00
null=True
2023-12-01 18:31:09 +00:00
)
2023-11-15 10:43:13 +00:00
issuer_did = models.ForeignKey(
DID,
on_delete=models.CASCADE,
related_name='vcredentials',
)
2024-01-18 14:09:19 +00:00
eidas1_did = models.ForeignKey(
DID,
on_delete=models.CASCADE,
null=True
)
2023-11-14 17:50:23 +00:00
schema = models.ForeignKey(
Schemas,
on_delete=models.CASCADE,
related_name='vcredentials',
)
# revocationBitmapIndex = models.AutoField()
2024-02-13 19:49:50 +00:00
@property
def is_didweb(self):
if self.issuer_did.type == DID.Types.WEB.value:
return True
return False
def get_data(self):
2024-01-06 18:18:59 +00:00
if not self.data:
return ""
2024-02-13 19:49:50 +00:00
return self.user.decrypt_data(self.data)
def set_data(self, value):
self.data = self.user.encrypt_data(value)
2023-10-26 11:33:13 +00:00
def get_description(self):
2024-01-22 17:13:06 +00:00
return self.schema._description or ''
2023-10-26 11:33:13 +00:00
def description(self):
2024-01-18 14:09:19 +00:00
for des in json.loads(self.render("")).get('description', []):
2024-01-15 18:11:22 +00:00
if settings.LANGUAGE_CODE in des.get('lang'):
2023-11-20 18:18:00 +00:00
return des.get('value', '')
return ''
2023-10-26 11:33:13 +00:00
2024-01-15 18:11:22 +00:00
def get_type(self, lang=None):
2024-01-24 15:53:19 +00:00
return self.type
2023-10-26 11:33:13 +00:00
def get_status(self):
return self.Status(self.status).label
2023-10-30 12:53:19 +00:00
def get_datas(self):
data = self.render()
credential_subject = ujson.loads(data).get("credentialSubject", {})
return credential_subject.items()
2023-11-02 13:17:07 +00:00
2024-03-04 08:44:53 +00:00
def issue(self, did, domain):
2023-11-15 10:43:13 +00:00
if self.status == self.Status.ISSUED:
return
self.subject_did = did
2023-11-15 10:52:19 +00:00
self.issued_on = datetime.datetime.now().astimezone(pytz.utc)
2024-01-18 19:32:40 +00:00
# hash of credential without sign
self.hash = hashlib.sha3_256(self.render(domain).encode()).hexdigest()
2024-06-06 09:40:26 +00:00
key = self.issuer_did.get_key_material()
signing_key = get_signing_key(key)
credential = self.render(domain)
vc = sign(credential, signing_key, self.issuer_did.did)
vc_str = json.dumps(vc)
valid = verify_vc(vc_str)
2024-02-15 23:25:04 +00:00
if not valid:
return
2024-06-06 09:40:26 +00:00
self.data = self.user.encrypt_data(vc_str)
2023-11-15 10:43:13 +00:00
self.status = self.Status.ISSUED
2024-01-18 14:09:19 +00:00
def get_context(self, domain):
2023-11-15 10:43:13 +00:00
d = json.loads(self.csv_data)
issuance_date = ''
if self.issued_on:
format = "%Y-%m-%dT%H:%M:%SZ"
issuance_date = self.issued_on.strftime(format)
2023-11-15 10:43:13 +00:00
cred_path = 'credentials'
2024-01-18 19:32:40 +00:00
sid = self.id
2024-02-14 09:46:31 +00:00
if self.eidas1_did:
cred_path = 'public/credentials'
2024-01-18 19:32:40 +00:00
sid = self.hash
2024-01-18 14:09:19 +00:00
2024-03-15 18:18:39 +00:00
url_id = "{}/{}/{}".format(
2024-01-18 14:09:19 +00:00
domain,
cred_path,
2024-01-18 19:32:40 +00:00
sid
2024-01-10 18:11:22 +00:00
)
2024-01-15 18:11:22 +00:00
2024-02-27 08:27:55 +00:00
org = Organization.objects.get(main=True)
credential_status_id = 'https://revocation.not.supported/'
if self.issuer_did.type == DID.Types.WEB:
credential_status_id = self.issuer_did.did
2023-11-15 10:43:13 +00:00
context = {
2024-02-14 16:33:24 +00:00
'id_credential': str(self.id),
2024-01-10 18:11:22 +00:00
'vc_id': url_id,
2023-11-15 10:43:13 +00:00
'issuer_did': self.issuer_did.did,
2023-12-04 09:56:22 +00:00
'subject_did': self.subject_did and self.subject_did.did or '',
2023-11-15 10:43:13 +00:00
'issuance_date': issuance_date,
2024-01-15 18:11:22 +00:00
'firstName': self.user.first_name or "",
'lastName': self.user.last_name or "",
'email': self.user.email,
2024-02-27 08:27:55 +00:00
'organisation': org.name or '',
'credential_status_id': credential_status_id,
2023-11-15 10:43:13 +00:00
}
context.update(d)
return context
def render(self, domain=""):
2024-01-18 14:09:19 +00:00
context = self.get_context(domain)
2023-11-15 10:43:13 +00:00
template_name = 'credentials/{}'.format(
self.schema.file_schema
)
tmpl = get_template(template_name)
2024-01-17 13:11:47 +00:00
d_ordered = ujson.loads(tmpl.render(context))
d_minimum = self.filter_dict(d_ordered)
2024-02-14 16:33:24 +00:00
# You can revoke only didweb
if not self.is_didweb:
d_minimum.pop("credentialStatus", None)
2024-01-17 13:11:47 +00:00
return ujson.dumps(d_minimum)
2023-11-15 10:43:13 +00:00
2023-11-14 16:45:08 +00:00
def get_issued_on(self):
2023-11-14 17:50:23 +00:00
if self.issued_on:
return self.issued_on.strftime("%m/%d/%Y")
return ''
2023-10-30 12:53:19 +00:00
2024-01-24 15:10:10 +00:00
def set_type(self):
template_name = 'credentials/{}'.format(
self.schema.file_schema
)
tmpl = get_template(template_name)
d = json.loads(tmpl.render({}))
self.type = d.get('type')[-1]
2024-01-12 13:27:19 +00:00
def filter_dict(self, dic):
new_dict = OrderedDict()
2024-01-12 13:27:19 +00:00
for key, value in dic.items():
if isinstance(value, dict):
new_value = self.filter_dict(value)
if new_value:
new_dict[key] = new_value
elif value:
new_dict[key] = value
return new_dict
class VCTemplate(models.Model):
wkit_template_id = models.CharField(max_length=250)
data = models.TextField()
2023-10-25 10:18:42 +00:00
class File_datas(models.Model):
2024-03-20 12:02:50 +00:00
file_name = models.CharField(_("File"), max_length=250)
success = models.BooleanField(_("Success"), default=True)
created_at = models.DateTimeField(_("Date"), auto_now=True)
2023-10-25 10:18:42 +00:00
2023-10-16 17:08:18 +00:00
class Membership(models.Model):
"""
This model represent the relation of this user with the ecosystem.
"""
class Types(models.IntegerChoices):
BENEFICIARY = 1, _('Beneficiary')
EMPLOYEE = 2, _('Employee')
2023-11-13 09:15:52 +00:00
MEMBER = 3, _('Member')
2023-10-16 17:08:18 +00:00
type = models.PositiveSmallIntegerField(_('Type of membership'), choices=Types.choices)
start_date = models.DateField(
_('Start date'),
help_text=_('What date did the membership start?'),
blank=True,
null=True
)
end_date = models.DateField(
_('End date'),
2023-11-13 09:15:52 +00:00
help_text=_('What date will the membership end?'),
2023-10-16 17:08:18 +00:00
blank=True,
null=True
)
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='memberships',
)
2023-10-17 08:53:03 +00:00
def get_type(self):
return dict(self.Types.choices).get(self.type)
2023-10-17 11:40:34 +00:00
class Rol(models.Model):
2023-11-14 14:55:17 +00:00
name = models.CharField(_("name"), max_length=250)
description = models.CharField(_("Description"), max_length=250, null=True)
2023-10-17 13:49:56 +00:00
def __str__(self):
return self.name
class Service(models.Model):
2023-11-13 17:09:37 +00:00
domain = models.CharField(_("Domain"), max_length=250)
description = models.CharField(_("Description"), max_length=250)
2023-10-19 13:20:06 +00:00
rol = models.ManyToManyField(
2023-10-17 13:49:56 +00:00
Rol,
)
2023-10-17 15:42:48 +00:00
2023-10-19 13:20:06 +00:00
def get_roles(self):
2023-11-14 16:45:08 +00:00
if self.rol.exists():
2024-01-04 18:58:28 +00:00
return ", ".join([x.name for x in self.rol.order_by("name")])
2023-11-14 16:45:08 +00:00
return _("None")
2023-10-19 13:20:06 +00:00
2023-10-17 15:42:48 +00:00
def __str__(self):
2023-10-27 09:19:10 +00:00
return "{} -> {}".format(self.domain, self.get_roles())
2023-10-17 15:42:48 +00:00
class UserRol(models.Model):
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='roles',
)
service = models.ForeignKey(
Service,
2023-12-14 16:59:40 +00:00
verbose_name=_("Service"),
2023-10-17 15:42:48 +00:00
on_delete=models.CASCADE,
related_name='users',
)
2023-11-02 16:13:49 +00:00
2023-11-14 14:55:17 +00:00
class Meta:
unique_together = ('user', 'service',)