You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
88 lines
3.3 KiB
88 lines
3.3 KiB
from django.db import models
|
|
from django.utils import timezone
|
|
# from django.apps import apps
|
|
from django.core.exceptions import ObjectDoesNotExist
|
|
from django.conf import settings
|
|
|
|
from ..registry import model_registry
|
|
import uuid
|
|
|
|
from . import ModelLog, SideStoreModel, BaseModel
|
|
|
|
|
|
class DataAccess(BaseModel):
|
|
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
|
|
shared_with = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='shared_data')
|
|
model_name = models.CharField(max_length=50)
|
|
model_id = models.UUIDField()
|
|
granted_at = models.DateTimeField(auto_now_add=True)
|
|
|
|
def delete_dependencies(self):
|
|
pass
|
|
|
|
def create_revoke_access_log(self):
|
|
self.create_access_log(self.shared_with.all(), 'REVOKED_ACCESS')
|
|
|
|
def concerned_users(self):
|
|
users = list(self.shared_with.all())
|
|
if self.related_user:
|
|
users.append(self.related_user)
|
|
return users
|
|
|
|
def create_access_log(self, users, operation):
|
|
"""Create an access log for a list of users """
|
|
model_class = model_registry.get_model(self.model_name)
|
|
if model_class:
|
|
try:
|
|
obj = model_class.objects.get(id=self.model_id)
|
|
store_id = None
|
|
if isinstance(obj, SideStoreModel):
|
|
store_id = obj.store_id
|
|
|
|
for user in users:
|
|
existing_log = ModelLog.objects.filter(user=user, model_id=self.model_id, operation=operation).first()
|
|
if existing_log:
|
|
existing_log.date = timezone.now()
|
|
existing_log.model_operation = operation
|
|
existing_log.save()
|
|
else:
|
|
ModelLog.objects.create(
|
|
user=user,
|
|
model_id=self.model_id,
|
|
model_name=self.model_name,
|
|
operation=operation,
|
|
date=timezone.now(),
|
|
store_id=store_id
|
|
)
|
|
except ObjectDoesNotExist:
|
|
pass
|
|
else:
|
|
print(f'model not found: {self.model_name}')
|
|
|
|
def add_references(self):
|
|
model_class = model_registry.get_model(self.model_name)
|
|
if model_class:
|
|
try:
|
|
obj = model_class.objects.get(id=self.model_id)
|
|
related_instance = obj.related_instances()
|
|
related_instance.append(obj)
|
|
for instance in related_instance:
|
|
if isinstance(instance, BaseModel):
|
|
instance.add_data_access_relation(self)
|
|
instance.save()
|
|
except ObjectDoesNotExist:
|
|
pass
|
|
|
|
def cleanup_references(self):
|
|
model_class = model_registry.get_model(self.model_name)
|
|
if model_class:
|
|
try:
|
|
obj = model_class.objects.get(id=self.model_id)
|
|
related_instance = obj.related_instances()
|
|
related_instance.append(obj)
|
|
for instance in related_instance:
|
|
if isinstance(instance, BaseModel):
|
|
instance.remove_data_access_relation(self)
|
|
instance.save()
|
|
except ObjectDoesNotExist:
|
|
pass
|
|
|