encription from a env key and password admin

This commit is contained in:
Cayo Puigdefabregas 2024-01-03 17:52:46 +01:00
parent 20f40b43d0
commit d2f7e5395d
6 changed files with 41 additions and 29 deletions

View File

@ -645,7 +645,7 @@ class DidRegisterView(Credentials, CreateView):
def form_valid(self, form): def form_valid(self, form):
form.instance.user = self.request.user form.instance.user = self.request.user
form.instance.set_did(self.request.session) form.instance.set_did()
form.save() form.save()
messages.success(self.request, _('DID created successfully')) messages.success(self.request, _('DID created successfully'))
Event.set_EV_ORG_DID_CREATED_BY_ADMIN(form.instance) Event.set_EV_ORG_DID_CREATED_BY_ADMIN(form.instance)

View File

@ -421,16 +421,16 @@ class DID(models.Model):
null=True, null=True,
) )
def get_key_material(self, session): def get_key_material(self):
if "sensitive_data_encryption_key" not in session: if not settings.KEY_CREDENTIALS_CLEAN:
raise Exception("Ojo! Se intenta acceder a datos cifrados sin tener la clave de usuario.") raise Exception("Ojo! Se intenta acceder a datos cifrados sin tener la clave.")
sb = secret.SecretBox(session["sensitive_data_encryption_key"]) sb = secret.SecretBox(settings.KEY_CREDENTIALS_CLEAN)
return sb.decrypt(self._key_material) return sb.decrypt(self._key_material)
def set_key_material(self, value, session): def set_key_material(self, value):
if "sensitive_data_encryption_key" not in session: if not settings.KEY_CREDENTIALS_CLEAN:
raise Exception("Ojo! Se intenta acceder a datos cifrados sin tener la clave de usuario.") raise Exception("Ojo! Se intenta acceder a datos cifrados sin tener la clave.")
sb = secret.SecretBox(session["sensitive_data_encryption_key"]) sb = secret.SecretBox(settings.KEY_CREDENTIALS_CLEAN)
self._key_material = sb.encrypt(value) self._key_material = sb.encrypt(value)
@property @property
@ -439,7 +439,7 @@ class DID(models.Model):
return True return True
return False return False
def set_did(self, session): def set_did(self):
""" """
Generates a new DID Controller Key and derives a DID from it. Generates a new DID Controller Key and derives a DID from it.
Because DID Controller Keys are stored encrypted using a User's Sensitive Data Encryption Key, Because DID Controller Keys are stored encrypted using a User's Sensitive Data Encryption Key,
@ -447,7 +447,7 @@ class DID(models.Model):
""" """
new_key_material = generate_did_controller_key() new_key_material = generate_did_controller_key()
self.did = keydid_from_controller_key(new_key_material) self.did = keydid_from_controller_key(new_key_material)
self.set_key_material(new_key_material, session) self.set_key_material(new_key_material)
# TODO: darmengo: esta funcion solo se llama desde un fichero que sube cosas a s3 (??) Preguntar a ver que hace. # TODO: darmengo: esta funcion solo se llama desde un fichero que sube cosas a s3 (??) Preguntar a ver que hace.
@ -513,16 +513,16 @@ class VerificableCredential(models.Model):
related_name='vcredentials', related_name='vcredentials',
) )
def get_data(self, session): def get_data(self):
if "sensitive_data_encryption_key" not in session: if not settings.KEY_CREDENTIALS_CLEAN:
raise Exception("Ojo! Se intenta acceder a datos cifrados sin tener la clave de usuario.") raise Exception("Ojo! Se intenta acceder a datos cifrados sin tener la clave.")
sb = secret.SecretBox(session["sensitive_data_encryption_key"]) sb = secret.SecretBox(settings.KEY_CREDENTIALS_CLEAN)
return sb.decrypt(self._data) return sb.decrypt(self._data)
def set_data(self, value, session): def set_data(self, value):
if "sensitive_data_encryption_key" not in session: if not settings.KEY_CREDENTIALS_CLEAN:
raise Exception("Ojo! Se intenta acceder a datos cifrados sin tener la clave de usuario.") raise Exception("Ojo! Se intenta acceder a datos cifrados sin tener la clave.")
sb = secret.SecretBox(session["sensitive_data_encryption_key"]) sb = secret.SecretBox(settings.KEY_CREDENTIALS_CLEAN)
self._data = sb.encrypt(value) self._data = sb.encrypt(value)
@property @property
@ -553,7 +553,7 @@ class VerificableCredential(models.Model):
data = json.loads(self.csv_data).items() data = json.loads(self.csv_data).items()
return data return data
def issue(self, did, session): def issue(self, did):
if self.status == self.Status.ISSUED: if self.status == self.Status.ISSUED:
return return
@ -562,7 +562,7 @@ class VerificableCredential(models.Model):
self.issued_on = datetime.datetime.now().astimezone(pytz.utc) self.issued_on = datetime.datetime.now().astimezone(pytz.utc)
self.data = sign_credential( self.data = sign_credential(
self.render(), self.render(),
self.issuer_did.get_key_material(session) self.issuer_did.get_key_material()
) )
def get_context(self): def get_context(self):

View File

@ -18,7 +18,6 @@ class RequestCredentialForm(forms.Form):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None) self.user = kwargs.pop('user', None)
self.session = kwargs.pop('session', None)
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.fields['did'].choices = [ self.fields['did'].choices = [
(x.did, x.label) for x in DID.objects.filter(user=self.user) (x.did, x.label) for x in DID.objects.filter(user=self.user)
@ -46,7 +45,7 @@ class RequestCredentialForm(forms.Form):
did = did[0].did did = did[0].did
cred = cred[0] cred = cred[0]
try: try:
cred.issue(did, self.session) cred.issue(did)
except Exception: except Exception:
return return

View File

@ -128,7 +128,6 @@ class CredentialsRequestView(MyWallet, FormView):
def get_form_kwargs(self): def get_form_kwargs(self):
kwargs = super().get_form_kwargs() kwargs = super().get_form_kwargs()
kwargs['user'] = self.request.user kwargs['user'] = self.request.user
kwargs['session'] = self.request.session
return kwargs return kwargs
def form_valid(self, form): def form_valid(self, form):
@ -190,7 +189,7 @@ class DidRegisterView(MyWallet, CreateView):
def form_valid(self, form): def form_valid(self, form):
form.instance.user = self.request.user form.instance.user = self.request.user
form.instance.set_did(self.request.session) form.instance.set_did()
form.save() form.save()
messages.success(self.request, _('DID created successfully')) messages.success(self.request, _('DID created successfully'))

View File

@ -1,8 +1,10 @@
from django.urls import reverse_lazy from django.urls import reverse_lazy
from django.conf import settings
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.contrib.auth import views as auth_views from django.contrib.auth import views as auth_views
from django.contrib.auth import login as auth_login from django.contrib.auth import login as auth_login
from django.http import HttpResponseRedirect from django.http import HttpResponseRedirect
from nacl import secret
class LoginView(auth_views.LoginView): class LoginView(auth_views.LoginView):
@ -24,9 +26,19 @@ class LoginView(auth_views.LoginView):
admin_dashboard = reverse_lazy('idhub:admin_dashboard') admin_dashboard = reverse_lazy('idhub:admin_dashboard')
if self.extra_context['success_url'] == user_dashboard: if self.extra_context['success_url'] == user_dashboard:
self.extra_context['success_url'] = admin_dashboard self.extra_context['success_url'] = admin_dashboard
password = form.cleaned_data.get("password")
# Decrypt the user's sensitive data encryption key and store it in the session.
self.decript_key(user, password)
auth_login(self.request, user) auth_login(self.request, user)
# Decrypt the user's sensitive data encryption key and store it in the session.
password = form.cleaned_data.get("password") # TODO: Is this right????????
sensitive_data_encryption_key = user.decrypt_sensitive_data_encryption_key(password)
self.request.session["sensitive_data_encryption_key"] = sensitive_data_encryption_key
return HttpResponseRedirect(self.extra_context['success_url']) return HttpResponseRedirect(self.extra_context['success_url'])
def decript_key(self, user, password):
if not settings.KEY_CREDENTIALS:
return
sb_key = user.derive_key_from_password(password)
sb = secret.SecretBox(sb_key)
data_decript = sb.decrypt(settings.KEY_CREDENTIALS)
settings.KEY_CREDENTIALS_CLEAN = data_decript

View File

@ -184,3 +184,5 @@ USE_I18N = True
USE_L10N = True USE_L10N = True
AUTH_USER_MODEL = 'idhub_auth.User' AUTH_USER_MODEL = 'idhub_auth.User'
KEY_CREDENTIALS = config("KEY_CREDENTIALS")
KEY_CREDENTIALS_CLEAN = ""